answer
stringlengths
17
10.2M
package org.innovateuk.ifs.project.financecheck.controller; import org.innovateuk.ifs.commons.rest.RestResult; import org.junit.Test; import org.mockito.Mock; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.web.servlet.MvcResult; import org.innovateuk.ifs.BaseControllerMockMVCTest; import org.innovateuk.ifs.file.resource.FileEntryResource; import org.innovateuk.ifs.finance.service.OverheadFileRestService; import org.springframework.core.io.ByteArrayResource; import org.springframework.web.multipart.MultipartFile; import static org.innovateuk.ifs.file.builder.FileEntryResourceBuilder.newFileEntryResource; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.assertj.core.api.Assertions.assertThat; public class OverheadFileDownloaderControllerTest extends BaseControllerMockMVCTest<OverheadFileDownloaderController>{ @Mock private OverheadFileRestService overheadFileRestServiceMock; @Test public void testDownloadJesFileSuccess() throws Exception { final String fileName = "overhead-spread-sheet"; final String extension = ".xlsx"; Long projectId = 1L; Long overheadId = 1L; MultipartFile file = new MockMultipartFile(fileName+extension, fileName.getBytes()); FileEntryResource fileEntryResource = newFileEntryResource().withId(overheadId).withFilesizeBytes(file.getSize()).build(); given(overheadFileRestServiceMock.getOverheadFile( overheadId)).willReturn(RestResult.restSuccess(new ByteArrayResource(file.getBytes()))); given(overheadFileRestServiceMock.getOverheadFileDetails( overheadId)).willReturn(RestResult.restSuccess(fileEntryResource)); MvcResult result = mockMvc.perform(get("/download/overheadfile/" + overheadId)) .andExpect(status().isOk()) .andReturn(); verify(overheadFileRestServiceMock).getOverheadFileDetails(projectId); assertThat(fileName).isEqualTo(result.getResponse().getContentAsString()); } @Override protected OverheadFileDownloaderController supplyControllerUnderTest() { return new OverheadFileDownloaderController(); } }
package org.ndexbio.rest.client; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.UUID; import org.apache.commons.codec.binary.Base64; import org.ndexbio.model.object.NdexObject; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; /** * Simple REST Client for NDEX web service. * * TODO: support user authentication! * */ public class NdexRestClient { // for authorization String _username = null; String _password = null; UUID _userUid = null; String _baseroute = null; public NdexRestClient(String username, String password, String route) { super(); System.out.println("Starting init of NDExRestClient "); _baseroute = route; _username = username; _password = password; System.out.println("init of NDExRestClient with " + _baseroute + " " + _username + " " + password); } public NdexRestClient(String username, String password) { super(); System.out.println("Starting init of NDExRestClient "); // Default to localhost, standard location for testing _baseroute = "http://localhost:8080/ndexbio-rest"; _username = username; _password = password; System.out.println("init of NDExRestClient with " + _baseroute + " " + _username + " " + password); } private void addBasicAuth(HttpURLConnection con) { String credentials = _username + ":" + _password; String basicAuth = "Basic " + new String(new Base64().encode(credentials.getBytes())); con.setRequestProperty("Authorization", basicAuth); } public void setCredential(String username, String password) { this._username = username; this._password = password; } /* * GET */ public JsonNode get(final String route, final String query) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; try { ObjectMapper mapper = new ObjectMapper(); con = getReturningConnection(route, query); input = con.getInputStream(); JsonNode result = null; if (null != input) { result = mapper.readTree(input); return result; } throw new IOException("failed to connect to ndex"); } finally { if ( input != null) input.close(); if ( con != null) con.disconnect(); } } public NdexObject getNdexObject( final String route, final String query, final Class<? extends NdexObject> mappedClass) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; try { ObjectMapper mapper = new ObjectMapper(); con = getReturningConnection(route, query); input = con.getInputStream(); if (null != input){ return mapper.readValue(input, mappedClass); } throw new IOException("failed to connect to ndex"); } finally { if (null != input) input.close(); if ( con != null ) con.disconnect(); } } public List<? extends NdexObject> getNdexObjectList( final String route, final String query, final Class<? extends NdexObject> mappedClass) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; try { ObjectMapper mapper = new ObjectMapper(); JavaType type = mapper.getTypeFactory(). constructCollectionType(List.class, mappedClass); con = getReturningConnection(route, query); input = con.getInputStream(); if (null != input){ return mapper.readValue(input, type); } throw new IOException("failed to connect to ndex"); } finally { if (null != input) input.close(); if ( con != null) con.disconnect(); } } public HttpURLConnection getReturningConnection(final String route, final String query) throws IOException { URL request = new URL(_baseroute + route + query); System.out.println("GET (returning connection) URL = " + request); HttpURLConnection con = (HttpURLConnection) request.openConnection(); addBasicAuth(con); return con; } /* * PUT */ public JsonNode put( final String route, final JsonNode putData) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; try { ObjectMapper mapper = new ObjectMapper(); con = putReturningConnection(route, putData); input = con.getInputStream(); // TODO 401 error handling return mapper.readTree(input); } finally { if (null != input) input.close(); if ( con != null ) con.disconnect(); } } public NdexObject putNdexObject( final String route, final JsonNode putData, final Class<? extends NdexObject> mappedClass) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; try { ObjectMapper mapper = new ObjectMapper(); con = putReturningConnection(route, putData); input = con.getInputStream(); if (null != input){ return mapper.readValue(input, mappedClass); } throw new IOException("failed to connect to ndex"); } finally { if (null != input) input.close(); if ( con != null) con.disconnect(); } } public HttpURLConnection putReturningConnection(final String route, final Object putData) throws JsonProcessingException, IOException { URL request = new URL(_baseroute + route); System.out.println("PUT (returning connection) URL = " + request); ObjectMapper objectMapper = new ObjectMapper(); HttpURLConnection con = (HttpURLConnection) request.openConnection(); addBasicAuth(con); con.setDoOutput(true); con.setRequestMethod("PUT"); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Accept", "application/json"); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); String putDataString = objectMapper.writeValueAsString(putData); out.write(putDataString); out.flush(); out.close(); return con; } /* * POST */ public JsonNode post( final String route, final JsonNode postData) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; try { ObjectMapper mapper = new ObjectMapper(); con = postReturningConnection(route, postData); input = con.getInputStream(); JsonNode result = null; if (null != input) { result = mapper.readTree(input); return result; } throw new IOException("failed to connect to ndex"); } finally { if (null != input) input.close(); if ( con != null) con.disconnect(); } } public NdexObject postNdexObject( final String route, final JsonNode postData, final Class<? extends NdexObject> mappedClass) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; try { ObjectMapper mapper = new ObjectMapper(); con = postReturningConnection(route, postData); input = con.getInputStream(); if (null != input){ return mapper.readValue(input, mappedClass); } throw new IOException("failed to connect to ndex"); } finally { if (null != input) input.close(); if ( con != null ) con.disconnect(); } } public List <? extends NdexObject> postNdexObjectList( final String route, final JsonNode postData, final Class<? extends NdexObject> mappedClass) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; try { ObjectMapper mapper = new ObjectMapper(); JavaType type = mapper.getTypeFactory(). constructCollectionType(List.class, mappedClass); con = postReturningConnection(route, postData); input = con.getInputStream(); if (null != input){ return mapper.readValue(input, type); } throw new IOException("failed to connect to ndex"); } finally { if (null != input) input.close(); if ( con != null ) con.disconnect(); } } public HttpURLConnection postReturningConnection(String route, JsonNode postData) throws JsonProcessingException, IOException { URL request = new URL(_baseroute + route); System.out.println("POST (returning connection) URL = " + request); HttpURLConnection con = (HttpURLConnection) request.openConnection(); String postDataString = postData.toString(); // System.out.println(postDataString); con.setDoOutput(true); con.setDoInput(true); con.setInstanceFollowRedirects(false); con.setRequestMethod("POST"); // con.setRequestProperty("Content-Type", // "application/x-www-form-urlencoded"); con.setRequestProperty("Content-Type", "application/json; charset=utf-8"); // con.setRequestProperty("charset", "utf-8"); // con.setRequestProperty("Content-Length", // "" + Integer.toString(postDataString.getBytes().length)); con.setUseCaches(false); addBasicAuth(con); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8")); writer.write(postDataString); writer.flush(); writer.close(); wr.close(); return con; } /* * DELETE */ public JsonNode delete(final String route) throws JsonProcessingException, IOException { InputStream input = null; HttpURLConnection con = null; ObjectMapper mapper = new ObjectMapper(); URL request = new URL(_baseroute + route); try { con = (HttpURLConnection) request.openConnection(); addBasicAuth(con); con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestMethod("DELETE"); input = con.getInputStream(); JsonNode result = null; if (null != input) { result = mapper.readTree(input); return result; } throw new IOException("failed to connect to ndex"); } finally { if (null != input) input.close(); if ( con != null) con.disconnect(); } } /* * Getters and Setters */ public String getUsername() { return _username; } public void setUsername(String _username) { this._username = _username; } public String getPassword() { return _password; } public void setPassword(String _password) { this._password = _password; } public String getBaseroute() { return _baseroute; } public void setBaseroute(String _baseroute) { this._baseroute = _baseroute; } public UUID getUserUid() { return _userUid; } public void setUserUid(UUID _userUid) { this._userUid = _userUid; } }
package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.*; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * * @author Roi and Simon */ public class RobotShoot { private static boolean needsToBeWound; private static boolean needsToBeUnwound; private static boolean latched; private static boolean windMax; public static double speed; public static double WIND_SPEED = .3; public static final double UNWIND_SPEED = -.3; private static Timer timerRelatch; public static final int ENCODER_REVOLUTIONS = 5; public static int revolutionsOfShooter; private static double time; private static final double rewindMaxRevolutions = 5000; public static void initialize() { time = 0; RobotSensors.shooterWinchEncoder.start(); latched = false; } /** * It is a test method to test the shooter */ public static void testShooter() { RobotShoot.automatedShoot(); } /** * This is an automated Shooter to be used */ public static void automatedShoot() { //RobotShoot.releaseBall(); if (timerRelatch == null) { timerRelatch = new Timer(); //timerRelatch.start(); //time = timerRelatch.get(); } RobotShoot.unwindShooter(); } /** * This releases the ball if it is loaded, and if it is not, it displays * that it is not. */ public static void releaseBall() { if (RobotPickUp.ifLoaded()|| true) { //TODO: Remove true||, and start the timer here RobotActuators.latchRelease.set(false); timerRelatch.start(); System.out.println("Success: Ball has been shot"); } else { SmartDashboard.putString("Error", "Ball not loaded"); //or blink a light } } /** * it gets the encoder value of the shooter wheel * * @returns the encoderValue */ private static int getEncoderValue() { return RobotSensors.shooterWinchEncoder.get(); } /** * This will unwind the shooter if .5 seconds have passed, and until the * limit switch is reached or until it has exceeded the max number of * revolutions. */ public static void unwindShooter() { if (timerRelatch == null && !latched) { needsToBeUnwound = true; } else { needsToBeUnwound = false; } } /** * It rewinds the shooter until the limit switch has been reached or again * max number of revolutions */ public static void rewindShooter() { if (!windMax) { needsToBeWound = true; } else { needsToBeWound = false; } } public static void stopShooter() { RobotActuators.shooterWinch.set(0); } static int rc = 0; /** * This method will set the movement of the shooter winch based on two * booleans which represent two buttons * * @param forward * @param backward */ public static void manualWind(boolean forward, boolean backward) { if (forward && !backward) { speed = WIND_SPEED; System.out.println("Wind Speed: " + WIND_SPEED); } else if (!forward && backward) { speed = UNWIND_SPEED; System.out.println("Wind Speed: " + UNWIND_SPEED); } else { speed = 0; } RobotActuators.shooterWinch.set(speed); } /** * This will get all of the new values that we need as well as setting the * shooter speed */ public static void update() { if (timerRelatch != null) { double b = timerRelatch.get(); if (b /*- time*/ > .5) { timerRelatch = null; RobotSensors.shooterWinchEncoder.reset(); System.out.println("reset encoder"); unwindShooter(); } } if (RobotShoot.getEncoderValue() >= rewindMaxRevolutions) { needsToBeUnwound = false; } if (RobotShoot.getEncoderValue() <= 0){ needsToBeWound = true; } if (needsToBeWound && latched) { RobotActuators.shooterWinch.set(WIND_SPEED); //TODO: Change speed to constant value WIND_SPEED } if (needsToBeUnwound && !latched) { RobotActuators.shooterWinch.set(UNWIND_SPEED); //TODO: Change speed to constant value UNWIND_SPEED } if (!needsToBeUnwound && latched) { RobotShoot.rewindShooter(); } windMax = RobotSensors.shooterLoadedLim.get(); //SHOOTER_LOADED_LIM latched = RobotSensors.shooterAtBack.get(); //SHOOTER_LATCHED_LIM if (latched && !windMax) { RobotActuators.latchRelease.set(true); //true means it goes in } //System.out.println("sneedsToBeUnwound: " + needsToBeUnwound); //System.out.println("needsToBeWound: " + needsToBeWound); //System.out.println("latched: " + latched + rc++); //System.out.println("windMax: " + windMax + rc++); System.out.println(getEncoderValue()); //FOR TESTING PURPOSES ONLY } } //IF WE WANT A MANUAL SHOT YOU WILL NEED TO SET THE MOTOR IN TELEOP
package org.ndexbio.security; import java.util.AbstractMap; import java.util.Hashtable; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.InitialLdapContext; import javax.naming.ldap.LdapContext; import org.ndexbio.model.exceptions.NdexException; import org.ndexbio.model.exceptions.UnauthorizedOperationException; import org.ndexbio.model.object.NewUser; import org.ndexbio.task.Configuration; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; public class LDAPAuthenticator { static Logger logger = Logger.getLogger(LDAPAuthenticator.class.getName()); private final static int CACHE_SIZE = 100; private final static String PROP_LDAP_URL = "PROP_LDAP_URL"; private final static String AD_SEARCH_BASE= "AD_SEARCH_BASE"; private final static String AD_NDEX_GROUP_NAME="AD_NDEX"; private final static String AD_AUTH_USE_CACHE="AD_AUTH_USE_CACHE"; private final static String JAVA_KEYSTORE="KEYSTORE_PATH"; private final static String AD_USE_SSL="AD_USE_SSL"; private final static String AD_TRACE_MODE="AD_TRACE_MODE"; private final static String JAVA_KEYSTORE_PASSWD= "JAVA_KEYSTORE_PASSWD"; private final static String AD_CTX_PRINCIPLE = "AD_CTX_PRINCIPLE"; protected final static String AD_SEARCH_FILTER = "AD_SEARCH_FILTER"; protected final static String userNamePattern = "%%USER_NAME%%"; private String ldapAdServer; protected String ldapSearchBase; private String ldapNDExGroup; protected Hashtable <String,Object> env ; private Pattern pattern ; private boolean useCache = false; protected String ctxPrinciplePattern ; protected String searchFilterPattern ; public static final String AD_DELEGATED_ACCOUNT="AD_DELEGATED_ACCOUNT"; private static final String AD_DELEGATED_ACCOUNT_PASSWORD="AD_DELEGATED_ACCOUNT_PASSWORD"; // private static final String AD_DELEGATED_ACCOUNT_USER_NAME_PATTERN="AD_DELEGATED_ACCOUNT_USER_NAME_PATTERN"; private String delegatedUserName ; private String delegatedUserPassword; //key is the combination of protected LoadingCache<java.util.Map.Entry<String,String>, Boolean> userCredentials; public LDAPAuthenticator (Configuration config) throws NdexException { ldapAdServer = config.getRequiredProperty(PROP_LDAP_URL); ldapSearchBase=config.getRequiredProperty(AD_SEARCH_BASE); ldapNDExGroup = config.getProperty(AD_NDEX_GROUP_NAME); ctxPrinciplePattern = config.getRequiredProperty(AD_CTX_PRINCIPLE); if ( ctxPrinciplePattern.indexOf(userNamePattern) == -1) throw new NdexException ("Pattern "+ userNamePattern + " not found in configuration property " + AD_CTX_PRINCIPLE + "."); searchFilterPattern = config.getRequiredProperty(AD_SEARCH_FILTER); if ( searchFilterPattern.indexOf(userNamePattern) == -1) throw new NdexException ("Pattern "+ userNamePattern + " not found in configuration property " + AD_SEARCH_FILTER + "."); delegatedUserName = config.getProperty(AD_DELEGATED_ACCOUNT); if ( delegatedUserName !=null) delegatedUserPassword = config.getRequiredProperty(AD_DELEGATED_ACCOUNT_PASSWORD); env = new Hashtable<>(); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapAdServer); env.put("java.naming.ldap.attributes.binary", "objectSID"); String valueStr = config.getProperty(AD_TRACE_MODE); if ( valueStr != null && Boolean.parseBoolean(valueStr)) { // env.put("com.sun.jndi.ldap.trace.ber", System.err); } pattern = Pattern.compile("^CN=(.*?[^\\\\]),"); String useCacheStr = config.getProperty(AD_AUTH_USE_CACHE); if (useCacheStr != null && Boolean.parseBoolean(useCacheStr)) { useCache = true; logger.info("Server AD Authentication cache turned on."); userCredentials = CacheBuilder .newBuilder().maximumSize(CACHE_SIZE) .expireAfterAccess(10L, TimeUnit.MINUTES) .build(new CacheLoader<java.util.Map.Entry<String,String>, Boolean>() { @Override public Boolean load(java.util.Map.Entry<String,String> entry) throws NdexException, ExecutionException { String userName = entry.getKey(); String pswd = entry.getValue(); Boolean userIsInGrp = userIsInNdexGroup(userName, pswd); if ( userIsInGrp.booleanValue() ) { userCredentials.put(new AbstractMap.SimpleImmutableEntry<>(userName, pswd), Boolean.TRUE); return Boolean.TRUE; } throw new UnauthorizedOperationException("User " + userName + " is not in the required group." ); } }); } else { useCache = false; } String configValue = config.getProperty(AD_USE_SSL); if (configValue != null && Boolean.parseBoolean(configValue)){ String keystore = config.getProperty(JAVA_KEYSTORE); if ( keystore == null) throw new NdexException("Requried property " + JAVA_KEYSTORE + " is not defined in ndex.properties file."); System.setProperty("javax.net.ssl.trustStore", keystore); String keystorePasswd = config.getProperty(JAVA_KEYSTORE_PASSWD); // if (keystorePasswd ==null ) // throw new NdexException ("Requried property " + JAVA_KEYSTORE_PASSWD + " is not defined in ndex.properties file."); if ( keystorePasswd != null ) System.setProperty("javax.net.ssl.trustStorePassword", keystorePasswd); // System.setProperty("javax.net.debug", "INFO"); env.put(Context.SECURITY_PROTOCOL, "ssl"); logger.info("Server AD authentication using ssl with keystore "+ keystore); } } protected Boolean userIsInNdexGroup (String username, String password) throws UnauthorizedOperationException { //env.put(Context.SECURITY_PRINCIPAL, "NA\\" +username); if ( delegatedUserName != null) { env.put(Context.SECURITY_PRINCIPAL,username); } else { env.put(Context.SECURITY_PRINCIPAL, ctxPrinciplePattern.replaceAll(userNamePattern, username)); } env.put(Context.SECURITY_CREDENTIALS, password); try { LdapContext ctx = new InitialLdapContext(env,null); // String searchFilter = "(&(SAMAccountName="+ username + ")(objectClass=user)(objectCategory=person))"; String searchFilter = searchFilterPattern.replaceAll(userNamePattern, username); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls); SearchResult searchResult = null; if ( results.hasMoreElements()) { searchResult = results.nextElement(); Attributes attrs = searchResult.getAttributes(); // Attribute uWWID = attrs.get("employeeID"); if ( ldapNDExGroup != null ) { Attribute grp = attrs.get("memberOf"); NamingEnumeration enu = grp.getAll(); while ( enu.hasMore()) { String obj = (String)enu.next(); // System.out.println(obj); Matcher matcher = pattern.matcher(obj); if (matcher.find()) { if ( matcher.group(1).equals(ldapNDExGroup) ) return Boolean.TRUE; } } return Boolean.FALSE; } return Boolean.TRUE; } return Boolean.FALSE; } catch (NamingException e) { throw new UnauthorizedOperationException(e.getMessage()); } } public NewUser getNewUser (String username, String password) throws UnauthorizedOperationException { //env.put(Context.SECURITY_PRINCIPAL, "NA\\" +username); env.put(Context.SECURITY_PRINCIPAL, ctxPrinciplePattern.replaceAll(userNamePattern, username)); env.put(Context.SECURITY_CREDENTIALS, password); try { LdapContext ctx = new InitialLdapContext(env,null); // String searchFilter = "(&(SAMAccountName="+ username + ")(objectClass=user)(objectCategory=person))"; String searchFilter = searchFilterPattern.replaceAll(userNamePattern, username); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls); SearchResult searchResult = null; if ( results.hasMoreElements()) { searchResult = results.nextElement(); Attributes attrs = searchResult.getAttributes(); // Attribute uWWID = attrs.get("employeeID"); NewUser newUser = new NewUser(); newUser.setAccountName(username); newUser.setPassword(password); Attribute attr =attrs.get("givenName"); if ( attr.size()>0) { newUser.setFirstName(attr.get(0).toString()); } attr =attrs.get("sn"); if ( attr.size()>0) { newUser.setLastName(attr.get(0).toString()); } attr =attrs.get("mail"); if ( attr.size()>0) { newUser.setEmailAddress(attr.get(0).toString()); } return newUser; } return null; } catch (NamingException e) { throw new UnauthorizedOperationException(e.getMessage()); } } public boolean authenticateUser(String username, String password) throws UnauthorizedOperationException { if ( !useCache) { if ( delegatedUserName !=null) { return userIsInNdexGroup(getFullyQualifiedNameByUserId(username),password).booleanValue(); } return userIsInNdexGroup(username,password).booleanValue(); } Boolean result; try { result = userCredentials.get(new AbstractMap.SimpleImmutableEntry<>(username, password)); } catch (ExecutionException e) { throw new UnauthorizedOperationException(e.getMessage()); } return result.booleanValue() ; } private String getFullyQualifiedNameByUserId(String userId) throws UnauthorizedOperationException { env.put(Context.SECURITY_PRINCIPAL, ctxPrinciplePattern.replaceAll(userNamePattern, delegatedUserName)); env.put(Context.SECURITY_CREDENTIALS, delegatedUserPassword); try { LdapContext ctx = new InitialLdapContext(env,null); String searchFilter = searchFilterPattern.replaceAll(userNamePattern, userId); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls); SearchResult searchResult = null; if (results.hasMoreElements()) { searchResult = results.nextElement(); return searchResult.getNameInNamespace(); } return null; } catch (NamingException e) { throw new UnauthorizedOperationException(e.getMessage()); } } }
package railo.commons.lang; import railo.runtime.op.Caster; public final class CFTypes { /** * Field <code>TYPE_ANY</code> */ public static final short TYPE_ANY=0; /** * Field <code>TYPE_ARRAY</code> */ public static final short TYPE_ARRAY=1; /** * Field <code>TYPE_BOOLEAN</code> */ public static final short TYPE_BASE64=20; /** * Field <code>TYPE_BOOLEAN</code> */ public static final short TYPE_BOOLEAN=2; /** * Field <code>TYPE_BINARY</code> */ public static final short TYPE_BINARY=3; /** * Field <code>TYPE_DATETIME</code> */ public static final short TYPE_DATETIME=4; /** * Field <code>TYPE_NUMERIC</code> */ public static final short TYPE_NUMERIC=5; /** * Field <code>TYPE_QUERY</code> */ public static final short TYPE_QUERY=6; /** * Field <code>TYPE_STRING</code> */ public static final short TYPE_STRING=7; /** * Field <code>TYPE_STRUCT</code> */ public static final short TYPE_STRUCT=8; /** * Field <code>TYPE_TIMESPAN</code> */ public static final short TYPE_TIMESPAN=9; /** * Field <code>TYPE_UUID</code> */ public static final short TYPE_UUID=10; /** * Field <code>TYPE_VARIABLE_NAME</code> */ public static final short TYPE_VARIABLE_NAME=11; /** * Field <code>TYPE_VARIABLE_STRING</code> */ public static final short TYPE_VARIABLE_STRING=12; /** * Field <code>TYPE_UNKNOW</code> */ public static final short TYPE_UNKNOW=-1; /** * Field <code>TYPE_UNKNOW</code> */ public static final short TYPE_UNDEFINED=14; /** * Field <code>TYPE_VOID</code> */ public static final short TYPE_VOID=15; /** * Field <code>TYPE_XML</code> */ public static final short TYPE_XML = 16; /** * Field <code>TYPE_SIZE</code> */ public static final short TYPE_SIZE = 21; public static final short TYPE_GUID = 22; public static final short TYPE_FUNCTION = 23; public static final short TYPE_QUERY_COLUMN=24; /** * Wandelt einen String Datentypen in ein CFML short Typ um. * @param type * @param defaultValue * @return short Data Type */ public static String toString(int type,String defaultValue) { switch(type){ case TYPE_ANY:return "any"; case TYPE_ARRAY:return "array"; case TYPE_BASE64:return "base64"; case TYPE_BINARY:return "binary"; case TYPE_BOOLEAN:return "boolean"; case TYPE_DATETIME:return "datetime"; case TYPE_GUID:return "guid"; case TYPE_NUMERIC:return "numeric"; case TYPE_QUERY:return "query"; case TYPE_QUERY_COLUMN:return "querycolumn"; case TYPE_STRING:return "string"; case TYPE_STRUCT:return "struct"; case TYPE_TIMESPAN:return "timespan"; case TYPE_UNDEFINED:return "any"; case TYPE_UNKNOW:return "any"; case TYPE_UUID:return "uuid"; case TYPE_VARIABLE_NAME:return "variablename"; case TYPE_VARIABLE_STRING:return "variablestring"; case TYPE_VOID:return "void"; case TYPE_XML:return "xml"; case TYPE_FUNCTION:return "function"; } return defaultValue; } public static short toShortStrict(String type, short defaultValue) { type=type.toLowerCase().trim(); if(type.length()>2) { char first=type.charAt(0); switch(first) { case 'a': if(type.equals("any")) return TYPE_ANY; if(type.equals("array")) return TYPE_ARRAY; break; case 'b': if(type.equals("boolean") || type.equals("bool")) return TYPE_BOOLEAN; if(type.equals("binary")) return TYPE_BINARY; break; case 'd': if(type.equals("date") || type.equals("datetime")) return TYPE_DATETIME; case 'f': if(type.equals("function")) return TYPE_FUNCTION; break; case 'g': if("guid".equals(type)) return TYPE_GUID; break; case 'n': if(type.equals("numeric")) return TYPE_NUMERIC; else if(type.equals("number")) return TYPE_NUMERIC; break; case 'o': if(type.equals("object")) return TYPE_ANY; break; case 'q': if(type.equals("query")) return TYPE_QUERY; if(type.equals("querycolumn")) return TYPE_QUERY_COLUMN; break; case 's': if(type.equals("string")) return TYPE_STRING; else if(type.equals("struct")) return TYPE_STRUCT; break; case 't': if(type.equals("timespan")) return TYPE_TIMESPAN; if(type.equals("time")) return TYPE_DATETIME; if(type.equals("timestamp")) return TYPE_DATETIME; break; case 'u': if(type.equals("uuid")) return TYPE_UUID; break; case 'v': if(type.equals("variablename")) return TYPE_VARIABLE_NAME; if(type.equals("variable_name")) return TYPE_VARIABLE_NAME; if(type.equals("variablestring")) return TYPE_VARIABLE_STRING; if(type.equals("variable_string")) return TYPE_VARIABLE_STRING; if(type.equals("void")) return TYPE_VOID; break; case 'x': if(type.equals("xml")) return TYPE_XML; break; } } return defaultValue; } public static short toShort(String type, boolean alsoAlias, short defaultValue) { type=type.toLowerCase().trim(); if(type.length()>2) { char first=type.charAt(0); switch(first) { case 'a': if(type.equals("any")) return TYPE_ANY; if(type.equals("array")) return TYPE_ARRAY; break; case 'b': if(type.equals("boolean") || (alsoAlias && type.equals("bool"))) return TYPE_BOOLEAN; if(type.equals("binary")) return TYPE_BINARY; if(alsoAlias && type.equals("bigint")) return TYPE_NUMERIC; if("base64".equals(type))return TYPE_STRING; break; case 'c': if(alsoAlias && "char".equals(type))return TYPE_STRING; break; case 'd': if(alsoAlias && "double".equals(type)) return TYPE_NUMERIC; if(alsoAlias && "decimal".equals(type)) return TYPE_STRING; if(type.equals("date") || type.equals("datetime")) return TYPE_DATETIME; break; case 'e': if("eurodate".equals(type)) return TYPE_DATETIME; break; case 'f': if(alsoAlias && "float".equals(type)) return TYPE_NUMERIC; if("function".equals(type)) return TYPE_FUNCTION; break; case 'g': if("guid".equals(type)) return TYPE_GUID; break; case 'i': if(alsoAlias && ("int".equals(type) || "integer".equals(type))) return TYPE_NUMERIC; break; case 'l': if(alsoAlias && "long".equals(type)) return TYPE_NUMERIC; break; case 'n': if(type.equals("numeric")) return TYPE_NUMERIC; else if(type.equals("number")) return TYPE_NUMERIC; if(alsoAlias) { if(type.equals("node")) return TYPE_XML; else if(type.equals("nvarchar")) return TYPE_STRING; else if(type.equals("nchar")) return TYPE_STRING; } break; case 'o': if(type.equals("object")) return TYPE_ANY; if(alsoAlias && type.equals("other")) return TYPE_ANY; break; case 'q': if(type.equals("query")) return TYPE_QUERY; if(type.equals("querycolumn")) return TYPE_QUERY_COLUMN; break; case 's': if(type.equals("string")) return TYPE_STRING; else if(type.equals("struct")) return TYPE_STRUCT; if(alsoAlias && "short".equals(type))return TYPE_NUMERIC; break; case 't': if(type.equals("timespan")) return TYPE_TIMESPAN; if(type.equals("time")) return TYPE_DATETIME; if(alsoAlias && type.equals("timestamp")) return TYPE_DATETIME; if(alsoAlias && type.equals("text")) return TYPE_STRING; break; case 'u': if(type.equals("uuid")) return TYPE_UUID; if(alsoAlias && "usdate".equals(type))return TYPE_DATETIME; if(alsoAlias && "udf".equals(type))return TYPE_FUNCTION; break; case 'v': if(type.equals("variablename")) return TYPE_VARIABLE_NAME; if(alsoAlias && type.equals("variable_name")) return TYPE_VARIABLE_NAME; if(type.equals("variablestring")) return TYPE_VARIABLE_STRING; if(alsoAlias && type.equals("variable_string")) return TYPE_VARIABLE_STRING; if(type.equals("void")) return TYPE_VOID; if(alsoAlias && type.equals("varchar")) return TYPE_STRING; break; case 'x': if(type.equals("xml")) return TYPE_XML; break; } } return defaultValue; } public static boolean isSimpleType(short type) { return type==TYPE_BOOLEAN || type==TYPE_DATETIME || type==TYPE_NUMERIC || type==TYPE_STRING; } }
package io.subutai.core.environment.impl.adapter; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.commons.lang3.StringUtils; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.Sets; import io.subutai.common.command.CommandException; import io.subutai.common.command.CommandResult; import io.subutai.common.command.Request; import io.subutai.common.command.RequestBuilder; import io.subutai.common.host.ContainerHostInfoModel; import io.subutai.common.host.ContainerHostState; import io.subutai.common.host.HostArchitecture; import io.subutai.common.host.HostInterfaceModel; import io.subutai.common.host.HostInterfaces; import io.subutai.common.host.Quota; import io.subutai.common.peer.Host; import io.subutai.common.peer.PeerException; import io.subutai.common.security.SshKeys; import io.subutai.common.settings.Common; import io.subutai.core.environment.impl.EnvironmentManagerImpl; import io.subutai.core.environment.impl.entity.EnvironmentContainerImpl; import io.subutai.hub.share.quota.ContainerQuota; import io.subutai.hub.share.quota.ContainerSize; class ProxyEnvironmentContainer extends EnvironmentContainerImpl { private static final Logger LOG = LoggerFactory.getLogger( ProxyEnvironmentContainer.class ); private static final RequestBuilder WHOAMI = new RequestBuilder( "whoami" ); private Host proxyContainer; private final boolean local; ProxyEnvironmentContainer( JsonNode json, EnvironmentManagerImpl environmentManager, Set<String> localContainerIds ) { super( Common.HUB_ID, json.get( "peerId" ).asText(), new ContainerHostInfoModel( json.get( "id" ).asText(), json.get( "hostName" ).asText(), json.get( "name" ).asText(), initHostInterfaces( json ), HostArchitecture.AMD64, ContainerHostState.RUNNING ), json.get( "templateId" ).asText(), json.get( "domainName" ).asText(), new ContainerQuota( parseSize( json ) ), json.get( "hostId" ).asText() ); local = localContainerIds.contains( getId() ); setEnvironmentManager( environmentManager ); } @Override public boolean isLocal() { return local; } @Override public boolean isConnected() { return isLocal() ? super.isConnected() : isRemoteContainerConnected(); } private boolean isRemoteContainerConnected() { try { CommandResult result = execute( WHOAMI ); return result.hasSucceeded() && StringUtils.isNotBlank( result.getStdOut() ) && result.getStdOut() .contains( "root" ); } catch ( CommandException e ) { LOG.error( "Error to check if remote container is connected: ", e ); return false; } } private static ContainerSize parseSize( JsonNode json ) { String size = json.get( "type" ).asText(); return ContainerSize.valueOf( size ); } private static HostInterfaces initHostInterfaces( JsonNode json ) { String ip = json.get( "ipAddress" ).asText(); String id = json.get( "id" ).asText(); HostInterfaceModel him = new HostInterfaceModel( Common.DEFAULT_CONTAINER_INTERFACE, ip ); Set<HostInterfaceModel> set = Sets.newHashSet(); set.add( him ); return new HostInterfaces( id, set ); } void setProxyContainer( Host proxyContainer ) { this.proxyContainer = proxyContainer; LOG.debug( "Set proxy: container={}, proxy={}", getId(), proxyContainer == null ? "no proxy" : proxyContainer.getId() ); } @Override public CommandResult execute( RequestBuilder requestBuilder ) throws CommandException { Host host = this; // If this is a remote host then the command is sent via a proxyContainer // b/c the remote host is not directly accessible from the current peer. if ( !isLocal() ) { if ( proxyContainer != null ) { requestBuilder = wrapForProxy( requestBuilder ); host = proxyContainer; } else { throw new CommandException( "Please start at least one local container from this environment to be able to execute " + "commands on remote ones" ); } } return host.getPeer().execute( requestBuilder, host ); } private RequestBuilder wrapForProxy( RequestBuilder requestBuilder ) { String proxyIp = proxyContainer.getHostInterfaces().getAll().iterator().next().getIp(); String targetHostIp = getHostInterfaces().getAll().iterator().next().getIp(); if ( targetHostIp.contains( "/" ) ) { targetHostIp = StringUtils.substringBefore( targetHostIp, "/" ); } Request req = requestBuilder.build( "id" ); String command = String.format( "ssh root@%s %s", targetHostIp, req.getCommand().replace( "\\", "\\\\" ) ); LOG.debug( "Command wrapped '{}' to send via {}", command, proxyIp ); return new RequestBuilder( command ).withTimeout( requestBuilder.getTimeout() ); } @Override public ContainerHostState getState() { if ( isLocal() ) { return super.getState(); } else { //TODO for remote containers obtain from Hub metadata return ContainerHostState.UNKNOWN; } } @Override public Quota getRawQuota() { if ( isLocal() ) { return super.getRawQuota(); } else { //TODO for remote containers obtain from Hub metadata return null; } } @Override public SshKeys getAuthorizedKeys() throws PeerException { if ( isLocal() ) { return super.getAuthorizedKeys(); } else { //TODO for remote containers obtain from Hub metadata return new SshKeys(); } } @Override public ContainerQuota getQuota() throws PeerException { if ( isLocal() ) { return super.getQuota(); } else { //TODO for remote containers obtain from Hub metadata return null; } } }
package fr.openwide.core.spring.notification.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import fr.openwide.core.spring.util.SpringBeanUtils; public class AbstractNotificationServiceImpl { @Autowired protected ApplicationContext applicationContext; protected final INotificationBuilderBaseState builder() { INotificationBuilderBaseState notificationBuilder = new NotificationBuilder(); SpringBeanUtils.autowireBean(applicationContext, notificationBuilder); return notificationBuilder; } }
package com.gallatinsystems.survey.dao; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.jdo.PersistenceManager; import com.gallatinsystems.framework.dao.BaseDAO; import com.gallatinsystems.framework.servlet.PersistenceFilter; import com.gallatinsystems.survey.domain.Question; import com.gallatinsystems.survey.domain.QuestionGroup; public class QuestionGroupDao extends BaseDAO<QuestionGroup> { public QuestionGroupDao() { super(QuestionGroup.class); } public QuestionGroup save(QuestionGroup item, Long surveyId, Integer order) { item = save(item); return item; } public void delete(QuestionGroup item, Long surveyId) { delete(item); } public QuestionGroup getId(String questionGroupCode) { return findByProperty("code", questionGroupCode, "String"); } public TreeMap<Integer, QuestionGroup> listQuestionGroupsBySurvey( Long surveyId) { List<QuestionGroup> groups = listByProperty("surveyId", surveyId, "Long"); TreeMap<Integer, QuestionGroup> map = new TreeMap<Integer, QuestionGroup>(); if (groups != null) { int i = 1; for (QuestionGroup group : groups) { map.put(group.getOrder() != null ? group.getOrder() : i, group); i++; } } return map; } @SuppressWarnings("unchecked") public QuestionGroup getByPath(String code, String path) { PersistenceManager pm = PersistenceFilter.getManager(); javax.jdo.Query query = pm.newQuery(QuestionGroup.class); query.setFilter(" path == pathParam && code == codeParam"); query.declareParameters("String pathParam, String codeParam"); List<QuestionGroup> results = (List<QuestionGroup>) query.execute(path, code); if (results != null && results.size() > 0) { return results.get(0); } else { return null; } } public void delete(QuestionGroup item) { QuestionDao qDao = new QuestionDao(); for (Map.Entry<Integer, Question> qItem : qDao .listQuestionsByQuestionGroup(item.getKey().getId(), false) .entrySet()) { SurveyTaskUtil.spawnDeleteTask("deleteQuestion", qItem.getValue() .getKey().getId()); } QuestionGroup group = getByKey(item.getKey()); if (group != null) { super.delete(item); } } }
package org.penguin.kayako; import java.util.List; import org.penguin.kayako.ApiRequest.ApiRequestException; import org.penguin.kayako.ApiResponse.ApiResponseException; public class DepartmentConnector { private final KayakoClient client; public DepartmentConnector(KayakoClient client) { this.client = client; } public Department get(int id) throws ApiResponseException, ApiRequestException { return new ApiRequest(client) .withPath("Base").withPath("Department") .withPath(String.valueOf(id)) .get().as(DepartmentCollection.class).getDepartments().get(0); } public List<Department> list() throws ApiResponseException, ApiRequestException { return new ApiRequest(client) .withPath("Base").withPath("Department") .get().as(DepartmentCollection.class).getDepartments(); } }
package ie.nuim.cs.dri.interactROS; public class ROSInteract { static { System.loadLibrary("GenerateROS"); } private native long GenerateROS(String filename, String longid); private native int ROSCountNodes(long neoId); private native detailednode[] GetNeo4jGraphNodes(long neoId); private native detailednode[] GetNeo4jGraphNodes(String longid); }
package org.deviceconnect.android.deviceplugin.host.activity.recorder.settings; import android.os.Bundle; import org.deviceconnect.android.deviceplugin.host.R; public class SettingsPortFragment extends SettingsBaseFragment { @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { getPreferenceManager().setSharedPreferencesName(getRecorderId().replaceAll("/", "_")); setPreferencesFromResource(R.xml.settings_host_recorder_port, rootKey); } @Override public void onBindService() { setInputTypeNumber("mjpeg_port"); setInputTypeNumber("rtsp_port"); setInputTypeNumber("srt_port"); } }
package fr.openwide.core.jpa.more.business.task.service; import static fr.openwide.core.jpa.more.property.JpaMoreTaskPropertyIds.START_MODE; import static fr.openwide.core.jpa.more.property.JpaMoreTaskPropertyIds.STOP_TIMEOUT; import static fr.openwide.core.jpa.more.property.JpaMoreTaskPropertyIds.queueNumberOfThreads; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.PreDestroy; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.util.Assert; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Supplier; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import fr.openwide.core.jpa.exception.SecurityServiceException; import fr.openwide.core.jpa.exception.ServiceException; import fr.openwide.core.jpa.more.business.task.model.AbstractTask; import fr.openwide.core.jpa.more.business.task.model.IQueueId; import fr.openwide.core.jpa.more.business.task.model.QueuedTaskHolder; import fr.openwide.core.jpa.more.business.task.service.impl.TaskConsumer; import fr.openwide.core.jpa.more.business.task.service.impl.TaskQueue; import fr.openwide.core.jpa.more.business.task.util.TaskStatus; import fr.openwide.core.jpa.more.config.spring.AbstractTaskManagementConfig; import fr.openwide.core.jpa.more.util.transaction.model.ITransactionSynchronizationAfterCommitTask; import fr.openwide.core.jpa.more.util.transaction.service.ITransactionSynchronizationTaskManagerService; import fr.openwide.core.spring.config.util.TaskQueueStartMode; import fr.openwide.core.spring.property.service.IPropertyService; import fr.openwide.core.spring.util.SpringBeanUtils; public class QueuedTaskHolderManagerImpl implements IQueuedTaskHolderManager, ApplicationListener<ContextRefreshedEvent> { private static final Logger LOGGER = LoggerFactory.getLogger(QueuedTaskHolderManagerImpl.class); @Autowired private ApplicationContext applicationContext; @Autowired private IQueuedTaskHolderService queuedTaskHolderService; @Autowired @Qualifier(AbstractTaskManagementConfig.OBJECT_MAPPER_BEAN_NAME) private ObjectMapper queuedTaskHolderObjectMapper; @Autowired private IPropertyService propertyService; @Autowired private ITransactionSynchronizationTaskManagerService synchronizationManager; @Resource private Collection<? extends IQueueId> queueIds; private int stopTimeout; private final Multimap<TaskQueue, TaskConsumer> consumersByQueue = Multimaps.newListMultimap(new HashMap<TaskQueue, Collection<TaskConsumer>>(), new Supplier<List<TaskConsumer>>() { @Override public List<TaskConsumer> get() { return Lists.newArrayList(); } }); private final Map<String, TaskQueue> queuesById = Maps.newHashMap(); private TaskQueue defaultQueue; private AtomicBoolean active = new AtomicBoolean(false); private AtomicBoolean availableForAction = new AtomicBoolean(true); @Override public void onApplicationEvent(ContextRefreshedEvent event) { /* * onApplicationEvent is called for every context initialization, including potential child contexts. * We avoid starting queues multiple times, by calling init() only on the root application context initialization. */ if (event != null && event.getSource() != null && AbstractApplicationContext.class.isAssignableFrom(event.getSource().getClass()) && ((AbstractApplicationContext) event.getSource()).getParent() == null) { init(); } } private void init() { stopTimeout = propertyService.get(STOP_TIMEOUT); initQueues(); if (TaskQueueStartMode.auto.equals(propertyService.get(START_MODE))) { start(); } else { LOGGER.warn("Task queue start configured in \"manual\" mode."); } } private final void initQueues() { Collection<String> queueIdsAsStrings = Lists.newArrayList(); // Sanity checks for (IQueueId queueId : queueIds) { String queueIdAsString = queueId.getUniqueStringId(); Assert.state(!IQueueId.RESERVED_DEFAULT_QUEUE_ID_STRING.equals(queueIdAsString), "Queue ID '" + IQueueId.RESERVED_DEFAULT_QUEUE_ID_STRING + "' is reserved for implementation purposes. Please choose another ID."); Assert.state(!queueIdsAsStrings.contains(queueIdAsString), "Queue ID '" + queueIdAsString + "' was defined more than once. Queue IDs must be unique."); queueIdsAsStrings.add(queueIdAsString); } defaultQueue = initQueue(IQueueId.RESERVED_DEFAULT_QUEUE_ID_STRING, 1); for (String queueIdAsString : queueIdsAsStrings) { int numberOfThreads = propertyService.get(queueNumberOfThreads(queueIdAsString)); if (numberOfThreads < 1) { LOGGER.warn("Number of threads for queue '{}' is set to an invalid value ({}); defaulting to 1", queueIdAsString, numberOfThreads); numberOfThreads = 1; } initQueue(queueIdAsString, numberOfThreads); } } private TaskQueue initQueue(String queueId, int numberOfThreads) { TaskQueue queue = new TaskQueue(queueId); for (int i = 0 ; i < numberOfThreads ; ++i) { TaskConsumer consumer = new TaskConsumer(queue, i); SpringBeanUtils.autowireBean(applicationContext, consumer); consumersByQueue.put(queue, consumer); } queuesById.put(queueId, queue); return queue; } private String selectQueue(AbstractTask task) { SpringBeanUtils.autowireBean(applicationContext, task); IQueueId queueId = task.selectQueue(); String queueIdString = queueId == null ? null : queueId.getUniqueStringId(); return queueIdString; } private TaskQueue getQueue(String queueId) { if (queueId == null) { return defaultQueue; } TaskQueue queue = queuesById.get(queueId); if (queue == null) { LOGGER.warn("Queue ID '{}' is unknown ; falling back to default queue", queueId); queue = defaultQueue; } return queue; } @Override public boolean isAvailableForAction() { return availableForAction.get(); } @Override public boolean isActive() { return active.get(); } @Override public int getNumberOfWaitingTasks() { int total = 0; for (TaskQueue queue : queuesById.values()) { total += queue.size(); } return total; } @Override public int getNumberOfRunningTasks() { int total = 0; for (TaskQueue queue : queuesById.values()) { Collection<TaskConsumer> consumers = consumersByQueue.get(queue); for (TaskConsumer consumer : consumers) { if (consumer.isWorking()) { total++; } } } return total; } @Override public Collection<IQueueId> getQueueIds() { return Collections.unmodifiableCollection(queueIds); } @Override public void start() { start(0L); } /** * @param startDelay A length of time the consumer threads will wait before their first access to their task queue. */ protected synchronized void start(long startDelay) { if (!active.get()) { availableForAction.set(false); try { initQueuesFromDatabase(); for (TaskConsumer consumer : consumersByQueue.values()) { consumer.start(startDelay); } } finally { active.set(true); availableForAction.set(true); } } } private void initQueuesFromDatabase() { for (TaskQueue queue : queuesById.values()) { try { List<Long> taskIds = queuedTaskHolderService.initializeTasksAndListConsumable(queue.getId()); if (queue == defaultQueue) { taskIds.addAll(queuedTaskHolderService.initializeTasksAndListConsumable(null)); } for (Long taskId : taskIds) { boolean status = queue.offer(taskId); if (!status) { LOGGER.error("Unable to offer the task " + taskId + " to the queue"); } } } catch (RuntimeException | ServiceException | SecurityServiceException e) { LOGGER.error("Error while trying to init queue " + queue + " from database", e); } } } @Override public final QueuedTaskHolder submit(AbstractTask task) throws ServiceException { QueuedTaskHolder newQueuedTaskHolder = null; final String selectedQueueId; try { String serializedTask; selectedQueueId = selectQueue(task); serializedTask = queuedTaskHolderObjectMapper.writeValueAsString(task); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Serialized task: " + serializedTask); } newQueuedTaskHolder = new QueuedTaskHolder( task.getTaskName(), selectedQueueId /* May differ from selectedQueue.getId() */, task.getTaskType(), serializedTask ); queuedTaskHolderService.create(newQueuedTaskHolder); } catch (IOException e) { throw new ServiceException("Error while trying to serialize task " + task, e); } catch (RuntimeException | ServiceException | SecurityServiceException e) { throw new ServiceException("Error while creating and saving task " + task, e); } final Long newQueuedTaskHolderId = newQueuedTaskHolder.getId(); synchronizationManager.push(new ITransactionSynchronizationAfterCommitTask() { @Override public void run() throws Exception { doSubmit(selectedQueueId, newQueuedTaskHolderId); } }); return newQueuedTaskHolder; } protected void doSubmit(String queueId, Long newQueuedTaskHolderId) throws ServiceException { if (active.get()) { TaskQueue selectedQueue = getQueue(queueId); boolean status = selectedQueue.offer(newQueuedTaskHolderId); if (!status) { LOGGER.error("Unable to offer the task " + newQueuedTaskHolderId + " to the queue"); } } } @Override public void reload(Long queuedTaskHolderId) throws ServiceException, SecurityServiceException { QueuedTaskHolder queuedTaskHolder = queuedTaskHolderService.getById(queuedTaskHolderId); if (queuedTaskHolder != null) { queuedTaskHolder.setStatus(TaskStatus.TO_RUN); queuedTaskHolder.resetExecutionInformation(); queuedTaskHolderService.update(queuedTaskHolder); TaskQueue queue = getQueue(queuedTaskHolder.getQueueId()); if (active.get()) { boolean status = queue.offer(queuedTaskHolder.getId()); if (!status) { LOGGER.error("Unable to offer the task " + queuedTaskHolder.getId() + " to the queue"); } } } } @Override public void cancel(Long queuedTaskHolderId) throws ServiceException, SecurityServiceException { QueuedTaskHolder queuedTaskHolder = queuedTaskHolderService.getById(queuedTaskHolderId); if (queuedTaskHolder != null) { queuedTaskHolder.setStatus(TaskStatus.CANCELLED); queuedTaskHolderService.update(queuedTaskHolder); } } /** * Warning: this destroy method is called twice, so all the related code has * to be written with this constraint * * @throws Exception */ @PreDestroy private void destroy() { stop(); } @Override public synchronized void stop() { if (active.get()) { availableForAction.set(false); try { for (TaskQueue queue : queuesById.values()) { for (TaskConsumer consumer : consumersByQueue.get(queue)) { try { consumer.stop(stopTimeout); } catch (RuntimeException e) { LOGGER.error("Error while trying to stop consumer " + consumer, e); } } interruptQueueProcesses(queue); } } finally { active.set(false); availableForAction.set(true); } } } private void interruptQueueProcesses(TaskQueue queue) { List<Long> queuedTaskHolderIds = new LinkedList<Long>(); queue.drainTo(queuedTaskHolderIds); for (Long queuedTaskHolderId : queuedTaskHolderIds) { QueuedTaskHolder queuedTaskHolder = queuedTaskHolderService.getById(queuedTaskHolderId); if (queuedTaskHolder != null) { try { queuedTaskHolder.setStatus(TaskStatus.INTERRUPTED); queuedTaskHolder.setEndDate(new Date()); queuedTaskHolder.resetExecutionInformation(); queuedTaskHolderService.update(queuedTaskHolder); } catch (RuntimeException | ServiceException | SecurityServiceException e) { throw new RuntimeException(e); } } } } }
package org.geomajas.widget.searchandfilter.client.widget.search; import org.geomajas.annotation.Api; import org.geomajas.gwt.client.map.layer.VectorLayer; import org.geomajas.gwt.client.widget.MapWidget; import org.geomajas.widget.searchandfilter.client.widget.geometricsearch.GeometryUpdateHandler; import org.geomajas.widget.searchandfilter.search.dto.Criterion; import com.smartgwt.client.widgets.Canvas; /** * @see SearchWidgetRegistry * @author Kristof Heirwegh * @since 1.0.0 */ @Api(allMethods = true) public abstract class AbstractSearchPanel extends Canvas { protected MapWidget mapWidget; protected GeometryUpdateHandler handler; private boolean canAddToFavourites = true; private boolean canFilterLayer; private boolean canReset = true; private boolean canCancel = true; /** * Constructor. * * @param mapWidget map widget */ public AbstractSearchPanel(MapWidget mapWidget) { super(); if (mapWidget == null) { throw new IllegalArgumentException("Please provide a mapWidget."); } this.mapWidget = mapWidget; } /** * Called before getFeatureSearchCriterion(). * <p> * Search will be cancelled if you return false. * * @return true if a criterion can be returned. */ public abstract boolean validate(); /** * Should the "Add To Favourites" button be shown? * * @return true when "add to favourites" button is visible */ public boolean canAddToFavourites() { return canAddToFavourites; } /** * Indicate whether add to favourites is possible or not. * * @param canAddToFavourites * new value */ public void setCanAddToFavourites(boolean canAddToFavourites) { this.canAddToFavourites = canAddToFavourites; } /** * Should the "Filter layer" button be shown? * * @return true when "Filter layer" button is visible */ public boolean canFilterLayer() { return canFilterLayer; } /** * Indicate whether filter layer is possible or not. * * @param canFilterLayer * new value */ public void setCanFilterLayer(boolean canFilterLayer) { this.canFilterLayer = canFilterLayer; } /** * Should the "Reset" button be shown? * * @return true when reset button is visible */ public boolean canReset() { return canReset; } /** * Set whether the reset button can exist. * * @param canReset * new value */ public void setCanReset(boolean canReset) { this.canReset = canReset; } /** * Should the "Cancel" button be shown? * * @return true when cancel button is visible */ public boolean canCancel() { return canCancel; } /** * Set whether the cancel button can exist. * * @param canCancel * new value */ public void setCanCancel(boolean canCancel) { this.canCancel = canCancel; } /** * @return an object with the settings of your search, allowing the specifics of the search to be stored (in * favourites). */ public abstract Criterion getFeatureSearchCriterion(); /** * Get the vector layer which is to be searched. * * @return the vector layer to search in. */ public abstract VectorLayer getFeatureSearchVectorLayer(); /** {@inheritDoc} */ public abstract void reset(); /** * Called to restore the settings previously requested through getSettings(). * * @param featureSearch settings */ public abstract void initialize(Criterion featureSearch); /** * Get the map widget to which this search panel applies. * * @return map widget */ public MapWidget getMapWidget() { return mapWidget; } }
package prg2.connectfour.ui; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.awt.GridLayout; import javax.swing.JPanel; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.JOptionPane; import javax.swing.DefaultListModel; import javax.swing.ListSelectionModel; import prg2.connectfour.comlayer.BasePlayer; import prg2.connectfour.comlayer.InvitationMsg; import prg2.connectfour.comlayer.InvitationResponseMsg; import prg2.connectfour.comlayer.NetworkEnv; import prg2.connectfour.comlayer.NetworkEnv.*; /** * SearchPlayerScreen displays a list of players to choose * from. A player can be selected to send an invitation * request. * * @author David Craven <david@craven.ch> */ public class SearchPlayerScreen extends JPanel implements PlayerHandler, InvitationHandler, InvitationResponseHandler{ private NetworkEnv networkEnv; private HashMap<String, BasePlayer> invitationTokens = new HashMap<>(); private ArrayList<StartGameHandler> startGameListeners = new ArrayList<>(); private JList<String> playerList; private JScrollPane playerPane; private DefaultListModel<String> playerListModel; /** * The constructor initializes the UI and registers event listeners * for the network interface. After initialization the constructor * starts a search for possible opponents. */ public SearchPlayerScreen(NetworkEnv env) { this.setLayout(new GridLayout(1, 3)); this.networkEnv = env; // init all ui components here this.playerListModel = new DefaultListModel<>(); this.playerListModel.addElement("player 1"); this.playerListModel.addElement("player 2"); this.playerListModel.addElement("player 3"); this.playerListModel.addElement("player 4"); this.playerList = new JList<>(this.playerListModel); this.playerList.setLayoutOrientation(JList.VERTICAL); this.playerList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); this.add(playerList); this.playerPane = new JScrollPane(this.playerList); this.add(this.playerPane); // register listeners on network env this.networkEnv.addNewPlayerListener(this); this.networkEnv.addInvitationListener(this); this.networkEnv.addInvitationResponseListener(this); startSearch(); } /** * Event handler for the newPlayerDetected event. It adds the * player to the invitationTokens HashMap and inserts a new * player into the UI. */ @Override public void newPlayerDetected(BasePlayer newPlayer) { // TODO // this.invitationTokens.put(newPlayer.getInvitationToken(), newPlayer); this.playerListModel.addElement(newPlayer.getName()); } /** * Event handler for the invitationReceived event. It provides * message dialog to accept or reject an invitation and sends * an invitation response. An invitation response is also sent * when rejected. */ @Override public void invitationReceived(InvitationMsg msg) { String str = "Do you want to accept an invitation from " + msg.getName() + " to play connect four?"; int result = JOptionPane.showConfirmDialog(null, str, "Invitation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (this.invitationTokens.containsKey(msg.getInvitationToken())) { BasePlayer opponent = this.invitationTokens.get(msg.getInvitationToken()); this.networkEnv.sendInvitationResponse(opponent, result == 0 ? true : false); } } /** * Event handler for the invitationResponseReceived event. It starts * a new game. */ @Override public void invitationResponseReceived(InvitationResponseMsg msg) { if(this.invitationTokens.containsKey(msg.getInvitationToken())) { BasePlayer opponent = this.invitationTokens.get(msg.getInvitationToken()); this.onStartGame(msg.getInvitationToken(), opponent); } } private void startSearch() { this.networkEnv.broadcastHelloMsg(); } private void invitePlayer(BasePlayer player) { String newToken = this.networkEnv.sendInvitation(player, 7, 5); //TODO: ask for playground size invitationTokens.put(newToken, player); } private void onStartGame(String gameToken, BasePlayer player) { for(StartGameHandler listener : this.startGameListeners) listener.startGame(gameToken, player, true, 7, 7); } public void addStartGameListener(StartGameHandler listener) { startGameListeners.add(listener); } public interface StartGameHandler { void startGame(String gameToken, BasePlayer player, boolean isStartSend, int x, int y); } }
package com.npaduch.reminder; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.JsonReader; import android.util.JsonWriter; import android.util.Log; import android.widget.Toast; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Calendar; import java.util.Random; public class Reminder { // initialize values public static final String STRING_INIT = "STRING_INVALID"; public static final int INT_INIT = -1; private String description; // timing private double year; private double month; private double monthDay; private double hour; private double minute; private long msTime; private String dateString; private String timeString; private String dateTimeString; private int dateOffset; private int timeOffset; private boolean completed; // output file public final static String filename = "reminders.json"; // JSON tags private final static String JSON_DESCRIPTION = "description"; private final static String JSON_DATETIME = "datetime"; private final static String JSON_COMPLETED = "completed"; private final static String JSON_REMINDER_ID = "reminder_id"; private final static String JSON_TIME_MS = "time_ms"; private int reminderID; public final static String INTENT_REMINDER_ID = "intent_reminder_id"; // reminder ID should be greater than 0 public static final int BAD_REMINDER_ID = -1; // logging private final static String TAG = "RaminderClass"; // time definitions public static final int TIME_MORNING_HOUR = 9; public static final int TIME_MORNING_MINUTE = 0; public static final int TIME_NOON_HOUR = 12; public static final int TIME_NOON_MINUTE = 0; public static final int TIME_AFTERNOON_HOUR = 3; public static final int TIME_AFTERNOON_MINUTE = 0; public static final int TIME_EVENING_HOUR = 6; public static final int TIME_EVENING_MINUTE = 0; public static final int TIME_NIGHT_HOUR = 8; public static final int TIME_NIGHT_MINUTE = 0; // Called when reminder created for the first time public Reminder() { setDescription(STRING_INIT); setDateString(STRING_INIT); setTimeString(STRING_INIT); setDateTimeString(STRING_INIT); setYear(INT_INIT); setMonth(INT_INIT); setMonthDay(INT_INIT); setHour(INT_INIT); setMinute(INT_INIT); setCompleted(false); // random value greater than 0 // TODO: make sure reminder ID not already in use setReminderID(new Random().nextInt(Integer.MAX_VALUE)); } // Called when read from file public Reminder(String description, String dateTimeString, boolean completed, int reminderID, long msTime){ this.description = description; this.dateTimeString = dateTimeString; this.completed = completed; this.reminderID = reminderID; this.msTime = msTime; setYear(INT_INIT); setMonth(INT_INIT); setMonthDay(INT_INIT); setHour(INT_INIT); setMinute(INT_INIT); setCompleted(false); } public int getDateOffset() { return dateOffset; } public void setDateOffset(int dateOffset) { this.dateOffset = dateOffset; } public int getTimeOffset() { return timeOffset; } public void setTimeOffset(int timeOffset) { this.timeOffset = timeOffset; } public String getDateString() { return dateString; } public void setDateString(String dayString) { this.dateString = dayString; } public String getTimeString() { return timeString; } public void setTimeString(String timeString) { this.timeString = timeString; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getDateTimeString() { return dateTimeString; } public void setDateTimeString(String dateTimeString) { this.dateTimeString = dateTimeString; } public boolean isCompleted() { return completed; } public void setCompleted(boolean completed) { this.completed = completed; } public double getYear() { return year; } public void setYear(double year) { this.year = year; } public double getMonth() { return month; } public void setMonth(double month) { this.month = month; } public double getHour() { return hour; } public void setHour(double hour) { this.hour = hour; } public double getMonthDay() { return monthDay; } public void setMonthDay(double monthDay) { this.monthDay = monthDay; } public double getMinute() { return minute; } public void setMinute(double minute) { this.minute = minute; } public int getReminderID() { return reminderID; } public void setReminderID(int reminderID) { this.reminderID = reminderID; } public long getMsTime() { return msTime; } public void setMsTime(long msTime) { this.msTime = msTime; } public void calculateMsTime(int year, int month, int day, int hour, int minute){ // This initializes the class with the time RIGHT NOW Calendar reminderCal = Calendar.getInstance(); // handle day if(getDateOffset() == NewReminderFragment.DATE_TODAY){ // we don't have to change anything Log.d(TAG,"Date is today"); } else if(getDateOffset() == NewReminderFragment.DATE_TOMORROW) { // add time for 1 day // this will increment across months/years accordingly reminderCal.add(Calendar.DAY_OF_MONTH, 1); } else { // Custom date was given reminderCal.set(year, month, day); } // handle time // TODO: Make these settings switch(getTimeOffset()){ case NewReminderFragment.TIME_MORNING: reminderCal.set(Calendar.HOUR_OF_DAY, TIME_MORNING_HOUR); reminderCal.set(Calendar.MINUTE, TIME_MORNING_MINUTE); break; case NewReminderFragment.TIME_NOON: reminderCal.set(Calendar.HOUR_OF_DAY, TIME_NOON_HOUR); reminderCal.set(Calendar.MINUTE, TIME_NOON_MINUTE); break; case NewReminderFragment.TIME_AFTERNOON: reminderCal.set(Calendar.HOUR_OF_DAY, TIME_AFTERNOON_HOUR); reminderCal.set(Calendar.MINUTE, TIME_AFTERNOON_MINUTE); break; case NewReminderFragment.TIME_EVENING: reminderCal.set(Calendar.HOUR_OF_DAY, TIME_EVENING_HOUR); reminderCal.set(Calendar.MINUTE, TIME_EVENING_MINUTE); break; case NewReminderFragment.TIME_NIGHT: reminderCal.set(Calendar.HOUR_OF_DAY, TIME_NIGHT_HOUR); reminderCal.set(Calendar.MINUTE, TIME_NIGHT_MINUTE); break; case NewReminderFragment.TIME_OTHER: reminderCal.set(Calendar.HOUR_OF_DAY, hour); reminderCal.set(Calendar.MINUTE, minute); break; } // set values long ms = reminderCal.getTimeInMillis(); setMsTime(ms); } public void setAlarm(Context context){ Log.d(TAG, "Setting alarm for reminder."); // set time for a minute from now Long time = getMsTime(); // create an Intent and set the class which will execute when Alarm triggers Intent intentAlarm = new Intent(context, AlarmReceiver.class); intentAlarm.putExtra(INTENT_REMINDER_ID, getReminderID()); // create the object AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); //set the alarm for particular time alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(context, 1, intentAlarm, 0)); Log.d(TAG, "Alarm scheduled"); } public static void initFile(Context context) { Log.d(TAG, "Initializing file "+context.getFilesDir()+File.pathSeparator+filename); File file = new File(context.getFilesDir(), filename); ArrayList<Reminder> reminders = new ArrayList<Reminder>(); try { // Append to file if it exists FileOutputStream fOutputStream = new FileOutputStream(file, false); writeJsonStream(fOutputStream, reminders); Log.d(TAG, "Output To file successful."); } catch (Exception e) { Log.e(TAG, "Exception when writing to file. "+e); } } public void writeToFile(Context context) { Log.d(TAG, "Adding to file "+context.getFilesDir()+File.pathSeparator+filename); File file = new File(context.getFilesDir(), filename); ArrayList<Reminder> reminderList = null; // 1. Read in JSON file content try { // Open file FileInputStream fileInputStream = new FileInputStream(file); reminderList = readJsonStream(fileInputStream); Log.d(TAG, "File read successful."); } catch (Exception e) { Log.e(TAG, "Exception when writing to file."+e); } if(reminderList == null){ Log.d(TAG, "Reminder list null. Creating a new list."); reminderList = new ArrayList<Reminder>(); } // add new item to the beginning of the list reminderList.add(0, this); try { // Append to file if it exists FileOutputStream fOutputStream = new FileOutputStream(file, false); writeJsonStream(fOutputStream, reminderList); Log.d(TAG, "Output To file successful."); } catch (Exception e) { Log.e(TAG, "Exception when writing to file. "+e); } } /** All required for JSON Parsing **/ public static ArrayList<Reminder> readJsonStream(InputStream in) throws IOException { Log.d(TAG, "Begin readJsonStream"); JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); try { return readRemindersArray(reader); } finally{ reader.close(); } } public static ArrayList<Reminder> readRemindersArray(JsonReader reader) throws IOException { Log.d(TAG,"Begin readReminderArray"); ArrayList<Reminder> reminderList = new ArrayList<Reminder>(); reader.beginArray(); Log.d(TAG,"beginArray"); while (reader.hasNext()) { reminderList.add(readReminder(reader)); } Log.d(TAG,"endArray"); reader.endArray(); return reminderList; } public static Reminder readReminder(JsonReader reader) throws IOException { String description = ""; String dateTimeString = ""; Boolean completed = false; int reminderId = Reminder.BAD_REMINDER_ID; long timeMs = Reminder.INT_INIT; Log.d(TAG, "Begin to read reminder"); reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals(JSON_DESCRIPTION)) { description = reader.nextString(); } else if (name.equals(JSON_DATETIME)) { dateTimeString = reader.nextString(); } else if (name.equals(JSON_COMPLETED)) { completed = reader.nextBoolean(); } else if (name.equals(JSON_REMINDER_ID)) { reminderId = reader.nextInt(); } else if (name.equals(JSON_TIME_MS)) { timeMs = reader.nextLong(); } else { reader.skipValue(); } } reader.endObject(); Reminder r = new Reminder(description, dateTimeString, completed, reminderId, timeMs); r.outputReminderToLog(); Log.d(TAG, "End read reminder"); return r; } /** JSON Writing **/ public static void writeJsonStream(OutputStream out, ArrayList<Reminder> reminders) throws IOException { JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8")); writer.setIndent(" "); writeMessagesArray(writer, reminders); writer.close(); } public static void writeMessagesArray(JsonWriter writer, ArrayList<Reminder> reminders) throws IOException { writer.beginArray(); for (Reminder r : reminders){ writeMessage(writer, r); } writer.endArray(); } public static void writeMessage(JsonWriter writer, Reminder reminder) throws IOException { writer.beginObject(); writer.name(JSON_DESCRIPTION).value(reminder.getDescription()); writer.name(JSON_DATETIME).value(reminder.getDateTimeString()); writer.name(JSON_COMPLETED).value(reminder.isCompleted()); writer.name(JSON_REMINDER_ID).value(reminder.getReminderID()); writer.name(JSON_TIME_MS).value(reminder.getMsTime()); writer.endObject(); } public void outputReminderToLog(){ Log.d(TAG,"Reminder: START"); Log.d(TAG,"Reminder: Description: "+getDescription()); Log.d(TAG,"Reminder: Date/Time: "+getDateTimeString()); Log.d(TAG,"Reminder: Completed: "+isCompleted()); Log.d(TAG,"Reminder: ID: "+getReminderID()); Log.d(TAG,"Reminder: Time (ms): "+getMsTime()); Log.d(TAG,"Reminder: END"); } }
package io.getlime.security.powerauth.lib.webauth.authentication.sms.controller; import io.getlime.core.rest.model.base.response.ObjectResponse; import io.getlime.security.powerauth.lib.bankadapter.client.BankAdapterClient; import io.getlime.security.powerauth.lib.bankadapter.client.BankAdapterClientErrorException; import io.getlime.security.powerauth.lib.bankadapter.model.response.CreateSMSAuthorizationResponse; import io.getlime.security.powerauth.lib.nextstep.client.NextStepServiceException; import io.getlime.security.powerauth.lib.nextstep.model.entity.AuthStep; import io.getlime.security.powerauth.lib.nextstep.model.enumeration.AuthMethod; import io.getlime.security.powerauth.lib.nextstep.model.enumeration.AuthResult; import io.getlime.security.powerauth.lib.nextstep.model.enumeration.AuthStepResult; import io.getlime.security.powerauth.lib.nextstep.model.enumeration.OperationCancelReason; import io.getlime.security.powerauth.lib.nextstep.model.response.GetOperationDetailResponse; import io.getlime.security.powerauth.lib.nextstep.model.response.UpdateOperationResponse; import io.getlime.security.powerauth.lib.webauth.authentication.controller.AuthMethodController; import io.getlime.security.powerauth.lib.webauth.authentication.exception.AuthStepException; import io.getlime.security.powerauth.lib.webauth.authentication.sms.model.request.SMSAuthorizationRequest; import io.getlime.security.powerauth.lib.webauth.authentication.sms.model.response.SMSAuthorizationResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpSession; import java.util.List; /** * This controller provides endpoints for SMS authorization. * * @author Roman Strobl, roman.strobl@lime-company.eu */ @Controller @RequestMapping(value = "/api/auth/sms") public class SMSAuthorizationController extends AuthMethodController<SMSAuthorizationRequest, SMSAuthorizationResponse, AuthStepException> { @Autowired private BankAdapterClient bankAdapterClient; @Autowired private HttpSession httpSession; /** * Verifies the authorization code entered by user against code generated during initialization. * * @param request Request with authentication object information. * @return User ID. * @throws AuthStepException Exception is thrown when authorization fails. */ @Override protected String authenticate(SMSAuthorizationRequest request) throws AuthStepException { final GetOperationDetailResponse operation = getOperation(); final Object messageId = httpSession.getAttribute("messageId"); if (messageId == null) { // verify called before create or other error occurred, request is rejected throw new AuthStepException("error.invalidRequest", new NullPointerException()); } try { bankAdapterClient.verifyAuthorizationSMS(messageId.toString(), request.getAuthCode()); httpSession.removeAttribute("messageId"); return operation.getUserId(); } catch (BankAdapterClientErrorException e) { // log failed authorization into operation history so that maximum number of Next Step update calls can be checked try { UpdateOperationResponse response = failAuthorization(getOperation().getOperationId(), operation.getUserId(), null); if (response.getResult() == AuthResult.FAILED) { // FAILED result instead of CONTINUE means the authentication method is failed throw new AuthStepException("authentication.maxAttemptsExceeded", e); } } catch (NextStepServiceException e2) { throw new AuthStepException(e2.getError().getMessage(), e2); } throw new AuthStepException(e.getError().getMessage(), e); } } @Override protected AuthMethod getAuthMethodName() { return AuthMethod.SMS_KEY; } /** * Initializes the SMS authorization process by creating authorization SMS using Bank Adapter. * * @return Authorization response. */ @RequestMapping(value = "/init", method = RequestMethod.POST) public @ResponseBody SMSAuthorizationResponse initSMSAuthorization() { final GetOperationDetailResponse operation = getOperation(); final String userId = operation.getUserId(); SMSAuthorizationResponse initResponse = new SMSAuthorizationResponse(); try { ObjectResponse<CreateSMSAuthorizationResponse> baResponse = bankAdapterClient.createAuthorizationSMS(userId, operation.getOperationName(), operation.getOperationData(), LocaleContextHolder.getLocale().getLanguage()); String messageId = baResponse.getResponseObject().getMessageId(); httpSession.setAttribute("messageId", messageId); initResponse.setResult(AuthStepResult.CONFIRMED); return initResponse; } catch (BankAdapterClientErrorException e) { initResponse.setResult(AuthStepResult.AUTH_FAILED); initResponse.setMessage(e.getMessage()); return initResponse; } } /** * Performs the authorization and resolves the next step. * * @param request Authorization request which includes the authorization code. * @return Authorization response. */ @RequestMapping(value = "/authenticate", method = RequestMethod.POST) public @ResponseBody SMSAuthorizationResponse authenticateHandler(@RequestBody SMSAuthorizationRequest request) { try { return buildAuthorizationResponse(request, new AuthResponseProvider() { @Override public SMSAuthorizationResponse doneAuthentication(String userId) { authenticateCurrentBrowserSession(); final SMSAuthorizationResponse response = new SMSAuthorizationResponse(); response.setResult(AuthStepResult.CONFIRMED); response.setMessage("authentication.success"); return response; } @Override public SMSAuthorizationResponse failedAuthentication(String userId, String failedReason) { clearCurrentBrowserSession(); final SMSAuthorizationResponse response = new SMSAuthorizationResponse(); response.setResult(AuthStepResult.AUTH_FAILED); response.setMessage(failedReason); return response; } @Override public SMSAuthorizationResponse continueAuthentication(String operationId, String userId, List<AuthStep> steps) { final SMSAuthorizationResponse response = new SMSAuthorizationResponse(); response.setResult(AuthStepResult.CONFIRMED); response.setMessage("authentication.success"); response.getNext().addAll(steps); return response; } }); } catch (AuthStepException e) { final SMSAuthorizationResponse response = new SMSAuthorizationResponse(); response.setResult(AuthStepResult.AUTH_FAILED); response.setMessage(e.getMessage()); return response; } } /** * Cancels the SMS authorization. * * @return Authorization response. */ @RequestMapping(value = "/cancel", method = RequestMethod.POST) public @ResponseBody SMSAuthorizationResponse cancelAuthentication() { try { httpSession.removeAttribute("messageId"); cancelAuthorization(getOperation().getOperationId(), null, OperationCancelReason.UNKNOWN, null); final SMSAuthorizationResponse cancelResponse = new SMSAuthorizationResponse(); cancelResponse.setResult(AuthStepResult.CANCELED); cancelResponse.setMessage("operation.canceled"); return cancelResponse; } catch (NextStepServiceException e) { final SMSAuthorizationResponse cancelResponse = new SMSAuthorizationResponse(); cancelResponse.setResult(AuthStepResult.AUTH_FAILED); cancelResponse.setMessage(e.getMessage()); return cancelResponse; } } }
package seedu.task.commons.core; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.List; import java.util.logging.Logger; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.store.FileDataStoreFactory; import com.google.api.services.calendar.CalendarScopes; // @@author A0140063X-reused public class GoogleCalendar { public static final String CALENDAR_ID = "primary"; public static final String CONNECTION_FAIL_MESSAGE = "Unable to connect to Google."; private static final Logger logger = LogsCenter.getLogger(LogsCenter.class); private static final String APPLICATION_NAME = "Keep It Tidy"; /** Directory to store user credentials for this application. */ private static final java.io.File DATA_STORE_FILE = new java.io.File( System.getProperty("user.home"), ".credentials/keep-it-tidy"); /** Global instance of the {@link FileDataStoreFactory}. */ private static FileDataStoreFactory dataStoreFactory; /** Global instance of the JSON factory. */ private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); /** Global instance of the HTTP transport. */ private static HttpTransport httpTransport; /** Global instance of the scopes required by this quickstart. * * If modifying these scopes, delete your previously saved credentials * at ~/.credentials/calendar-java-quickstart */ private static final List<String> SCOPES = Arrays.asList(CalendarScopes.CALENDAR); static { try { httpTransport = GoogleNetHttpTransport.newTrustedTransport(); dataStoreFactory = new FileDataStoreFactory(DATA_STORE_FILE); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } } /** * Creates an authorized Credential object. * @return an authorized Credential object. * @throws IOException */ public static Credential authorize() throws IOException { // Load client secrets. InputStream in = GoogleCalendar.class.getResourceAsStream("/client_secret.json"); GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); // Build flow and trigger user authorization request. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( httpTransport, JSON_FACTORY, clientSecrets, SCOPES) .setDataStoreFactory(dataStoreFactory) .setAccessType("offline") .build(); Credential credential = new AuthorizationCodeInstalledApp( flow, new LocalServerReceiver()).authorize("user"); logger.info("Credentials saved to " + DATA_STORE_FILE.getAbsolutePath()); return credential; } /** * Build and return an authorized Calendar client service. * @return an authorized Calendar client service * @throws IOException */ public static com.google.api.services.calendar.Calendar getCalendarService() throws IOException { Credential credential = authorize(); return new com.google.api.services.calendar.Calendar.Builder( httpTransport, JSON_FACTORY, credential) .setApplicationName(APPLICATION_NAME) .build(); } }
package seedu.tasklist.model.task; import java.util.Calendar; import java.util.Date; import org.apache.commons.lang.time.DateUtils; /** * A read-only immutable interface for a Task in the task list. * Implementations should guarantee: details are present and not null, field values are validated. */ public interface ReadOnlyTask { TaskDetails getTaskDetails(); StartTime getStartTime(); EndTime getEndTime(); Priority getPriority(); String getRecurringFrequency(); int getUniqueID(); boolean isFloating(); boolean isOverDue(); boolean isComplete(); boolean isRecurring(); boolean isToday(); boolean isTomorrow(); boolean isEvent(); boolean equals(Task task); *//* /** * The returned TagList is a deep copy of the internal TagList, * changes on the returned list will not affect the person's internal tags. UniqueTagList getTags();*/ /** * Returns true if both have the same state. (interfaces cannot override .equals) */ default boolean isSameStateAs(ReadOnlyTask other) { return other == this // short circuit if same object || (other != null // this is first to avoid NPE below && other.getTaskDetails().equals(this.getTaskDetails()) // state checks here onwards && other.getStartTime().equals(this.getStartTime()) && other.getEndTime().equals(this.getEndTime()) && other.getPriority().equals(this.getPriority()) && (other.isRecurring() == this.isRecurring()) && other.getRecurringFrequency().equals(this.getRecurringFrequency()) && (other.getUniqueID()==this.getUniqueID())); } /** * Formats the person as text, showing all contact details. */ default String getAsText() { final StringBuilder builder = new StringBuilder(); builder.append(getTaskDetails()+ "\n") .append("Starts:\t") .append(getStartTime().toCardString() + "\t") .append("Ends:\t") .append(getEndTime().toCardString()+ "\n") .append("Priority:\t") .append(getPriority()+ "\n"); // getTags().forEach(builder::append); return builder.toString(); } /** * Returns a string representation of this Person's tags */ /* default String tagsString() { final StringBuffer buffer = new StringBuffer(); final String separator = ", "; getTags().forEach(tag -> buffer.append(tag).append(separator)); if (buffer.length() == 0) { return ""; } else { return buffer.substring(0, buffer.length() - separator.length()); } }*/ /** * Updates the dates of a task based on its recurring frequency. */ default Calendar updateRecurringDate(Calendar toUpdate, String frequency, int value) { if (!toUpdate.getTime().equals(new Date(0))) { switch (frequency) { case "daily": toUpdate.add(Calendar.DAY_OF_YEAR, value); break; case "weekly": toUpdate.add(Calendar.WEEK_OF_YEAR, value); break; case "monthly": toUpdate.add(Calendar.MONTH, value); break; case "yearly": toUpdate.add(Calendar.YEAR, value); break; } } return toUpdate; } /** * Checks if the date of the task matches user requested date based on its recurring frequency. */ default boolean recurringMatchesRequestedDate(Calendar task, String frequency, Calendar requested) { if (!task.getTime().equals(new Date(0)) && !requested.getTime().equals(new Date (0)) && (task.getTime().compareTo(requested.getTime()) < 0 || DateUtils.isSameDay(task, requested)) && (frequency.equals("daily") || (frequency.equals("weekly") && task.get(Calendar.DAY_OF_WEEK) == requested.get(Calendar.DAY_OF_WEEK)) || (frequency.equals("monthly") && task.get(Calendar.DAY_OF_MONTH) == requested.get(Calendar.DAY_OF_MONTH)) || (frequency.equals("yearly") && task.get(Calendar.DAY_OF_YEAR) == requested.get(Calendar.DAY_OF_YEAR)))) { return true; } return false; } }
package seedu.todo.controllers; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.joestelmach.natty.DateGroup; import com.joestelmach.natty.Parser; import seedu.todo.commons.exceptions.UnmatchedQuotesException; import seedu.todo.commons.util.DateUtil; import seedu.todo.commons.util.StringUtil; import seedu.todo.controllers.concerns.Renderer; import seedu.todo.controllers.concerns.Tokenizer; import seedu.todo.models.TodoListDB; public class ClearController implements Controller { private static final String NAME = "Clear"; private static final String DESCRIPTION = "Clear all tasks/events or by specify date."; private static final String COMMAND_SYNTAX = "clear"; private static final String MESSAGE_CLEAR_SUCCESS = "A total of %s tasks and events have been deleted!"; private static final String MESSAGE_CLEAR_FAILURE = "Invalid format for clear command. Date entered : %s"; private static CommandDefinition commandDefinition = new CommandDefinition(NAME, DESCRIPTION, COMMAND_SYNTAX); public static CommandDefinition getCommandDefinition() { return commandDefinition; } @Override public float inputConfidence(String input) { return (input.toLowerCase().startsWith(COMMAND_SYNTAX)) ? 1 : 0; } /** * Get the token definitions for use with <code>tokenizer</code>.<br> * This method exists primarily because Java does not support HashMap * literals... * * @return tokenDefinitions */ private static Map<String, String[]> getTokenDefinitions() { Map<String, String[]> tokenDefinitions = new HashMap<String, String[]>(); tokenDefinitions.put("default", new String[] {"clear"}); tokenDefinitions.put("eventType", new String[] { "event", "task" }); tokenDefinitions.put("time", new String[] { "at", "by", "on", "before", "time" }); tokenDefinitions.put("timeFrom", new String[] { "from" }); tokenDefinitions.put("timeTo", new String[] { "to" }); return tokenDefinitions; } @Override public void process(String input) { TodoListDB db = TodoListDB.getInstance(); Map<String, String[]> parsedResult; try { parsedResult = Tokenizer.tokenize(getTokenDefinitions(), input); } catch (UnmatchedQuotesException e) { System.out.println("Unmatched quote!"); return ; } String[] parsedDates = parseDates(parsedResult); //no dates provided if (parsedDates == null) { destroyAll(db); return; } String naturalOn = parsedDates[0]; String naturalFrom = parsedDates[1]; String naturalTo = parsedDates[2]; // if all are null = no date provided // Parse natural date using Natty. LocalDateTime dateOn = naturalOn == null ? null : parseNatural(naturalOn); LocalDateTime dateFrom = naturalFrom == null ? null : parseNatural(naturalFrom); LocalDateTime dateTo = naturalTo == null ? null : parseNatural(naturalTo); destroyByDate(db, naturalOn, naturalFrom, naturalTo, dateOn, dateFrom, dateTo); } private void destroyByDate(TodoListDB db, String naturalOn, String naturalFrom, String naturalTo, LocalDateTime dateOn, LocalDateTime dateFrom, LocalDateTime dateTo) { if (dateOn != null) { destroyByDate(db, dateOn); return; } else if (dateFrom != null || dateTo != null) { destroyByRange(db, dateFrom, dateTo); return; } else { //natty deem all dates as invalid displayErrorMessage(db, naturalOn, naturalFrom, naturalTo); } } /** * clear all tasks and events of given date range that exist in the database. * * @param TodoListDB, dateFrom, dateTo */ private void destroyByRange(TodoListDB db, LocalDateTime dateFrom, LocalDateTime dateTo) { int totalCalendarItems = db.getEventByRange(dateFrom, dateTo).size() + db.getTaskByRange(dateFrom, dateTo).size(); db.destroyAllEventByRange(dateFrom, dateTo); db.destroyAllTaskByRange(dateFrom, dateTo); Renderer.renderIndex(db, String.format(MESSAGE_CLEAR_SUCCESS, totalCalendarItems)); } /** * display error message due to failure in parsing given date * * @param TodoListDB, naturalOn, nautralFrom, naturalTo */ private void displayErrorMessage(TodoListDB db, String naturalOn, String naturalFrom, String naturalTo) { String errorMessage; if (naturalOn == null) { errorMessage = String.format(MESSAGE_CLEAR_FAILURE, naturalOn); } else if (naturalFrom == null) { errorMessage = String.format(MESSAGE_CLEAR_FAILURE, naturalFrom); } else { errorMessage = String.format(MESSAGE_CLEAR_FAILURE, naturalTo); } Renderer.renderIndex(db, errorMessage); } /** * clear all tasks and events of the date that exist in the database. * * @param TodoListDB, givenDate */ private void destroyByDate(TodoListDB db, LocalDateTime givenDate) { int totalCalendarItems = db.getEventByDate(givenDate).size() + db.getTaskByDate(givenDate).size(); db.destroyAllEventByDate(givenDate); db.destroyAllTaskByDate(givenDate); Renderer.renderIndex(db, String.format(MESSAGE_CLEAR_SUCCESS, totalCalendarItems)); } /** * clear all tasks and events that exist in the database. * * @param TodoListDB */ private void destroyAll(TodoListDB db) { int totalCalendarItems = db.getAllEvents().size() + db.getAllTasks().size(); db.destroyAllEvent(); db.destroyAllTask(); Renderer.renderIndex(db, String.format(MESSAGE_CLEAR_SUCCESS, totalCalendarItems)); } /** * Parse a natural date into a LocalDateTime object. * * @param natural * @return LocalDateTime object */ private LocalDateTime parseNatural(String natural) { Parser parser = new Parser(); List<DateGroup> groups = parser.parse(natural); Date date = null; try { date = groups.get(0).getDates().get(0); } catch (IndexOutOfBoundsException e) { System.out.println("Error!"); // TODO return null; } LocalDateTime ldt = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); return DateUtil.floorDate(ldt); } /** * Extracts the natural dates from parsedResult. * * @param parsedResult * @return { naturalOn, naturalFrom, naturalTo } or null if no date provided */ private String[] parseDates(Map<String, String[]> parsedResult) { String naturalFrom = null; String naturalTo = null; String naturalOn = null; if (parsedResult.get("time") == null) { if (parsedResult.get("timeFrom") != null) { naturalFrom = parsedResult.get("timeFrom")[1]; } if (parsedResult.get("timeTo") != null) { naturalTo = parsedResult.get("timeTo")[1]; } } else { naturalOn = parsedResult.get("time")[1]; } if (naturalFrom != null || naturalTo != null || naturalOn != null) { return new String[] { naturalOn, naturalFrom, naturalTo }; } else { return null; } } }
package org.xwiki.component.internal; import java.util.Arrays; import java.util.List; import javax.inject.Inject; import org.xwiki.component.event.ComponentDescriptorAddedEvent; import org.xwiki.component.event.ComponentDescriptorRemovedEvent; import org.xwiki.component.internal.multi.AbstractGenericComponentManager; import org.xwiki.component.manager.ComponentLifecycleException; import org.xwiki.component.manager.ComponentManager; import org.xwiki.component.phase.Disposable; import org.xwiki.component.phase.Initializable; import org.xwiki.context.Execution; import org.xwiki.context.ExecutionContext; import org.xwiki.model.reference.EntityReference; import org.xwiki.model.reference.EntityReferenceSerializer; import org.xwiki.observation.AbstractEventListener; import org.xwiki.observation.EventListener; import org.xwiki.observation.ObservationManager; import org.xwiki.observation.event.Event; public abstract class AbstractEntityComponentManager extends AbstractGenericComponentManager implements Initializable, Disposable { private static final List<Event> EVENTS = Arrays.<Event>asList(new ComponentDescriptorAddedEvent(), new ComponentDescriptorRemovedEvent()); private static class EntityComponentManagerInstance { protected final EntityReference entityReference; protected final ComponentManager componentManager; public EntityComponentManagerInstance(EntityReference entityReference, ComponentManager componentManager) { this.entityReference = entityReference; this.componentManager = componentManager; } } @Inject protected ObservationManager observation; @Inject private EntityReferenceSerializer<String> serializer; @Inject private Execution execution; private volatile EventListener listener; private final String contextKey = getClass().getName(); protected abstract EntityReference getCurrentReference(); @Override public void dispose() throws ComponentLifecycleException { if (this.listener != null) { this.observation.removeListener(this.listener.getName()); } } @Override protected ComponentManager getComponentManagerInternal() { // Get current user reference EntityReference entityReference = getCurrentReference(); if (entityReference == null) { return null; } ExecutionContext econtext = this.execution.getContext(); // If there is no context don't try to find or register the component manager if (econtext == null) { return super.getComponentManagerInternal(); } // Try to find the user component manager in the context EntityComponentManagerInstance contextComponentManager = (EntityComponentManagerInstance) econtext.getProperty(this.contextKey); if (contextComponentManager != null && contextComponentManager.entityReference.equals(entityReference)) { return contextComponentManager.componentManager; } // Fallback on regular user component manager search ComponentManager componentManager = super.getComponentManagerInternal(); // Cache the component manager if (this.listener == null) { startListening(); } econtext.setProperty(this.contextKey, new EntityComponentManagerInstance(entityReference, componentManager)); return componentManager; } private synchronized void startListening() { if (this.listener == null) { this.listener = new AbstractEventListener(this.contextKey, EVENTS) { @Override public void onEvent(Event event, Object source, Object data) { // Reset context component manager cache // TODO: improve a bit granularity of the reset ExecutionContext econtext = execution.getContext(); if (econtext != null) { econtext.removeProperty(contextKey); } } }; this.observation.addListener(this.listener); } } @Override protected String getKey() { EntityReference reference = getCurrentReference(); return reference != null ? reference.getType().getLowerCase() + ':' + this.serializer.serialize(reference) : null; } }
package tbax.baxshops.serialization; import org.bukkit.Location; import org.bukkit.OfflinePlayer; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import tbax.baxshops.BaxShop; import tbax.baxshops.Format; import tbax.baxshops.ShopPlugin; import tbax.baxshops.notification.Notification; import tbax.baxshops.serialization.states.State_00300; import tbax.baxshops.serialization.states.State_00411; import java.io.*; import java.text.DecimalFormat; import java.util.*; import java.util.logging.Logger; import java.util.stream.Collectors; public final class SavedState { static final String YAML_FILE_PATH = "shops.yml"; private static final double STATE_VERSION = State_00411.VERSION; // state file format version private static double loadedState; /** * A map of ids map to their shops */ ShopMap shops = new ShopMap(); /** * A map containing each player's notifications */ Map<UUID, Deque<Notification>> pending = new HashMap<>(); /** * A map containing each player's attributes for when they're offline */ PlayerMap players = new PlayerMap(); final ShopPlugin plugin; final Logger log; Configuration config; SavedState(@NotNull ShopPlugin plugin) { this.plugin = plugin; this.log = plugin.getLogger(); players.put(StoredPlayer.DUMMY); shops.put(BaxShop.DUMMY_UUID, BaxShop.DUMMY_SHOP); } public static double getLoadedState() { return loadedState; } public @Nullable BaxShop getShop(UUID uid) { return shops.get(uid); } public @Nullable BaxShop getShop(Location loc) { return shops.getShopByLocation(loc); } public static SavedState readFromDisk(@NotNull ShopPlugin plugin) { File stateLocation = new File(plugin.getDataFolder(), YAML_FILE_PATH); if (!stateLocation.exists()) { plugin.getLogger().info("YAML file did not exist"); return new SavedState(plugin); } double ver; if (plugin.getConfig().contains("StateVersion")) { ver = plugin.getConfig().getDouble("StateVersion", STATE_VERSION); } else { ver = State_00300.VERSION; // version 3.0 was the last version not to be in config.yml } loadedState = ver; StateLoader loader; try { loader = UpgradeableSerialization.getStateLoader(plugin, ver); } catch (ReflectiveOperationException e) { plugin.getLogger().warning("Unknown state file version. Starting from scratch..."); return new SavedState(plugin); } if (ver != STATE_VERSION) { plugin.getLogger().info("Converting state file version " + (new DecimalFormat("0.0")).format(ver)); } return loader.loadState(YamlConfiguration.loadConfiguration(stateLocation)); } private void deleteLatestBackup(File backupFolder) { File[] backups = backupFolder.listFiles((f, name) -> name.endsWith(".yml")); int nBaks = getConfig().getBackups(); if (backups == null || nBaks <= 0 || backups.length < nBaks) { return; } List<String> names = Arrays.stream(backups) .map(f -> f.getName().substring(0, f.getName().lastIndexOf('.'))) .filter(n -> Format.parseFileDate(n) != null) .sorted(Comparator.comparing(Format::parseFileDate)) .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); while (names.size() >= nBaks) { File delete = new File(backupFolder, names.remove(names.size() - 1) + ".yml"); if (!delete.delete()) { log.warning(String.format("Unable to delete old backup %s", delete.getName())); } } } /** * Attempts to back up the shops.yml save file. * @return a boolean indicating success */ public boolean backup() { File stateLocation = new File(plugin.getDataFolder(), YAML_FILE_PATH); if (!stateLocation.exists()) { log.warning("Aborting backup: shops.yml not found"); return false; } File backupFolder = new File(plugin.getDataFolder(), "backups"); if (!backupFolder.exists() && !backupFolder.mkdirs()) { log.severe("Unable to create backups folder!"); return false; } deleteLatestBackup(backupFolder); try { String backupName = Format.FILE_DATE_FORMAT.format(new Date()) + ".yml"; File backup = new File(backupFolder, backupName); try (InputStream in = new FileInputStream(stateLocation)) { try (OutputStream out = new FileOutputStream(backup)) { byte[] buf = new byte[1024]; int i; while ((i = in.read(buf)) > 0) { out.write(buf, 0, i); } } } } catch (IOException e) { e.printStackTrace(); log.severe("Backup failed!"); return false; } return true; } public void addShop(BaxShop shop) { shops.put(shop.getId(), shop); } public boolean addLocation(BaxShop shop, Location loc) { BaxShop otherShop = shops.getShopByLocation(loc); if (otherShop == null) { shops.addLocation(shop.getId(), loc); return true; } return false; } /** * Gets a list of notifications for a player. * * @param player the player * @return the player's notifications */ public @NotNull Deque<Notification> getNotifications(OfflinePlayer player) { Deque<Notification> n = pending.get(player.getUniqueId()); if (n == null) { n = new ArrayDeque<>(); pending.put(player.getUniqueId(), n); } return n; } private void resaveConfig() { File configFile = new File(plugin.getDataFolder(), "config.yml"); if (!configFile.renameTo(new File(plugin.getDataFolder(), "config.bak"))) { plugin.getLogger().warning("Could not backup config. Configuration may be lost."); } plugin.getConfig().set("Backups", config.getBackups()); plugin.getConfig().set("LogNotes", config.isLogNotes()); plugin.getConfig().set("XPConvert", config.getXpConvert()); plugin.getConfig().set("DeathTax.Enabled", config.isDeathTaxEnabled()); plugin.getConfig().set("DeathTax.GoesTo", config.getDeathTaxGoesToId().toString()); plugin.getConfig().set("DeathTax.Percentage", config.getDeathTaxPercentage()); plugin.getConfig().set("DeathTax.Minimum", config.getDeathTaxMinimum()); plugin.getConfig().set("DeathTax.Maximum", config.getDeathTaxMaximum()); plugin.getConfig().set("StateVersion", STATE_VERSION); plugin.saveConfig(); } /** * Saves all shops */ public void writeToDisk() { if (!backup()) { log.warning("Failed to back up BaxShops"); } if (loadedState != STATE_VERSION) { resaveConfig(); } FileConfiguration state = new YamlConfiguration(); state.set("shops", new ArrayList<>(shops.values())); ConfigurationSection notes = state.createSection("notes"); for (Map.Entry<UUID, Deque<Notification>> entry : pending.entrySet()) { notes.set(entry.getKey().toString(), new ArrayList<>(entry.getValue())); } state.set("players", new ArrayList<>(players.values())); try { File dir = plugin.getDataFolder(); if (!dir.exists() && !dir.mkdirs()) { log.severe("Unable to make data folder!"); } else { state.save(new File(dir, YAML_FILE_PATH)); } } catch (IOException e) { log.severe("Save failed"); e.printStackTrace(); } } public @NotNull StoredPlayer getOfflinePlayer(UUID uuid) { StoredPlayer player = players.get(uuid); if (player == null) return StoredPlayer.ERROR; return player; } public @NotNull StoredPlayer getOfflinePlayerSafe(UUID uuid) { StoredPlayer player = players.get(uuid); if (player == null) { player = new StoredPlayer(uuid.toString(), uuid); players.put(player); } return player; } public List<StoredPlayer> getOfflinePlayer(String playerName) { return players.get(playerName); } public void joinPlayer(Player player) { StoredPlayer storedPlayer = players.convertLegacy(player); if (storedPlayer == null) { storedPlayer = new StoredPlayer(player); } else { Deque<Notification> notes = pending.remove(storedPlayer.getUniqueId()); players.remove(storedPlayer.getUniqueId()); if (notes != null) pending.put(storedPlayer.getUniqueId(), notes); } players.put(storedPlayer.getUniqueId(), storedPlayer); } public Configuration getConfig() { if (config == null) config = new Configuration(); return config; } public void reload() { log.info("Reloading BaxShops..."); writeToDisk(); log.info("Clearing memory..."); shops.clear(); players.clear(); pending.clear(); log.info("Loading BaxShops..."); SavedState savedState = readFromDisk(plugin); shops = savedState.shops; players = savedState.players; pending = savedState.pending; config = savedState.config; log.info("BaxShops has finished reloading"); } public void removeLocation(UUID shopId, Location loc) { shops.removeLocation(shopId, loc); } public void removeShop(UUID shopId) { shops.remove(shopId); } public Collection<StoredPlayer> getRegisteredPlayers() { return players.values().stream() .filter(n -> !StoredPlayer.ERROR.equals(n)) .collect(Collectors.toList()); } }
package think.rpgitems.power.impl; import org.bukkit.Bukkit; import org.bukkit.Sound; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.*; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.util.Vector; import think.rpgitems.Events; import think.rpgitems.I18n; import think.rpgitems.RPGItems; import think.rpgitems.power.*; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import static think.rpgitems.power.Utils.*; /** * Power deflect. * <p> * Deflect arrows or fireballs towards player within {@link #facing} when * 1. manual triggered when some of initiative trigger are enabled with a cooldown of {@link #cooldown} and duration {@link #duration} * 2. auto triggered when {@link Trigger#HIT_TAKEN} is enabled with a chance of {@link #chance} and a cooldown of {@link #cooldownpassive} * </p> */ @SuppressWarnings("WeakerAccess") @PowerMeta(defaultTrigger = "RIGHT_CLICK") public class PowerDeflect extends BasePower implements PowerHitTaken, PowerRightClick, PowerLeftClick, PowerPlain { /** * Cooldown time of this power */ @Property(order = 2) public int cooldown = 20; /** * Cooldown time of this power in passive mode */ @Property(order = 4) public int cooldownpassive = 20; /** * Cost of this power */ @Property public int cost = 0; /** * Chance in percentage of triggering this power in passive mode */ @Property public int chance = 50; /** * Duration of this power */ @Property public int duration = 50; /** * Maximum view angle */ @Property(order = 0, required = true) public double facing = 30; private static Map<UUID, Long> time = new HashMap<>(); @Override public String displayText() { return I18n.format("power.deflect", (double) cooldown / 20d); } @Override public String getName() { return "deflect"; } @Override public void init(ConfigurationSection section) { cooldownpassive = section.getInt("cooldownpassive", 20); boolean passive = section.getBoolean("passive", false); boolean initiative = section.getBoolean("initiative", true); boolean isRight = section.getBoolean("isRight", true); triggers = new HashSet<>(); if (passive) { triggers.add(Trigger.HIT_TAKEN); } if (initiative) { triggers.add(isRight ? Trigger.RIGHT_CLICK : Trigger.LEFT_CLICK); } super.init(section); } @Override public PowerResult<Double> takeHit(Player target, ItemStack stack, double damage, EntityDamageEvent event) { if (!(target.getInventory().getItemInMainHand().equals(stack) || target.getInventory().getItemInOffHand().equals(stack))) { return PowerResult.noop(); } boolean activated = System.currentTimeMillis() / 50 < time.getOrDefault(target.getUniqueId(), 0L); if (!activated) { if (!triggers.contains(Trigger.HIT_TAKEN) || ThreadLocalRandom.current().nextInt(0, 100) >= chance) return PowerResult.noop(); if (!checkCooldown(this, target, cooldownpassive, false)) return PowerResult.cd(); } if (!getItem().consumeDurability(stack, cost)) return PowerResult.cost(); if (event instanceof EntityDamageByEntityEvent) { EntityDamageByEntityEvent byEntityEvent = (EntityDamageByEntityEvent) event; if (byEntityEvent.getDamager() instanceof Projectile) { Projectile p = (Projectile) byEntityEvent.getDamager(); if (!(p.getShooter() instanceof LivingEntity)) return PowerResult.noop(); LivingEntity source = (LivingEntity) p.getShooter(); Vector relativePosition = target.getEyeLocation().toVector(); relativePosition.subtract(source.getEyeLocation().toVector()); if (getAngleBetweenVectors(target.getEyeLocation().getDirection(), relativePosition.multiply(-1)) < facing && (p instanceof SmallFireball || p instanceof LargeFireball || p instanceof Arrow)) { event.setCancelled(true); p.remove(); target.getLocation().getWorld().playSound(target.getLocation(), Sound.ITEM_SHIELD_BLOCK, 1.0f, 3.0f); Bukkit.getScheduler().runTaskLater(RPGItems.plugin, () -> { if (!target.isOnline() || target.isDead()) { return; } Projectile t = target.launchProjectile(p.getClass()); if (p instanceof TippedArrow) { TippedArrow tippedArrowP = (TippedArrow) p; TippedArrow tippedArrowT = (TippedArrow) t; tippedArrowT.setBasePotionData(tippedArrowP.getBasePotionData()); tippedArrowP.getCustomEffects().forEach(potionEffect -> tippedArrowT.addCustomEffect(potionEffect, true)); } t.setShooter(target); t.setMetadata("rpgitems.force", new FixedMetadataValue(RPGItems.plugin, 1)); Events.removeArrows.add(t.getEntityId()); }, 1); return PowerResult.ok(0.0); } } } return PowerResult.noop(); } @Override public PowerResult<Void> rightClick(Player player, ItemStack stack, PlayerInteractEvent event) { return fire(player, stack); } @Override public PowerResult<Void> fire(Player player, ItemStack stack) { if (!checkCooldownByString(player, getItem(), "deflect.initiative", cooldown, true)) return PowerResult.noop(); if (!getItem().consumeDurability(stack, cost)) return PowerResult.cost(); time.put(player.getUniqueId(), System.currentTimeMillis() / 50 + duration); return PowerResult.ok(); } @Override public PowerResult<Void> leftClick(Player player, ItemStack stack, PlayerInteractEvent event) { return fire(player, stack); } @Override public Set<Trigger> getTriggers() { HashSet<Trigger> triggers = new HashSet<>(super.getTriggers()); triggers.add(Trigger.HIT_TAKEN); return triggers; } }
package tondeuse.fr.application.model; import tondeuse.fr.application.exceptions.IllegalPositionException; public class Position { private int xPosition; private int yPosition; public Position(int xPosition, int yPosition) throws IllegalPositionException { if (xPosition < 0 || yPosition < 0) throw new IllegalPositionException("Position (" + xPosition + "," + yPosition + ") est en dehors du plateau"); this.xPosition = xPosition; this.yPosition = yPosition; } public int getxPosition() { return xPosition; } public void setxPosition(int xPosition) throws IllegalPositionException { if (xPosition < 0 || yPosition < 0) throw new IllegalPositionException("xPosition (" + xPosition + ") doit etre superieur a 0"); this.xPosition = xPosition; } public int getyPosition() { return yPosition; } public void setyPosition(int yPosition) throws IllegalPositionException { if (xPosition < 0 || yPosition < 0) throw new IllegalPositionException("xPosition (" + yPosition + ") doit etre superieur a 0"); this.yPosition = yPosition; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + xPosition; result = prime * result + yPosition; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Position other = (Position) obj; if (xPosition != other.xPosition) return false; if (yPosition != other.yPosition) return false; return true; } }
package top.quantic.sentry.discord; import org.ocpsoft.prettytime.shade.edu.emory.mathcs.backport.java.util.Collections; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import sx.blah.discord.api.IDiscordClient; import sx.blah.discord.handle.obj.IMessage; import sx.blah.discord.util.DiscordException; import top.quantic.sentry.discord.command.Command; import top.quantic.sentry.discord.command.CommandBuilder; import top.quantic.sentry.discord.command.CommandContext; import top.quantic.sentry.discord.module.CommandSupplier; import java.util.List; import static top.quantic.sentry.discord.util.DiscordUtil.answer; import static top.quantic.sentry.discord.util.DiscordUtil.deleteMessage; import static top.quantic.sentry.discord.util.DiscordUtil.ourBotHash; @Component public class PowerSwitch implements CommandSupplier { private static final Logger log = LoggerFactory.getLogger(PowerSwitch.class); @Override public List<Command> getCommands() { return Collections.singletonList(logout()); } private Command logout() { return CommandBuilder.of("logout") .describedAs("Disconnect from Discord") .in("Power") .nonParsed() .secured() .onExecute(context -> { IMessage message = context.getMessage(); String[] args = context.getArgs(); if (args.length >= 1) { String hash = ourBotHash(message.getClient()); if (args[1].equals(hash)) { deleteMessage(message); doLogout(context); } } else { deleteMessage(message); answer(message, ":wave:"); doLogout(context); } }).build(); } private void doLogout(CommandContext context) { IDiscordClient client = context.getMessage().getClient(); log.info("[{}] Logging out via command", client.getOurUser().getName()); if (client.isLoggedIn()) { try { client.logout(); } catch (DiscordException e) { log.warn("Could not logout bot", e); } } } }
package org.springframework.cloud.zookeeper.discovery; import java.lang.invoke.MethodHandles; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.curator.framework.CuratorFramework; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.zookeeper.discovery.test.CommonTestConfig; import org.springframework.cloud.zookeeper.discovery.test.TestRibbonClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Profile; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; import static com.toomuchcoding.jsonassert.JsonAssertion.assertThat; import static org.assertj.core.api.BDDAssertions.then; /** * @author Marcin Grzejszczak */ @RunWith(SpringRunner.class) @SpringBootTest(classes = ZookeeperDiscoveryHealthIndicatorWithNestedStructureTests.Config.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("nestedstructure") public class ZookeeperDiscoveryHealthIndicatorWithNestedStructureTests { private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); @Autowired TestRibbonClient testRibbonClient; @Autowired CuratorFramework curatorFramework; // Issue: #54 - ZookeeperDiscoveryHealthIndicator fails on nested structure @Test public void should_return_a_response_that_app_is_in_a_healthy_state_when_nested_folders_in_zookeeper_are_present() throws Exception { // when: String response = this.testRibbonClient.callService("me", "health"); // then: log.info("Received response [" + response + "]"); then(this.curatorFramework.getChildren().forPath("/services/me")).isNotEmpty(); then(this.curatorFramework.getChildren().forPath("/services/a/b/c/d/anotherservice")).isNotEmpty(); } @Configuration @EnableAutoConfiguration @EnableDiscoveryClient @Import(CommonTestConfig.class) @Profile("nestedstructure") static class Config { @Autowired CuratorFramework curatorFramework; CustomZookeeperServiceDiscovery customZookeeperServiceDiscovery; @PostConstruct void registerNestedDependency() { this.customZookeeperServiceDiscovery = new CustomZookeeperServiceDiscovery("/a/b/c/d/anotherservice", "/services", this.curatorFramework); this.customZookeeperServiceDiscovery.build(); } @PreDestroy void unregisterServiceDiscovery() { if (this.customZookeeperServiceDiscovery != null) { this.customZookeeperServiceDiscovery.close(); } } @Bean TestRibbonClient testRibbonClient(@LoadBalanced RestTemplate restTemplate, @Value("${spring.application.name}") String springAppName) { return new TestRibbonClient(restTemplate, springAppName); } } }
package xmlparser.translator; import java.util.List; import org.apache.commons.lang3.StringUtils; import reciter.model.article.ReCiterArticle; import reciter.model.article.ReCiterArticleAuthors; import reciter.model.article.ReCiterArticleKeywords; import reciter.model.article.ReCiterJournal; import reciter.model.author.AuthorAffiliation; import reciter.model.author.AuthorName; import reciter.model.author.ReCiterAuthor; import xmlparser.pubmed.model.MedlineCitationArticleAuthor; import xmlparser.pubmed.model.MedlineCitationKeyword; import xmlparser.pubmed.model.MedlineCitationKeywordList; import xmlparser.pubmed.model.MedlineCitationMeshHeading; import xmlparser.pubmed.model.PubmedArticle; import xmlparser.scopus.model.Author; import xmlparser.scopus.model.ScopusArticle; /** * Translator that translates a PubmedArticle to ReCiterArticle. * @author jil3004 * */ public class ArticleTranslator { /** * Translates a PubmedArticle into a ReCiterArticle. * @param pubmedArticle * @return */ public static ReCiterArticle translate(PubmedArticle pubmedArticle, ScopusArticle scopusArticle) { // PMID String pmid = pubmedArticle.getMedlineCitation().getPmid().getPmidString(); ReCiterArticle reCiterArticle = new ReCiterArticle(Integer.parseInt(pmid)); // Article title String articleTitle = pubmedArticle.getMedlineCitation().getArticle().getArticleTitle(); // Journal Title String journalTitle = pubmedArticle.getMedlineCitation().getArticle().getJournal().getJournalTitle(); // Translating Journal Issue PubDate Year. int journalIssuePubDateYear = Integer.parseInt(pubmedArticle.getMedlineCitation().getArticle().getJournal().getJournalIssue().getPubDate().getYear()); // Co-authors List<MedlineCitationArticleAuthor> coAuthors = pubmedArticle.getMedlineCitation().getArticle().getAuthorList(); // Translating Co-Authors ReCiterArticleAuthors reCiterCoAuthors = new ReCiterArticleAuthors(); for (MedlineCitationArticleAuthor author : coAuthors) { String lastName = author.getLastName(); String foreName = author.getForeName(); String initials = author.getInitials(); String firstName = null; String middleName = null; // PubMed sometimes concatenates the first name and middle initial into <ForeName> xml tag. // This extracts the first name and middle initial. // Sometimes forename doesn't exist in XML (ie: 8661541). So initials are used instead. // Forename take precedence. If foreName doesn't exist, use initials. If initials doesn't exist, use null. // TODO: Deal with collective names in XML. if (lastName != null) { if (foreName != null) { String[] foreNameArray = foreName.split("\\s+"); if (foreNameArray.length == 2) { firstName = foreNameArray[0]; middleName = foreNameArray[1]; } else { firstName = foreName; } } else if (initials != null) { firstName = initials; } String affiliation = author.getAffiliation(); AuthorName authorName = new AuthorName(firstName, middleName, lastName); AuthorAffiliation authorAffiliation = new AuthorAffiliation(affiliation); ReCiterAuthor reCiterAuthor = new ReCiterAuthor(authorName, authorAffiliation); reCiterCoAuthors.addAuthor(reCiterAuthor); } } MedlineCitationKeywordList keywordList = pubmedArticle.getMedlineCitation().getKeywordList(); // Translating Keywords. ReCiterArticleKeywords articleKeywords = new ReCiterArticleKeywords(); if (keywordList != null) { for (MedlineCitationKeyword keyword : keywordList.getKeywordList()) { articleKeywords.addKeyword(keyword.getKeyword()); } } List<MedlineCitationMeshHeading> meshList = pubmedArticle.getMedlineCitation().getMeshHeadingList(); if (meshList != null) { // Translating Mesh for (MedlineCitationMeshHeading mesh : meshList) { articleKeywords.addKeyword(mesh.getDescriptorName().getDescriptorNameString()); } } reCiterArticle.setArticleTitle(articleTitle); reCiterArticle.setJournal(new ReCiterJournal(journalTitle)); reCiterArticle.setArticleCoAuthors(reCiterCoAuthors); reCiterArticle.setArticleKeywords(articleKeywords); reCiterArticle.getJournal().setJournalIssuePubDateYear(journalIssuePubDateYear); reCiterArticle.getJournal().setIsoAbbreviation(pubmedArticle.getMedlineCitation().getArticle().getJournal().getIsoAbbreviation()); if (scopusArticle != null) { for (Author scopusAuthor : scopusArticle.getAuthors().values()) { String scopusAuthorFirstName = scopusAuthor.getGivenName(); String scopusAuthorLastName = scopusAuthor.getSurname(); for (ReCiterAuthor reCiterAuthor : reCiterArticle.getArticleCoAuthors().getAuthors()) { String reCiterAuthorLastName = reCiterAuthor.getAuthorName().getLastName(); if (StringUtils.equalsIgnoreCase(scopusAuthorLastName, reCiterAuthorLastName)) { String reCiterAuthorFirstName = reCiterAuthor.getAuthorName().getFirstName(); String reCiterAuthorFirstInitial = reCiterAuthor.getAuthorName().getFirstInitial(); if (scopusAuthorFirstName != null && scopusAuthorFirstName.length() > 1) { if (scopusAuthorFirstName.substring(0, 1).equals(reCiterAuthorFirstInitial)) { if (scopusAuthorFirstName.length() > reCiterAuthorFirstName.length()) { // System.out.println("[" + scopusAuthorFirstName + "], [" + reCiterAuthorFirstName + "]"); if (reCiterAuthorFirstName.length() == 1) { int indexOfWhiteSpace = scopusAuthorFirstName.indexOf(" "); scopusAuthorFirstName = scopusAuthorFirstName.replaceAll("[\\.]", ""); if (indexOfWhiteSpace == -1) { reCiterAuthor.getAuthorName().setFirstName(scopusAuthorFirstName); } else { reCiterAuthor.getAuthorName().setFirstName(scopusAuthorFirstName.substring(0, indexOfWhiteSpace)); } } } } } } } } } reCiterArticle.setScopusArticle(scopusArticle); return reCiterArticle; } }
package xyz.upperlevel.uppercore.config; import org.bukkit.*; import org.bukkit.configuration.ConfigurationSection; import xyz.upperlevel.uppercore.config.exceptions.InvalidConfigurationException; import xyz.upperlevel.uppercore.config.exceptions.InvalidVauleConfigException; import xyz.upperlevel.uppercore.config.exceptions.RequiredPropertyNotFoundException; import xyz.upperlevel.uppercore.itemstack.CustomItem; import xyz.upperlevel.uppercore.message.Message; import xyz.upperlevel.uppercore.placeholder.*; import xyz.upperlevel.uppercore.sound.CompatibleSound; import xyz.upperlevel.uppercore.util.LocUtil; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import static java.util.Collections.singletonList; @SuppressWarnings("unchecked") public interface Config { Object get(String key); default Object get(String key, Object defaultValue) { final Object res = get(key); return res != null ? res : defaultValue; } default Object getRequired(String key) { final Object res = get(key); if (res == null) requiredPropertyNotFound(key); return res; } default boolean has(String key) { return get(key) != null; } default DyeColor getDye(String key, DyeColor def) { String raw = getString(key); if (raw == null) return def; else { try { return ConfigUtils.parseDye(raw); } catch (InvalidConfigurationException e) { e.addLocalizer("in property \"" + key + "\""); throw e; } } } default DyeColor getDye(String key) { return getDye(key, null); } default DyeColor getDyeRequired(String key) { DyeColor color = getDye(key, null); if (color == null) requiredPropertyNotFound(key); return color; } default String getString(String key) { Object raw = get(key); return raw == null ? null : raw.toString(); } default String getString(String key, String def) { final String res = getString(key); return res != null ? res : def; } default String getStringRequired(String key) { String str = getString(key); if (str == null) requiredPropertyNotFound(key); return str; } default List<String> getStringList(String key) { List<String> res = null; try { res = (List<String>) get(key); } catch (ClassCastException e) { invalidValue(key, get(key), "List"); } return res; } default List<String> getStringList(String key, List<String> def) { List<String> res = getStringList(key); return res != null ? res : def; } default List<String> getStringListRequired(String key) { List<String> res = getStringList(key); if (res == null) requiredPropertyNotFound(key); return res; } default <T> List<T> getList(String key) { return (List<T>) get(key); } default <T> List<T> getList(String key, List<T> def) { List<T> res = getList(key); return res != null ? res : def; } default <T> List<T> getListRequired(String key) { List<T> res = getList(key); if (res == null) requiredPropertyNotFound(key); return res; } default Message getMessage(String key) { return Message.fromConfig(get(key)); } default Message getMessage(String key, Message def) { Message message = getMessage(key); return message == null ? def : message; } default Message getMessage(String key, String def) { Message message = getMessage(key); if(message != null) return message; else return new Message(singletonList(PlaceholderValue.stringValue(def))); } default Message getMessageRequired(String key) { return Message.fromConfig(getRequired(key)); } default PlaceholderValue<String> getMessageStr(String key) { return PlaceholderValue.stringValue(getString(key)); } default PlaceholderValue<String> getMessageStr(String key, String def) { return PlaceholderValue.stringValue(getString(key, def)); } default PlaceholderValue<String> getMessageStr(String key, PlaceholderValue<String> def) { String str = getString(key); return str == null ? def : PlaceholderValue.stringValue(str); } default PlaceholderValue<String> getMessageStrRequired(String key) { return PlaceholderValue.stringValue(getStringRequired(key)); } default List<PlaceholderValue<String>> getMessageStrList(String key) { List<String> tmp = getStringList(key); if (tmp == null) return null; return tmp.stream() .map(PlaceholderUtil::process) .collect(Collectors.toList()); } default List<PlaceholderValue<String>> getMessageStrList(String key, List<PlaceholderValue<String>> def) { List<PlaceholderValue<String>> res = getMessageStrList(key); return res != null ? res : def; } default List<PlaceholderValue<String>> getMessageStrListRequired(String key) { List<PlaceholderValue<String>> res = getMessageStrList(key); if (res == null) requiredPropertyNotFound(key); return res; } default Integer getInt(String key) { Number res = null; try { res = ((Number) get(key)); } catch (ClassCastException e) { invalidValue(key, get(key), "Number"); } return res == null ? null : res.intValue(); } default int getInt(String key, int def) { final Integer res = getInt(key); return res != null ? res : def; } default int getIntRequired(String key) { Object raw = get(key); if (raw == null) requiredPropertyNotFound(key); try { return ((Number) get(key)).intValue(); } catch (ClassCastException e) { invalidValue(key, raw, "Number"); return -1; } } default Short getShort(String key) { Number res = null; try { res = ((Number) get(key)); } catch (ClassCastException e) { invalidValue(key, get(key), "Number"); } return res == null ? null : res.shortValue(); } default short getShort(String key, short def) { final Short res = getShort(key); return res != null ? res : def; } default short getShortRequired(String key) { Object raw = get(key); if (raw == null) requiredPropertyNotFound(key); try { return ((Number) get(key)).shortValue(); } catch (ClassCastException e) { invalidValue(key, raw, "Number"); return -1; } } default Byte getByte(String key) { Number res = null; try { res = ((Number) get(key)); } catch (ClassCastException e) { invalidValue(key, get(key), "Number"); } return res == null ? null : res.byteValue(); } default byte getByte(String key, byte def) { final Byte res = getByte(key); return res != null ? res : def; } default byte getByteRequired(String key) { Object raw = get(key); if (raw == null) requiredPropertyNotFound(key); try { return ((Number) get(key)).byteValue(); } catch (ClassCastException e) { invalidValue(key, raw, "Number"); return -1; } } default Long getLong(String key) { Number res = null; try { res = ((Number) get(key)); } catch (ClassCastException e) { invalidValue(key, get(key), "Number"); } return res == null ? null : res.longValue(); } default long getLong(String key, long def) { final Long res = getLong(key); return res != null ? res : def; } default long getLongRequired(String key) { Object raw = get(key); if (raw == null) requiredPropertyNotFound(key); try { return ((Number) get(key)).longValue(); } catch (ClassCastException e) { invalidValue(key, raw, "Number"); return -1; } } default Boolean getBool(String key) { Object raw = get(key); if (raw == null) return null; if (raw instanceof Boolean) { return (Boolean) raw; } else if (raw instanceof String) { switch (((String) raw).toLowerCase()) { case "no": case "false": return false; case "yes": case "true": return true; } } else if (raw instanceof Number) { return ((Number) raw).intValue() == 1; } invalidValue(key, raw, "Boolean"); return null; } default boolean getBool(String key, boolean def) { final Boolean res = getBool(key); return res != null ? res : def; } default boolean getBoolRequired(String key) { Boolean raw = getBool(key); if (raw == null) requiredPropertyNotFound(key); return raw; } default Float getFloat(String key) { Number res; try { res = ((Number) get(key)); } catch (ClassCastException e) { invalidValue(key, get(key), "Number"); return null; } return res == null ? null : res.floatValue(); } default float getFloat(String key, float def) { Float res = getFloat(key); return res != null ? res : def; } default float getFloatRequired(String key) { Object raw = get(key); if (raw == null) requiredPropertyNotFound(key); try { return ((Number) get(key)).floatValue(); } catch (ClassCastException e) { invalidValue(key, raw, "Number"); return -1; } } default Double getDouble(String key) { Number res = null; try { res = ((Number) get(key)); } catch (ClassCastException e) { invalidValue(key, get(key), "Number"); } return res == null ? null : res.doubleValue(); } default double getDouble(String key, double def) { Double res = getDouble(key); return res != null ? res : def; } default double getDoubleRequired(String key) { Object raw = get(key); if (raw == null) requiredPropertyNotFound(key); try { return ((Number) get(key)).doubleValue(); } catch (ClassCastException e) { invalidValue(key, raw, "Number"); return -1; } } default <T extends Enum<T>> T getEnum(String key, Class<T> clazz) { String raw = getString(key); if (raw == null) return null; raw = raw.replace(' ', '_').toUpperCase(Locale.ENGLISH); try { return Enum.valueOf(clazz, raw); } catch (IllegalArgumentException e) { throw new InvalidConfigurationException("Cannot find \"" + clazz.getSimpleName().toLowerCase() + "\" \"" + raw + "\""); } } default <T extends Enum<T>> T getEnum(String key, T def, Class<T> clazz) { final T res = getEnum(key, clazz); return res != null ? res : def; } default <T extends Enum<T>> T getEnumRequired(String key, Class<T> clazz) { T res = getEnum(key, clazz); if (res == null) requiredPropertyNotFound(key); return res; } default Color getColor(String key, Color def) { String raw = getString(key); if (raw == null) return def; else { try { return ConfigUtils.parseColor(raw); } catch (InvalidConfigurationException e) { e.addLocalizer("in property \"" + key + "\""); throw e; } } } default Color getColor(String key) { return getColor(key, null); } default Color getColorRequired(String key) { Color color = getColor(key, null); if (color == null) requiredPropertyNotFound(key); return color; } default Sound getSound(String key, Sound def) { String raw = getString(key); if (raw == null) return def; else { Sound s = CompatibleSound.get(key); if(s == null) throw new InvalidConfigurationException("Cannot find sound \"" + raw + "\", is it supported?"); else return s; } } default Sound getSound(String key) { return getSound(key, null); } default Sound getSoundRequired(String key) { Sound sound = getSound(key, null); if (sound == null) requiredPropertyNotFound(key); return sound; } default Material getMaterial(String key, Material def) { Object raw = get(key); if (raw == null) return def; else { Material res = null; if (raw instanceof Number) res = Material.getMaterial(((Number) raw).intValue()); else if (raw instanceof String) { res = Material.getMaterial(((String) raw).replace(' ', '_').toUpperCase()); } else invalidValue(key, raw, "String|Number"); if (res == null) throw new InvalidConfigurationException("Cannot find material \"" + raw + "\""); else return res; } } default Material getMaterial(String key) { return getMaterial(key, null); } default Material getMaterialRequired(String key) { Material mat = getMaterial(key, null); if (mat == null) requiredPropertyNotFound(key); return mat; } @SuppressWarnings("unchecked") default Map<String, Object> getSection(String key) { Object raw = get(key); if(raw == null) return null; if (raw instanceof Map) return (Map<String, Object>) raw; else if (raw instanceof ConfigurationSection) return ((ConfigurationSection) raw).getValues(false); else invalidValue(key, raw, "Map"); return null; } default Map<String, Object> getSection(String key, Map<String, Object> def) { final Map<String, Object> res = getSection(key); return res != null ? res : def; } default Map<String, Object> getSectionRequired(String key) { Map<String, Object> res = getSection(key); if (res == null) requiredPropertyNotFound(key); return res; } default Config getConfig(String key, Config def) { Object raw = get(key); if (raw == null) return def; if (raw instanceof Map) return Config.wrap((Map<String, Object>) raw); else if (raw instanceof ConfigurationSection) return Config.wrap((ConfigurationSection) raw); else invalidValue(key, raw, "Map"); return null; } default Config getConfig(String key) { return getConfig(key, null); } default Config getConfigRequired(String key) { Config res = getConfig(key, null); if (res == null) requiredPropertyNotFound(key); return res; } default List<Config> getConfigList(String key, List<Config> def) { Collection<Map<String, Object>> raw = getCollection(key); if (raw == null) return def; return raw.stream() .map(Config::wrap) .collect(Collectors.toList()); } default List<Config> getConfigList(String key) { return getConfigList(key, null); } default List<Config> getConfigListRequired(String key) { List<Config> res = getConfigList(key, null); if (res == null) requiredPropertyNotFound(key); return res; } default Collection getCollection(String key) { try { return ((Collection) get(key)); } catch (ClassCastException e) { invalidValue(key, get(key), "Collection"); return null; } } default Collection getCollection(String key, Collection def) { Collection found = getCollection(key); return found == null ? def : found; } default Collection getCollectionRequired(String key) { Object raw = get(key); if (raw == null) requiredPropertyNotFound(key); try { return ((Collection) get(key)); } catch (ClassCastException e) { invalidValue(key, get(key), "Collection"); return null; } } default Location getLocation(String key, Location def) { try { return LocUtil.deserialize(getConfig(key)); } catch (Exception e) { return def; } } default Location getLocation(String key) { return getLocation(key, null); } default Location getLocationRequired(String key) { Location l = getLocation(key); if (l == null) requiredPropertyNotFound(key); return l; } default List<Location> getLocationList(String key, List<Location> def) { List<Config> cfgs = getConfigList(key); List<Location> res = new ArrayList<>(); if (cfgs == null) return def; try { for (Config cfg : cfgs) res.add(LocUtil.deserialize(cfg)); } catch (Exception e) { return def; } return res; } default List<Location> getLocationList(String key) { return getLocationList(key, null); } default List<Location> getLocationListRequired(String key) { List<Location> res = getLocationList(key); if (res == null) requiredPropertyNotFound(key); return res; } default CustomItem getCustomItem(String key, Function<Config, CustomItem> deserializer) { Config sub = getConfig(key); if (sub == null) return null; try { return deserializer.apply(sub); } catch (InvalidConfigurationException e) { e.addLocalizer("in item " + key); throw e; } } default CustomItem getCustomItem(String key) { return getCustomItem(key, CustomItem::deserialize); } default CustomItem getCustomItem(String key, PlaceholderRegistry local) { return getCustomItem(key, config -> CustomItem.deserialize(config, local)); } default CustomItem getCustomItem(String key, CustomItem def) { CustomItem res = getCustomItem(key); return res != null ? res : def; } default CustomItem getCustomItemRequired(String key) { CustomItem res = getCustomItem(key); if (res == null) requiredPropertyNotFound(key); return res; } default CustomItem getCustomItemRequired(String key, PlaceholderRegistry local) { CustomItem res = getCustomItem(key, local); if (res == null) requiredPropertyNotFound(key); return res; } static void requiredPropertyNotFound(String key) { throw new RequiredPropertyNotFoundException(key); } static void invalidValue(String key, Object value, String expected) { throw new InvalidVauleConfigException(key, value, expected); } static Config wrap(Map<String, Object> map) { return map::get; } static Config wrap(ConfigurationSection section) { return section::get; } }
package za.redbridge.experiment; import org.encog.neural.neat.NEATLink; import org.encog.neural.neat.NEATNetwork; import org.encog.neural.neat.NEATNeuronType; import org.encog.neural.neat.training.NEATGenome; import org.encog.neural.neat.training.NEATLinkGene; import org.encog.neural.neat.training.NEATNeuronGene; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.List; import java.util.Map; import za.redbridge.experiment.MMNEAT.training.MMNEATNeuronGene; public class GraphvizEngine { private static final Logger log = LoggerFactory.getLogger(GraphvizEngine.class); public static void saveGenome(NEATGenome genome, Path path) { try (BufferedWriter writer = Files.newBufferedWriter(path)) { writer.write("digraph G {"); writer.newLine(); writeNeuronGenes(writer, genome.getNeuronsChromosome()); writeLinkGenes(writer, genome.getLinksChromosome()); writer.write("}"); writer.newLine(); writer.flush(); } catch (IOException e) { log.error("Failed to save graphviz representation of network", e); } } private static void writeNeuronGenes(BufferedWriter writer, List<NEATNeuronGene> neurons) throws IOException { for (NEATNeuronGene neuron : neurons) { writer.write(" "); writer.write(String.valueOf(neuron.getId())); if (neuron.getNeuronType() == NEATNeuronType.Input && neuron instanceof MMNEATNeuronGene) { MMNEATNeuronGene mmneatNeuronGene = (MMNEATNeuronGene) neuron; writer.write(" [ label=\"" + neuron.getNeuronType() + " (" + neuron.getId() + ")" + "\\n" + mmneatNeuronGene.getInputSensorType() + "\" ];"); } else { writer.write(" [ label=\"" + neuron.getNeuronType() + "\" ];"); } writer.newLine(); } } private static void writeLinkGenes(BufferedWriter writer, List<NEATLinkGene> links) throws IOException { for (NEATLinkGene link : links) { writer.write(" "); writer.write(link.getFromNeuronID() + " -> " + link.getToNeuronID()); if (link.isEnabled()) { writer.write(" [ label=\"" + String.format("%.3f", link.getWeight()) + "\" ];"); } else { writer.write(" [ style=\"dashed\" ];"); } writer.newLine(); } } public static void saveNetwork(NEATNetwork network, Path path) { try (BufferedWriter writer = Files.newBufferedWriter(path)) { writer.write("digraph G {"); writer.newLine(); writeNodes(writer, network); writeLinks(writer, network.getLinks()); writer.write("}"); writer.newLine(); writer.flush(); } catch (IOException e) { log.error("Failed to save graphviz representation of network", e); } } private static void writeNodes(BufferedWriter writer, NEATNetwork network) throws IOException { // Reconstruct node information from links (only works for constant inputs/outputs) Map<Integer, String> nodes = new HashMap<>(); NEATLink[] links = network.getLinks(); int inputCount = network.getInputCount(); int outputCount = network.getOutputCount(); for (NEATLink link : links) { int fromNeuron = link.getFromNeuron(); if (!nodes.containsKey(fromNeuron)) { nodes.put(fromNeuron, labelForNode(fromNeuron, inputCount, outputCount)); } int toNeuron = link.getToNeuron(); if (!nodes.containsKey(toNeuron)) { nodes.put(toNeuron, labelForNode(toNeuron, inputCount, outputCount)); } } // Write to file for (Map.Entry<Integer, String> entry : nodes.entrySet()) { writer.write(" "); writer.write(entry.getKey().toString()); writer.write(" [ label=\"" + entry.getValue() + " (" + entry.getKey() + ")\" ]"); writer.newLine(); } } private static String labelForNode(int node, int inputCount, int outputCount) { if (node == 0) { return NEATNeuronType.Bias.toString(); } if (node < inputCount + 1) { return NEATNeuronType.Input.toString(); } if (node < inputCount + outputCount + 1) { return NEATNeuronType.Output.toString(); } return NEATNeuronType.Hidden.toString(); } private static void writeLinks(BufferedWriter writer, NEATLink[] links) throws IOException { for (NEATLink link : links) { writer.write(" "); writer.write(link.getFromNeuron() + " -> " + link.getToNeuron()); writer.write(" [ label=\"" + String.format("%.3f", link.getWeight()) + "\" ];"); writer.newLine(); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.heeere.opencl; import java.awt.image.BufferedImageOp; import java.awt.RenderingHints; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.DataBufferInt; import java.awt.image.Kernel; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import org.jocl.Pointer; import org.jocl.Sizeof; import org.jocl.cl_command_queue; import org.jocl.cl_context; import org.jocl.cl_context_properties; import org.jocl.cl_device_id; import org.jocl.cl_kernel; import org.jocl.cl_mem; import org.jocl.cl_platform_id; import org.jocl.cl_program; import static org.jocl.CL.*; /** * * @author twilight */ public class JOCLConvolveOp implements BufferedImageOp { public static JOCLConvolveOp createNaiveConvolution(Kernel kernel) { return create("../cl/SimpleConvolution.cl", kernel); } public static JOCLConvolveOp createGoodConvolution(Kernel kernel) { return create("../cl/GoodConvolution.cl", kernel); } /** * Compute the value which is the smallest multiple * of the given group size that is greater than or * equal to the given global size. * * @param groupSize The group size * @param globalSize The global size * @return The rounded global size */ private static long round(long groupSize, long globalSize) { long r = globalSize % groupSize; if (r == 0) { return globalSize; } else { return globalSize + groupSize - r; } } /** * Helper function which reads the file with the given name and returns * the contents of this file as a String. Will exit the application * if the file can not be read. * * @param fileName The name of the file to read. * @return The contents of the file */ private static String readFile(String fileName) { try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); StringBuffer sb = new StringBuffer(); String line = null; while (true) { line = br.readLine(); if (line == null) { break; } sb.append(line).append("\n"); } return sb.toString(); } catch (IOException e) { e.printStackTrace(); System.exit(1); return null; } } /** * The OpenCL context */ private cl_context context; /** * The OpenCL command queue */ private cl_command_queue commandQueue; /** * The OpenCL kernel which will perform the convolution */ private cl_kernel clKernel; /** * The kernel which is used for the convolution */ private Kernel kernel; /** * The memory object that stores the kernel data */ private cl_mem kernelMem; /** * The memory object for the input image */ private cl_mem inputImageMem; /** * The memory object for the output image */ private cl_mem outputImageMem; /** * Creates a new JOCLConvolveOp which may be used to apply the * given kernel to a BufferedImage. This method will create * an OpenCL context for the first platform that is found, * and a command queue for the first device that is found. * To create a JOCLConvolveOp for an existing context and * command queue, use the constructor of this class. * * @param kernel The kernel to apply * @return The JOCLConvolveOp for the given kernel. */ public static JOCLConvolveOp create(String kernelSourceFileName, Kernel kernel) { // Obtain the platform IDs and initialize the context properties cl_platform_id platforms[] = new cl_platform_id[1]; clGetPlatformIDs(platforms.length, platforms, null); cl_context_properties contextProperties = new cl_context_properties(); contextProperties.addProperty(CL_CONTEXT_PLATFORM, platforms[0]); // Create an OpenCL context on a GPU device cl_context context = clCreateContextFromType( contextProperties, CL_DEVICE_TYPE_GPU, null, null, null); if (context == null) { // If no context for a GPU device could be created, // try to create one for a CPU device. context = clCreateContextFromType( contextProperties, CL_DEVICE_TYPE_CPU, null, null, null); if (context == null) { System.out.println("Unable to create a context"); System.exit(1); return null; } } // Enable exceptions and subsequently omit error checks in this sample setExceptionsEnabled(true); // Get the list of GPU devices associated with the context, // and create a command queue for the first device long numBytes[] = new long[1]; clGetContextInfo(context, CL_CONTEXT_DEVICES, 0, null, numBytes); int numDevices = (int) numBytes[0] / Sizeof.cl_device_id; cl_device_id devices[] = new cl_device_id[numDevices]; clGetContextInfo(context, CL_CONTEXT_DEVICES, numBytes[0], Pointer.to(devices), null); cl_device_id device = devices[0]; cl_command_queue commandQueue = clCreateCommandQueue(context, device, 0, null); return new JOCLConvolveOp(kernelSourceFileName, context, commandQueue, kernel); } /** * Creates a JOCLConvolveOp for the given context and command queue, * which may be used to apply the given kernel to a BufferedImage. * * @param context The context * @param commandQueue The command queue * @param kernel The kernel to apply */ public JOCLConvolveOp(String kernelSourceFileName, cl_context context, cl_command_queue commandQueue, Kernel kernel) { this.context = context; this.commandQueue = commandQueue; this.kernel = kernel; // Create the OpenCL kernel from the program String source = readFile(kernelSourceFileName); cl_program program = clCreateProgramWithSource(context, 1, new String[]{source}, null, null); String compileOptions = "-cl-mad-enable"; clBuildProgram(program, 0, null, compileOptions, null, null); clKernel = clCreateKernel(program, "convolution", null); // Create the ... other kernel... for the convolution float kernelData[] = kernel.getKernelData(null); kernelMem = clCreateBuffer(context, CL_MEM_READ_ONLY, kernelData.length * Sizeof.cl_uint, null, null); clEnqueueWriteBuffer(commandQueue, kernelMem, true, 0, kernelData.length * Sizeof.cl_uint, Pointer.to(kernelData), 0, null, null); } @Override public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM) { int w = src.getWidth(); int h = src.getHeight(); BufferedImage result = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); return result; } @Override public BufferedImage filter(BufferedImage src, BufferedImage dst) { // Validity checks for the given images if (src.getType() != BufferedImage.TYPE_INT_RGB) { throw new IllegalArgumentException("Source image is not TYPE_INT_RGB"); } if (dst == null) { dst = createCompatibleDestImage(src, null); } else if (dst.getType() != BufferedImage.TYPE_INT_RGB) { throw new IllegalArgumentException("Destination image is not TYPE_INT_RGB"); } if (src.getWidth() != dst.getWidth() || src.getHeight() != dst.getHeight()) { throw new IllegalArgumentException( "Images do not have the same size"); } int imageSizeX = src.getWidth(); int imageSizeY = src.getHeight(); // Create the memory object for the input- and output image DataBufferInt dataBufferSrc = (DataBufferInt) src.getRaster().getDataBuffer(); int dataSrc[] = dataBufferSrc.getData(); inputImageMem = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, dataSrc.length * Sizeof.cl_uint, Pointer.to(dataSrc), null); outputImageMem = clCreateBuffer(context, CL_MEM_WRITE_ONLY, imageSizeX * imageSizeY * Sizeof.cl_uint, null, null); // Set work sizes and arguments, and execute the kernel int kernelSizeX = kernel.getWidth(); int kernelSizeY = kernel.getHeight(); int kernelOriginX = kernel.getXOrigin(); int kernelOriginY = kernel.getYOrigin(); long localWorkSize[] = new long[2]; localWorkSize[0] = kernelSizeX; localWorkSize[1] = kernelSizeY; long globalWorkSize[] = new long[2]; globalWorkSize[0] = round(localWorkSize[0], imageSizeX); globalWorkSize[1] = round(localWorkSize[1], imageSizeY); int imageSize[] = new int[]{imageSizeX, imageSizeY}; int kernelSize[] = new int[]{kernelSizeX, kernelSizeY}; int kernelOrigin[] = new int[]{kernelOriginX, kernelOriginY}; clSetKernelArg(clKernel, 0, Sizeof.cl_mem, Pointer.to(inputImageMem)); clSetKernelArg(clKernel, 1, Sizeof.cl_mem, Pointer.to(kernelMem)); clSetKernelArg(clKernel, 2, Sizeof.cl_mem, Pointer.to(outputImageMem)); clSetKernelArg(clKernel, 3, Sizeof.cl_int2, Pointer.to(imageSize)); clSetKernelArg(clKernel, 4, Sizeof.cl_int2, Pointer.to(kernelSize)); clSetKernelArg(clKernel, 5, Sizeof.cl_int2, Pointer.to(kernelOrigin)); //System.out.println("global "+Arrays.toString(globalWorkSize)); //System.out.println("local "+Arrays.toString(localWorkSize)); clEnqueueNDRangeKernel(commandQueue, clKernel, 2, null, globalWorkSize, localWorkSize, 0, null, null); // Read the pixel data into the BufferedImage DataBufferInt dataBufferDst = (DataBufferInt) dst.getRaster().getDataBuffer(); int dataDst[] = dataBufferDst.getData(); clEnqueueReadBuffer(commandQueue, outputImageMem, CL_TRUE, 0, dataDst.length * Sizeof.cl_uint, Pointer.to(dataDst), 0, null, null); // Clean up clReleaseMemObject(inputImageMem); clReleaseMemObject(outputImageMem); return dst; } @Override public Rectangle2D getBounds2D(BufferedImage src) { return src.getRaster().getBounds(); } @Override public final Point2D getPoint2D(Point2D srcPt, Point2D dstPt) { if (dstPt == null) { dstPt = new Point2D.Float(); } dstPt.setLocation(srcPt.getX(), srcPt.getY()); return dstPt; } @Override public RenderingHints getRenderingHints() { return null; } @Override public void finalize() throws Throwable { clReleaseMemObject(kernelMem); super.finalize(); } }
package de.kimminich.kata.tcg.strategy; import de.kimminich.kata.tcg.Card; import de.kimminich.kata.tcg.Game; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.List; import java.util.Optional; import java.util.logging.Logger; public class ConsoleInputStrategy implements Strategy { private static final Logger logger = Logger.getLogger(ConsoleInputStrategy.class.getName()); @Override public Optional<Card> nextCard(int mana, List<Card> availableCards) { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { return Optional.of(new Card(Integer.parseInt(br.readLine()))); } catch (IOException e) { logger.severe("Could not read console input!"); } return Optional.empty(); } }
package de.lmu.ifi.dbs.elki.algorithm.outlier; import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm; import de.lmu.ifi.dbs.elki.data.NumberVector; import de.lmu.ifi.dbs.elki.database.AssociationID; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.database.datastore.DataStoreFactory; import de.lmu.ifi.dbs.elki.database.datastore.DataStoreUtil; import de.lmu.ifi.dbs.elki.database.datastore.WritableDataStore; import de.lmu.ifi.dbs.elki.database.ids.DBID; import de.lmu.ifi.dbs.elki.math.MinMax; import de.lmu.ifi.dbs.elki.math.linearalgebra.Matrix; import de.lmu.ifi.dbs.elki.math.linearalgebra.Vector; import de.lmu.ifi.dbs.elki.result.AnnotationFromDataStore; import de.lmu.ifi.dbs.elki.result.AnnotationResult; import de.lmu.ifi.dbs.elki.result.OrderingFromDataStore; import de.lmu.ifi.dbs.elki.result.OrderingResult; import de.lmu.ifi.dbs.elki.result.outlier.BasicOutlierScoreMeta; import de.lmu.ifi.dbs.elki.result.outlier.InvertedOutlierScoreMeta; import de.lmu.ifi.dbs.elki.result.outlier.OutlierResult; import de.lmu.ifi.dbs.elki.result.outlier.OutlierScoreMeta; import de.lmu.ifi.dbs.elki.utilities.DatabaseUtil; import de.lmu.ifi.dbs.elki.utilities.documentation.Description; import de.lmu.ifi.dbs.elki.utilities.documentation.Title; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.Flag; /** * Outlier have smallest GMOD_PROB: the outlier scores is the * <em>probability density</em> of the assumed distribution. * * @author Lisa Reichert * * @param <V> Vector type */ @Title("Gaussian Model Outlier Detection") @Description("Fit a multivariate gaussian model onto the data, and use the PDF to compute an outlier score.") public class GaussianModel<V extends NumberVector<V, Double>> extends AbstractAlgorithm<V, OutlierResult> { /** * OptionID for {@link #INVERT_FLAG} */ public static final OptionID INVERT_ID = OptionID.getOrCreateOptionID("gaussod.invert", "Invert the value range to [0:1], with 1 being outliers instead of 0."); /** * Parameter to specify a scaling function to use. * <p> * Key: {@code -gaussod.invert} * </p> */ private final Flag INVERT_FLAG = new Flag(INVERT_ID); /** * Invert the result */ private boolean invert = false; /** * Association ID for the Gaussian model outlier probability */ public static final AssociationID<Double> GMOD_PROB = AssociationID.getOrCreateAssociationID("gmod.prob", Double.class); /** * Constructor, adhering to * {@link de.lmu.ifi.dbs.elki.utilities.optionhandling.Parameterizable} * * @param config Parameterization */ public GaussianModel(Parameterization config) { super(config); if(config.grab(INVERT_FLAG)) { invert = INVERT_FLAG.getValue(); } } @Override protected OutlierResult runInTime(Database<V> database) throws IllegalStateException { MinMax<Double> mm = new MinMax<Double>(); // resulting scores WritableDataStore<Double> oscores = DataStoreUtil.makeStorage(database.getIDs(), DataStoreFactory.HINT_TEMP | DataStoreFactory.HINT_HOT, Double.class); // Compute mean and covariance Matrix V mean = DatabaseUtil.centroid(database); // debugFine(mean.toString()); Matrix covarianceMatrix = DatabaseUtil.covarianceMatrix(database, mean); // debugFine(covarianceMatrix.toString()); Matrix covarianceTransposed = covarianceMatrix.inverse(); // Normalization factors for Gaussian PDF final double fakt = (1.0 / (Math.sqrt(Math.pow(2 * Math.PI, database.dimensionality()) * covarianceMatrix.det()))); // for each object compute Mahalanobis distance for(DBID id : database) { V x = database.get(id); Vector x_minus_mean = x.minus(mean).getColumnVector(); // Gaussian PDF final double mDist = x_minus_mean.transposeTimes(covarianceTransposed).times(x_minus_mean).get(0, 0); final double prob = fakt * Math.exp(-mDist / 2.0); mm.put(prob); oscores.put(id, prob); } final OutlierScoreMeta meta; if(invert) { double max = mm.getMax() != 0 ? mm.getMax() : 1.; for(DBID id : database.getIDs()) { oscores.put(id, (max - oscores.get(id)) / max); } meta = new BasicOutlierScoreMeta(0.0, 1.0); } else { meta = new InvertedOutlierScoreMeta(mm.getMin(), mm.getMax(), 0.0, Double.POSITIVE_INFINITY); } AnnotationResult<Double> res1 = new AnnotationFromDataStore<Double>(GMOD_PROB, oscores); OrderingResult res2 = new OrderingFromDataStore<Double>(oscores, invert); return new OutlierResult(meta, res1, res2); } }
package de.st_ddt.crazyspawner.commands; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.bukkit.command.CommandSender; import org.bukkit.entity.EntityType; import de.st_ddt.crazyplugin.exceptions.CrazyCommandNoSuchException; import de.st_ddt.crazyplugin.exceptions.CrazyCommandUsageException; import de.st_ddt.crazyplugin.exceptions.CrazyException; import de.st_ddt.crazyspawner.CrazySpawner; import de.st_ddt.crazyspawner.entities.CustomEntitySpawner; import de.st_ddt.crazyutil.ChatHelperExtended; import de.st_ddt.crazyutil.NamedEntitySpawner; import de.st_ddt.crazyutil.modules.permissions.PermissionModule; import de.st_ddt.crazyutil.paramitrisable.EnumParamitrisable; import de.st_ddt.crazyutil.paramitrisable.NamedEntitySpawnerParamitrisable; import de.st_ddt.crazyutil.paramitrisable.StringParamitrisable; import de.st_ddt.crazyutil.paramitrisable.TabbedParamitrisable; import de.st_ddt.crazyutil.source.Localized; import de.st_ddt.crazyutil.source.Permission; public class CommandModifyEntity extends CommandExecutor { public CommandModifyEntity(final CrazySpawner plugin) { super(plugin); } @Override @Localized("CRAZYSPAWNER.COMMAND.MODIFYENTITY $EntityType$ $Name$") public void command(final CommandSender sender, final String[] args) throws CrazyException { if (args.length < 2) throw new CrazyCommandUsageException("<Inheritance/EntityType> [name:String] [Params...]"); final String inheritance = args[0]; final EntityType type; final StringParamitrisable nameParam; final Map<String, TabbedParamitrisable> params = new TreeMap<String, TabbedParamitrisable>(); final NamedEntitySpawner spawner = NamedEntitySpawnerParamitrisable.getNamedEntitySpawner(inheritance); if (spawner == null || !(spawner instanceof CustomEntitySpawner)) { type = EntityType.valueOf(inheritance.toUpperCase()); if (type == null) throw new CrazyCommandNoSuchException("Inheritance/EntityType", inheritance, EnumParamitrisable.getEnumNames(CustomEntitySpawner.getSpawnableEntityTypes())); nameParam = CustomEntitySpawner.getCommandParams(type, params, sender); } else { type = spawner.getType(); nameParam = ((CustomEntitySpawner) spawner).getCommandParams(params, sender); } ChatHelperExtended.readParameters(ChatHelperExtended.shiftArray(args, 1), new HashMap<String, TabbedParamitrisable>(params), nameParam); if (nameParam.getValue() == null) throw new CrazyCommandUsageException("<Inheritance/EntityType> <name:String> [Params...]"); final CustomEntitySpawner entitySpawner = new CustomEntitySpawner(type, params); plugin.addCustomEntity(entitySpawner); plugin.sendLocaleMessage("COMMAND.MODIFYENTITY", sender, type.getName(), nameParam.getValue()); } @Override public List<String> tab(final CommandSender sender, final String[] args) { if (args.length == 1) { final List<String> res = new ArrayList<String>(); res.addAll(EnumParamitrisable.getEnumNames(CustomEntitySpawner.getSpawnableEntityTypes())); for (final CustomEntitySpawner spawner : plugin.getCustomEntities()) res.add(spawner.getName().toUpperCase()); final String inheritance = args[0].toUpperCase(); final Iterator<String> it = res.iterator(); while (it.hasNext()) if (!it.next().startsWith(inheritance)) it.remove(); return res; } else { final String inheritance = args[0]; final EntityType type; final StringParamitrisable nameParam; final Map<String, TabbedParamitrisable> params = new TreeMap<String, TabbedParamitrisable>(); final NamedEntitySpawner spawner = NamedEntitySpawnerParamitrisable.getNamedEntitySpawner(inheritance); if (spawner == null || !(spawner instanceof CustomEntitySpawner)) { type = EntityType.valueOf(inheritance.toUpperCase()); if (type == null) return new ArrayList<String>(0); nameParam = CustomEntitySpawner.getCommandParams(type, params, sender); } else { type = spawner.getType(); nameParam = ((CustomEntitySpawner) spawner).getCommandParams(params, sender); } return ChatHelperExtended.tabHelp(ChatHelperExtended.shiftArray(args, 1), params, nameParam); } } @Override @Permission("crazyspawner.modifyentity") public boolean hasAccessPermission(final CommandSender sender) { return PermissionModule.hasPermission(sender, "crazyspawner.modifyentity"); } }
package edu.mit.streamjit.impl.compiler2; import edu.mit.streamjit.util.Combinators; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.util.HashMap; import java.util.Map; /** * An unsynchronized ConcreteStorage implementation using a Map<Integer, T>. * As its adjust is a no-op, only useful as internal or initialization storage. * @author Jeffrey Bosboom <jeffreybosboom@gmail.com> * @since 10/27/2013 */ public final class MapConcreteStorage implements ConcreteStorage { private static final MethodHandle MAP_GET, MAP_PUT; static { try { MAP_GET = MethodHandles.publicLookup().findVirtual(Map.class, "get", MethodType.methodType(Object.class, Object.class)) .asType(MethodType.methodType(Object.class, Map.class, Integer.class)); MAP_PUT = MethodHandles.publicLookup().findVirtual(Map.class, "put", MethodType.methodType(boolean.class, Object.class, Object.class)) .asType(MethodType.methodType(void.class, Map.class, Integer.class, Object.class)); } catch (NoSuchMethodException | IllegalAccessException ex) { throw new AssertionError("Can't happen! No Map.get?", ex); } } private final Class<?> type; private final Map<Integer, Object> map = new HashMap<>(); private final MethodHandle readHandle, writeHandle; public MapConcreteStorage(Class<?> type) { this.type = type; this.readHandle = MAP_GET.bindTo(map).asType(MethodType.methodType(type, Integer.class)); this.writeHandle = MAP_PUT.bindTo(map).asType(MethodType.methodType(void.class, Integer.class, type)); } @Override public Class<?> type() { return type; } @Override public MethodHandle readHandle() { return readHandle; } @Override public MethodHandle writeHandle() { return writeHandle; } @Override public MethodHandle adjustHandle() { return Combinators.nop(); } @Override public String toString() { return map.toString(); } public static StorageFactory factory() { return new StorageFactory() { @Override public ConcreteStorage make(Storage storage) { return new MapConcreteStorage(storage.type()); } }; } }
package edu.rit.csh.agargiulo.Gatekeeper; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; /** * This is the class for the Main Activity of the Gatekeeper App * * @author Anthony Gargiulo <anthony@agargiulo.com> */ @SuppressLint("NewApi") public class GatekeeperActivity extends Activity { class InvalidCredsOnClickListener implements DialogInterface.OnClickListener { /* (non-Javadoc) * @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int) */ @Override public void onClick (DialogInterface dialog, int whichButton) { switch(whichButton) { case DialogInterface.BUTTON_POSITIVE: startActivity(new Intent(getApplicationContext(), LoginActivity.class)); break; case DialogInterface.BUTTON_NEGATIVE: logout(); break; } } } // This is here because Crawford doesn't // number the doors in a sane manner private static final int FIRST_DOOR = 4; private static final int LAST_DOOR = 9; private HttpsConnector connector; private SharedPreferences prefs; /** * Start the about view */ public void about (View view) { startActivity(new Intent(this, AboutActivity.class)); } /** * * @param doorState * can be one of unknown, unlocked, or locked * @return Gray for unlocked, red for unlocked, or green for locked */ private int getColorFromState (String doorState) { int color; if(doorState.equals("unknown")) { // #DDDDDD = Gray color = Color.parseColor("#DDDDDD"); } else if(doorState.equals("unlocked")) { // #FF8080 = The red used on the web app color = Color.parseColor("#FF8080"); } else if(doorState.equals("locked")) { // #80c080 = The green used on the web app color = Color.parseColor("#80c080"); } else { color = Color.MAGENTA; } return color; } private int getId (int doorId) { switch(doorId) { /* case 1: return R.id.door_1; case 2: return R.id.door_2; case 3: return R.id.door_3; */ case 4: return R.id.door_4; case 5: return R.id.door_5; case 6: return R.id.door_6; case 7: return R.id.door_7; case 8: return R.id.door_8; case 9: return R.id.door_9; default: return -1; } } public void login (View view) { startActivityForResult(new Intent(this, LoginActivity.class), 0); } /** * Deletes the stored username and password from the preferences effectivly * logging out of the app */ private void logout () { // This is possible because awesomeness prefs.edit().remove("username").remove("password").remove("loggedin").commit(); connector = null; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { invalidateOptionsMenu(); } // Log.d("logout", "logged out user"); resetView(); } @Override protected void onActivityResult (int requestCode, int resultCode, Intent data) { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()); String username = prefs.getString("username", ""); if(username == "") { Log.e("Gatekeeper", "LoginActivity.onActivityResults: Invalid username"); prefs.edit().remove("loggedin").commit(); } else { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { invalidateOptionsMenu(); } // Log.d("gatekeeper", username); if(connector == null) { connector = new HttpsConnector(this); } connector.getAllDoors(); } } @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); if(!prefs.getBoolean("loggedin", false)) { // User is not logged in // show Welcome message and the login/about buttons resetView(); } else { // User was already logged in, get ALL of the doors! if(connector == null) { connector = new HttpsConnector(this); } connector.getAllDoors(); } } @Override public boolean onCreateOptionsMenu (Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Override public boolean onOptionsItemSelected (MenuItem item) { switch(item.getItemId()) { case R.id.menu_login: // login(); startActivityForResult(new Intent(this, LoginActivity.class), 0); return true; case R.id.menu_logout: logout(); return true; case R.id.menu_about: startActivity(new Intent(this, AboutActivity.class)); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onPrepareOptionsMenu (Menu menu) { boolean result = super.onPrepareOptionsMenu(menu); if(prefs.getBoolean("loggedin", false)) { menu.findItem(R.id.menu_login).setVisible(false); menu.findItem(R.id.menu_logout).setVisible(true); menu.findItem(R.id.menu_about).setVisible(true); } else { menu.findItem(R.id.menu_logout).setVisible(false); menu.findItem(R.id.menu_login).setVisible(false); menu.findItem(R.id.menu_about).setVisible(false); } return result; } public void popLock (View view) { ((Button) view).setBackgroundColor(Color.parseColor("#FFD280")); int doorId; switch(view.getId()) { /* case R.id.door_1: doorId = 1; break; case R.id.door_2: doorId = 2; break; case R.id.door_3: doorId = 3; break; */ case R.id.door_4: doorId = 4; break; case R.id.door_5: doorId = 5; break; case R.id.door_6: doorId = 6; break; case R.id.door_7: doorId = 7; break; case R.id.door_8: doorId = 8; break; case R.id.door_9: doorId = 9; break; default: doorId = -1; } connector.popDoor(doorId); try { Thread.sleep(1); } catch(InterruptedException e) { Log.e("InterruptedException", "", e); } connector.getAllDoors(); } private void resetView () { Button tempButton; for(int i = FIRST_DOOR; i <= LAST_DOOR; i ++) { tempButton = (Button) findViewById(getId(i)); tempButton.setVisibility(View.GONE); } findViewById(R.id.about_button).setVisibility(View.VISIBLE); findViewById(R.id.welcome_message).setVisibility(View.VISIBLE); findViewById(R.id.login_button).setVisibility(View.VISIBLE); } public void update (String jsonstr) { JSONObject obj; int doorId; String doorState, doorName; Button tempButton; AlertDialog.Builder dialogBuild; AlertDialog dialog; TextView wel_mesg; // RelativeLayout relLayout = (RelativeLayout) // findViewById(R.id.gatekeeper_main_screen); try { obj = new JSONObject(jsonstr); // Log.d("GatekeeperActivity.update(s): ", obj.toString()); if(obj.has("response") && !obj.getString("response").equals("null")) { // all_doors or door_state/id was called JSONArray response = obj.getJSONArray("response"); for(int i = 0; i < response.length(); i ++) { doorState = response.getJSONObject(i).getString("state"); doorId = response.getJSONObject(i).getInt("id"); doorName = response.getJSONObject(i).getString("name"); tempButton = (Button) findViewById(getId(doorId)); tempButton.setText(doorName + ":" + doorState); // tempButton.setBackground // tempButton.setBackgroundColor(getColorFromState(doorState)); tempButton.setBackgroundColor(getColorFromState(doorState)); tempButton.setVisibility(View.VISIBLE); if(doorState.equals("unknown")) { tempButton.setEnabled(false); } } wel_mesg = (TextView) findViewById(R.id.welcome_message); wel_mesg.setVisibility(View.GONE); tempButton = (Button) findViewById(R.id.about_button); tempButton.setVisibility(View.GONE); tempButton = (Button) findViewById(R.id.login_button); tempButton.setVisibility(View.GONE); } else if(obj.has("success") && obj.getString("success").equals("false")) { // We did a lock/pop/unlock opperation InvalidCredsOnClickListener alertListener = new InvalidCredsOnClickListener(); String errorMessage = obj.getString("error") + "\nGo to the log in screen?"; dialogBuild = new AlertDialog.Builder(GatekeeperActivity.this).setTitle( obj.getString("error_type")).setMessage(errorMessage); dialogBuild.setPositiveButton("Yes, please!", alertListener); dialogBuild.setNegativeButton("Clear invalid credentials", alertListener); dialog = dialogBuild.create(); dialog.show(); } } catch(JSONException je) { Log.e(this.getClass().toString(), je.getMessage(), je); return; } } }
package org.bridj; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.Array; import java.nio.*; import java.util.*; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import static org.bridj.SizeT.safeIntCast; /** * Pointer to a native memory location.<br/> * Pointer is the entry point of any pointer-related operation in BridJ. * <p> * <u><b>Manipulating memory</b></u> * <p> * <ul> * <li>Wrapping a memory address as a pointer : {@link Pointer#pointerToAddress(long)} * </li> * <li>Reading / writing a primitive from / to the pointed memory location :<br/> #foreach ($prim in $primitives) * {@link Pointer#get${prim.CapName}()} / {@link Pointer#set${prim.CapName}(${prim.Name})} ; With an offset : {@link Pointer#get${prim.CapName}(long)} / {@link Pointer#set${prim.CapName}(long, ${prim.Name})}<br/> #end #foreach ($sizePrim in ["SizeT", "CLong"]) * {@link Pointer#get${sizePrim}()} / {@link Pointer#set${sizePrim}(long)} ; With an offset : {@link Pointer#get${sizePrim}(long)} / {@link Pointer#set${sizePrim}(long, long)} <br/> #end * </li> * <li>Reading / writing an array of primitives from / to the pointed memory location :<br/> #foreach ($prim in $primitives) * {@link Pointer#get${prim.CapName}s(int)} / {@link Pointer#set${prim.CapName}s(${prim.Name}[])} ; With an offset : {@link Pointer#get${prim.CapName}s(long, int)} / {@link Pointer#set${prim.CapName}s(long, ${prim.Name}[])}<br/> #end #foreach ($sizePrim in ["SizeT", "CLong"]) * {@link Pointer#get${sizePrim}s(int)} / {@link Pointer#set${sizePrim}s(long[])} ; With an offset : {@link Pointer#get${sizePrim}s(long, int)} / {@link Pointer#set${sizePrim}s(long, long[])}<br/> #end * </li> * <li>Reading / writing an NIO buffer of primitives from / to the pointed memory location :<br/> #foreach ($prim in $primitivesNoBool) * {@link Pointer#get${prim.BufferName}(long)} (can be used for writing as well) / {@link Pointer#set${prim.CapName}s(${prim.BufferName})}<br/> #end * </li> * <li>Reading / writing a String from / to the pointed memory location using the default charset :<br/> #foreach ($string in ["C", "WideC"]) * {@link Pointer#get${string}String()} / {@link Pointer#set${string}String(String)} ; With an offset : {@link Pointer#get${string}String(long)} / {@link Pointer#set${string}String(long, String)}<br/> #end * </li> * <li>Reading / writing a String with control on the charset :<br/> * {@link Pointer#getString(long, Charset, StringType)} / {@link Pointer#setString(long, String, Charset, StringType)}<br/> * </ul> * <p> * <u><b>Allocating memory</b></u> * <p> * <ul> * <li>Getting the pointer to a struct / a C++ class / a COM object : * {@link Pointer#pointerTo(NativeObject)} * </li> * <li>Allocating a primitive with / without an initial value (zero-initialized) :<br/> #foreach ($prim in $primitives) * {@link Pointer#pointerTo${prim.CapName}(${prim.Name})} / {@link Pointer#allocate${prim.CapName}()}<br/> #end #foreach ($sizePrim in ["SizeT", "CLong"]) * {@link Pointer#pointerTo${sizePrim}(long)} / {@link Pointer#allocate${sizePrim}()}<br/> #end * </li> * <li>Allocating an array of primitives with / without initial values (zero-initialized) :<br/> #foreach ($prim in $primitives) * {@link Pointer#pointerTo${prim.CapName}s(${prim.Name}[])} or {@link Pointer#pointerTo${prim.CapName}s(${prim.BufferName})} / {@link Pointer#allocate${prim.CapName}s(long)}<br/> #end #foreach ($sizePrim in ["SizeT", "CLong"]) * {@link Pointer#pointerTo${sizePrim}s(long[])} / {@link Pointer#allocate${sizePrim}s(long)}<br/> #end * {@link Pointer#pointerToBuffer(Buffer)} / n/a<br/> * </li> * <li>Allocating a native String :<br/> #foreach ($string in ["C", "WideC", "Pascal", "WidePascal"]) * {@link Pointer#pointerTo${string}String(String)} (default charset)<br/> #end * {@link Pointer#pointerToString(String, Charset, StringType)}<br/> * </li> * </ul> */ public class Pointer<T> implements Comparable<Pointer<?>>, List<T>//Iterable<T> //, com.sun.jna.Pointer<Pointer<T>> { #macro (docAllocateCopy $cPrimName $primWrapper) /** * Allocate enough memory for a single $cPrimName value, copy the value provided in argument into it and return a pointer to that memory.<br/> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to Pointer.release().<br/> * The pointer won't be garbage-collected until all its clones / views are garbage-collected themselves (see {@link #clone()}, {@link #offset(long)}, {@link #next(long)}, {@link #next()}).<br/> * @param value initial value for the created memory location * @return pointer to a new memory location that initially contains the $cPrimName value given in argument */ #end #macro (docAllocateArrayCopy $cPrimName $primWrapper) /** * Allocate enough memory for values.length $cPrimName values, copy the values provided as argument into it and return a pointer to that memory.<br/> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to Pointer.release().<br/> * The pointer won't be garbage-collected until all its clones / views are garbage-collected themselves (see {@link #clone()}, {@link #offset(long)}, {@link #next(long)}, {@link #next()}).<br/> * The returned pointer is also an {@code Iterable<$primWrapper>} instance that can be safely iterated upon : <pre>{@code for (float f : pointerTo(1f, 2f, 3.3f)) System.out.println(f); }</pre> * @param values initial values for the created memory location * @return pointer to a new memory location that initially contains the $cPrimName consecutive values provided in argument */ #end #macro (docAllocateArray2DCopy $cPrimName $primWrapper) /** * Allocate enough memory for all the values in the 2D $cPrimName array, copy the values provided as argument into it as packed multi-dimensional C array and return a pointer to that memory.<br/> * Assumes that all of the subarrays of the provided array are non null and have the same size.<br/> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to Pointer.release().<br/> * The pointer won't be garbage-collected until all its clones / views are garbage-collected themselves (see {@link #clone()}, {@link #offset(long)}, {@link #next(long)}, {@link #next()}).<br/> * @param values initial values for the created memory location * @return pointer to a new memory location that initially contains the $cPrimName values provided in argument packed as a 2D C array would be */ #end #macro (docAllocateArray3DCopy $cPrimName $primWrapper) /** * Allocate enough memory for all the values in the 3D $cPrimName array, copy the values provided as argument into it as packed multi-dimensional C array and return a pointer to that memory.<br/> * Assumes that all of the subarrays of the provided array are non null and have the same size.<br/> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to Pointer.release().<br/> * The pointer won't be garbage-collected until all its clones / views are garbage-collected themselves (see {@link #clone()}, {@link #offset(long)}, {@link #next(long)}, {@link #next()}).<br/> * @param values initial values for the created memory location * @return pointer to a new memory location that initially contains the $cPrimName values provided in argument packed as a 3D C array would be */ #end #macro (docAllocate $cPrimName $primWrapper) /** * Allocate enough memory for a $cPrimName value and return a pointer to it.<br/> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to Pointer.release().<br/> * @return pointer to a single zero-initialized $cPrimName value */ #end #macro (docAllocateArray $cPrimName $primWrapper) /** * Allocate enough memory for arrayLength $cPrimName values and return a pointer to that memory.<br/> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to Pointer.release().<br/> * The pointer won't be garbage-collected until all its clones / views are garbage-collected themselves (see {@link Pointer#clone()}, {@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br/> * The returned pointer is also an {@code Iterable<$primWrapper>} instance that can be safely iterated upon. * @return pointer to arrayLength zero-initialized $cPrimName consecutive values */ #end #macro (docAllocateArray2D $cPrimName $primWrapper) /** * Allocate enough memory for dim1 * dim2 $cPrimName values in a packed multi-dimensional C array and return a pointer to that memory.<br/> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to Pointer.release().<br/> * The pointer won't be garbage-collected until all its clones / views are garbage-collected themselves (see {@link Pointer#clone()}, {@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br/> * @return pointer to dim1 * dim2 zero-initialized $cPrimName consecutive values */ #end #macro (docAllocateArray3D $cPrimName $primWrapper) /** * Allocate enough memory for dim1 * dim2 * dim3 $cPrimName values in a packed multi-dimensional C array and return a pointer to that memory.<br/> * The memory will be automatically be freed when the pointer is garbage-collected or upon manual calls to Pointer.release().<br/> * The pointer won't be garbage-collected until all its clones / views are garbage-collected themselves (see {@link Pointer#clone()}, {@link Pointer#offset(long)}, {@link Pointer#next(long)}, {@link Pointer#next()}).<br/> * @return pointer to dim1 * dim2 * dim3 zero-initialized $cPrimName consecutive values */ #end #macro (docGet $cPrimName $primWrapper) /** * Read a $cPrimName value from the pointed memory location */ #end #macro (docGetOffset $cPrimName $primWrapper) /** * Read a $cPrimName value from the pointed memory location shifted by a byte offset */ #end #macro (docGetArray $cPrimName $primWrapper) /** * Read an array of $cPrimName values of the specified size from the pointed memory location */ #end #macro (docGetArrayOffset $cPrimName $primWrapper) /** * Read an array of $cPrimName values of the specified size from the pointed memory location shifted by a byte offset */ #end #macro (docSet $cPrimName $primWrapper) /** * Write a $cPrimName value to the pointed memory location */ #end #macro (docSetOffset $cPrimName $primWrapper) /** * Write a $cPrimName value to the pointed memory location shifted by a byte offset */ #end #macro (docSetArray $cPrimName $primWrapper) /** * Write an array of $cPrimName values to the pointed memory location */ #end #macro (docSetArrayOffset $cPrimName $primWrapper) /** * Write an array of $cPrimName values to the pointed memory location shifted by a byte offset */ #end /** The NULL pointer is <b>always</b> Java's null value */ public static final Pointer NULL = null; /** * Size of a pointer in bytes. <br> * This is 4 bytes in a 32 bits environment and 8 bytes in a 64 bits environment.<br> * Note that some 64 bits environments allow for 32 bits JVM execution (using the -d32 command line argument for Sun's JVM, for instance). In that case, Java programs will believe they're executed in a 32 bits environment. */ public static final int SIZE = JNI.POINTER_SIZE; static { JNI.initLibrary(); } private static long UNKNOWN_VALIDITY = -1; private static long NO_PARENT = 0; private final PointerIO<T> io; private final long peer, offsetInParent; private final Pointer<?> parent; private Object sibling; private final long validStart, validEnd; private final boolean ordered; /** * Object responsible for reclamation of some pointed memory when it's not used anymore. */ public interface Releaser { void release(Pointer<?> p); } Pointer(PointerIO<T> io, long peer) { this(io, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, 0, null); } Pointer(PointerIO<T> io, long peer, boolean ordered, long validStart, long validEnd, Pointer<?> parent, long offsetInParent, Object sibling) { this.io = io; this.peer = peer; this.ordered = ordered; this.validStart = validStart; this.validEnd = validEnd; this.parent = parent; this.offsetInParent = offsetInParent; this.sibling = sibling; } /** * Create a {@code Pointer<T>} type. <br> * For Instance, {@code Pointer.pointerType(Integer.class) } returns a type that represents {@code Pointer<Integer> } */ public static Type pointerType(Type targetType) { return org.bridj.util.DefaultParameterizedType.paramType(Pointer.class, targetType); } /** * Create a {@code IntValuedEnum<T>} type. <br> * For Instance, {@code Pointer.intEnumType(SomeEnum.class) } returns a type that represents {@code IntValuedEnum<SomeEnum> } */ public static <E extends Enum<E>> Type intEnumType(Class<? extends IntValuedEnum<E>> targetType) { return org.bridj.util.DefaultParameterizedType.paramType(IntValuedEnum.class, targetType); } /** * Manually release the memory pointed by this pointer if it was allocated on the Java side.<br> * If the pointer is an offset version of another pointer (using {@link Pointer#share(long)} or {@link Pointer#next(long)}, for instance), this method tries to release the original pointer.<br> * If the memory was not allocated from the Java side, this method does nothing either.<br> * If the memory was already successfully released, this throws a RuntimeException. * @throws RuntimeException if the pointer was already released */ public void release() { if (sibling instanceof Pointer) ((Pointer)sibling).release(); sibling = null; } /** * Compare to another pointer based on pointed addresses. * @param p other pointer * @return 1 if this pointer's address is greater than p's (or if p is null), -1 if the opposite is true, 0 if this and p point to the same memory location. */ @Override public int compareTo(Pointer<?> p) { if (p == null) return 1; long p1 = getPeer(), p2 = p.getPeer(); return p1 == p2 ? 0 : p1 < p2 ? -1 : 1; } /** * Compare the byteCount bytes at the memory location pointed by this pointer to the byteCount bytes at the memory location pointer by other using the C memcmp function.<br> * @return 0 if the two memory blocks are equal, -1 if this pointer's memory is "less" than the other and 1 otherwise. */ public int compareBytes(Pointer<?> other, long byteCount) { return compareBytes(0, other, 0, byteCount); } /** * Compare the byteCount bytes at the memory location pointed by this pointer shifted by byteOffset to the byteCount bytes at the memory location pointer by other shifted by otherByteOffset using the C memcmp function.<br> * @return 0 if the two memory blocks are equal, -1 if this pointer's memory is "less" than the other and 1 otherwise. */ public int compareBytes(long byteOffset, Pointer<?> other, long otherByteOffset, long byteCount) { return JNI.memcmp(getCheckedPeer(byteOffset, byteCount), other.getCheckedPeer(otherByteOffset, byteCount), byteCount); } /** * Compute a hash code based on pointed address. */ @Override public int hashCode() { int hc = new Long(getPeer()).hashCode(); return hc; } private final long getCheckedPeer(long byteOffset, long validityCheckLength) { long offsetPeer = getPeer() + byteOffset; //*/ /** * Returns a pointer which address value was obtained by this pointer's by adding a byte offset.<br/> * The returned pointer will prevent the memory associated to this pointer from being automatically reclaimed as long as it lives, unless Pointer.release() is called on the originally-allocated pointer. * @param byteOffset offset in bytes of the new pointer vs. this pointer. The expression {@code p.offset(byteOffset).getPeer() - p.getPeer() == byteOffset} is always true. */ public Pointer<T> offset(long byteOffset) { return offset(byteOffset, getIO()); } <U> Pointer<U> offset(long byteOffset, PointerIO<U> pio) { if (byteOffset == 0) return pio == this.io ? (Pointer<U>)this : withIO(pio); long newPeer = getPeer() + byteOffset; Object newSibling = getSibling() != null ? getSibling() : this; if (validStart == UNKNOWN_VALIDITY) return newPointer(pio, newPeer, ordered, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, null, newSibling); if (newPeer >= validEnd || newPeer < validStart) throw new IndexOutOfBoundsException("Invalid pointer offset !"); return newPointer(pio, newPeer, ordered, validStart, validEnd, null, NO_PARENT, null, newSibling); } /** * Creates a pointer that has the given number of valid bytes ahead.<br> * If the pointer was already bound, the valid bytes must be lower or equal to the current getRemainingBytes() value. */ public Pointer<T> validBytes(long byteCount) { long peer = getPeer(); long newValidEnd = peer + byteCount; if (validStart == 0 && validEnd == newValidEnd) return this; if (validEnd != UNKNOWN_VALIDITY && newValidEnd > validEnd) throw new IndexOutOfBoundsException("Cannot extend validity of pointed memory from " + validEnd + " to " + newValidEnd); Object newSibling = getSibling() != null ? getSibling() : this; return newPointer(getIO(), peer, ordered, peer, newValidEnd, parent, offsetInParent, null, newSibling); } /** * Creates a pointer that has the given number of valid elements ahead.<br> * If the pointer was already bound, the valid bytes must be lower or equal to the current getRemainingElements() value. */ public Pointer<T> validElements(long elementCount) { PointerIO<T> io = getIO(); if (io == null) throwBecauseUntyped("Cannot define elements validity"); return validBytes(elementCount * io.getTargetSize()); } /** * Returns a pointer to this pointer.<br/> * It will only succeed if this pointer was dereferenced from another pointer.<br/> * Let's take the following C++ code : * <pre>{@code int** pp = ...; int* p = pp[10]; int** ref = &p; ASSERT(pp == ref); }</pre> * Here is its equivalent Java code : * <pre>{@code Pointer<Pointer<Integer>> pp = ...; Pointer<Integer> p = pp.get(10); Pointer<Pointer<Integer>> ref = p.getReference(); assert pp.equals(ref); }</pre> */ public Pointer<Pointer<T>> getReference() { if (parent == null) throw new UnsupportedOperationException("Cannot get reference to this pointer, it wasn't created from Pointer.getPointer(offset) or from a similar method."); PointerIO io = getIO(); return parent.offset(offsetInParent).withIO(io == null ? null : io.getReferenceIO()); } /** * Get the address of the memory pointed to by this pointer ("cast this pointer to long", in C jargon).<br> * This is equivalent to the C code {@code (size_t)&pointer} * @return Address of the memory pointed to by this pointer */ public final long getPeer() { return peer; } /** * Cast this pointer to another pointer type * @param newIO */ public <U> Pointer<U> withIO(PointerIO<U> newIO) { return cloneAs(isOrdered(), newIO); } /** * Create a clone of this pointer that has the byte order provided in argument, or return this if this pointer already uses the requested byte order. * @param order byte order (endianness) of the returned pointer */ public Pointer<T> order(ByteOrder order) { if (order.equals(ByteOrder.nativeOrder()) == isOrdered()) return this; return cloneAs(!isOrdered(), getIO()); } /** * Get the byte order (endianness) of this pointer. */ public ByteOrder order() { return isOrdered() ? ByteOrder.nativeOrder() : ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN; } <U> Pointer<U> cloneAs(boolean ordered, PointerIO<U> newIO) { if (newIO == io && ordered == isOrdered()) return (Pointer<U>)this; else return newPointer(newIO, getPeer(), ordered, getValidStart(), getValidEnd(), getParent(), getOffsetInParent(), null, getSibling() != null ? getSibling() : this); } /** * Get the PointerIO instance used by this pointer to get and set pointed values. */ public final PointerIO<T> getIO() { return io; } /** * Whether this pointer reads data in the system's native byte order or not. * See {@link Pointer#order()}, {@link Pointer#order(ByteOrder)} */ final boolean isOrdered() { return ordered; } final long getOffsetInParent() { return offsetInParent; } final Pointer<?> getParent() { return parent; } final Object getSibling() { return sibling; } final long getValidEnd() { return validEnd; } final long getValidStart() { return validStart; } /** * Cast this pointer to another pointer type<br> * The following C code :<br> * <code>{@code * T* pointerT = ...; * U* pointerU = (U*)pointerT; * }</code><br> * Can be translated to the following Java code :<br> * <code>{@code * Pointer<T> pointerT = ...; * Pointer<U> pointerU = pointerT.as(U.class); // or pointerT.asPointerTo(U.class); * }</code><br> * @param <U> * @param newIO * @return */ public <U> Pointer<U> asPointerTo(Type type) { PointerIO<U> pio = PointerIO.getInstance(type); return withIO(pio); } /** * Cast this pointer to another pointer type<br>. * The following C code :<br> * <code>{@code * T* pointerT = ...; * U* pointerU = (U*)pointerT; * }</code><br> * Can be translated to the following Java code :<br> * <code>{@code * Pointer<T> pointerT = ...; * Pointer<U> pointerU = pointerT.as(U.class); // or pointerT.asPointerTo(U.class); * }</code><br> * {@link Pointer#asPointerTo(Type)} * @param <U> * @param newIO * @return */ public <U> Pointer<U> as(Class<U> type) { return asPointerTo(type); } /** * Get the amount of memory known to be valid from this pointer, or -1 if it is unknown.<br/> * Memory validity information is available when the pointer was created out of another pointer (with {@link #offset(long)}, {@link #next()}, {@link #next(long)}) or from a direct NIO buffer ({@link #pointerToBuffer(Buffer)}, {@link #pointerToInts(IntBuffer)}...) * @return amount of bytes that can be safely read or written from this pointer, or -1 if this amount is unknown */ public long getRemainingBytes() { long ve = getValidEnd(); return ve == UNKNOWN_VALIDITY ? -1 : ve - getPeer(); } /** * Get the amount of memory known to be valid from this pointer (expressed in elements of the target type, see {@link #getTargetType()}) or -1 if it is unknown.<br/> * Memory validity information is available when the pointer was created out of another pointer (with {@link #offset(long)}, {@link #next()}, {@link #next(long)}) or from a direct NIO buffer ({@link #pointerToBuffer(Buffer)}, {@link #pointerToInts(IntBuffer)}...) * @return amount of elements that can be safely read or written from this pointer, or -1 if this amount is unknown */ public long getRemainingElements() { long bytes = getRemainingBytes(); long elementSize = getTargetSize(); if (bytes < 0 || elementSize <= 0) return -1; return bytes / elementSize; } public ListIterator<T> iterator() { return new ListIterator<T>() { Pointer<T> next = Pointer.this.getRemainingElements() > 0 ? Pointer.this : null; Pointer<T> previous; @Override public T next() { if (next == null) throw new NoSuchElementException(); T value = next.get(); previous = next; next = next.getRemainingElements() > 1 ? next.next(1) : null; return value; } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public boolean hasNext() { long rem; return next != null && ((rem = next.getRemainingBytes()) < 0 || rem > 0); } @Override public void add(T o) { throw new UnsupportedOperationException(); } @Override public boolean hasPrevious() { return previous != null; } @Override public int nextIndex() { throw new UnsupportedOperationException(); } @Override public T previous() { //TODO return previous; throw new UnsupportedOperationException(); } @Override public int previousIndex() { throw new UnsupportedOperationException(); } @Override public void set(T o) { if (previous == null) throw new NoSuchElementException("You haven't called next() prior to calling ListIterator.set(E)"); previous.set(o); } }; } /** * Get a pointer to a native object (C++ or ObjectiveC class, struct, union, callback...) */ public static <N extends NativeObject> Pointer<N> pointerTo(N instance) { return pointerTo(instance, null); } /** * Get a pointer to a native object, specifying the type of the pointer's target.<br/> * In C++, the address of the pointer to an object as its canonical class is not always the same as the address of the pointer to the same object cast to one of its parent classes. */ public static <R extends NativeObject> Pointer<R> pointerTo(NativeObject instance, Class<R> targetType) { return instance == null ? null : (Pointer<R>)instance.peer; } /** * Get the address of a native object, specifying the type of the pointer's target (same as {@code pointerTo(instance, targetType).getPeer()}, see {@link pointerTo(NativeObject, Class)}).<br/> * In C++, the address of the pointer to an object as its canonical class is not always the same as the address of the pointer to the same object cast to one of its parent classes. */ public static long getAddress(NativeObject instance, Class targetType) { return getPeer(pointerTo(instance, targetType)); } #docGetOffset("native object", "O extends NativeObject") public <O extends NativeObject> O getNativeObject(long byteOffset, Type type) { return (O)BridJ.createNativeObjectFromPointer((Pointer<O>)this, type); } #docGetOffset("native object", "O extends NativeObject") public <O extends NativeObject> O getNativeObject(long byteOffset, Class<O> type) { return (O)getNativeObject(byteOffset, (Type)type); } #docGet("native object", "O extends NativeObject") public <O extends NativeObject> O getNativeObject(Class<O> type) { return getNativeObject(0, type); } #docGet("native object", "O extends NativeObject") public <O extends NativeObject> O getNativeObject(Type type) { O o = (O)getNativeObject(0, type); return o; } /** * Check that the pointer's peer is aligned to the target type alignment. * @throw RuntimeException If the target type of this pointer is unknown * @return getPeer() % alignment == 0 */ public boolean isAligned() { PointerIO<T> io = getIO(); if (io == null) throwBecauseUntyped("Cannot check alignment"); return isAligned(io.getTargetAlignment()); } /** * Check that the pointer's peer is aligned to the given alignment. * If the pointer has no peer, this method returns true. * @return getPeer() % alignment == 0 */ public boolean isAligned(int alignment) { return isAligned(getPeer(), alignment); } /** * Check that the provided address is aligned to the given alignment. * @return address % alignment == 0 */ protected static boolean isAligned(long address, int alignment) { switch (alignment) { case 1: return true; case 2: return (address & 1) == 0; case 4: return (address & 3) == 0; case 8: return (address & 7) == 0; case 16: return (address & 15) == 0; case 32: return (address & 31) == 0; case 64: return (address & 63) == 0; default: return (address % alignment) == 0; } } /** * Dereference this pointer (*ptr).<br/> Take the following C++ code fragment : <pre>{@code int* array = new int[10]; for (int index = 0; index < 10; index++, array++) printf("%i\n", *array); }</pre> Here is its equivalent in Java : <pre>{@code import static org.bridj.Pointer.*; Pointer<Integer> array = allocateInts(10); for (int index = 0; index < 10; index++) { System.out.println("%i\n".format(array.get())); array = array.next(); } }</pre> Here is a simpler equivalent in Java : <pre>{@code import static org.bridj.Pointer.*; Pointer<Integer> array = allocateInts(10); for (int value : array) // array knows its size, so we can iterate on it System.out.println("%i\n".format(value)); }</pre> @throws RuntimeException if called on an untyped {@code Pointer<?>} instance (see {@link Pointer#getTargetType()}) */ public T get() { return get(0); } /** Gets the n-th element from this pointer.<br/> This is equivalent to the C/C++ square bracket syntax.<br/> Take the following C++ code fragment : <pre>{@code int* array = new int[10]; int index = 5; int value = array[index]; }</pre> Here is its equivalent in Java : <pre>{@code import static org.bridj.Pointer.*; Pointer<Integer> array = allocateInts(10); int index = 5; int value = array.get(index); }</pre> @param index offset in pointed elements at which the value should be copied. Can be negative if the pointer was offset and the memory before it is valid. @throws RuntimeException if called on an untyped {@code Pointer<?>} instance ({@link Pointer#getTargetType()}) */ public T get(long index) { PointerIO<T> io = getIO(); if (io == null) throwBecauseUntyped("Cannot get pointed value"); return io.get(this, index); } /** Assign a value to the pointed memory location.<br/> Take the following C++ code fragment : <pre>{@code int* array = new int[10]; for (int index = 0; index < 10; index++, array++) { int value = index; *array = value; } }</pre> Here is its equivalent in Java : <pre>{@code import static org.bridj.Pointer.*; Pointer<Integer> array = allocateInts(10); for (int index = 0; index < 10; index++) { int value = index; array.set(value); array = array.next(); } }</pre> @throws RuntimeException if called on an untyped {@code Pointer<?>} instance ({@link Pointer#getTargetType()}) */ public T set(T value) { return set(0, value); } static void throwBecauseUntyped(String message) { throw new RuntimeException("Pointer is not typed (call Pointer.asPointerTo(Type) to create a typed pointer) : " + message); } static void throwUnexpected(Throwable ex) { throw new RuntimeException("Unexpected error", ex); } /** Sets the n-th element from this pointer.<br/> This is equivalent to the C/C++ square bracket assignment syntax.<br/> Take the following C++ code fragment : <pre>{@code float* array = new float[10]; int index = 5; float value = 12; array[index] = value; }</pre> Here is its equivalent in Java : <pre>{@code import static org.bridj.Pointer.*; Pointer<Float> array = allocateFloats(10); int index = 5; float value = 12; array.set(index, value); }</pre> @param index offset in pointed elements at which the value should be copied. Can be negative if the pointer was offset and the memory before it is valid. @param value value to set at pointed memory location @throws RuntimeException if called on an untyped {@code Pointer<?>} instance ({@link Pointer#getTargetType()}) */ public T set(long index, T value) { PointerIO<T> io = getIO(); if (io == null) throwBecauseUntyped("Cannot set pointed value"); io.set(this, index, value); return value; } /** * Get a pointer's peer (see {@link Pointer#getPeer}), or zero if the pointer is null. */ public static long getPeer(Pointer<?> pointer) { return pointer == null ? 0 : pointer.getPeer(); } /** * Get the unitary size of the pointed elements in bytes. * @throws RuntimeException if the target type is unknown (see {@link Pointer#getTargetType()}) */ public long getTargetSize() { PointerIO<T> io = getIO(); if (io == null) throwBecauseUntyped("Cannot compute target size"); return io.getTargetSize(); } /** * Returns a pointer to the next target. * Same as incrementing a C pointer of delta elements, but creates a new pointer instance. * @return next(1) */ public Pointer<T> next() { return next(1); } /** * Returns a pointer to the n-th next (or previous) target. * Same as incrementing a C pointer of delta elements, but creates a new pointer instance. * @return offset(getTargetSize() * delta) */ public Pointer<T> next(long delta) { PointerIO<T> io = getIO(); if (io == null) throwBecauseUntyped("Cannot get pointers to next or previous targets"); return offset(io.getTargetSize() * delta); } /** * Release pointers, if they're not null (see {@link Pointer#release}). */ public static void release(Pointer... pointers) { for (Pointer pointer : pointers) if (pointer != null) pointer.release(); } /** * Test equality of the pointer using the address.<br> * @return true if and only if obj is a Pointer instance and {@code obj.getPeer() == this.getPeer() } */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Pointer)) return false; Pointer p = (Pointer)obj; return getPeer() == p.getPeer(); } /** * Create a pointer out of a native memory address * @param address native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == address } */ @Deprecated public static Pointer<?> pointerToAddress(long peer) { return newPointer(null, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, null, null); } /** * Create a pointer out of a native memory address * @param size number of bytes known to be readable at the pointed address * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ @Deprecated public static Pointer<?> pointerToAddress(long peer, long size) { return newPointer(null, peer, true, peer, peer + size, null, NO_PARENT, null, null); } /** * Create a pointer out of a native memory address * @param targetClass type of the elements pointed by the resulting pointer * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ public static Pointer<?> pointerToAddress(long peer, Class<?> targetClass, final Releaser releaser) { return newPointer(PointerIO.getInstance(targetClass), peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, -1, null, null); } /** * Create a pointer out of a native memory address * @param io PointerIO instance that knows how to read the elements pointed by the resulting pointer * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ static <P> Pointer<P> pointerToAddress(long peer, PointerIO<P> io) { return newPointer(io, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, null, null); } /** * Create a pointer out of a native memory address * @param io PointerIO instance that knows how to read the elements pointed by the resulting pointer * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ static <P> Pointer<P> pointerToAddress(long peer, PointerIO<P> io, Releaser releaser) { return newPointer(io, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, releaser, null); } /** * Create a pointer out of a native memory address * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ @Deprecated public static Pointer<?> pointerToAddress(long peer, Releaser releaser) { return newPointer(null, peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, NO_PARENT, releaser, null); } /** * Create a pointer out of a native memory address * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param size number of bytes known to be readable at the pointed address * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ public static Pointer<?> pointerToAddress(long peer, long size, Releaser releaser) { return newPointer(null, peer, true, peer, peer + size, null, NO_PARENT, releaser, null); } /** * Create a pointer out of a native memory address * @param targetClass type of the elements pointed by the resulting pointer * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ @Deprecated public static <P> Pointer<P> pointerToAddress(long peer, Class<P> targetClass) { return newPointer((PointerIO<P>)PointerIO.getInstance(targetClass), peer, true, UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, null, -1, null, null); } /** * Create a pointer out of a native memory address * @param size number of bytes known to be readable at the pointed address * @param io PointerIO instance that knows how to read the elements pointed by the resulting pointer * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ static <U> Pointer<U> pointerToAddress(long peer, long size, PointerIO<U> io) { return newPointer(io, peer, true, peer, peer + size, null, NO_PARENT, null, null); } /** * Create a pointer out of a native memory address * @param releaser object responsible for reclaiming the native memory once whenever the returned pointer is garbage-collected * @param peer native memory address that is to be converted to a pointer * @return a pointer with the provided address : {@code pointer.getPeer() == peer } */ static <U> Pointer<U> newPointer( PointerIO<U> io, long peer, boolean ordered, long validStart, long validEnd, Pointer<?> parent, long offsetInParent, final Releaser releaser, Object sibling) { if (peer == 0) return null; if (validEnd != UNKNOWN_VALIDITY) { long size = validEnd - validStart; if (size <= 0) return null; } if (releaser == null) return new Pointer<U>(io, peer, ordered, validStart, validEnd, parent, offsetInParent, sibling); else { assert sibling == null; return new Pointer<U>(io, peer, ordered, validStart, validEnd, parent, offsetInParent, sibling) { private Releaser rel = releaser; @Override public synchronized void release() { if (rel != null) { rel.release(this); rel = null; } } protected void finalize() { release(); } }; } } #docAllocate("typed pointer", "P extends TypedPointer") public static <P extends TypedPointer> Pointer<P> allocateTypedPointer(Class<P> type) { return (Pointer<P>)(Pointer)allocate(PointerIO.getInstance(type)); } #docAllocateArray("typed pointer", "P extends TypedPointer") public static <P extends TypedPointer> Pointer<P> allocateTypedPointers(Class<P> type, long arrayLength) { return (Pointer<P>)(Pointer)allocateArray(PointerIO.getInstance(type), arrayLength); } /** * Create a memory area large enough to hold a pointer. * @param targetType target type of the pointer values to be stored in the allocated memory * @return a pointer to a new memory area large enough to hold a single typed pointer */ public static <P> Pointer<Pointer<P>> allocatePointer(Class<P> targetType) { return (Pointer<Pointer<P>>)(Pointer)allocate(PointerIO.getPointerInstance(targetType)); } /** * Create a memory area large enough to hold a pointer. * @param targetType target type of the pointer values to be stored in the allocated memory * @return a pointer to a new memory area large enough to hold a single typed pointer */ public static <P> Pointer<Pointer<P>> allocatePointer(Type targetType) { return (Pointer<Pointer<P>>)(Pointer)allocate(PointerIO.getPointerInstance(targetType)); } /** * Create a memory area large enough to hold a pointer to a pointer * @param targetType target type of the values pointed by the pointer values to be stored in the allocated memory * @return a pointer to a new memory area large enough to hold a single typed pointer */ public static <P> Pointer<Pointer<Pointer<P>>> allocatePointerPointer(Type targetType) { return allocatePointer(pointerType(targetType)); }/** * Create a memory area large enough to hold a pointer to a pointer * @param targetType target type of the values pointed by the pointer values to be stored in the allocated memory * @return a pointer to a new memory area large enough to hold a single typed pointer */ public static <P> Pointer<Pointer<Pointer<P>>> allocatePointerPointer(Class<P> targetType) { return allocatePointerPointer(targetType); } #docAllocate("untyped pointer", "Pointer<?>") /** * Create a memory area large enough to hold an untyped pointer. * @return a pointer to a new memory area large enough to hold a single untyped pointer */ public static <V> Pointer<Pointer<?>> allocatePointer() { return (Pointer)allocate(PointerIO.getPointerInstance()); } #docAllocateArray("untyped pointer", "Pointer<?>") public static Pointer<Pointer<?>> allocatePointers(int arrayLength) { return (Pointer<Pointer<?>>)(Pointer)allocateArray(PointerIO.getPointerInstance(), arrayLength); } /** * Create a memory area large enough to hold an array of arrayLength typed pointers. * @param targetType target type of element pointers in the resulting pointer array. * @param arrayLength size of the allocated array, in elements * @return a pointer to a new memory area large enough to hold an array of arrayLength typed pointers */ public static <P> Pointer<Pointer<P>> allocatePointers(Class<P> targetType, int arrayLength) { return (Pointer<Pointer<P>>)(Pointer)allocateArray(PointerIO.getPointerInstance(targetType), arrayLength); // TODO } /** * Create a memory area large enough to a single items of type elementClass. * @param elementClass type of the array elements * @return a pointer to a new memory area large enough to hold a single item of type elementClass. */ public static <V> Pointer<V> allocate(Class<V> elementClass) { return allocateArray(elementClass, 1); } public static <V> Pointer<V> allocate(PointerIO<V> io) { long targetSize = io.getTargetSize(); if (targetSize < 0) throwBecauseUntyped("Cannot allocate array "); return allocateBytes(io, targetSize, null); } /** * Create a memory area large enough to hold arrayLength items of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) * @param elementClass type of the array elements * @param arrayLength length of the array in elements * @return a pointer to a new memory area large enough to hold arrayLength items of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) */ public static <V> Pointer<V> allocateArray(PointerIO<V> io, long arrayLength) { long targetSize = io.getTargetSize(); if (targetSize < 0) throwBecauseUntyped("Cannot allocate array "); return allocateBytes(io, targetSize * arrayLength, null); } /** * Create a memory area large enough to hold arrayLength items of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) * @param elementClass type of the array elements * @param arrayLength length of the array in elements * @param beforeDeallocation fake releaser that should be run just before the memory is actually released, for instance in order to call some object destructor * @return a pointer to a new memory area large enough to hold arrayLength items of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) */ public static <V> Pointer<V> allocateArray(PointerIO<V> io, long arrayLength, final Releaser beforeDeallocation) { long targetSize = io.getTargetSize(); if (targetSize < 0) throwBecauseUntyped("Cannot allocate array "); return allocateBytes(io, targetSize * arrayLength, beforeDeallocation); } /** * Create a memory area large enough to hold byteSize consecutive bytes and return a pointer to elements of the type associated to the provided PointerIO instance (see {@link PointerIO#getTargetType()}) * @param elementClass type of the array elements * @param arrayLength length of the array in elements * @param beforeDeallocation fake releaser that should be run just before the memory is actually released, for instance in order to call some object destructor * @return a pointer to a new memory area large enough to hold byteSize consecutive bytes */ public static <V> Pointer<V> allocateBytes(PointerIO<V> io, long byteSize, final Releaser beforeDeallocation) { if (byteSize == 0) return null; if (byteSize < 0) throw new IllegalArgumentException("Cannot allocate a negative amount of memory !"); long address = JNI.mallocNulled(byteSize); if (address == 0) throw new RuntimeException("Failed to allocate " + byteSize); return newPointer(io, address, true, address, address + byteSize, null, NO_PARENT, beforeDeallocation == null ? freeReleaser : new Releaser() { @Override public void release(Pointer<?> p) { beforeDeallocation.release(p); freeReleaser.release(p); } }, null); } static FreeReleaser freeReleaser = new FreeReleaser(); static class FreeReleaser implements Releaser { @Override public void release(Pointer<?> p) { assert p.getSibling() == null; assert p.validStart == p.getPeer(); JNI.free(p.getPeer()); } } /** * Create a memory area large enough to hold arrayLength items of type elementClass. * @param elementClass type of the array elements * @param arrayLength length of the array in elements * @return a pointer to a new memory area large enough to hold arrayLength items of type elementClass. */ public static <V> Pointer<V> allocateArray(Class<V> elementClass, long arrayLength) { if (arrayLength == 0) return null; #foreach ($prim in $primitives) if (elementClass == ${prim.WrapperName}.TYPE || elementClass == ${prim.WrapperName}.class) return (Pointer<V>)allocateArray(PointerIO.get${prim.CapName}Instance(), arrayLength); #end if (Pointer.class.isAssignableFrom(elementClass)) return (Pointer<V>)allocateArray(PointerIO.getPointerInstance(elementClass), arrayLength); // TODO if (SizeT.class.isAssignableFrom(elementClass)) return (Pointer<V>)allocateArray(PointerIO.getSizeTInstance(), arrayLength); // TODO if (CLong.class.isAssignableFrom(elementClass)) return (Pointer<V>)allocateArray(PointerIO.getCLongInstance(), arrayLength); // TODO if (StructObject.class.isAssignableFrom(elementClass)) { CRuntime runtime = (CRuntime)BridJ.getRuntime(elementClass); StructIO sio = StructIO.getInstance(elementClass, elementClass); PointerIO pio = PointerIO.getInstance(sio); return (Pointer<V>)allocateArray(pio, arrayLength); // TODO } //if (CLong.class.isAssignableFrom(elementClass)) // return (Pointer<V>)allocate(PointerIO.getPointerInstance(), Pointer.SIZE * arrayLength); // TODO throw new UnsupportedOperationException("Cannot allocate memory for type " + elementClass.getName()); } /** * Create a pointer to the memory location used by a direct NIO buffer.<br/> * The returned pointer (and its subsequent clones returned by {@link #clone()}, {@link #offset(long)} or {@link #next(long)}) retains a reference to the original NIO buffer, so its lifespan is at least that of the pointer.</br> * @throws UnsupportedOperationException if the buffer is not direct */ public static Pointer<?> pointerToBuffer(Buffer buffer) { if (buffer == null) return null; #foreach ($prim in $primitivesNoBool) if (buffer instanceof ${prim.BufferName}) return (Pointer)pointerTo${prim.CapName}s((${prim.BufferName})buffer); #end throw new UnsupportedOperationException(); } #foreach ($prim in $primitives) #docAllocateCopy($prim.Name $prim.WrapperName) public static Pointer<${prim.WrapperName}> pointerTo${prim.CapName}(${prim.Name} value) { Pointer<${prim.WrapperName}> mem = allocate(PointerIO.get${prim.CapName}Instance()); mem.set${prim.CapName}(0, value); return mem; } #docAllocateArrayCopy($prim.Name $prim.WrapperName) public static Pointer<${prim.WrapperName}> pointerTo${prim.CapName}s(${prim.Name}... values) { if (values == null) return null; Pointer<${prim.WrapperName}> mem = allocateArray(PointerIO.get${prim.CapName}Instance(), values.length); mem.set${prim.CapName}s(0, values, 0, values.length); return mem; } #docAllocateArray2DCopy($prim.Name $prim.WrapperName) public static Pointer<Pointer<${prim.WrapperName}>> pointerTo${prim.CapName}s(${prim.Name}[][] values) { if (values == null) return null; int dim1 = values.length, dim2 = values[0].length; Pointer<Pointer<${prim.WrapperName}>> mem = allocate${prim.CapName}s(dim1, dim2); for (int i1 = 0; i1 < dim1; i1++) mem.set${prim.CapName}s(i1 * dim2 * ${prim.Size}, values[i1], 0, dim2); return mem; } #docAllocateArray3DCopy($prim.Name $prim.WrapperName) public static Pointer<Pointer<Pointer<${prim.WrapperName}>>> pointerTo${prim.CapName}s(${prim.Name}[][][] values) { if (values == null) return null; int dim1 = values.length, dim2 = values[0].length, dim3 = values[0][0].length; Pointer<Pointer<Pointer<${prim.WrapperName}>>> mem = allocate${prim.CapName}s(dim1, dim2, dim3); for (int i1 = 0; i1 < dim1; i1++) { int offset1 = i1 * dim2; for (int i2 = 0; i2 < dim2; i2++) { int offset2 = (offset1 + i2) * dim3; mem.set${prim.CapName}s(offset2 * ${prim.Size}, values[i1][i2], 0, dim3); } } return mem; } #docAllocate($prim.Name $prim.WrapperName) public static Pointer<${prim.WrapperName}> allocate${prim.CapName}() { return allocate(PointerIO.get${prim.CapName}Instance()); } #docAllocateArray($prim.Name $prim.WrapperName) public static Pointer<${prim.WrapperName}> allocate${prim.CapName}s(long arrayLength) { return allocateArray(PointerIO.get${prim.CapName}Instance(), arrayLength); } #docAllocateArray2D($prim.Name $prim.WrapperName) public static Pointer<Pointer<${prim.WrapperName}>> allocate${prim.CapName}s(long dim1, long dim2) { return allocateArray(PointerIO.getArrayInstance(PointerIO.get${prim.CapName}Instance(), new long[] { dim1, dim2 }, 0), dim1); } #docAllocateArray3D($prim.Name $prim.WrapperName) public static Pointer<Pointer<Pointer<${prim.WrapperName}>>> allocate${prim.CapName}s(long dim1, long dim2, long dim3) { long[] dims = new long[] { dim1, dim2, dim3 }; return allocateArray( PointerIO.getArrayInstance( PointerIO.getArrayInstance( PointerIO.get${prim.CapName}Instance(), dims, 1 ), dims, 0 ), dim1 ) ; } #end #foreach ($prim in $primitivesNoBool) /** * Create a pointer to the memory location used by a direct NIO ${prim.BufferName}}.<br/> * The returned pointer (and its subsequent clones returned by {@link #clone()}, {@link #offset(long)} or {@link #next(long)}) retains a reference to the original NIO buffer, so its lifespan is at least that of the pointer.</br> * @throws UnsupportedOperationException if the buffer is not direct */ public static Pointer<${prim.WrapperName}> pointerTo${prim.CapName}s(${prim.BufferName} buffer) { if (buffer == null) return null; if (!buffer.isDirect()) throw new UnsupportedOperationException("Cannot create pointers to indirect ${prim.BufferName} buffers"); long address = JNI.getDirectBufferAddress(buffer); long size = JNI.getDirectBufferCapacity(buffer); if (address == 0 || size == 0) return null; PointerIO<${prim.WrapperName}> io = CommonPointerIOs.${prim.Name}IO; boolean ordered = buffer.order().equals(ByteOrder.nativeOrder()); return newPointer(io, address, ordered, address, address + size, null, NO_PARENT, null, buffer); } #end /** * Get the type of pointed elements. */ public Type getTargetType() { PointerIO<T> io = getIO(); return io == null ? null : io.getTargetType(); } /** * Read an untyped pointer value from the pointed memory location */ @Deprecated public Pointer<?> getPointer() { return getPointer(0, (PointerIO)null); } /** * Read a pointer value from the pointed memory location shifted by a byte offset */ public Pointer<?> getPointer(long byteOffset) { return getPointer(byteOffset, (PointerIO)null); } /** * Read a pointer value from the pointed memory location.<br> * @param c class of the elements pointed by the resulting pointer */ public <U> Pointer<U> getPointer(Class<U> c) { return getPointer(0, (PointerIO<U>)PointerIO.getInstance(c)); } /** * Read a pointer value from the pointed memory location * @param pio PointerIO instance that knows how to read the elements pointed by the resulting pointer */ public <U> Pointer<U> getPointer(PointerIO<U> pio) { return getPointer(0, pio); } /** * Read a pointer value from the pointed memory location shifted by a byte offset * @param c class of the elements pointed by the resulting pointer */ public <U> Pointer<U> getPointer(long byteOffset, Class<U> c) { return getPointer(byteOffset, (PointerIO<U>)PointerIO.getInstance(c)); } /** * Read a pointer value from the pointed memory location shifted by a byte offset * @param c class of the elements pointed by the resulting pointer */ public <U> Pointer<U> getPointer(long byteOffset, Type t) { return getPointer(byteOffset, t == null ? null : (PointerIO<U>)PointerIO.getInstance(t)); } /** * Read a pointer value from the pointed memory location shifted by a byte offset * @param pio PointerIO instance that knows how to read the elements pointed by the resulting pointer */ public <U> Pointer<U> getPointer(long byteOffset, PointerIO<U> pio) { long value = getSizeT(byteOffset); if (value == 0) return null; return newPointer(pio, value, isOrdered(), UNKNOWN_VALIDITY, UNKNOWN_VALIDITY, this, byteOffset, null, null); } /** * Write a pointer value to the pointed memory location */ public Pointer<T> setPointer(Pointer<?> value) { return setPointer(0, value); } /** * Write a pointer value to the pointed memory location shifted by a byte offset */ public Pointer<T> setPointer(long byteOffset, Pointer<?> value) { setSizeT(byteOffset, value == null ? 0 : value.getPeer()); return this; } /** * Read an array of untyped pointer values from the pointed memory location shifted by a byte offset * @deprecated Use a typed version instead : {@link Pointer#getPointers(long, int, Type)}, {@link Pointer#getPointers(long, int, Class)} or {@link Pointer#getPointers(long, int, PointerIO)} */ @Deprecated public Pointer<?>[] getPointers(long byteOffset, int arrayLength) { return getPointers(byteOffset, arrayLength, (PointerIO)null); } /** * Read an array of pointer values from the pointed memory location shifted by a byte offset * @param t type of the elements pointed by the resulting pointer */ public <U> Pointer<U>[] getPointers(long byteOffset, int arrayLength, Type t) { return getPointers(byteOffset, arrayLength, t == null ? null : (PointerIO<U>)PointerIO.getInstance(t)); } /** * Read an array of pointer values from the pointed memory location shifted by a byte offset * @param t class of the elements pointed by the resulting pointer */ public <U> Pointer<U>[] getPointers(long byteOffset, int arrayLength, Class<U> t) { return getPointers(byteOffset, arrayLength, t == null ? null : PointerIO.getInstance(t)); } /** * Read an array of pointer values from the pointed memory location shifted by a byte offset * @param pio PointerIO instance that knows how to read the elements pointed by the resulting pointer */ public <U> Pointer<U>[] getPointers(long byteOffset, int arrayLength, PointerIO pio) { Pointer<U>[] values = (Pointer<U>[])new Pointer[arrayLength]; int s = JNI.POINTER_SIZE; for (int i = 0; i < arrayLength; i++) values[i] = getPointer(i * s, pio); return values; } /** * Write an array of pointer values to the pointed memory location shifted by a byte offset */ public Pointer<T> setPointers(long byteOffset, Pointer<?>... values) { if (values == null) throw new IllegalArgumentException("Null values"); int n = values.length, s = JNI.POINTER_SIZE; for (int i = 0; i < n; i++) setPointer(i * s, values[i]); return this; } #foreach ($sizePrim in ["SizeT", "CLong"]) #docAllocateCopy($sizePrim $sizePrim) public static Pointer<${sizePrim}> pointerTo${sizePrim}(long value) { Pointer<${sizePrim}> p = allocate(PointerIO.get${sizePrim}Instance()); p.set${sizePrim}(0, value); return p; } #docAllocateArrayCopy($sizePrim $sizePrim) public static Pointer<${sizePrim}> pointerTo${sizePrim}s(long... values) { if (values == null) return null; return allocateArray(PointerIO.get${sizePrim}Instance(), values.length).set${sizePrim}s(0, values); } #docAllocateArrayCopy($sizePrim $sizePrim) public static Pointer<${sizePrim}> pointerTo${sizePrim}s(${sizePrim}[] values) { if (values == null) return null; return allocateArray(PointerIO.get${sizePrim}Instance(), values.length).set${sizePrim}s(0, values); } #docAllocateArrayCopy($sizePrim $sizePrim) public static Pointer<${sizePrim}> pointerTo${sizePrim}s(int[] values) { if (values == null) return null; return allocateArray(PointerIO.get${sizePrim}Instance(), values.length).set${sizePrim}s(0, values); } #docAllocateArray($sizePrim $sizePrim) public static Pointer<${sizePrim}> allocate${sizePrim}s(long arrayLength) { return allocateArray(PointerIO.get${sizePrim}Instance(), arrayLength); } #docAllocate($sizePrim $sizePrim) public static Pointer<${sizePrim}> allocate${sizePrim}() { return allocate(PointerIO.get${sizePrim}Instance()); } #docGet($sizePrim $sizePrim) public long get${sizePrim}() { return get${sizePrim}(0); } #docGetOffset($sizePrim $sizePrim) public long get${sizePrim}(long byteOffset) { return ${sizePrim}.SIZE == 8 ? getLong(byteOffset) : 0xffffffffL & getInt(byteOffset); } #docGetArray($sizePrim $sizePrim) public long[] get${sizePrim}s(int arrayLength) { return get${sizePrim}s(0, arrayLength); } #docGetArrayOffset($sizePrim $sizePrim) public long[] get${sizePrim}s(long byteOffset, int arrayLength) { if (${sizePrim}.SIZE == 8) return getLongs(byteOffset, arrayLength); int[] values = getInts(byteOffset, arrayLength); long[] ret = new long[arrayLength]; for (int i = 0; i < arrayLength; i++) { ret[i] = 0xffffffffL & values[i]; } return ret; } #docSet($sizePrim $sizePrim) public Pointer<T> set${sizePrim}(long value) { return set${sizePrim}(0, value); } #docSet($sizePrim $sizePrim) public Pointer<T> set${sizePrim}(${sizePrim} value) { return set${sizePrim}(0, value); } #docSetOffset($sizePrim $sizePrim) public Pointer<T> set${sizePrim}(long byteOffset, long value) { if (${sizePrim}.SIZE == 8) setLong(byteOffset, value); else { setInt(byteOffset, SizeT.safeIntCast(value)); } return this; } #docSetOffset($sizePrim $sizePrim) public Pointer<T> set${sizePrim}(long byteOffset, ${sizePrim} value) { return set${sizePrim}(byteOffset, value.longValue()); } #docSetArray($sizePrim $sizePrim) public Pointer<T> set${sizePrim}s(long[] values) { return set${sizePrim}s(0, values); } #docSetArray($sizePrim $sizePrim) public Pointer<T> set${sizePrim}s(int[] values) { return set${sizePrim}s(0, values); } #docSetArray($sizePrim $sizePrim) public Pointer<T> set${sizePrim}s(${sizePrim}[] values) { return set${sizePrim}s(0, values); } #docSetArrayOffset($sizePrim $sizePrim) public Pointer<T> set${sizePrim}s(long byteOffset, long[] values) { if (${sizePrim}.SIZE == 8) { setLongs(byteOffset, values); } else { int n = values.length, s = 4; for (int i = 0; i < n; i++) setInt(i * s, (int)values[i]); } return this; } #docSetArrayOffset($sizePrim $sizePrim) public Pointer<T> set${sizePrim}s(long byteOffset, ${sizePrim}... values) { if (values == null) throw new IllegalArgumentException("Null values"); int n = values.length, s = 4; for (int i = 0; i < n; i++) set${sizePrim}(i * s, values[i].longValue()); return this; } #docSetArrayOffset($sizePrim $sizePrim) public Pointer<T> set${sizePrim}s(long byteOffset, int[] values) { if (${sizePrim}.SIZE == 4) { setInts(byteOffset, values); } else { int n = values.length, s = 8; for (int i = 0; i < n; i++) setLong(i * s, values[i]); } return this; } #end #docAllocateCopy("pointer", "Pointer") public static <T> Pointer<Pointer<T>> pointerToPointer(Pointer<T> value) { Pointer<Pointer<T>> p = (Pointer<Pointer<T>>)(Pointer)allocate(PointerIO.getPointerInstance()); p.setPointer(0, value); return p; } #docAllocateArrayCopy("pointer", "Pointer") public static <T> Pointer<Pointer<T>> pointerToPointers(Pointer<T>... values) { if (values == null) return null; int n = values.length, s = Pointer.SIZE; PointerIO<Pointer> pio = PointerIO.getPointerInstance(); // TODO get actual pointer instances PointerIO !!! Pointer<Pointer<T>> p = (Pointer<Pointer<T>>)(Pointer)allocateArray(pio, n); for (int i = 0; i < n; i++) { p.setPointer(i * s, values[i]); } return p; } static Class<?> getPrimitiveType(Buffer buffer) { #foreach ($prim in $primitivesNoBool) if (buffer instanceof ${prim.BufferName}) return ${prim.WrapperName}.TYPE; #end throw new UnsupportedOperationException(); } /** * Copy length values from an NIO buffer (beginning at element at valuesOffset index) to the pointed memory location shifted by a byte offset */ public void setValues(long byteOffset, Buffer values, int valuesOffset, int length) { #foreach ($prim in $primitivesNoBool) if (values instanceof ${prim.BufferName}) { set${prim.CapName}s(byteOffset, (${prim.BufferName})values, valuesOffset, length); return; } #end throw new UnsupportedOperationException(); } /** * Copy bytes from the memory location indicated by this pointer to that of another pointer (with byte offsets for both the source and the destination), using the memcpy C function.<br> * If the destination and source memory locations are likely to overlap, {@link #moveTo(long, Pointer, long, long)} must be used instead. */ public void copyBytesTo(long byteOffset, Pointer<?> destination, long byteOffsetInDestination, long byteCount) { JNI.memcpy(destination.getCheckedPeer(byteOffsetInDestination, byteCount), getCheckedPeer(byteOffset, byteCount), byteCount); } /** * Copy bytes from the memory location indicated by this pointer to that of another pointer (with byte offsets for both the source and the destination), using the memcpy C function.<br> * Works even if the destination and source memory locations are overlapping. */ public void moveBytesTo(long byteOffset, Pointer<?> destination, long byteOffsetInDestination, long byteCount) { JNI.memmove(destination.getCheckedPeer(byteOffsetInDestination, byteCount), getCheckedPeer(byteOffset, byteCount), byteCount); } /** * Copy remaining bytes from this pointer to a destination (see {@link #copyTo(long, Pointer, long, long)}, {@link #getRemainingBytes}) */ public void copyTo(Pointer<?> destination) { copyBytesTo(0, destination, 0, getRemainingBytes()); } #foreach ($prim in $primitives) /** * Write a ${prim.Name} value to the pointed memory location */ public Pointer<T> set${prim.CapName}(${prim.Name} value) { return set${prim.CapName}(0, value); } /** * Read a ${prim.Name} value from the pointed memory location shifted by a byte offset */ public Pointer<T> set${prim.CapName}(long byteOffset, ${prim.Name} value) { #if ($prim.Name != "byte" && $prim.Name != "boolean") if (!isOrdered()) { JNI.set_${prim.Name}_disordered(getCheckedPeer(byteOffset, ${prim.Size}), value); return this; } #end JNI.set_${prim.Name}(getCheckedPeer(byteOffset, ${prim.Size}), value); return this; } /** * Write an array of ${prim.Name} values of the specified length to the pointed memory location */ public Pointer<T> set${prim.CapName}s(${prim.Name}[] values) { return set${prim.CapName}s(0, values, 0, values.length); } /** * Write an array of ${prim.Name} values of the specified length to the pointed memory location shifted by a byte offset */ public Pointer<T> set${prim.CapName}s(long byteOffset, ${prim.Name}[] values) { return set${prim.CapName}s(byteOffset, values, 0, values.length); } /** * Write an array of ${prim.Name} values of the specified length to the pointed memory location shifted by a byte offset, reading values at the given array offset and for the given length from the provided array. */ public Pointer<T> set${prim.CapName}s(long byteOffset, ${prim.Name}[] values, int valuesOffset, int length) { #if ($prim.Name != "byte" && $prim.Name != "boolean") if (!isOrdered()) { JNI.set_${prim.Name}_array_disordered(getCheckedPeer(byteOffset, ${prim.Size} * length), values, valuesOffset, length); return this; } #end JNI.set_${prim.Name}_array(getCheckedPeer(byteOffset, ${prim.Size} * length), values, valuesOffset, length); return this; } /** * Read a ${prim.Name} value from the pointed memory location */ public ${prim.Name} get${prim.CapName}() { return get${prim.CapName}(0); } /** * Read a ${prim.Name} value from the pointed memory location shifted by a byte offset */ public ${prim.Name} get${prim.CapName}(long byteOffset) { #if ($prim.Name != "byte" && $prim.Name != "boolean") if (!isOrdered()) return JNI.get_${prim.Name}_disordered(getCheckedPeer(byteOffset, ${prim.Size})); #end return JNI.get_${prim.Name}(getCheckedPeer(byteOffset, ${prim.Size})); } /** * Read an array of ${prim.Name} values of the specified length from the pointed memory location */ public ${prim.Name}[] get${prim.CapName}s(int length) { return get${prim.CapName}s(0, length); } /** * Read the array of remaining ${prim.Name} values */ public ${prim.Name}[] get${prim.CapName}s() { long rem = getRemainingElements(); if (rem < 0) throwBecauseUntyped("Cannot create array if remaining length is not known. Please use get${prim.CapName}s(int length) instead."); return get${prim.CapName}s(0, (int)rem); } /** * Read an array of ${prim.Name} values of the specified length from the pointed memory location shifted by a byte offset */ public ${prim.Name}[] get${prim.CapName}s(long byteOffset, int length) { #if ($prim.Name != "byte" && $prim.Name != "boolean") if (!isOrdered()) return JNI.get_${prim.Name}_array_disordered(getCheckedPeer(byteOffset, ${prim.Size} * length), length); #end return JNI.get_${prim.Name}_array(getCheckedPeer(byteOffset, ${prim.Size} * length), length); } #end #foreach ($prim in $primitivesNoBool) /** * Read ${prim.Name} values into the specified destination array from the pointed memory location */ public void get${prim.CapName}s(${prim.Name}[] dest) { get${prim.BufferName}().get(dest); } /** * Read length ${prim.Name} values into the specified destination array from the pointed memory location shifted by a byte offset, storing values after the provided destination offset. */ public void get${prim.CapName}s(long byteOffset, ${prim.Name}[] dest, int destOffset, int length) { get${prim.BufferName}(byteOffset).get(dest, destOffset, length); } /** * Write a buffer of ${prim.Name} values of the specified length to the pointed memory location */ public Pointer<T> set${prim.CapName}s(${prim.BufferName} values) { return set${prim.CapName}s(0, values, 0, values.capacity()); } /** * Write a buffer of ${prim.Name} values of the specified length to the pointed memory location shifted by a byte offset, reading values at the given buffer offset and for the given length from the provided buffer. */ public Pointer<T> set${prim.CapName}s(long byteOffset, ${prim.BufferName} values, long valuesOffset, long length) { if (values == null) throw new IllegalArgumentException("Null values"); if (values.isDirect()) { long len = length * ${prim.Size}, off = valuesOffset * ${prim.Size}; long cap = JNI.getDirectBufferCapacity(values); if (cap < off + len) throw new IndexOutOfBoundsException("The provided buffer has a capacity (" + cap + " bytes) smaller than the requested write operation (" + len + " bytes starting at byte offset " + off + ")"); JNI.memcpy(getCheckedPeer(byteOffset, ${prim.Size} * length), JNI.getDirectBufferAddress(values) + off, len); } else if (values.isReadOnly()) { get${prim.BufferName}(byteOffset, length).put(values.duplicate()); } else { set${prim.CapName}s(byteOffset, values.array(), (int)(values.arrayOffset() + valuesOffset), (int)length); } return this; } /** * Read a buffer of ${prim.Name} values of the specified length from the pointed memory location */ public ${prim.BufferName} get${prim.BufferName}(long length) { return get${prim.BufferName}(0, length); } /** * Read a buffer of ${prim.Name} values of the remaining length from the pointed memory location */ public ${prim.BufferName} get${prim.BufferName}() { long rem = getRemainingElements(); if (rem < 0) throwBecauseUntyped("Cannot create buffer if remaining length is not known. Please use get${prim.BufferName}(long length) instead."); return get${prim.BufferName}(0, rem); } /** * Read a buffer of ${prim.Name} values of the specified length from the pointed memory location shifted by a byte offset */ public ${prim.BufferName} get${prim.BufferName}(long byteOffset, long length) { long blen = ${prim.Size} * length; ByteBuffer buffer = JNI.newDirectByteBuffer(getCheckedPeer(byteOffset, blen), blen); buffer.order(order()); #if ($prim.Name == "byte") return buffer; #else return buffer.as${prim.BufferName}(); #end } #end /** * Type of a native character string.<br> * In the native world, there are several ways to represent a string.<br> * See {@link Pointer#getString(long, Charset, StringType)} and {@link Pointer#setString(long, String, Charset, StringType)} */ public enum StringType { /** * C strings (a.k.a "NULL-terminated strings") have no size limit and are the most used strings in the C world. * They are stored with the bytes of the string (using either a single-byte encoding such as ASCII, ISO-8859 or windows-1252 or a C-string compatible multi-byte encoding, such as UTF-8), followed with a zero byte that indicates the end of the string.<br> * Corresponding C types : {@code char* }, {@code const char* }, {@code LPCSTR }<br> * Corresponding Pascal type : {@code PChar }<br> * See {@link Pointer#pointerToCString(String)}, {@link Pointer#getCString()} and {@link Pointer#setCString(String)} */ C(false, true), /** * Wide C strings are stored as C strings (see {@link StringType#C}) except they are composed of shorts instead of bytes (and are ended by one zero short value = two zero byte values). * This allows the use of two-bytes encodings, which is why this kind of strings is often found in modern Unicode-aware system APIs.<br> * Corresponding C types : {@code wchar_t* }, {@code const wchar_t* }, {@code LPCWSTR }<br> * See {@link Pointer#pointerToWideCString(String)}, {@link Pointer#getWideCString()} and {@link Pointer#setWideCString(String)} */ WideC(true, true), PascalShort(false, true), PascalWide(true, true), PascalAnsi(false, true), BSTR(true, true), /** * STL strings have compiler- and STL library-specific implementations and memory layouts.<br> * BridJ support reading and writing to / from pointers to most implementation's STL strings, though. * See {@link Pointer#pointerToString(String, StringType)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, */ STL(false, false), /** * STL wide strings have compiler- and STL library-specific implementations and memory layouts.<br> * BridJ supports reading and writing to / from pointers to most implementation's STL strings, though. * See {@link Pointer#pointerToString(String, StringType)}, {@link Pointer#getString(StringType)}, {@link Pointer#setString(String, StringType)}, */ WideSTL(true, false); //MFCCString, //CComBSTR, //_bstr_t final boolean isWide, canCreate; StringType(boolean isWide, boolean canCreate) { this.isWide = isWide; this.canCreate = canCreate; } } private static void notAString(StringType type, String reason) { throw new RuntimeException("There is no " + type + " String here ! (" + reason + ")"); } private void checkIntRefCount(StringType type, long byteOffset) { int refCount = getInt(byteOffset); if (refCount <= 0) notAString(type, "invalid refcount: " + refCount); } /** * Read a native string from the pointed memory location using the default charset.<br> * See {@link Pointer#getString(long, Charset, StringType)} for more options. * @param type Type of the native String to read. See {@link StringType} for details on the supported types. * @return string read from native memory */ public String getString(StringType type) { return getString(0, null, type); } String getSTLString(long byteOffset, Charset charset, StringType type) { // Assume the following layout : // - fixed buff of 16 chars // - ptr to dynamic array if the string is bigger // - size of the string (size_t) // - max allowed size of the string without the need for reallocation boolean wide = type == StringType.WideSTL; int fixedBuffLength = 16; int fixedBuffSize = wide ? fixedBuffLength * 2 : fixedBuffLength; long length = getSizeT(byteOffset + fixedBuffSize + Pointer.SIZE); long pOff; Pointer<?> p; if (length < fixedBuffLength - 1) { pOff = byteOffset; p = this; } else { pOff = 0; p = getPointer(byteOffset + fixedBuffSize + Pointer.SIZE); } int endChar = wide ? p.getChar(pOff + length * 2) : p.getByte(pOff + length); if (endChar != 0) notAString(type, "STL string format is not recognized : did not find a NULL char at the expected end of string of expected length " + length); return p.getString(pOff, charset, wide ? StringType.WideC : StringType.C); } static <U> Pointer<U> setSTLString(Pointer<U> pointer, long byteOffset, String s, Charset charset, StringType type) { boolean wide = type == StringType.WideSTL; int fixedBuffLength = 16; int fixedBuffSize = wide ? fixedBuffLength * 2 : fixedBuffLength; long lengthOffset = byteOffset + fixedBuffSize + Pointer.SIZE; long capacityOffset = lengthOffset + Pointer.SIZE; long length = s.length(); if (pointer == null)// { && length > fixedBuffLength - 1) throw new UnsupportedOperationException("Cannot create STL strings (yet)"); long currentLength = pointer.getSizeT(lengthOffset); long currentCapacity = pointer.getSizeT(capacityOffset); if (currentLength < 0 || currentCapacity < 0 || currentLength > currentCapacity) notAString(type, "STL string format not recognized : currentLength = " + currentLength + ", currentCapacity = " + currentCapacity); if (length > currentCapacity) throw new RuntimeException("The target STL string is not large enough to write a string of length " + length + " (current capacity = " + currentCapacity + ")"); pointer.setSizeT(lengthOffset, length); long pOff; Pointer<?> p; if (length < fixedBuffLength - 1) { pOff = byteOffset; p = pointer; } else { pOff = 0; p = pointer.getPointer(byteOffset + fixedBuffSize + SizeT.SIZE); } int endChar = wide ? p.getChar(pOff + currentLength * 2) : p.getByte(pOff + currentLength); if (endChar != 0) notAString(type, "STL string format is not recognized : did not find a NULL char at the expected end of string of expected length " + currentLength); p.setString(pOff, s, charset, wide ? StringType.WideC : StringType.C); return pointer; } /** * Read a native string from the pointed memory location shifted by a byte offset, using the provided charset or the system's default if not provided. * @param byteOffset * @param charset Character set used to convert String characters to bytes. If null, {@link Charset#defaultCharset()} will be used * @param type Type of the native String to read. See {@link StringType} for details on the supported types. * @return string read from native memory */ public String getString(long byteOffset, Charset charset, StringType type) { try { long len; switch (type) { case PascalShort: len = getByte(byteOffset) & 0xff; return new String(getBytes(byteOffset + 1, safeIntCast(len)), charset(charset)); case PascalWide: checkIntRefCount(type, byteOffset - 8); case BSTR: len = getInt(byteOffset - 4); if (len < 0 || ((len & 1) == 1)) notAString(type, "invalid byte length: " + len); //len = wcslen(byteOffset); if (getChar(byteOffset + len) != 0) notAString(type, "no null short after the " + len + " declared bytes"); return new String(getChars(byteOffset, safeIntCast(len / 2))); case PascalAnsi: checkIntRefCount(type, byteOffset - 8); len = getInt(byteOffset - 4); if (len < 0) notAString(type, "invalid byte length: " + len); if (getByte(byteOffset + len) != 0) notAString(type, "no null short after the " + len + " declared bytes"); return new String(getBytes(byteOffset, safeIntCast(len)), charset(charset)); case C: len = strlen(byteOffset); return new String(getBytes(byteOffset, safeIntCast(len)), charset(charset)); case WideC: len = wcslen(byteOffset); return new String(getChars(byteOffset, safeIntCast(len))); case STL: case WideSTL: return getSTLString(byteOffset, charset, type); default: throw new RuntimeException("Unhandled string type : " + type); } } catch (UnsupportedEncodingException ex) { throwUnexpected(ex); return null; } } /** * Write a native string to the pointed memory location using the default charset.<br> * See {@link Pointer#setString(long, String, Charset, StringType)} for more options. * @param s string to write * @param type Type of the native String to write. See {@link StringType} for details on the supported types. * @return this */ public Pointer<T> setString(String s, StringType type) { return setString(this, 0, s, null, type); } /** * Write a native string to the pointed memory location shifted by a byte offset, using the provided charset or the system's default if not provided. * @param byteOffset * @param s string to write * @param charset Character set used to convert String characters to bytes. If null, {@link Charset#defaultCharset()} will be used * @param type Type of the native String to write. See {@link StringType} for details on the supported types. * @return this */ public Pointer<T> setString(long byteOffset, String s, Charset charset, StringType type) { return setString(this, byteOffset, s, charset, type); } private static String charset(Charset charset) { return (charset == null ? Charset.defaultCharset() : charset).name(); } static <U> Pointer<U> setString(Pointer<U> pointer, long byteOffset, String s, Charset charset, StringType type) { try { if (s == null) return null; byte[] bytes; char[] chars; int bytesCount, headerBytes; int headerShift; switch (type) { case PascalShort: bytes = s.getBytes(charset(charset)); bytesCount = bytes.length; if (pointer == null) pointer = (Pointer<U>)allocateBytes(bytesCount + 1); if (bytesCount > 255) throw new IllegalArgumentException("Pascal strings cannot be more than 255 chars long (tried to write string of byte length " + bytesCount + ")"); pointer.setByte(byteOffset, (byte)bytesCount); pointer.setBytes(byteOffset + 1, bytes, 0, bytesCount); break; case C: bytes = s.getBytes(charset(charset)); bytesCount = bytes.length; if (pointer == null) pointer = (Pointer<U>)allocateBytes(bytesCount + 1); pointer.setBytes(byteOffset, bytes, 0, bytesCount); pointer.setByte(byteOffset + bytesCount, (byte)0); break; case WideC: chars = s.toCharArray(); bytesCount = chars.length * 2; if (pointer == null) pointer = (Pointer<U>)allocateChars(bytesCount + 2); pointer.setChars(byteOffset, chars); pointer.setChar(byteOffset + bytesCount, (char)0); break; case PascalWide: headerBytes = 8; chars = s.toCharArray(); bytesCount = chars.length * 2; if (pointer == null) { pointer = (Pointer<U>)allocateChars(headerBytes + bytesCount + 2); byteOffset = headerShift = headerBytes; } else headerShift = 0; pointer.setInt(byteOffset - 8, 1); // refcount pointer.setInt(byteOffset - 4, bytesCount); // length header pointer.setChars(byteOffset, chars); pointer.setChar(byteOffset + bytesCount, (char)0); // Return a pointer to the WideC string-compatible part of the Pascal WideString return (Pointer<U>)pointer.offset(headerShift); case PascalAnsi: headerBytes = 8; bytes = s.getBytes(charset(charset)); bytesCount = bytes.length; if (pointer == null) { pointer = (Pointer<U>)allocateBytes(headerBytes + bytesCount + 1); byteOffset = headerShift = headerBytes; } else headerShift = 0; pointer.setInt(byteOffset - 8, 1); // refcount pointer.setInt(byteOffset - 4, bytesCount); // length header pointer.setBytes(byteOffset, bytes); pointer.setByte(byteOffset + bytesCount, (byte)0); // Return a pointer to the WideC string-compatible part of the Pascal WideString return (Pointer<U>)pointer.offset(headerShift); case BSTR: headerBytes = 4; chars = s.toCharArray(); bytesCount = chars.length * 2; if (pointer == null) { pointer = (Pointer<U>)allocateChars(headerBytes + bytesCount + 2); byteOffset = headerShift = headerBytes; } else headerShift = 0; pointer.setInt(byteOffset - 4, bytesCount); // length header IN BYTES pointer.setChars(byteOffset, chars); pointer.setChar(byteOffset + bytesCount, (char)0); // Return a pointer to the WideC string-compatible part of the Pascal WideString return (Pointer<U>)pointer.offset(headerShift); case STL: case WideSTL: return setSTLString(pointer, byteOffset, s, charset, type); default: throw new RuntimeException("Unhandled string type : " + type); } return (Pointer<U>)pointer; } catch (UnsupportedEncodingException ex) { throwUnexpected(ex); return null; } } /** * Allocate memory and write a ${string} string to it, using the system's default charset to convert the string. (see {@link StringType#${string}}).<br> * See {@link Pointer#setString(String, StringType)}, {@link Pointer#getString(StringType)}. * @param charset Character set used to convert String characters to bytes. If null, {@link Charset#defaultCharset()} will be used * @param type Type of the native String to create. See {@link StringType} for details on the supported types. */ public static Pointer<?> pointerToString(String string, Charset charset, StringType type) { return setString(null, 0, string, charset, type); } #macro (defPointerToString $string $eltWrapper) /** * Allocate memory and write a ${string} string to it, using the system's default charset to convert the string. (see {@link StringType#${string}}).<br> * See {@link Pointer#set${string}String(String)}, {@link Pointer#get${string}String()}.<br> * See {@link Pointer#pointerToString(String, Charset, StringType)} for choice of the String type or Charset. */ public static Pointer<$eltWrapper> pointerTo${string}String(String string) { return setString(null, 0, string, null, StringType.${string}); } /** * The update will take place inside the release() call */ public static Pointer<Pointer<$eltWrapper>> pointerTo${string}Strings(final String... strings) { if (strings == null) return null; final int len = strings.length; final Pointer<$eltWrapper>[] pointers = (Pointer<$eltWrapper>[])new Pointer[len]; Pointer<Pointer<$eltWrapper>> mem = allocateArray((PointerIO<Pointer<$eltWrapper>>)(PointerIO)PointerIO.getPointerInstance(${eltWrapper}.class), len, new Releaser() { @Override public void release(Pointer<?> p) { Pointer<Pointer<$eltWrapper>> mem = (Pointer<Pointer<$eltWrapper>>)p; for (int i = 0; i < len; i++) { Pointer<$eltWrapper> pp = mem.get(i); if (pp != null) strings[i] = pp.get${string}String(); pp = pointers[i]; if (pp != null) pp.release(); } } }); for (int i = 0; i < len; i++) mem.set(i, pointers[i] = pointerTo${string}String(strings[i])); return mem; } #end #defPointerToString("C" "Byte") #defPointerToString("WideC" "Character") #foreach ($string in ["C", "WideC"]) /** * Read a ${string} string using the default charset from the pointed memory location (see {@link StringType#${string}}).<br> * See {@link Pointer#get${string}String(long)}, {@link Pointer#getString(StringType)} and {@link Pointer#getString(long, Charset, StringType)} for more options */ public String get${string}String() { return get${string}String(0); } /** * Read a ${string} string using the default charset from the pointed memory location shifted by a byte offset (see {@link StringType#${string}}).<br> * See {@link Pointer#getString(long, Charset, StringType)} for more options */ public String get${string}String(long byteOffset) { return getString(byteOffset, null, StringType.${string}); } /** * Write a ${string} string using the default charset to the pointed memory location (see {@link StringType#${string}}).<br> * See {@link Pointer#set${string}String(long, String)} and {@link Pointer#setString(long, Charset, StringType)} for more options */ public Pointer<T> set${string}String(String s) { return set${string}String(0, s); } /** * Write a ${string} string using the default charset to the pointed memory location shifted by a byte offset (see {@link StringType#${string}}).<br> * See {@link Pointer#setString(long, Charset, StringType)} for more options */ public Pointer<T> set${string}String(long byteOffset, String s) { return setString(byteOffset, s, null, StringType.${string}); } #end /** * Get the length of the C string at the pointed memory location shifted by a byte offset (see {@link StringType#C}). */ protected long strlen(long byteOffset) { return JNI.strlen(getCheckedPeer(byteOffset, 1)); } /** * Get the length of the wide C string at the pointed memory location shifted by a byte offset (see {@link StringType#WideC}). */ protected long wcslen(long byteOffset) { long len = 0; while (getShort(byteOffset + len * 2) != 0) len++; return len; //BUGGY: JNI.wcslen(getCheckedPeer(byteOffset, 1)); } /** * Write zero bytes to the first length bytes pointed by this pointer */ public void clearBytes(long length) { clearBytes(0, length, (byte)0); } /** * Write a byte {@code value} to each of the {@code length} bytes at the address pointed to by this pointer shifted by a {@code byteOffset} */ public void clearBytes(long byteOffset, long length, byte value) { JNI.memset(getCheckedPeer(byteOffset, length), value, length); } /** * Find the first occurrence of a value in the memory block of length searchLength bytes pointed by this pointer shifted by a byteOffset */ public Pointer<T> findByte(long byteOffset, byte value, long searchLength) { long ptr = getCheckedPeer(byteOffset, searchLength); long found = JNI.memchr(ptr, value, searchLength); return found == 0 ? null : offset(found - ptr); } /** * Implementation of {@link List#add(Object)} that throws UnsupportedOperationException * @throws UnsupportedOperationException */ @Deprecated public boolean add(T item) { throw new UnsupportedOperationException(); } /** * Implementation of {@link List#add(int, Object)} that throws UnsupportedOperationException * @throws UnsupportedOperationException */ @Deprecated public void add(int index, T element) { throw new UnsupportedOperationException(); } /** * Implementation of {@link List#addAll(Collection)} that throws UnsupportedOperationException * @throws UnsupportedOperationException */ @Deprecated public boolean addAll(Collection<? extends T> c) { throw new UnsupportedOperationException(); } /** * Implementation of {@link List#addAll(int, Collection)} that throws UnsupportedOperationException * @throws UnsupportedOperationException */ @Deprecated public boolean addAll(int index, Collection<? extends T> c) { throw new UnsupportedOperationException(); } /** * Implementation of {@link List#clear()} that throws UnsupportedOperationException * @throws UnsupportedOperationException */ @Deprecated public void clear() { throw new UnsupportedOperationException(); } /** * Implementation of {@link List#contains(Object)} that throws UnsupportedOperationException * @throws UnsupportedOperationException */ @Deprecated public boolean contains(Object o) { throw new UnsupportedOperationException(); } /** * Implementation of {@link List#containsAll(Collection)} that throws UnsupportedOperationException * @throws UnsupportedOperationException */ @Deprecated public boolean containsAll(Collection<?> c) { throw new UnsupportedOperationException(); } /** * Implementation of {@link List#get(int)} */ public final T get(int index) { return get((long)index); } /** * Alias for {@link #get(long)} defined for more natural use from the Scala language. */ public final T apply(long index) { return get(index); } /** * Implementation of {@link List#indexOf(Object)} that throws UnsupportedOperationException * @throws UnsupportedOperationException */ @Deprecated public int indexOf(Object o) { throw new UnsupportedOperationException(); } /** * Implementation of {@link List#isEmpty()} */ public boolean isEmpty() { return getRemainingElements() == 0; } /** * Implementation of {@link List#lastIndexOf(Object)} that throws UnsupportedOperationException * @throws UnsupportedOperationException */ @Deprecated public int lastIndexOf(Object o) { throw new UnsupportedOperationException(); } /** * Implementation of {@link List#listIterator()} */ public ListIterator<T> listIterator() { return iterator(); } /** * Implementation of {@link List#listIterator(int)} */ public ListIterator<T> listIterator(int index) { return next(index).listIterator(); } /** * Implementation of {@link List#remove(int)} that throws UnsupportedOperationException * @throws UnsupportedOperationException */ @Deprecated public T remove(int index) { throw new UnsupportedOperationException(); } /** * Implementation of {@link List#remove(Object)} that throws UnsupportedOperationException * @throws UnsupportedOperationException */ @Deprecated public boolean remove(Object o) { throw new UnsupportedOperationException(); } /** * Implementation of {@link List#removeAll(Collection)} that throws UnsupportedOperationException * @throws UnsupportedOperationException */ @Deprecated public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } /** * Implementation of {@link List#retainAll(Collection)} that throws UnsupportedOperationException * @throws UnsupportedOperationException */ @Deprecated public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } /** * Implementation of {@link List\#set(int, T)} */ public final T set(int index, T element) { set((long)index, element); return element; } /** * Alias for {@link Pointer\#set(long, Object)} defined for more natural use from the Scala language. */ public final void update(long index, T element) { set(index, element); } /** * Implementation of {@link List#size()} * @deprecated Casts the result of getRemainingElements() to int, so sizes greater that 2^31 will be invalid * @return {@link Pointer#getRemainingElements()} */ public int size() { long size = getRemainingElements(); if (size > Integer.MAX_VALUE) throw new RuntimeException("Size is greater than Integer.MAX_VALUE, cannot convert to int in Pointer.size()"); return (int)size; } /** * Implementation of {@link List#subList(int, int)} */ public List<T> subList(int fromIndex, int toIndex) { PointerIO<T> io = getIO(); if (io == null) throwBecauseUntyped("Cannot create sublist"); return next(fromIndex).validElements(toIndex - fromIndex); } /** * Implementation of {@link List#toArray()} */ public T[] toArray() { PointerIO<T> io = getIO(); if (io == null) throwBecauseUntyped("Cannot create array"); if (validEnd == UNKNOWN_VALIDITY) throw new IndexOutOfBoundsException("Length of pointed memory is unknown, cannot create array out of this pointer"); Class<?> c = Utils.getClass(io.getTargetType()); return (T[])toArray((Object[])Array.newInstance(c, (int)getRemainingElements())); } /** * Implementation of {@link List#toArray(Object[])} */ public <U> U[] toArray(U[] array) { int n = (int)getRemainingElements(); if (n < 0) throwBecauseUntyped("Cannot create array"); if (array.length != n) return (U[])toArray(); for (int i = 0; i < n; i++) array[i] = (U)get(i); return array; } }
package com.melnykov.fab; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.StateListDrawable; import android.graphics.drawable.shapes.OvalShape; import android.os.*; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewTreeObserver; import android.widget.AbsListView; import android.widget.ImageButton; import com.melnykov.floatingactionbutton.R; /** * Android Google+ like floating action button which reacts on the attached list view scrolling events. * * @author Oleksandr Melnykov * */ public class FloatingActionButton extends ImageButton { private StateListDrawable mDrawable; private AbsListView mListView; private int mScrollY; private boolean mVisible; private int mColorNormal; private int mColorPressed; private boolean mShadow; private ScrollSettleHandler mScrollSettleHandler = new ScrollSettleHandler(); public FloatingActionButton(Context context) { super(context); init(context, null); } public FloatingActionButton(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public FloatingActionButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int size = getDimension(R.dimen.fab_size); if (mShadow) { int shadowSize = getDimension(R.dimen.fab_shadow_size); size += shadowSize * 2; } setMeasuredDimension(size, size); } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState savedState = new SavedState(superState); savedState.mScrollY = mScrollY; return savedState; } @Override public void onRestoreInstanceState(Parcelable state) { if (state instanceof SavedState) { SavedState savedState = (SavedState) state; mScrollY = savedState.mScrollY; super.onRestoreInstanceState(savedState.getSuperState()); } else { super.onRestoreInstanceState(state); } } private void init(Context context, AttributeSet attributeSet) { mVisible = true; mColorNormal = getColor(android.R.color.holo_blue_dark); mColorPressed = getColor(android.R.color.holo_blue_light); mShadow = true; if (attributeSet != null) { initAttributes(context, attributeSet); } updateBackground(); } private void initAttributes(Context context, AttributeSet attributeSet) { TypedArray attr = getTypedArray(context, attributeSet, R.styleable.FloatingActionButton); if (attr != null) { try { mColorNormal = attr.getColor(R.styleable.FloatingActionButton_fab_colorNormal, getColor(android.R.color.holo_blue_dark)); mColorPressed = attr.getColor(R.styleable.FloatingActionButton_fab_colorPressed, getColor(android.R.color.holo_blue_light)); mShadow = attr.getBoolean(R.styleable.FloatingActionButton_fab_shadow, true); } finally { attr.recycle(); } } } private void updateBackground() { mDrawable = new StateListDrawable(); mDrawable.addState(new int[] {android.R.attr.state_pressed}, createDrawable(mColorPressed)); mDrawable.addState(new int[] {}, createDrawable(mColorNormal)); setBackgroundCompat(mDrawable); } private Drawable createDrawable(int color) { OvalShape ovalShape = new OvalShape(); ShapeDrawable shapeDrawable = new ShapeDrawable(ovalShape); shapeDrawable.getPaint().setColor(color); if (mShadow) { LayerDrawable layerDrawable = new LayerDrawable(new Drawable[] {getResources().getDrawable(R.drawable.shadow), shapeDrawable}); int shadowSize = getDimension(R.dimen.fab_shadow_size); layerDrawable.setLayerInset(1, shadowSize, shadowSize, shadowSize, shadowSize); return layerDrawable; } else { return shapeDrawable; } } private TypedArray getTypedArray(Context context, AttributeSet attributeSet, int[] attr) { return context.obtainStyledAttributes(attributeSet, attr, 0, 0); } private int getColor(int id) { return getResources().getColor(id); } private int getDimension(int id) { return getResources().getDimensionPixelSize(id); } @SuppressWarnings("deprecation") @SuppressLint("NewApi") private void setBackgroundCompat(Drawable drawable) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { setBackground(drawable); } else { setBackgroundDrawable(drawable); } } private int getListViewScrollY() { View topChild = mListView.getChildAt(0); return topChild == null ? 0 : mListView.getFirstVisiblePosition() * topChild.getHeight() - topChild.getTop(); } private class ScrollSettleHandler extends Handler { private static final int SETTLE_DELAY_MILLIS = 100; private static final int TRANSLATE_DURATION_MILLIS = 500; private int mSettledScrollY; public void onScroll(int scrollY) { if (mSettledScrollY != scrollY) { mSettledScrollY = scrollY; removeMessages(0); // Clear any pending messages and post delayed sendEmptyMessageDelayed(0, SETTLE_DELAY_MILLIS); } } @Override public void handleMessage(Message msg) { animate().setDuration(TRANSLATE_DURATION_MILLIS).translationY(mSettledScrollY); } } public void setColorNormal(int color) { if (color != mColorNormal) { mColorNormal = color; updateBackground(); } } public int getColorNormal() { return mColorNormal; } public void setColorPressed(int color) { if (color != mColorPressed) { mColorPressed = color; updateBackground(); } } public int getColorPressed() { return mColorPressed; } public void setShadow(boolean shadow) { if (shadow != mShadow) { mShadow = shadow; updateBackground(); } } public boolean hasShadow() { return mShadow; } public void attachToListView(AbsListView listView) { mListView = listView; mListView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { int newScrollY = getListViewScrollY(); if (newScrollY == mScrollY) { return; } if (newScrollY > mScrollY && mVisible) { // Scrolling up mVisible = false; mScrollSettleHandler.onScroll(getTop()); } else if (newScrollY < mScrollY && !mVisible) { // Scrolling down mVisible = true; mScrollSettleHandler.onScroll(0); } mScrollY = newScrollY; } }); } /** * A {@link android.os.Parcelable} representing the {@link com.melnykov.fab.FloatingActionButton}'s * state. */ public static class SavedState extends BaseSavedState { private int mScrollY; public SavedState(Parcelable parcel) { super(parcel); } private SavedState(Parcel in) { super(in); mScrollY = in.readInt(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(mScrollY); } public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
package fi.cie.chiru.servicefusionar.serviceApi; import util.IO; import util.Vec; import java.io.IOException; import java.io.InputStream; import java.util.Vector; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import fi.cie.chiru.servicefusionar.gdx.GDXLoader; import fi.cie.chiru.servicefusionar.gdx.GDXMesh; import fi.cie.chiru.servicefusionar.commands.CommandFactory; import android.util.Log; public class SceneParser { private static final String LOG_TAG = "SceneParser"; String sceneContent; private GDXLoader gdxLoader; public SceneParser() { gdxLoader = new GDXLoader(); } public Vector<ServiceApplication> parseFile(ServiceManager serviceManager, String fileName) { Vector<ServiceApplication> serviceApplications = new Vector<ServiceApplication>(); InputStream in = null; try { in = serviceManager.getSetup().myTargetActivity.getAssets().open(fileName); sceneContent = IO.convertInputStreamToString(in); } catch (IOException e) { Log.e(LOG_TAG, "Could not read file: " +fileName); e.printStackTrace(); } finally { try { Log.i(LOG_TAG, "Closing scene input stream"); in.close(); } catch (IOException e) { Log.e(LOG_TAG, e.toString()); } } JSONObject jsonObj = null; try { jsonObj = new JSONObject(sceneContent); } catch (JSONException e) { Log.e(LOG_TAG, "parsing failed"); e.printStackTrace(); } JSONArray entries = null; try { entries = jsonObj.getJSONArray("ServiceApplication"); for(int i=0; i<entries.length(); i++) { JSONObject ServiceAppObj = entries.getJSONObject(i); String name = ServiceAppObj.getString("name"); ServiceApplication serviceApp = new ServiceApplication(serviceManager,name); String meshName = ServiceAppObj.getString("meshRef"); String textureName = ServiceAppObj.getString("textRef"); if(meshName!=null && textureName!=null) { GDXMesh gdxMesh = gdxLoader.loadModelFromFile(meshName, textureName); gdxMesh.enableMeshPicking(); serviceApp.setMesh(gdxMesh); JSONObject posObj = ServiceAppObj.getJSONObject("position"); JSONObject rotObj = ServiceAppObj.getJSONObject("rotation"); JSONObject scaleObj = ServiceAppObj.getJSONObject("scale"); serviceApp.setPosition(new Vec((float)posObj.getDouble("x"), (float)posObj.getDouble("y"), (float)posObj.getDouble("z"))); serviceApp.setRotation(new Vec((float)rotObj.getDouble("x"), (float)rotObj.getDouble("y"), (float)rotObj.getDouble("z"))); serviceApp.setScale(new Vec((float)scaleObj.getDouble("x"), (float)scaleObj.getDouble("y"), (float)scaleObj.getDouble("z"))); } JSONObject geoLocation = null; try { geoLocation = ServiceAppObj.getJSONObject("geoLocation"); } catch (JSONException e){} if (geoLocation != null) { double latitude = 0.0d; double longitude = 0.0d; try { latitude = geoLocation.getDouble("Latitude"); longitude = geoLocation.getDouble("Longitude"); } catch (JSONException e) {} Log.i(LOG_TAG, "Location: " + geoLocation.toString()); serviceApp.setGeoLocation(latitude, longitude); } JSONObject commandObj = ServiceAppObj.getJSONObject("commands"); String clickCommand = commandObj.getString("CLICK"); String dropCommand = commandObj.getString("DROP"); String longClickCommand = commandObj.getString("LONG_CLICK"); serviceApp.setOnClickCommand(CommandFactory.createCommand(clickCommand, serviceManager, name)); serviceApp.setOnDoubleClickCommand(CommandFactory.createCommand(dropCommand, serviceManager, name)); serviceApp.setOnLongClickCommand(CommandFactory.createCommand(longClickCommand, serviceManager, name)); boolean visible = ServiceAppObj.getBoolean("visible"); if(!visible) serviceApp.setvisible(false); boolean attached = ServiceAppObj.getBoolean("attached"); serviceApp.attachToCamera(attached); serviceManager.getSetup().world.add(serviceApp); serviceApplications.add(serviceApp); } } catch (JSONException e) { Log.e(LOG_TAG, "parsing failed"); e.printStackTrace(); } return serviceApplications; } }
package com.joelapenna.foursquared; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.OverlayItem; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Stats; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.maps.VenueItemizedOverlay; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import java.util.ArrayList; import java.util.Observable; import java.util.Observer; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class SearchVenuesMapActivity extends MapActivity { public static final String TAG = "SearchVenuesMapActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; private Venue mTappedVenue; private Observer mSearchResultsObserver; private Button mVenueButton; private MapView mMapView; private MapController mMapController; private ArrayList<VenueItemizedOverlay> mVenuesGroupOverlays = new ArrayList<VenueItemizedOverlay>(); private MyLocationOverlay mMyLocationOverlay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search_map_activity); mVenueButton = (Button)findViewById(R.id.venueButton); mVenueButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (DEBUG) Log.d(TAG, "firing venue activity for venue"); Intent intent = new Intent(SearchVenuesMapActivity.this, VenueActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(Foursquared.EXTRA_VENUE_ID, mTappedVenue.getId()); startActivity(intent); } }); initMap(); mSearchResultsObserver = new Observer() { @Override public void update(Observable observable, Object data) { if (DEBUG) Log.d(TAG, "Observed search results change."); clearMap(); loadSearchResults(SearchVenuesActivity.searchResultsObservable.getSearchResults()); recenterMap(); } }; } @Override public void onResume() { super.onResume(); if (DEBUG) Log.d(TAG, "onResume()"); mMyLocationOverlay.enableMyLocation(); // mMyLocationOverlay.enableCompass(); // Disabled due to a sdk 1.5 emulator bug clearMap(); loadSearchResults(SearchVenuesActivity.searchResultsObservable.getSearchResults()); recenterMap(); SearchVenuesActivity.searchResultsObservable.addObserver(mSearchResultsObserver); } @Override public void onPause() { super.onPause(); if (DEBUG) Log.d(TAG, "onPause()"); mMyLocationOverlay.disableMyLocation(); mMyLocationOverlay.disableCompass(); SearchVenuesActivity.searchResultsObservable.deleteObserver(mSearchResultsObserver); } @Override protected boolean isRouteDisplayed() { return false; } private void initMap() { mMapView = (MapView)findViewById(R.id.mapView); mMapView.setBuiltInZoomControls(true); mMapController = mMapView.getController(); mMyLocationOverlay = new MyLocationOverlay(this, mMapView); mMapView.getOverlays().add(mMyLocationOverlay); mMyLocationOverlay.runOnFirstFix(new Runnable() { public void run() { if (DEBUG) Log.d(TAG, "runOnFirstFix()"); mMapView.getController().animateTo(mMyLocationOverlay.getMyLocation()); mMapView.getController().setZoom(16); } }); } private void loadSearchResults(Group searchResults) { if (searchResults == null) { if (DEBUG) Log.d(TAG, "no search results. Not loading."); return; } if (DEBUG) Log.d(TAG, "Loading search results"); final int groupCount = searchResults.size(); for (int groupIndex = 0; groupIndex < groupCount; groupIndex++) { Group group = (Group)searchResults.get(groupIndex); // One VenueItemizedOverlay per group! VenueItemizedOverlay mappableVenuesOverlay = createMappableVenuesOverlay(group); if (mappableVenuesOverlay != null) { if (DEBUG) Log.d(TAG, "adding a map view venue overlay."); mVenuesGroupOverlays.add(mappableVenuesOverlay); } } // Only add the list of venue group overlays if it contains any overlays. if (mVenuesGroupOverlays.size() > 0) { mMapView.getOverlays().addAll(mVenuesGroupOverlays); } } private void clearMap() { if (DEBUG) Log.d(TAG, "clearMap()"); mVenuesGroupOverlays.clear(); mMapView.getOverlays().clear(); mMapView.getOverlays().add(mMyLocationOverlay); mMapView.postInvalidate(); } /** * Create an overlay that contains a specific group's list of mappable venues. * * @param group * @return */ private VenueItemizedOverlay createMappableVenuesOverlay(Group group) { Group mappableVenues = new Group(); mappableVenues.setType(group.getType()); if (DEBUG) Log.d(TAG, "Adding items in group: " + group.getType()); final int venueCount = group.size(); for (int venueIndex = 0; venueIndex < venueCount; venueIndex++) { Venue venue = (Venue)group.get(venueIndex); if (VenueItemizedOverlay.isVenueMappable(venue)) { if (DEBUG) Log.d(TAG, "adding venue: " + venue.getName()); mappableVenues.add(venue); } } if (mappableVenues.size() > 0) { VenueItemizedOverlay mappableVenuesOverlay = new VenueItemizedOverlayWithButton( this.getResources().getDrawable(R.drawable.map_marker_blue), this.getResources().getDrawable(R.drawable.map_marker_blue_muted)); mappableVenuesOverlay.setGroup(mappableVenues); return mappableVenuesOverlay; } else { return null; } } private void recenterMap() { GeoPoint center = mMyLocationOverlay.getMyLocation(); if (center != null && SearchVenuesActivity.searchResultsObservable.getQuery() == SearchVenuesActivity.QUERY_NEARBY) { if (DEBUG) Log.d(TAG, "recenterMap via MyLocation as we are doing a nearby search"); mMapController.animateTo(center); mMapController.setZoom(16); } else if (mVenuesGroupOverlays.size() > 0) { if (DEBUG) Log.d(TAG, "recenterMap via venues overlay span."); VenueItemizedOverlay newestOverlay = mVenuesGroupOverlays.get(0); if (DEBUG) { Log.d(TAG, "recenterMap to: " + newestOverlay.getLatSpanE6() + " " + newestOverlay.getLonSpanE6()); } // For some reason, this is zooming us to some weird spot!. mMapController.zoomToSpan(newestOverlay.getLatSpanE6(), newestOverlay.getLonSpanE6()); mMapController.animateTo(newestOverlay.getCenter()); } else if (center != null) { if (DEBUG) Log.d(TAG, "Fallback, recenterMap via MyLocation overlay"); mMapController.animateTo(center); mMapController.setZoom(16); return; } if (DEBUG) Log.d(TAG, "Could not re-center; No known user location."); } private class VenueItemizedOverlayWithButton extends VenueItemizedOverlay { public static final String TAG = "VenueItemizedOverlayWithButton"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; private Drawable mBeenThereMarker; public VenueItemizedOverlayWithButton(Drawable defaultMarker, Drawable beenThereMarker) { super(defaultMarker); mBeenThereMarker = boundCenterBottom(beenThereMarker); } @Override public OverlayItem createItem(int i) { VenueOverlayItem item = (VenueOverlayItem)super.createItem(i); Stats stats = item.getVenue().getStats(); if (stats != null && stats.getBeenhere() != null && stats.getBeenhere().me()) { if (DEBUG) Log.d(TAG, "using the beenThereMarker for: " + item.getVenue()); item.setMarker(mBeenThereMarker); } return item; } @Override public boolean onTap(GeoPoint p, MapView mapView) { if (DEBUG) Log.d(TAG, "onTap: " + this + " " + p + " " + mapView); mVenueButton.setVisibility(View.GONE); return super.onTap(p, mapView); } @Override protected boolean onTap(int i) { if (DEBUG) Log.d(TAG, "onTap: " + this + " " + i); VenueOverlayItem item = (VenueOverlayItem)getItem(i); mTappedVenue = item.getVenue(); if (DEBUG) Log.d(TAG, "onTap: " + item.getVenue().getName()); mVenueButton.setText(item.getVenue().getName()); mVenueButton.setVisibility(View.VISIBLE); return true; } } }
package leveltypeslector; import java.awt.EventQueue; import java.awt.Window; import javax.swing.JFrame; import javax.swing.JTextArea; import javax.swing.SwingConstants; import javax.swing.UIManager; import levelbuilder.BuilderWindow; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JSplitPane; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import java.awt.Dimension; import javax.swing.ScrollPaneConstants; import javax.swing.JPanel; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Font; import java.awt.GridLayout; import javax.swing.JToggleButton; import javax.swing.ImageIcon; public class SelectionScreen { private JFrame frame; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SelectionScreen window = new SelectionScreen(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public SelectionScreen() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { Dimension levelPreviewSize = new Dimension(96, 72); frame = new JFrame(); frame.setResizable(false); frame.setBounds(100, 100, 640, 640); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.X_AXIS)); JSplitPane levelViewerAndSelector = new JSplitPane(); levelViewerAndSelector.setEnabled(false); levelViewerAndSelector.setOrientation(JSplitPane.VERTICAL_SPLIT); frame.getContentPane().add(levelViewerAndSelector); JSplitPane levelSelectorAndCreator = new JSplitPane(); levelSelectorAndCreator.setResizeWeight(1.0); levelSelectorAndCreator.setEnabled(false); levelSelectorAndCreator.setOrientation(JSplitPane.VERTICAL_SPLIT); levelViewerAndSelector.setRightComponent(levelSelectorAndCreator); JPanel createBtnPanel = new JPanel(); levelSelectorAndCreator.setRightComponent(createBtnPanel); JButton btnCreateLevel = new JButton("Create Level"); btnCreateLevel.setFont(new Font("Comic Sans MS", Font.PLAIN, 18)); btnCreateLevel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { } }); levelSelectorAndCreator.setDividerLocation(1.0); GroupLayout gl_createBtnPanel = new GroupLayout(createBtnPanel); gl_createBtnPanel.setAutoCreateGaps(true); gl_createBtnPanel.setAutoCreateContainerGaps(true); gl_createBtnPanel.setHorizontalGroup( gl_createBtnPanel.createParallelGroup(Alignment.CENTER) .addGroup(Alignment.CENTER, gl_createBtnPanel.createSequentialGroup() .addGap(256) .addComponent(btnCreateLevel) .addContainerGap(255, Short.MAX_VALUE)) ); gl_createBtnPanel.setVerticalGroup( gl_createBtnPanel.createParallelGroup(Alignment.CENTER) .addGroup(Alignment.CENTER, gl_createBtnPanel.createSequentialGroup() .addGap(10) .addComponent(btnCreateLevel) .addGap(10)) ); createBtnPanel.setLayout(gl_createBtnPanel); JSplitPane splitPane = new JSplitPane(); splitPane.setResizeWeight(0.75); splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); levelSelectorAndCreator.setLeftComponent(splitPane); final JTextArea txtrTextAboutLevel = new JTextArea(); txtrTextAboutLevel.setText("Puzzle"); splitPane.setRightComponent(txtrTextAboutLevel); JPanel levelTypesPanel = new JPanel(); splitPane.setLeftComponent(levelTypesPanel); levelTypesPanel.setLayout(new GridLayout(1, 3, 5, 5)); ButtonGroup levelTypeGroup = new ButtonGroup(); JToggleButton tglbtnPuzzle = new JToggleButton(""); tglbtnPuzzle.setSelected(true); tglbtnPuzzle.setIcon(new ImageIcon(SelectionScreen.class.getResource("/Icons/Puzzle.png"))); levelTypesPanel.add(tglbtnPuzzle); levelTypeGroup.add(tglbtnPuzzle); tglbtnPuzzle.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JToggleButton tBtn = (JToggleButton)arg0.getSource(); if (tBtn.isSelected()) { txtrTextAboutLevel.setText("Puzzle"); } } }); JToggleButton tglbtnLightning = new JToggleButton(""); tglbtnLightning.setIcon(new ImageIcon(SelectionScreen.class.getResource("/Icons/Lightning.png"))); levelTypesPanel.add(tglbtnLightning); levelTypeGroup.add(tglbtnLightning); tglbtnLightning.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JToggleButton tBtn = (JToggleButton)arg0.getSource(); if (tBtn.isSelected()) { txtrTextAboutLevel.setText("Lightning"); } } }); JToggleButton tglbtnRelease = new JToggleButton(""); tglbtnRelease.setIcon(new ImageIcon(SelectionScreen.class.getResource("/Icons/Release.png"))); levelTypesPanel.add(tglbtnRelease); levelTypeGroup.add(tglbtnRelease); tglbtnRelease.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JToggleButton tBtn = (JToggleButton)arg0.getSource(); if (tBtn.isSelected()) { txtrTextAboutLevel.setText("Release"); } } }); JScrollPane levelViewer = new JScrollPane(); levelViewer.setEnabled(false); levelViewer.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); levelViewerAndSelector.setLeftComponent(levelViewer); JPanel levelsList = new JPanel(); levelViewer.setViewportView(levelsList); for (int i=1; i<=5; i++){ JLabel lblPuzzle = new JLabel("Puzzle "+i); lblPuzzle.setHorizontalAlignment(SwingConstants.CENTER); lblPuzzle.setPreferredSize(levelPreviewSize); lblPuzzle.setMaximumSize(levelPreviewSize); lblPuzzle.setMinimumSize(levelPreviewSize); levelsList.add(lblPuzzle); } for (int i=1; i<=5; i++){ JLabel lblLightning = new JLabel("Lightning "+i); lblLightning.setHorizontalAlignment(SwingConstants.CENTER); lblLightning.setPreferredSize(levelPreviewSize); lblLightning.setMaximumSize(levelPreviewSize); lblLightning.setMinimumSize(levelPreviewSize); levelsList.add(lblLightning); } for (int i=1; i<=5; i++){ JLabel lblRelease = new JLabel("Release "+i); lblRelease.setHorizontalAlignment(SwingConstants.CENTER); lblRelease.setPreferredSize(levelPreviewSize); lblRelease.setMaximumSize(levelPreviewSize); lblRelease.setMinimumSize(levelPreviewSize); levelsList.add(lblRelease); } } }
package net.yazeed44.imagepicker.util; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.annotation.NonNull; import android.support.annotation.StyleRes; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.ColorUtils; import android.util.TypedValue; import net.yazeed44.imagepicker.library.R; import net.yazeed44.imagepicker.model.ImageEntry; import net.yazeed44.imagepicker.ui.PickerActivity; import java.util.ArrayList; import de.greenrobot.event.EventBus; public final class Picker { public final int limit; public final Context context; public final int fabBackgroundColor; public final int fabBackgroundColorWhenPressed; public final int imageBackgroundColorWhenChecked; public final int imageBackgroundColor; public final int imageCheckColor; public final int checkedImageOverlayColor; public final PickListener pickListener; public final int albumImagesCountTextColor; public final int albumBackgroundColor; public final int albumNameTextColor; public final PickMode pickMode; public final int themeResId; public final int popupThemeResId; public final int captureItemIconTintColor; public final int doneFabIconTintColor; public final boolean shouldShowCaptureMenuItem; public final int checkIconTintColor; public final boolean videosEnabled; public final int videoLengthLimit; public final int videoThumbnailOverlayColor; public final int videoIconTintColor; private Picker(final Builder builder) { context = builder.mContext; limit = builder.mLimit; fabBackgroundColor = builder.mFabBackgroundColor; fabBackgroundColorWhenPressed = builder.mFabBackgroundColorWhenPressed; imageBackgroundColorWhenChecked = builder.mImageBackgroundColorWhenChecked; imageBackgroundColor = builder.mImageBackgroundColor; imageCheckColor = builder.mImageCheckColor; checkedImageOverlayColor = builder.mCheckedImageOverlayColor; pickListener = builder.mPickListener; albumBackgroundColor = builder.mAlbumBackgroundColor; albumImagesCountTextColor = builder.mAlbumImagesCountTextColor; albumNameTextColor = builder.mAlbumNameTextColor; pickMode = builder.mPickMode; themeResId = builder.mThemeResId; popupThemeResId = builder.mPopupThemeResId; captureItemIconTintColor = builder.mCaptureItemIconTintColor; doneFabIconTintColor = builder.mDoneFabIconTintColor; shouldShowCaptureMenuItem = builder.mShouldShowCaptureMenuItem; checkIconTintColor = builder.mCheckIconTintColor; videosEnabled = builder.mVideosEnabled; videoLengthLimit = builder.mVideoLengthLimit; videoThumbnailOverlayColor = builder.mVideoThumbnailOverlayColor; videoIconTintColor = builder.mVideoIconTintColor; } public void startActivity() { EventBus.getDefault().postSticky(new Events.OnPublishPickOptionsEvent(this)); final Intent intent = new Intent(context, PickerActivity.class); context.startActivity(intent); } public enum PickMode { SINGLE_IMAGE, MULTIPLE_IMAGES } public interface PickListener { void onPickedSuccessfully(final ArrayList<ImageEntry> images); void onCancel(); } public static class Builder { private final Context mContext; private final PickListener mPickListener; private final int mThemeResId; private int mLimit = PickerActivity.NO_LIMIT; private int mFabBackgroundColor; private int mFabBackgroundColorWhenPressed; private int mImageBackgroundColorWhenChecked; private int mImageBackgroundColor; private int mImageCheckColor; private int mCheckedImageOverlayColor; private int mAlbumImagesCountTextColor; private int mAlbumBackgroundColor; private int mAlbumNameTextColor; private PickMode mPickMode; private int mPopupThemeResId; private int mDoneFabIconTintColor; private int mCaptureItemIconTintColor; private boolean mShouldShowCaptureMenuItem; private int mCheckIconTintColor; private boolean mVideosEnabled; private int mVideoLengthLimit; private int mVideoThumbnailOverlayColor; private int mVideoIconTintColor; //Use (Context,PickListener,themeResId) instead @Deprecated public Builder(final Context context, final PickListener listener) { mThemeResId = R.style.Theme_AppCompat_Light_NoActionBar; mContext = context; mContext.setTheme(mThemeResId); mPickListener = listener; init(); } public Builder(@NonNull final Context context, @NonNull final PickListener listener, @StyleRes final int themeResId) { mContext = context; mContext.setTheme(themeResId); mPickListener = listener; mThemeResId = themeResId; init(); } private void init() { final TypedValue typedValue = new TypedValue(); initUsingColorAccent(typedValue); mImageBackgroundColor = getColor(R.color.alter_unchecked_image_background); mImageCheckColor = getColor(R.color.alter_image_check_color); mCheckedImageOverlayColor = getColor(R.color.alter_checked_photo_overlay); mAlbumBackgroundColor = getColor(R.color.alter_album_background); mAlbumNameTextColor = getColor(R.color.alter_album_name_text_color); mAlbumImagesCountTextColor = getColor(R.color.alter_album_images_count_text_color); mFabBackgroundColorWhenPressed = ColorUtils.setAlphaComponent(mFabBackgroundColor, (int) (android.graphics.Color.alpha(mFabBackgroundColor) * 0.8f)); mPickMode = PickMode.MULTIPLE_IMAGES; mPopupThemeResId = Util.getDefaultPopupTheme(mContext); mCaptureItemIconTintColor = mDoneFabIconTintColor = Util.getDefaultIconTintColor(mContext); mShouldShowCaptureMenuItem = true; mCheckIconTintColor = Color.WHITE; mVideosEnabled = false; mVideoLengthLimit = 0; // No limit mVideoThumbnailOverlayColor = getColor(R.color.alter_video_thumbnail_overlay); mVideoIconTintColor = Color.WHITE; } private int getColor(@ColorRes final int colorRes) { return ContextCompat.getColor(mContext, colorRes); } private void initUsingColorAccent(final TypedValue typedValue) { mContext.getTheme().resolveAttribute(R.attr.colorAccent, typedValue, true); mImageBackgroundColorWhenChecked = mFabBackgroundColor = typedValue.data; } /** * @param limit limit for the count of image user can pick , By default it's infinite */ public Picker.Builder setLimit(final int limit) { mLimit = limit; return this; } public Picker.Builder setFabBackgroundColor(@ColorInt final int color) { mFabBackgroundColor = color; return this; } public Picker.Builder setFabBackgroundColorWhenPressed(@ColorInt final int color) { mFabBackgroundColorWhenPressed = color; return this; } public Picker.Builder setImageBackgroundColorWhenChecked(@ColorInt final int color) { mImageBackgroundColorWhenChecked = color; return this; } public Picker.Builder setImageBackgroundColor(@ColorInt final int color) { mImageBackgroundColor = color; return this; } public Picker.Builder setImageCheckColor(@ColorInt final int color) { mImageCheckColor = color; return this; } public Picker.Builder setCheckedImageOverlayColor(@ColorInt final int color) { mCheckedImageOverlayColor = color; return this; } public Picker.Builder setAlbumBackgroundColor(@ColorInt final int color) { mAlbumBackgroundColor = color; return this; } public Picker.Builder setAlbumNameTextColor(@ColorInt final int color) { mAlbumNameTextColor = color; return this; } public Picker.Builder setAlbumImagesCountTextColor(@ColorInt final int color) { mAlbumImagesCountTextColor = color; return this; } public Picker.Builder setPickMode(final PickMode pickMode) { mPickMode = pickMode; return this; } public Picker.Builder setToolbarPopupTheme(@StyleRes final int themeRes) { mPopupThemeResId = themeRes; return this; } public Picker.Builder setDoneFabIconTintColor(@ColorInt final int color) { mDoneFabIconTintColor = color; return this; } public Picker.Builder setCaptureItemIconTintColor(@ColorInt final int color) { mCaptureItemIconTintColor = color; return this; } public Picker.Builder disableCaptureImageFromCamera() { mShouldShowCaptureMenuItem = false; return this; } public Picker.Builder setCheckIconTintColor(@ColorInt final int color) { mCheckIconTintColor = color; return this; } public Picker.Builder setVideosEnabled(final boolean enabled) { mVideosEnabled = enabled; return this; } public Picker.Builder setVideoLengthLimitInMilliSeconds(final int limit) { mVideoLengthLimit = limit; return this; } public Picker.Builder setVideoThumbnailOverlayColor(@ColorInt final int color) { mVideoThumbnailOverlayColor = color; return this; } public Picker.Builder setVideoIconTintColor(@ColorInt final int color) { mVideoIconTintColor = color; return this; } public Picker build() { return new Picker(this); } } }
package org.intermine.web.struts; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.intermine.api.InterMineAPI; import org.intermine.api.profile.Profile; import org.intermine.api.search.Scope; import org.intermine.api.template.SwitchOffAbility; import org.intermine.api.template.TemplateManager; import org.intermine.api.template.TemplatePopulator; import org.intermine.api.template.TemplateQuery; import org.intermine.api.template.TemplateValue; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.pathquery.PathConstraint; import org.intermine.pathquery.PathConstraintAttribute; import org.intermine.pathquery.PathConstraintBag; import org.intermine.pathquery.PathConstraintLookup; import org.intermine.pathquery.PathConstraintLoop; import org.intermine.pathquery.PathConstraintMultiValue; import org.intermine.pathquery.PathConstraintNull; import org.intermine.pathquery.PathConstraintSubclass; import org.intermine.util.StringUtil; import org.intermine.web.logic.Constants; import org.intermine.web.logic.session.SessionMethods; import org.intermine.web.util.URLGenerator; import org.intermine.webservice.server.template.result.TemplateResultLinkGenerator; /** * Action to handle submit from the template page. <code>setSavingQueries</code> * can be used to set whether or not queries run by this action are * automatically saved in the user's query history. This property is true by * default. * * @author Mark Woodbridge * @author Thomas Riley */ public class TemplateAction extends InterMineAction { /** Name of skipBuilder parameter **/ public static final String SKIP_BUILDER_PARAMETER = "skipBuilder"; /** path of TemplateAction action **/ public static final String TEMPLATE_ACTION_PATH = "templateAction.do"; /** * Build a query based on the template and the input from the user. There * are some request parameters that, if present, effect the behaviour of the * action. These are: * * <dl> * <dt>skipBuilder</dt> * <dd>If this attribute is specifed (with any value) then the action will * forward directly to the object details page if the results contain just * one object.</dd> * <dt>noSaveQuery</dt> * <dd>If this attribute is specifed (with any value) then the query is not * automatically saved in the user's query history.</dd> * </dl> * * @param mapping * The ActionMapping used to select this instance * @param form * The optional ActionForm bean for this request (if any) * @param request * The HTTP request we are processing * @param response * The HTTP response we are creating * @return an ActionForward object defining where control goes next * * @exception Exception * if the application business logic throws an exception */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); TemplateForm tf = (TemplateForm) form; String templateName = tf.getName(); boolean saveQuery = (request.getParameter("noSaveQuery") == null); boolean skipBuilder = (request.getParameter(SKIP_BUILDER_PARAMETER) != null); boolean editTemplate = (request.getParameter("editTemplate") != null); boolean editQuery = (request.getParameter("editQuery") != null); // Note this is a workaround and will fail if a user has a template with the same name as // a public template but has executed the public one. TemplateManager always give // precedence to user templates when there is a naming clash. String scope = tf.getScope(); if (StringUtils.isBlank(scope)) { scope = Scope.ALL; } SessionMethods.logTemplateQueryUse(session, scope, templateName); Profile profile = SessionMethods.getProfile(session); TemplateManager templateManager = im.getTemplateManager(); TemplateQuery template = templateManager.getTemplate(profile, templateName, scope); TemplateQuery populatedTemplate = TemplatePopulator.getPopulatedTemplate( template, templateFormToTemplateValues(tf, template)); if (!populatedTemplate.isValid()) { recordError(new ActionError("errors.template.badtemplate", StringUtil.prettyList(populatedTemplate.verifyQuery())), request); return mapping.findForward("template"); } if (!editQuery && !skipBuilder && !editTemplate && forwardToLinksPage(request)) { TemplateResultLinkGenerator gen = new TemplateResultLinkGenerator(); String htmlLink = gen.getHtmlLink(new URLGenerator(request) .getPermanentBaseURL(), populatedTemplate); String tabLink = gen.getTabLink(new URLGenerator(request) .getPermanentBaseURL(), populatedTemplate); if (gen.getError() != null) { recordError(new ActionMessage("errors.linkGenerationFailed", gen.getError()), request); return mapping.findForward("template"); } session.setAttribute("htmlLink", htmlLink); session.setAttribute("tabLink", tabLink); String url = new URLGenerator(request).getPermanentBaseURL(); session.setAttribute("highlightedLink", gen.getHighlightedLink(url, populatedTemplate)); String title = populatedTemplate.getTitle(); title = title.replace(" "&nbsp;<img src=\"images/tmpl_arrow.png\" " + "style=\"vertical-align:middle\">&nbsp;"); session.setAttribute("pageTitle", title); session.setAttribute("pageDescription", populatedTemplate .getDescription()); return mapping.findForward("serviceLink"); } if (exportTemplate(request)) { SessionMethods.loadQuery(populatedTemplate, request.getSession(), response); return mapping.findForward("export"); } // We're editing the query: load as a PathQuery if (!skipBuilder && !editTemplate) { SessionMethods.loadQuery(populatedTemplate, request.getSession(), response); session.removeAttribute(Constants.NEW_TEMPLATE); session.removeAttribute(Constants.EDITING_TEMPLATE); form.reset(mapping, request); return mapping.findForward("query"); } else if (editTemplate) { // We want to edit the template: Load the query as a TemplateQuery // Don't care about the form // Reload the initial template session.removeAttribute(Constants.NEW_TEMPLATE); session.setAttribute(Constants.EDITING_TEMPLATE, Boolean.TRUE); template = templateManager.getTemplate(profile, templateName, Scope.ALL); if (template == null) { recordMessage(new ActionMessage("errors.edittemplate.empty"), request); return mapping.findForward("template"); } SessionMethods.loadQuery(template, request.getSession(), response); if (!template.isValid()) { recordError(new ActionError("errors.template.badtemplate", StringUtil.prettyList(template.verifyQuery())), request); } return mapping.findForward("query"); } // Otherwise show the results: load the modified query from the template if (saveQuery) { SessionMethods.loadQuery(populatedTemplate, request.getSession(), response); } form.reset(mapping, request); String qid = SessionMethods.startQueryWithTimeout(request, saveQuery, populatedTemplate); Thread.sleep(200); String trail = ""; // only put query on the trail if we are saving the query // otherwise its a "super top secret" query, e.g. quick search // also, note we are not saving any previous trails. trail resets at // queries and bags if (saveQuery) { trail = "|query"; } else { trail = ""; // session.removeAttribute(Constants.QUERY); } return new ForwardParameters(mapping.findForward("waiting")) .addParameter("qid", qid).addParameter("trail", trail) .forward(); } /** * Methods looks at request parameters if should forward to web service * links page. * * @param request the request * @return true if should be forwarded */ private boolean forwardToLinksPage(HttpServletRequest request) { return "links".equalsIgnoreCase(request.getParameter("actionType")); } private boolean exportTemplate(HttpServletRequest request) { return "exportTemplate".equalsIgnoreCase(request.getParameter("actionType")); } /** * The method returns a map of TemplateValue for each editable constraint. The map is obtained * matching the values retrieved from the request through the TemplateForm with the editable * constraint defined in the current template * @param tf the actionform containing the value from the requst * @param template the current template * @return Map<String, List<TemplateValue> */ protected Map<String, List<TemplateValue>> templateFormToTemplateValues(TemplateForm tf, TemplateQuery template) { Map<String, List<TemplateValue>> templateValues = new HashMap<String, List<TemplateValue>>(); for (String node : template.getEditablePaths()) { List<TemplateValue> nodeValues = new ArrayList<TemplateValue>(); templateValues.put(node, nodeValues); for (PathConstraint c : template.getEditableConstraints(node)) { String key = Integer.toString(template.getEditableConstraints().indexOf(c) + 1); TemplateValue value; SwitchOffAbility switchOffAbility = template.getSwitchOffAbility(c); if (tf.getSwitchOff(key) != null) { switchOffAbility = parseSwitchOffAbility(tf.getSwitchOff(key)); } if (tf.getUseBagConstraint(key)) { ConstraintOp constraintOp = ConstraintOp .getOpForIndex(Integer.valueOf(tf.getBagOp(key))); String constraintValue = (String) tf.getBag(key); value = new TemplateValue(c, constraintOp, constraintValue, TemplateValue.ValueType.BAG_VALUE, switchOffAbility); } else { if (tf.getSwitchOff(key) != null && tf.getSwitchOff(key).equalsIgnoreCase(SwitchOffAbility.OFF.toString())) { String constraintValue = constraintStringValue(c); value = new TemplateValue(c, c.getOp(), constraintValue, TemplateValue.ValueType.SIMPLE_VALUE, switchOffAbility); } else { String op = (String) tf.getAttributeOps(key); if (op == null) { if (c instanceof PathConstraintLookup) { value = new TemplateValue(c, ConstraintOp.LOOKUP, (String) tf.getAttributeValues(key), TemplateValue.ValueType.SIMPLE_VALUE, extraValueToString(tf.getExtraValues(key)), switchOffAbility); } else if (tf.getNullConstraint(key) != null) { if (ConstraintOp.IS_NULL.toString() .equals(tf.getNullConstraint(key))) { value = new TemplateValue(c, ConstraintOp.IS_NULL, ConstraintOp.IS_NULL.toString(), TemplateValue.ValueType.SIMPLE_VALUE, switchOffAbility); } else { value = new TemplateValue(c, ConstraintOp.IS_NOT_NULL, ConstraintOp.IS_NOT_NULL.toString(), TemplateValue.ValueType.SIMPLE_VALUE, switchOffAbility); } } else { continue; } } else { ConstraintOp constraintOp = ConstraintOp .getOpForIndex(Integer.valueOf(op)); String constraintValue = ""; String multiValueAttribute = tf.getMultiValueAttribute(key); if (multiValueAttribute != null && !("".equals(multiValueAttribute))) { constraintValue = tf.getMultiValueAttribute(key); } else { constraintValue = (String) tf.getAttributeValues(key); } String extraValue = (String) tf.getExtraValues(key); value = new TemplateValue(c, constraintOp, constraintValue, TemplateValue.ValueType.SIMPLE_VALUE, extraValue, switchOffAbility); } } } nodeValues.add(value); } } return templateValues; } private String constraintStringValue(PathConstraint con) { if (con instanceof PathConstraintAttribute) { return ((PathConstraintAttribute) con).getValue(); } else if (con instanceof PathConstraintBag) { return ((PathConstraintBag) con).getBag(); } else if (con instanceof PathConstraintLookup) { return ((PathConstraintLookup) con).getValue(); } else if (con instanceof PathConstraintSubclass) { return ((PathConstraintSubclass) con).getType(); } else if (con instanceof PathConstraintLoop) { return ((PathConstraintLoop) con).getLoopPath(); } else if (con instanceof PathConstraintNull) { return ((PathConstraintNull) con).getOp().toString(); } else if (con instanceof PathConstraintMultiValue) { return ((PathConstraintMultiValue) con).getOp().toString(); } return null; } private String extraValueToString(Object extraValue) { if (extraValue == null) { return null; } return extraValue.toString(); } private SwitchOffAbility parseSwitchOffAbility(String value) { for (SwitchOffAbility switchOffAbility : SwitchOffAbility.values()) { if (switchOffAbility.toString().equalsIgnoreCase(value)) { return switchOffAbility; } } throw new IllegalArgumentException("Invalid value specified for constraint" + " switchOffAbility '" + value + "', if this happens there is a bug. "); } }
package com.iterable.iterableapi; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import com.google.android.gms.ads.identifier.AdvertisingIdClient; import com.google.android.gms.common.GooglePlayServicesNotAvailableException; import com.google.android.gms.common.GooglePlayServicesRepairableException; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class IterableApi { //region Variables static final String TAG = "IterableApi"; static volatile IterableApi sharedInstance = new IterableApi(); private Context _applicationContext; private String _apiKey; private String _email; private String _userId; private boolean _debugMode; private Bundle _payloadData; private IterableNotificationData _notificationData; //endregion //region Constructor IterableApi(){ } //endregion //region Getters/Setters /** * Sets the icon to be displayed in notifications. * The icon name should match the resource name stored in the /res/drawable directory. * @param iconName */ public void setNotificationIcon(String iconName) { setNotificationIcon(_applicationContext, iconName); } /** * Retrieves the payload string for a given key. * Used for deeplinking and retrieving extra data passed down along with a campaign. * @param key * @return Returns the requested payload data from the current push campaign if it exists. */ public String getPayloadData(String key) { return (_payloadData != null) ? _payloadData.getString(key, null): null; } /** * Returns the current context for the application. * @return */ Context getMainActivityContext() { return _applicationContext; } /** * Sets debug mode. * @param debugMode */ void setDebugMode(boolean debugMode) { _debugMode = debugMode; } /** * Gets the current state of the debug mode. * @return */ boolean getDebugMode() { return _debugMode; } /** * Set the payload for a given intent if it is from Iterable. * @param intent */ void setPayloadData(Intent intent) { Bundle extras = intent.getExtras(); if (extras != null && extras.containsKey(IterableConstants.ITERABLE_DATA_KEY) && !IterableNotification.isGhostPush(extras)) { setPayloadData(extras); } } /** * Sets the payload bundle. * @param bundle */ void setPayloadData(Bundle bundle) { _payloadData = bundle; } /** * Sets the IterableNotification data * @param data */ void setNotificationData(IterableNotificationData data) { _notificationData = data; } //endregion //region Public Functions /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * @param currentActivity The current activity * @param userId The current userId * @return stored instance of IterableApi */ public static IterableApi sharedInstanceWithApiKeyWithUserId(Activity currentActivity, String apiKey, String userId) { return sharedInstanceWithApiKeyWithUserId(currentActivity, apiKey, userId, false); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * Allows the IterableApi to be intialized with debugging enabled * @param currentActivity The current activity * @param userId * The current userId@return stored instance of IterableApi */ public static IterableApi sharedInstanceWithApiKeyWithUserId(Activity currentActivity, String apiKey, String userId, boolean debugMode) { return sharedInstanceWithApiKeyWithUserId((Context) currentActivity, apiKey, userId, debugMode); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * @param currentContext The current context * @param userId The current userId * @return stored instance of IterableApi */ public static IterableApi sharedInstanceWithApiKeyWithUserId(Context currentContext, String apiKey, String userId) { return sharedInstanceWithApiKey(currentContext, apiKey, null, userId, false); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * Allows the IterableApi to be intialized with debugging enabled * @param currentContext The current context * @return stored instance of IterableApi */ public static IterableApi sharedInstanceWithApiKeyWithUserId(Context currentContext, String apiKey, String userId, boolean debugMode) { return sharedInstanceWithApiKey(currentContext, apiKey, null, userId, debugMode); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * @param currentActivity The current activity * @param email The current email * @return stored instance of IterableApi */ public static IterableApi sharedInstanceWithApiKey(Activity currentActivity, String apiKey, String email) { return sharedInstanceWithApiKey(currentActivity, apiKey, email, false); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * Allows the IterableApi to be intialized with debugging enabled * @param currentActivity The current activity * @param email The current email * @return stored instance of IterableApi */ public static IterableApi sharedInstanceWithApiKey(Activity currentActivity, String apiKey, String email, boolean debugMode) { return sharedInstanceWithApiKey((Context) currentActivity, apiKey, email, debugMode); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * @param currentContext The current context * @param email The current email * @return stored instance of IterableApi */ public static IterableApi sharedInstanceWithApiKey(Context currentContext, String apiKey, String email) { return sharedInstanceWithApiKey(currentContext, apiKey, email, false); } /** * Returns a shared instance of IterableApi. Updates the client data if an instance already exists. * Should be called whenever the app is opened. * Allows the IterableApi to be intialized with debugging enabled * @param currentContext The current context * @param email The current email * @return stored instance of IterableApi */ public static IterableApi sharedInstanceWithApiKey(Context currentContext, String apiKey, String email, boolean debugMode) { return sharedInstanceWithApiKey(currentContext, apiKey, email, null, debugMode); } private static IterableApi sharedInstanceWithApiKey(Context currentContext, String apiKey, String email, String userId, boolean debugMode) { sharedInstance.updateData(currentContext.getApplicationContext(), apiKey, email, userId); if (currentContext instanceof Activity) { Activity currentActivity = (Activity) currentContext; sharedInstance.onNewIntent(currentActivity.getIntent()); } else { IterableLogger.w(TAG, "Notification Opens will not be tracked: "+ "sharedInstanceWithApiKey called with a Context that is not an instance of Activity. " + "Pass in an Activity to IterableApi.sharedInstanceWithApiKey to enable open tracking" + "or call onNewIntent when a new Intent is received."); } sharedInstance.setDebugMode(debugMode); return sharedInstance; } /** * Debugging function to send API calls to different url endpoints. * @param url */ public static void overrideURLEndpointPath(String url) { IterableRequest.overrideUrl = url; } /** * Call onNewIntent to set the payload data and track pushOpens directly if * sharedInstanceWithApiKey was called with a Context rather than an Activity. */ public void onNewIntent(Intent intent) { if (isIterableIntent(intent)) { setPayloadData(intent); tryTrackNotifOpen(intent); } else { IterableLogger.d(TAG, "onNewIntent not triggered by an Iterable notification"); } } /** * Returns whether or not the intent was sent from Iterable. */ public boolean isIterableIntent(Intent intent) { if (intent != null) { Bundle extras = intent.getExtras(); return (extras != null && extras.containsKey(IterableConstants.ITERABLE_DATA_KEY)); } return false; } /** * Registers an existing GCM device token with Iterable. * Recommended to use registerForPush if you do not already have a deviceToken * @param applicationName * @param token */ public void registerDeviceToken(String applicationName, String token) { registerDeviceToken(applicationName, token, null); } /** * Track an event. * @param eventName */ public void track(String eventName) { track(eventName, 0, 0, null); } /** * Track an event. * @param eventName * @param dataFields */ public void track(String eventName, JSONObject dataFields) { track(eventName, 0, 0, dataFields); } /** * Track an event. * @param eventName * @param campaignId * @param templateId */ public void track(String eventName, int campaignId, int templateId) { track(eventName, campaignId, templateId, null); } /** * Track an event. * @param eventName * @param campaignId * @param templateId * @param dataFields */ public void track(String eventName, int campaignId, int templateId, JSONObject dataFields) { JSONObject requestJSON = new JSONObject(); try { addEmailOrUserIdToJson(requestJSON); requestJSON.put(IterableConstants.KEY_EVENT_NAME, eventName); requestJSON.put(IterableConstants.KEY_CAMPAIGN_ID, campaignId); requestJSON.put(IterableConstants.KEY_TEMPLATE_ID, templateId); requestJSON.put(IterableConstants.KEY_DATA_FIELDS, dataFields); } catch (JSONException e) { e.printStackTrace(); } sendPostRequest(IterableConstants.ENDPOINT_TRACK, requestJSON); } public void sendPush(String email, int campaignId) { sendPush(email, campaignId, null, null); } /** * Sends a push campaign to an email address at the given time. * @param sendAt Schedule the message for up to 365 days in the future. * If set in the past, message is sent immediately. * Format is YYYY-MM-DD HH:MM:SS in UTC */ public void sendPush(String email, int campaignId, Date sendAt) { sendPush(email, campaignId, sendAt, null); } /** * Sends a push campaign to an email address. * @param email * @param campaignId * @param dataFields */ public void sendPush(String email, int campaignId, JSONObject dataFields) { sendPush(email, campaignId, null, dataFields); } /** * Sends a push campaign to an email address at the given time. * @param sendAt Schedule the message for up to 365 days in the future. * If set in the past, message is sent immediately. * Format is YYYY-MM-DD HH:MM:SS in UTC */ public void sendPush(String email, int campaignId, Date sendAt, JSONObject dataFields) { JSONObject requestJSON = new JSONObject(); try { requestJSON.put(IterableConstants.KEY_RECIPIENT_EMAIL, email); requestJSON.put(IterableConstants.KEY_CAMPAIGN_ID, campaignId); if (sendAt != null){ SimpleDateFormat sdf = new SimpleDateFormat(IterableConstants.DATEFORMAT); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); String dateString = sdf.format(sendAt); requestJSON.put(IterableConstants.KEY_SEND_AT, dateString); } } catch (JSONException e) { e.printStackTrace(); } sendPostRequest(IterableConstants.ENDPOINT_PUSH_TARGET, requestJSON); } /** * Updates the current user's email. * @param newEmail */ public void updateEmail(String newEmail) { if (_email != null) { JSONObject requestJSON = new JSONObject(); try { requestJSON.put(IterableConstants.KEY_CURRENT_EMAIL, _email); requestJSON.put(IterableConstants.KEY_NEW_EMAIL, newEmail); } catch (JSONException e) { e.printStackTrace(); } sendPostRequest(IterableConstants.ENDPOINT_UPDATE_EMAIL, requestJSON); _email = newEmail; } else { IterableLogger.w(TAG, "updateEmail should not be called with a userId. " + "Init SDK with sharedInstanceWithApiKey instead of sharedInstanceWithApiKeyWithUserId"); } } /** * Updates the current user. * @param dataFields */ public void updateUser(JSONObject dataFields) { JSONObject requestJSON = new JSONObject(); try { addEmailOrUserIdToJson(requestJSON); requestJSON.put(IterableConstants.KEY_DATA_FIELDS, dataFields); } catch (JSONException e) { e.printStackTrace(); } sendPostRequest(IterableConstants.ENDPOINT_UPDATE_USER, requestJSON); } /** * Registers for push notifications. * @param iterableAppId * @param gcmProjectNumber */ public void registerForPush(String iterableAppId, String gcmProjectNumber) { registerForPush(iterableAppId, gcmProjectNumber, false); } /** * Disables the device from push notifications * * The disablePush call first calls registerForPush to obtain the device's registration token. * Then it calls the disablePush api endpoint. * * @param iterableAppId * @param gcmProjectNumber */ public void disablePush(String iterableAppId, String gcmProjectNumber) { registerForPush(iterableAppId, gcmProjectNumber, true); } /** * Gets a notification from Iterable and displays it on device. * @param context * @param clickCallback */ public void spawnInAppNotification(final Context context, final IterableHelper.IterableActionHandler clickCallback) { getInAppMessages(1, new IterableHelper.IterableActionHandler(){ @Override public void execute(String payload) { JSONObject dialogOptions = IterableInAppManager.getNextMessageFromPayload(payload); if (dialogOptions != null) { JSONObject message = dialogOptions.optJSONObject(IterableConstants.ITERABLE_IN_APP_CONTENT); int templateId = message.optInt(IterableConstants.KEY_TEMPLATE_ID); int campaignId = dialogOptions.optInt(IterableConstants.KEY_CAMPAIGN_ID); String messageId = dialogOptions.optString(IterableConstants.KEY_MESSAGE_ID); IterableApi.sharedInstance.trackInAppOpen(campaignId, templateId, messageId); IterableNotificationData trackParams = new IterableNotificationData(campaignId, templateId, messageId); IterableInAppManager.showNotification(context, message, trackParams, clickCallback); } } }); } /** * Gets a list of InAppNotifications from Iterable; passes the result to the callback. * @param count the number of messages to fetch * @param onCallback */ public void getInAppMessages(int count, IterableHelper.IterableActionHandler onCallback) { JSONObject requestJSON = new JSONObject(); addEmailOrUserIdToJson(requestJSON); try { addEmailOrUserIdToJson(requestJSON); requestJSON.put(IterableConstants.ITERABLE_IN_APP_COUNT, count); } catch (JSONException e) { e.printStackTrace(); } sendGetRequest(IterableConstants.ENDPOINT_GET_INAPP_MESSAGES, requestJSON, onCallback); } /** * Tracks an InApp open. * @param campaignId * @param templateId * @param messageId */ public void trackInAppOpen(int campaignId, int templateId, String messageId) { JSONObject requestJSON = new JSONObject(); try { addEmailOrUserIdToJson(requestJSON); requestJSON.put(IterableConstants.KEY_CAMPAIGN_ID, campaignId); requestJSON.put(IterableConstants.KEY_TEMPLATE_ID, templateId); requestJSON.put(IterableConstants.KEY_MESSAGE_ID, messageId); } catch (JSONException e) { e.printStackTrace(); } sendPostRequest(IterableConstants.ENDPOINT_TRACK_INAPP_OPEN, requestJSON); } /** * Tracks an InApp click. * @param campaignId * @param templateId * @param messageId * @param buttonIndex */ public void trackInAppClick(int campaignId, int templateId, String messageId, int buttonIndex) { JSONObject requestJSON = new JSONObject(); try { requestJSON.put(IterableConstants.KEY_EMAIL, _email); requestJSON.put(IterableConstants.KEY_CAMPAIGN_ID, campaignId); requestJSON.put(IterableConstants.KEY_TEMPLATE_ID, templateId); requestJSON.put(IterableConstants.KEY_MESSAGE_ID, messageId); requestJSON.put(IterableConstants.ITERABLE_IN_APP_BUTTON_INDEX, buttonIndex); } catch (JSONException e) { e.printStackTrace(); } sendPostRequest(IterableConstants.ENDPOINT_TRACK_INAPP_CLICK, requestJSON); } //endregion //region Protected Fuctions /** * Set the notification icon with the given iconName. * @param context * @param iconName */ static void setNotificationIcon(Context context, String iconName) { SharedPreferences sharedPref = context.getSharedPreferences(IterableConstants.NOTIFICATION_ICON_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(IterableConstants.NOTIFICATION_ICON_NAME, iconName); editor.commit(); } /** * Returns the stored notification icon. * @param context * @return */ static String getNotificationIcon(Context context) { SharedPreferences sharedPref = context.getSharedPreferences(IterableConstants.NOTIFICATION_ICON_NAME, Context.MODE_PRIVATE); String iconName = sharedPref.getString(IterableConstants.NOTIFICATION_ICON_NAME, ""); return iconName; } /** * Registers the device for push notifications. * @param iterableAppId * @param gcmProjectNumber * @param disableAfterRegistration */ protected void registerForPush(String iterableAppId, String gcmProjectNumber, boolean disableAfterRegistration) { Intent pushRegistrationIntent = new Intent(_applicationContext, IterablePushReceiver.class); pushRegistrationIntent.setAction(IterableConstants.ACTION_PUSH_REGISTRATION); pushRegistrationIntent.putExtra(IterableConstants.PUSH_APP_ID, iterableAppId); pushRegistrationIntent.putExtra(IterableConstants.PUSH_GCM_PROJECT_NUMBER, gcmProjectNumber); pushRegistrationIntent.putExtra(IterableConstants.PUSH_DISABLE_AFTER_REGISTRATION, disableAfterRegistration); _applicationContext.sendBroadcast(pushRegistrationIntent); } /** * Tracks when a push notification is opened on device. * @param campaignId * @param templateId */ protected void trackPushOpen(int campaignId, int templateId, String messageId) { JSONObject requestJSON = new JSONObject(); try { addEmailOrUserIdToJson(requestJSON); requestJSON.put(IterableConstants.KEY_CAMPAIGN_ID, campaignId); requestJSON.put(IterableConstants.KEY_TEMPLATE_ID, templateId); requestJSON.put(IterableConstants.KEY_MESSAGE_ID, messageId); } catch (JSONException e) { e.printStackTrace(); } sendPostRequest(IterableConstants.ENDPOINT_TRACK_PUSH_OPEN, requestJSON); } /** * Internal api call made from IterablePushRegistrationGCM after a registrationToken is obtained. * @param token */ protected void disablePush(String token) { JSONObject requestJSON = new JSONObject(); try { requestJSON.put(IterableConstants.KEY_TOKEN, token); addEmailOrUserIdToJson(requestJSON); } catch (JSONException e) { e.printStackTrace(); } sendPostRequest(IterableConstants.ENDPOINT_DISABLE_DEVICE, requestJSON); } //endregion //region Private Fuctions /** * Updates the data for the current user. * @param context * @param apiKey * @param email * @param userId */ private void updateData(Context context, String apiKey, String email, String userId) { this._applicationContext = context; this._apiKey = apiKey; this._email = email; this._userId = userId; } /** * Attempts to track a notifOpened event from the called Intent. * @param calledIntent */ private void tryTrackNotifOpen(Intent calledIntent) { Bundle extras = calledIntent.getExtras(); if (extras != null) { Intent intent = new Intent(); intent.setClass(_applicationContext, IterablePushOpenReceiver.class); intent.setAction(IterableConstants.ACTION_NOTIF_OPENED); intent.putExtras(extras); _applicationContext.sendBroadcast(intent); } } /** * Registers the GCM registration ID with Iterable. * @param applicationName * @param token * @param dataFields */ private void registerDeviceToken(String applicationName, String token, JSONObject dataFields) { String platform = IterableConstants.MESSAGING_PLATFORM_GOOGLE; JSONObject requestJSON = new JSONObject(); try { addEmailOrUserIdToJson(requestJSON); if (dataFields == null) { dataFields = new JSONObject(); dataFields.put("brand", Build.BRAND); //brand: google dataFields.put("manufacturer", Build.MANUFACTURER); //manufacturer: samsung dataFields.putOpt("advertisingId", getAdvertisingId()); //ADID: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" dataFields.put("systemName", Build.DEVICE); //device name: toro dataFields.put("systemVersion", Build.VERSION.RELEASE); dataFields.put("model", Build.MODEL); //device model: Galaxy Nexus dataFields.put("sdkVersion", Build.VERSION.SDK_INT); //sdk version/api level: 15 } JSONObject device = new JSONObject(); device.put(IterableConstants.KEY_TOKEN, token); device.put(IterableConstants.KEY_PLATFORM, platform); device.put(IterableConstants.KEY_APPLICATION_NAME, applicationName); device.putOpt(IterableConstants.KEY_DATA_FIELDS, dataFields); requestJSON.put(IterableConstants.KEY_DEVICE, device); } catch (JSONException e) { e.printStackTrace(); } sendPostRequest(IterableConstants.ENDPOINT_REGISTER_DEVICE_TOKEN, requestJSON); } /** * Sends the POST request to Iterable. * Performs network operations on an async thread instead of the main thread. * @param resourcePath * @param json */ private void sendPostRequest(String resourcePath, JSONObject json) { IterableApiRequest request = new IterableApiRequest(_apiKey, resourcePath, json, IterableApiRequest.POST, null); new IterableRequest().execute(request); } /** * Sends a GET request to Iterable. * Performs network operations on an async thread instead of the main thread. * @param resourcePath * @param json */ private void sendGetRequest(String resourcePath, JSONObject json, IterableHelper.IterableActionHandler onCallback) { IterableApiRequest request = new IterableApiRequest(_apiKey, resourcePath, json, IterableApiRequest.GET, onCallback); new IterableRequest().execute(request); } /** * Adds the current email or userID to the json request. * @param requestJSON */ private void addEmailOrUserIdToJson(JSONObject requestJSON) { try { if (_email != null) { requestJSON.put(IterableConstants.KEY_EMAIL, _email); } else { requestJSON.put(IterableConstants.KEY_USER_ID, _userId); } } catch (JSONException e) { e.printStackTrace(); } } /** * Gets the advertisingId if available * @return */ private String getAdvertisingId() { String advertisingId = null; try { Class adClass = Class.forName("com.google.android.gms.ads.identifier.AdvertisingIdClient"); if (adClass != null) { AdvertisingIdClient.Info advertisingIdInfo = AdvertisingIdClient.getAdvertisingIdInfo(_applicationContext); if (advertisingIdInfo != null) { advertisingId = advertisingIdInfo.getId(); } } } catch (IOException e) { IterableLogger.w(TAG, e.getMessage()); } catch (GooglePlayServicesNotAvailableException e) { IterableLogger.w(TAG, e.getMessage()); } catch (GooglePlayServicesRepairableException e) { IterableLogger.w(TAG, e.getMessage()); } catch (ClassNotFoundException e) { IterableLogger.d(TAG, "ClassNotFoundException: Can't track ADID. " + "Check that play-services-ads is added to the dependencies.", e); } return advertisingId; } //endregion }
package com.iterable.iterableapi; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RestrictTo; import androidx.annotation.VisibleForTesting; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.List; import java.util.UUID; public class IterableApi { //region Variables private static final String TAG = "IterableApi"; /** * {@link IterableApi} singleton instance */ static volatile IterableApi sharedInstance = new IterableApi(); private Context _applicationContext; IterableConfig config; private String _apiKey; private String _email; private String _userId; private String _authToken; private boolean _debugMode; private Bundle _payloadData; private IterableNotificationData _notificationData; private String _deviceId; private boolean _firstForegroundHandled; IterableApiClient apiClient = new IterableApiClient(new IterableApiAuthProvider()); private @Nullable IterableInAppManager inAppManager; private String inboxSessionId; private IterableAuthManager authManager; private HashMap<String, String> deviceAttributes = new HashMap<>(); //endregion //region Constructor IterableApi() { config = new IterableConfig.Builder().build(); } @VisibleForTesting IterableApi(IterableInAppManager inAppManager) { config = new IterableConfig.Builder().build(); this.inAppManager = inAppManager; } @VisibleForTesting IterableApi(IterableApiClient apiClient, IterableInAppManager inAppManager) { config = new IterableConfig.Builder().build(); this.apiClient = apiClient; this.inAppManager = inAppManager; } //endregion //region Getters/Setters /** * Sets the icon to be displayed in notifications. * The icon name should match the resource name stored in the /res/drawable directory. * @param iconName */ public void setNotificationIcon(@Nullable String iconName) { setNotificationIcon(_applicationContext, iconName); } /** * Retrieves the payload string for a given key. * Used for deeplinking and retrieving extra data passed down along with a campaign. * @param key * @return Returns the requested payload data from the current push campaign if it exists. */ @Nullable public String getPayloadData(@NonNull String key) { return (_payloadData != null) ? _payloadData.getString(key, null) : null; } /** * Retrieves all of the payload as a single Bundle Object * @return Bundle */ @Nullable public Bundle getPayloadData() { return _payloadData; } /** * Returns an {@link IterableInAppManager} that can be used to manage in-app messages. * Make sure the Iterable API is initialized before calling this method. * @return {@link IterableInAppManager} instance */ @NonNull public IterableInAppManager getInAppManager() { if (inAppManager == null) { throw new RuntimeException("IterableApi must be initialized before calling getInAppManager(). " + "Make sure you call IterableApi#initialize() in Application#onCreate"); } return inAppManager; } /** * Returns an {@link IterableAuthManager} that can be used to manage mobile auth. * Make sure the Iterable API is initialized before calling this method. * @return {@link IterableAuthManager} instance */ @NonNull IterableAuthManager getAuthManager() { if (authManager == null) { authManager = new IterableAuthManager(this, config.authHandler, config.expiringAuthTokenRefreshPeriod); } return authManager; } /** * Returns the attribution information ({@link IterableAttributionInfo}) for last push open * or app link click from an email. * @return {@link IterableAttributionInfo} Object containing */ @Nullable public IterableAttributionInfo getAttributionInfo() { return IterableAttributionInfo.fromJSONObject( IterableUtil.retrieveExpirableJsonObject(getPreferences(), IterableConstants.SHARED_PREFS_ATTRIBUTION_INFO_KEY) ); } /** * Stores attribution information. * @param attributionInfo Attribution information object */ void setAttributionInfo(IterableAttributionInfo attributionInfo) { if (_applicationContext == null) { IterableLogger.e(TAG, "setAttributionInfo: Iterable SDK is not initialized with a context."); return; } IterableUtil.saveExpirableJsonObject( getPreferences(), IterableConstants.SHARED_PREFS_ATTRIBUTION_INFO_KEY, attributionInfo.toJSONObject(), 3600 * IterableConstants.SHARED_PREFS_ATTRIBUTION_INFO_EXPIRATION_HOURS * 1000 ); } /** * Returns the current context for the application. * @return */ Context getMainActivityContext() { return _applicationContext; } /** * Sets debug mode. * @param debugMode */ void setDebugMode(boolean debugMode) { _debugMode = debugMode; } /** * Gets the current state of the debug mode. * @return */ boolean getDebugMode() { return _debugMode; } /** * Set the payload for a given intent if it is from Iterable. * @param intent */ void setPayloadData(Intent intent) { Bundle extras = intent.getExtras(); if (extras != null && extras.containsKey(IterableConstants.ITERABLE_DATA_KEY) && !IterableNotificationHelper.isGhostPush(extras)) { setPayloadData(extras); } } /** * Sets the payload bundle. * @param bundle */ void setPayloadData(Bundle bundle) { _payloadData = bundle; } /** * Sets the IterableNotification data * @param data */ void setNotificationData(IterableNotificationData data) { _notificationData = data; if (data != null) { setAttributionInfo(new IterableAttributionInfo(data.getCampaignId(), data.getTemplateId(), data.getMessageId())); } } void setAuthToken(String authToken) { setAuthToken(authToken, false); } void setAuthToken(String authToken, boolean bypassAuth) { if (isInitialized()) { if ((authToken != null && !authToken.equalsIgnoreCase(_authToken)) || (_authToken != null && !_authToken.equalsIgnoreCase(authToken))) { _authToken = authToken; storeAuthData(); completeUserLogin(); } else if (bypassAuth) { completeUserLogin(); } } } HashMap getDeviceAttributes() { return deviceAttributes; } public void setDeviceAttribute(String key, String value) { deviceAttributes.put(key, value); } public void removeDeviceAttribute(String key) { deviceAttributes.remove(key); } //endregion //region Public Functions /** * Get {@link IterableApi} singleton instance * @return {@link IterableApi} singleton instance */ @NonNull public static IterableApi getInstance() { return sharedInstance; } /** * Initializes IterableApi * This method must be called from {@link Application#onCreate()} * Note: Make sure you also call {@link #setEmail(String)} or {@link #setUserId(String)} before calling other methods * * @param context Application context * @param apiKey Iterable Mobile API key */ public static void initialize(@NonNull Context context, @NonNull String apiKey) { initialize(context, apiKey, null); } /** * Initializes IterableApi * This method must be called from {@link Application#onCreate()} * Note: Make sure you also call {@link #setEmail(String)} or {@link #setUserId(String)} before calling other methods * * @param context Application context * @param apiKey Iterable Mobile API key * @param config {@link IterableConfig} object holding SDK configuration options */ public static void initialize(@NonNull Context context, @NonNull String apiKey, @Nullable IterableConfig config) { sharedInstance._applicationContext = context.getApplicationContext(); sharedInstance._apiKey = apiKey; sharedInstance.config = config; if (sharedInstance.config == null) { sharedInstance.config = new IterableConfig.Builder().build(); } sharedInstance.retrieveEmailAndUserId(); IterableActivityMonitor.getInstance().registerLifecycleCallbacks(context); IterableActivityMonitor.getInstance().addCallback(sharedInstance.activityMonitorListener); if (sharedInstance.inAppManager == null) { sharedInstance.inAppManager = new IterableInAppManager(sharedInstance, sharedInstance.config.inAppHandler, sharedInstance.config.inAppDisplayInterval); } loadLastSavedConfiguration(context); IterablePushNotificationUtil.processPendingAction(context); } public static void setContext(Context context) { IterableActivityMonitor.getInstance().registerLifecycleCallbacks(context); } static void loadLastSavedConfiguration(Context context) { SharedPreferences sharedPref = context.getSharedPreferences(IterableConstants.SHARED_PREFS_SAVED_CONFIGURATION, Context.MODE_PRIVATE); boolean offlineMode = sharedPref.getBoolean(IterableConstants.SHARED_PREFS_OFFLINE_MODE_KEY, false); sharedInstance.apiClient.setOfflineProcessingEnabled(offlineMode); } void fetchRemoteConfiguration() { apiClient.getRemoteConfiguration(new IterableHelper.IterableActionHandler() { @Override public void execute(@Nullable String data) { if (data == null) { IterableLogger.e(TAG, "Remote configuration returned null"); return; } try { JSONObject jsonData = new JSONObject(data); boolean offlineConfiguration = jsonData.getBoolean(IterableConstants.KEY_OFFLINE_MODE); sharedInstance.apiClient.setOfflineProcessingEnabled(offlineConfiguration); SharedPreferences sharedPref = sharedInstance.getMainActivityContext().getSharedPreferences(IterableConstants.SHARED_PREFS_SAVED_CONFIGURATION, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putBoolean(IterableConstants.SHARED_PREFS_OFFLINE_MODE_KEY, offlineConfiguration); editor.apply(); } catch (JSONException e) { IterableLogger.e(TAG, "Failed to read remote configuration"); } } }); } /** * Set user email used for API calls * Calling this or {@link #setUserId(String)} is required before making any API calls. * * Note: This clears userId and persists the user email so you only need to call this once when the user logs in. * @param email User email */ public void setEmail(@Nullable String email) { setEmail(email, null); } public void setEmail(@Nullable String email, @Nullable String authToken) { //Only if passed in same non-null email if (_email != null && _email.equals(email)) { checkAndUpdateAuthToken(authToken); return; } if (_email == null && _userId == null && email == null) { return; } logoutPreviousUser(); _email = email; _userId = null; storeAuthData(); onLogin(authToken); } /** * Set user ID used for API calls * Calling this or {@link #setEmail(String)} is required before making any API calls. * * Note: This clears user email and persists the user ID so you only need to call this once when the user logs in. * @param userId User ID */ public void setUserId(@Nullable String userId) { setUserId(userId, null); } public void setUserId(@Nullable String userId, @Nullable String authToken) { //If same non null userId is passed if (_userId != null && _userId.equals(userId)) { checkAndUpdateAuthToken(authToken); return; } if (_email == null && _userId == null && userId == null) { return; } logoutPreviousUser(); _email = null; _userId = userId; storeAuthData(); onLogin(authToken); } private void checkAndUpdateAuthToken(@Nullable String authToken) { // If authHandler exists and if authToken is new, it will be considered as a call to update the authToken. if (config.authHandler != null && authToken != null && authToken != _authToken) { setAuthToken(authToken); } } /** * Tracks a click on the uri if it is an iterable link. * @param uri the * @param onCallback Calls the callback handler with the destination location * or the original url if it is not an Iterable link. */ public void getAndTrackDeepLink(@NonNull String uri, @NonNull IterableHelper.IterableActionHandler onCallback) { IterableDeeplinkManager.getAndTrackDeeplink(uri, onCallback); } /** * Handles an App Link * For Iterable links, it will track the click and retrieve the original URL, pass it to * {@link IterableUrlHandler} for handling * If it's not an Iterable link, it just passes the same URL to {@link IterableUrlHandler} * * Call this from {@link Activity#onCreate(Bundle)} and {@link Activity#onNewIntent(Intent)} * in your deep link handler activity * @param uri the URL obtained from {@link Intent#getData()} in your deep link * handler activity * @return whether or not the app link was handled */ public boolean handleAppLink(@NonNull String uri) { IterableLogger.printInfo(); if (IterableDeeplinkManager.isIterableDeeplink(uri)) { IterableDeeplinkManager.getAndTrackDeeplink(uri, new IterableHelper.IterableActionHandler() { @Override public void execute(String originalUrl) { IterableAction action = IterableAction.actionOpenUrl(originalUrl); IterableActionRunner.executeAction(getInstance().getMainActivityContext(), action, IterableActionSource.APP_LINK); } }); return true; } else { IterableAction action = IterableAction.actionOpenUrl(uri); return IterableActionRunner.executeAction(getInstance().getMainActivityContext(), action, IterableActionSource.APP_LINK); } } /** * Debugging function to send API calls to different url endpoints. * @param url */ public static void overrideURLEndpointPath(@NonNull String url) { IterableRequestTask.overrideUrl = url; } /** * Returns whether or not the intent was sent from Iterable. */ public boolean isIterableIntent(@Nullable Intent intent) { if (intent != null) { Bundle extras = intent.getExtras(); return (extras != null && extras.containsKey(IterableConstants.ITERABLE_DATA_KEY)); } return false; } /** * Registers a device token with Iterable. * Make sure {@link IterableConfig#pushIntegrationName} is set before calling this. * @param deviceToken Push token obtained from GCM or FCM */ public void registerDeviceToken(@NonNull String deviceToken) { registerDeviceToken(_email, _userId, _authToken, getPushIntegrationName(), deviceToken, deviceAttributes); } protected void registerDeviceToken(final @Nullable String email, final @Nullable String userId, final @Nullable String authToken, final @NonNull String applicationName, final @NonNull String deviceToken, final HashMap<String, String> deviceAttributes) { if (deviceToken != null) { final Thread registrationThread = new Thread(new Runnable() { public void run() { registerDeviceToken(email, userId, authToken, applicationName, deviceToken, null, deviceAttributes); } }); registrationThread.start(); } } /** * Track an event. * @param eventName */ public void track(@NonNull String eventName) { track(eventName, 0, 0, null); } /** * Track an event. * @param eventName * @param dataFields */ public void track(@NonNull String eventName, @Nullable JSONObject dataFields) { track(eventName, 0, 0, dataFields); } /** * Track an event. * @param eventName * @param campaignId * @param templateId */ public void track(@NonNull String eventName, int campaignId, int templateId) { track(eventName, campaignId, templateId, null); } /** * Track an event. * @param eventName * @param campaignId * @param templateId * @param dataFields */ public void track(@NonNull String eventName, int campaignId, int templateId, @Nullable JSONObject dataFields) { IterableLogger.printInfo(); if (!checkSDKInitialization()) { return; } apiClient.track(eventName, campaignId, templateId, dataFields); } /** * Updates the status of the cart * @param items */ public void updateCart(@NonNull List<CommerceItem> items) { if (!checkSDKInitialization()) { return; } apiClient.updateCart(items); } /** * Tracks a purchase. * @param total total purchase amount * @param items list of purchased items */ public void trackPurchase(double total, @NonNull List<CommerceItem> items) { trackPurchase(total, items, null); } /** * Tracks a purchase. * @param total total purchase amount * @param items list of purchased items * @param dataFields a `JSONObject` containing any additional information to save along with the event */ public void trackPurchase(double total, @NonNull List<CommerceItem> items, @Nullable JSONObject dataFields) { if (!checkSDKInitialization()) { return; } apiClient.trackPurchase(total, items, dataFields); } /** * Updates the current user's email. * Also updates the current email in this IterableAPI instance if the API call was successful. * @param newEmail New email */ public void updateEmail(final @NonNull String newEmail) { updateEmail(newEmail, null, null, null); } public void updateEmail(final @NonNull String newEmail, final @NonNull String authToken) { updateEmail(newEmail, authToken, null, null); } public void updateEmail(final @NonNull String newEmail, final @Nullable IterableHelper.SuccessHandler successHandler, @Nullable IterableHelper.FailureHandler failureHandler) { updateEmail(newEmail, null, successHandler, failureHandler); } /** * Updates the current user's email. * Also updates the current email and authToken in this IterableAPI instance if the API call was successful. * @param newEmail New email * @param successHandler Success handler. Called when the server returns a success code. * @param failureHandler Failure handler. Called when the server call failed. */ public void updateEmail(final @NonNull String newEmail, final @Nullable String authToken, final @Nullable IterableHelper.SuccessHandler successHandler, @Nullable IterableHelper.FailureHandler failureHandler) { if (!checkSDKInitialization()) { IterableLogger.e(TAG, "The Iterable SDK must be initialized with email or userId before " + "calling updateEmail"); if (failureHandler != null) { failureHandler.onFailure("The Iterable SDK must be initialized with email or " + "userId before calling updateEmail", null); } return; } apiClient.updateEmail(newEmail, new IterableHelper.SuccessHandler() { @Override public void onSuccess(@NonNull JSONObject data) { if (_email != null) { _email = newEmail; _authToken = authToken; } storeAuthData(); getAuthManager().requestNewAuthToken(false); if (successHandler != null) { successHandler.onSuccess(data); } } }, failureHandler); } /** * Updates the current user. * @param dataFields */ public void updateUser(@NonNull JSONObject dataFields) { updateUser(dataFields, false); } /** * Updates the current user. * @param dataFields * @param mergeNestedObjects */ public void updateUser(@NonNull JSONObject dataFields, Boolean mergeNestedObjects) { if (!checkSDKInitialization()) { return; } apiClient.updateUser(dataFields, mergeNestedObjects); } private String getPushIntegrationName() { if (config.pushIntegrationName != null) { return config.pushIntegrationName; } else { return _applicationContext.getPackageName(); } } /** * Registers for push notifications. * Make sure the API is initialized with {@link IterableConfig#pushIntegrationName} defined, and * user email or user ID is set before calling this method. */ public void registerForPush() { if (!checkSDKInitialization()) { return; } IterablePushRegistrationData data = new IterablePushRegistrationData(_email, _userId, _authToken, getPushIntegrationName(), IterablePushRegistrationData.PushRegistrationAction.ENABLE); IterablePushRegistration.executePushRegistrationTask(data); } /** * Disables the device from push notifications */ public void disablePush() { IterablePushRegistrationData data = new IterablePushRegistrationData(_email, _userId, _authToken, getPushIntegrationName(), IterablePushRegistrationData.PushRegistrationAction.DISABLE); IterablePushRegistration.executePushRegistrationTask(data); } /** * Updates the user subscription preferences. Passing in an empty array will clear the list, passing in null will not modify the list * @param emailListIds * @param unsubscribedChannelIds * @param unsubscribedMessageTypeIds */ public void updateSubscriptions(@Nullable Integer[] emailListIds, @Nullable Integer[] unsubscribedChannelIds, @Nullable Integer[] unsubscribedMessageTypeIds) { updateSubscriptions(emailListIds, unsubscribedChannelIds, unsubscribedMessageTypeIds, null, null, null); } public void updateSubscriptions(@Nullable Integer[] emailListIds, @Nullable Integer[] unsubscribedChannelIds, @Nullable Integer[] unsubscribedMessageTypeIds, @Nullable Integer[] subscribedMessageTypeIDs, Integer campaignId, Integer templateId) { if (!checkSDKInitialization()) { return; } apiClient.updateSubscriptions(emailListIds, unsubscribedChannelIds, unsubscribedMessageTypeIds, subscribedMessageTypeIDs, campaignId, templateId); } /** * Gets a list of InAppNotifications from Iterable; passes the result to the callback. * Now package-private. If you were previously using this method, use * {@link IterableInAppManager#getMessages()} instead * * @param count the number of messages to fetch * @param onCallback */ void getInAppMessages(int count, @NonNull IterableHelper.IterableActionHandler onCallback) { if (!checkSDKInitialization()) { return; } apiClient.getInAppMessages(count, onCallback); } /** * Tracks an in-app open. * @param message in-app message */ public void trackInAppOpen(@NonNull IterableInAppMessage message, @NonNull IterableInAppLocation location) { if (!checkSDKInitialization()) { return; } if (message == null) { IterableLogger.e(TAG, "trackInAppOpen: message is null"); return; } apiClient.trackInAppOpen(message, location, inboxSessionId); } /** * Tracks when a link inside an in-app is clicked * @param message the in-app message to be tracked * @param clickedUrl the URL of the clicked link * @param clickLocation the location of the in-app for this event */ public void trackInAppClick(@NonNull IterableInAppMessage message, @NonNull String clickedUrl, @NonNull IterableInAppLocation clickLocation) { if (!checkSDKInitialization()) { return; } if (message == null) { IterableLogger.e(TAG, "trackInAppClick: message is null"); return; } apiClient.trackInAppClick(message, clickedUrl, clickLocation, inboxSessionId); } /** * Tracks when an in-app has been closed * @param message the in-app message to be tracked * @param clickedURL the URL of the clicked link * @param closeAction the method of how the in-app was closed * @param clickLocation the location of the in-app for this event */ public void trackInAppClose(@NonNull IterableInAppMessage message, @Nullable String clickedURL, @NonNull IterableInAppCloseAction closeAction, @NonNull IterableInAppLocation clickLocation) { if (!checkSDKInitialization()) { return; } if (message == null) { IterableLogger.e(TAG, "trackInAppClose: message is null"); return; } apiClient.trackInAppClose(message, clickedURL, closeAction, clickLocation, inboxSessionId); } /** * Tracks in-app delivery events (per in-app) * @param message the in-app message to be tracked as delivered */ void trackInAppDelivery(@NonNull IterableInAppMessage message) { if (!checkSDKInitialization()) { return; } if (message == null) { IterableLogger.e(TAG, "trackInAppDelivery: message is null"); return; } apiClient.trackInAppDelivery(message); } /** * Consumes an InApp message. * @param messageId */ public void inAppConsume(@NonNull String messageId) { IterableInAppMessage message = getInAppManager().getMessageById(messageId); if (message == null) { IterableLogger.e(TAG, "inAppConsume: message is null"); return; } inAppConsume(message, null, null); IterableLogger.printInfo(); } /** * Tracks InApp delete. * This method from informs Iterable about inApp messages deleted with additional paramters. * Call this method from places where inApp deletion are invoked by user. The messages can be swiped to delete or can be deleted using the link to delete button. * * @param message message object * @param source An enum describing how the in App delete was triggered * @param clickLocation The module in which the action happened */ public void inAppConsume(@NonNull IterableInAppMessage message, @Nullable IterableInAppDeleteActionType source, @Nullable IterableInAppLocation clickLocation) { if (!checkSDKInitialization()) { return; } apiClient.inAppConsume(message, source, clickLocation, inboxSessionId); } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public void trackInboxSession(@NonNull IterableInboxSession session) { if (!checkSDKInitialization()) { return; } if (session == null) { IterableLogger.e(TAG, "trackInboxSession: session is null"); return; } if (session.sessionStartTime == null || session.sessionEndTime == null) { IterableLogger.e(TAG, "trackInboxSession: sessionStartTime and sessionEndTime must be set"); return; } apiClient.trackInboxSession(session, inboxSessionId); } /** * (DEPRECATED) Tracks an in-app open * @param messageId */ @Deprecated public void trackInAppOpen(@NonNull String messageId) { IterableLogger.printInfo(); if (!checkSDKInitialization()) { return; } apiClient.trackInAppOpen(messageId); } /** * (DEPRECATED) Tracks an in-app open * @param messageId the ID of the in-app message * @param location where the in-app was opened */ @Deprecated void trackInAppOpen(@NonNull String messageId, @NonNull IterableInAppLocation location) { IterableLogger.printInfo(); IterableInAppMessage message = getInAppManager().getMessageById(messageId); if (message != null) { trackInAppOpen(message, location); } else { IterableLogger.w(TAG, "trackInAppOpen: could not find an in-app message with ID: " + messageId); } } /** * (DEPRECATED) Tracks when a link inside an in-app is clicked * @param messageId the ID of the in-app message * @param clickedUrl the URL of the clicked link * @param location where the in-app was opened */ @Deprecated void trackInAppClick(@NonNull String messageId, @NonNull String clickedUrl, @NonNull IterableInAppLocation location) { IterableLogger.printInfo(); IterableInAppMessage message = getInAppManager().getMessageById(messageId); if (message != null) { trackInAppClick(message, clickedUrl, location); } else { trackInAppClick(messageId, clickedUrl); } } /** * (DEPRECATED) Tracks when a link inside an in-app is clicked * @param messageId the ID of the in-app message * @param clickedUrl the URL of the clicked link */ @Deprecated public void trackInAppClick(@NonNull String messageId, @NonNull String clickedUrl) { if (!checkSDKInitialization()) { return; } apiClient.trackInAppClick(messageId, clickedUrl); } /** * (DEPRECATED) Tracks when an in-app has been closed * @param messageId the ID of the in-app message * @param clickedURL the URL of the clicked link * @param closeAction the method of how the in-app was closed * @param clickLocation where the in-app was closed */ @Deprecated void trackInAppClose(@NonNull String messageId, @NonNull String clickedURL, @NonNull IterableInAppCloseAction closeAction, @NonNull IterableInAppLocation clickLocation) { IterableInAppMessage message = getInAppManager().getMessageById(messageId); if (message != null) { trackInAppClose(message, clickedURL, closeAction, clickLocation); IterableLogger.printInfo(); } else { IterableLogger.w(TAG, "trackInAppClose: could not find an in-app message with ID: " + messageId); } } //endregion //region Package-Protected Functions /** * Get user email * @return user email */ String getEmail() { return _email; } /** * Get user ID * @return user ID */ String getUserId() { return _userId; } /** * Get the authentication token * @return authentication token */ String getAuthToken() { return _authToken; } //endregion //region Protected Functions /** * Set the notification icon with the given iconName. * @param context * @param iconName */ static void setNotificationIcon(Context context, String iconName) { SharedPreferences sharedPref = context.getSharedPreferences(IterableConstants.NOTIFICATION_ICON_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(IterableConstants.NOTIFICATION_ICON_NAME, iconName); editor.commit(); } /** * Returns the stored notification icon. * @param context * @return */ static String getNotificationIcon(Context context) { SharedPreferences sharedPref = context.getSharedPreferences(IterableConstants.NOTIFICATION_ICON_NAME, Context.MODE_PRIVATE); String iconName = sharedPref.getString(IterableConstants.NOTIFICATION_ICON_NAME, ""); return iconName; } public void trackPushOpen(int campaignId, int templateId, @NonNull String messageId) { trackPushOpen(campaignId, templateId, messageId, null); } /** * Tracks when a push notification is opened on device. * @param campaignId * @param templateId */ public void trackPushOpen(int campaignId, int templateId, @NonNull String messageId, @Nullable JSONObject dataFields) { if (messageId == null) { IterableLogger.e(TAG, "messageId is null"); return; } apiClient.trackPushOpen(campaignId, templateId, messageId, dataFields); } protected void disableToken(@Nullable String email, @Nullable String userId, @NonNull String token) { disableToken(email, userId, null, token, null, null); } /** * Internal api call made from IterablePushRegistration after a registrationToken is obtained. * It disables the device for all users with this device by default. If `email` or `userId` is provided, it will disable the device for the specific user. * @param email User email for whom to disable the device. * @param userId User ID for whom to disable the device. * @param authToken * @param deviceToken The device token */ protected void disableToken(@Nullable String email, @Nullable String userId, @Nullable String authToken, @NonNull String deviceToken, @Nullable IterableHelper.SuccessHandler onSuccess, @Nullable IterableHelper.FailureHandler onFailure) { if (deviceToken == null) { IterableLogger.d(TAG, "device token not available"); return; } apiClient.disableToken(email, userId, authToken, deviceToken, onSuccess, onFailure); } /** * Registers the GCM registration ID with Iterable. * * @param authToken * @param applicationName * @param deviceToken * @param dataFields */ protected void registerDeviceToken(@Nullable String email, @Nullable String userId, @Nullable String authToken, @NonNull String applicationName, @NonNull String deviceToken, @Nullable JSONObject dataFields, HashMap<String, String> deviceAttributes) { if (!checkSDKInitialization()) { return; } if (deviceToken == null) { IterableLogger.e(TAG, "registerDeviceToken: token is null"); return; } if (applicationName == null) { IterableLogger.e(TAG, "registerDeviceToken: applicationName is null, check that pushIntegrationName is set in IterableConfig"); } apiClient.registerDeviceToken(email, userId, authToken, applicationName, deviceToken, dataFields, deviceAttributes); } //endregion //region Private Functions private final IterableActivityMonitor.AppStateCallback activityMonitorListener = new IterableActivityMonitor.AppStateCallback() { @Override public void onSwitchToForeground() { onForeground(); } @Override public void onSwitchToBackground() {} }; private void onForeground() { if (!_firstForegroundHandled) { _firstForegroundHandled = true; if (sharedInstance.config.autoPushRegistration && sharedInstance.isInitialized()) { IterableLogger.d(TAG, "Performing automatic push registration"); sharedInstance.registerForPush(); } fetchRemoteConfiguration(); } } private boolean isInitialized() { return _apiKey != null && (_email != null || _userId != null); } private boolean checkSDKInitialization() { if (!isInitialized()) { IterableLogger.e(TAG, "Iterable SDK must be initialized with an API key and user email/userId before calling SDK methods"); return false; } return true; } private SharedPreferences getPreferences() { return _applicationContext.getSharedPreferences(IterableConstants.SHARED_PREFS_FILE, Context.MODE_PRIVATE); } private String getDeviceId() { if (_deviceId == null) { _deviceId = getPreferences().getString(IterableConstants.SHARED_PREFS_DEVICEID_KEY, null); if (_deviceId == null) { _deviceId = UUID.randomUUID().toString(); getPreferences().edit().putString(IterableConstants.SHARED_PREFS_DEVICEID_KEY, _deviceId).apply(); } } return _deviceId; } private void storeAuthData() { try { SharedPreferences.Editor editor = getPreferences().edit(); editor.putString(IterableConstants.SHARED_PREFS_EMAIL_KEY, _email); editor.putString(IterableConstants.SHARED_PREFS_USERID_KEY, _userId); editor.putString(IterableConstants.SHARED_PREFS_AUTH_TOKEN_KEY, _authToken); editor.commit(); } catch (Exception e) { IterableLogger.e(TAG, "Error while persisting email/userId", e); } } private void retrieveEmailAndUserId() { try { SharedPreferences prefs = getPreferences(); _email = prefs.getString(IterableConstants.SHARED_PREFS_EMAIL_KEY, null); _userId = prefs.getString(IterableConstants.SHARED_PREFS_USERID_KEY, null); _authToken = prefs.getString(IterableConstants.SHARED_PREFS_AUTH_TOKEN_KEY, null); if (_authToken != null) { getAuthManager().queueExpirationRefresh(_authToken); } } catch (Exception e) { IterableLogger.e(TAG, "Error while retrieving email/userId/authToken", e); } } private void logoutPreviousUser() { if (config.autoPushRegistration && isInitialized()) { disablePush(); } getInAppManager().reset(); getAuthManager().clearRefreshTimer(); apiClient.onLogout(); } private void onLogin(@Nullable String authToken) { if (!isInitialized()) { setAuthToken(null); return; } if (authToken != null) { setAuthToken(authToken); } else { getAuthManager().requestNewAuthToken(false); } } private void completeUserLogin() { if (!isInitialized()) { return; } if (config.autoPushRegistration) { registerForPush(); } getInAppManager().syncInApp(); } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public void setInboxSessionId(@Nullable String inboxSessionId) { this.inboxSessionId = inboxSessionId; } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public void clearInboxSessionId() { this.inboxSessionId = null; } private class IterableApiAuthProvider implements IterableApiClient.AuthProvider { @Nullable @Override public String getEmail() { return _email; } @Nullable @Override public String getUserId() { return _userId; } @Nullable @Override public String getAuthToken() { return _authToken; } @Override public String getApiKey() { return _apiKey; } @Override public String getDeviceId() { return IterableApi.this.getDeviceId(); } @Override public Context getContext() { return _applicationContext; } @Override public void resetAuth() { IterableLogger.d(TAG, "Resetting authToken"); _authToken = null; } } //endregion }
package org.javarosa.demo.applogic; import java.io.IOException; import java.util.Vector; import javax.microedition.midlet.MIDlet; import org.javarosa.core.model.CoreModelModule; import org.javarosa.core.model.SubmissionProfile; import org.javarosa.core.model.condition.IFunctionHandler; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.model.utils.DateUtils; import org.javarosa.core.model.utils.IPreloadHandler; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.reference.RootTranslator; import org.javarosa.core.services.Logger; import org.javarosa.core.services.PropertyManager; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.services.properties.JavaRosaPropertyRules; import org.javarosa.core.util.JavaRosaCoreModule; import org.javarosa.core.util.PropertyUtils; import org.javarosa.demo.properties.DemoAppProperties; import org.javarosa.demo.util.MetaPreloadHandler; import org.javarosa.formmanager.FormManagerModule; import org.javarosa.formmanager.properties.FormManagerProperties; import org.javarosa.j2me.J2MEModule; import org.javarosa.j2me.util.DumpRMS; import org.javarosa.j2me.view.J2MEDisplay; import org.javarosa.location.LocationModule; import org.javarosa.model.xform.XFormsModule; import org.javarosa.resources.locale.LanguagePackModule; import org.javarosa.resources.locale.LanguageUtils; import org.javarosa.services.transport.SubmissionTransportHelper; import org.javarosa.services.transport.TransportManagerModule; import org.javarosa.services.transport.TransportMessage; import org.javarosa.user.activity.UserModule; import org.javarosa.user.model.User; import org.javarosa.user.utility.UserUtility; public class JRDemoContext { private static JRDemoContext instance; public static JRDemoContext _ () { if (instance == null) { instance = new JRDemoContext(); } return instance; } private MIDlet midlet; private User user; public void setMidlet(MIDlet m) { this.midlet = m; J2MEDisplay.init(m); } public MIDlet getMidlet() { return midlet; } public void init (MIDlet m) { DumpRMS.RMSRecoveryHook(m); loadModules(); //After load modules, so polish translations can be inserted. setMidlet(m); addCustomLanguages(); setProperties(); UserUtility.populateAdminUser(); loadRootTranslator(); } private void loadModules() { new J2MEModule().registerModule(); new JavaRosaCoreModule().registerModule(); new CoreModelModule().registerModule(); new XFormsModule().registerModule(); new TransportManagerModule().registerModule(); new UserModule().registerModule(); new FormManagerModule().registerModule(); new LanguagePackModule().registerModule(); new LocationModule().registerModule(); } private void addCustomLanguages() { Localization.registerLanguageFile("pt", "/messages_jrdemo_pt.txt"); Localization.registerLanguageFile("default", "/messages_jrdemo_default.txt"); } private void parseAndProcessLanguageResources(String resourceString) { Vector<String> resources = DateUtils.split(resourceString, ",", true); for(int i = 0 ; i < resources.size() ; i+=2) { String langkey = resources.elementAt(i); String resource = resources.elementAt(i+1); try { if(!ReferenceManager._().DeriveReference(resource).doesBinaryExist()) { Logger.die("Initialization", new RuntimeException("Language Resource (for locale: " + langkey + ") Unavailable during load. Could not resolve reference for " + resource)); } Localization.registerLanguageReference(langkey, resource); } catch (IOException e) { Logger.exception(e); Logger.die("Initialization", new RuntimeException("Language Resource (for locale: " + langkey + ") Unavailable during load. IO Exception while reading " + resource)); } catch (InvalidReferenceException e) { Logger.exception(e); Logger.die("Initialization", new RuntimeException("Language Resource (for locale: " + langkey + ") unavailable. Invalid JR Reference: " + resource)); } } } private void setProperties() { final String POST_URL = midlet.getAppProperty("JRDemo-Post-Url"); final String FORM_URL = midlet.getAppProperty("Form-Server-Url"); final String VIEW_TYPE = midlet.getAppProperty("Default-View"); final String LANGUAGE = midlet.getAppProperty("cur_locale"); final String LANGUAGE_RESOURCES = midlet.getAppProperty("Locale-Resources"); PropertyManager._().addRules(new JavaRosaPropertyRules()); PropertyManager._().addRules(new DemoAppProperties()); PropertyUtils.initializeProperty("DeviceID", PropertyUtils.genGUID(25)); PropertyUtils.initializeProperty(DemoAppProperties.POST_URL_PROPERTY, POST_URL); PropertyUtils.initializeProperty(DemoAppProperties.FORM_URL_PROPERTY, FORM_URL); PropertyUtils.initializeProperty(FormManagerProperties.VIEW_TYPE_PROPERTY, VIEW_TYPE); if(LANGUAGE_RESOURCES != null && LANGUAGE_RESOURCES != "") { parseAndProcessLanguageResources(LANGUAGE_RESOURCES); } LanguageUtils.initializeLanguage(false, LANGUAGE == null ? "default" : LANGUAGE); } public void setUser (User u) { this.user = u; } public User getUser () { return user; } public TransportMessage buildMessage(FormInstance data, SubmissionProfile profile) { //Right now we have to just give the message the stream, rather than the payload, //since the transport layer won't take payloads. This should be fixed _as soon //as possible_ so that we don't either (A) blow up the memory or (B) lose the ability //to send payloads > than the phones' heap. if(profile == null) { profile = SubmissionTransportHelper.defaultPostSubmission(PropertyManager._().getSingularProperty(DemoAppProperties.POST_URL_PROPERTY)); } try { return SubmissionTransportHelper.createMessage(data, profile); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Error Serializing Data to be transported"); } } public Vector<IPreloadHandler> getPreloaders() { Vector<IPreloadHandler> handlers = new Vector<IPreloadHandler>(); MetaPreloadHandler meta = new MetaPreloadHandler(this.getUser()); handlers.addElement(meta); return handlers; } public Vector<IFunctionHandler> getFuncHandlers () { return null; } public void loadRootTranslator(){ ReferenceManager._().addRootTranslator(new RootTranslator("jr://images/", "jr://resource/")); ReferenceManager._().addRootTranslator(new RootTranslator("jr://audio/", "jr://resource/")); } }
package org.openqa.selenium.chrome; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static java.util.concurrent.TimeUnit.SECONDS; import static org.openqa.selenium.os.CommandLine.findExecutable; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.browserlaunchers.AsyncExecute; import org.openqa.selenium.net.PortProber; import org.openqa.selenium.net.UrlChecker; import org.openqa.selenium.os.CommandLine; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.locks.ReentrantLock; /** * Manages the life and death of a chromedriver server. */ public class ChromeDriverService { /** * System property that defines the location of the chromedriver executable * that will be used by the {@link #createDefaultService() default service}. */ public static final String CHROME_DRIVER_EXE_PROPERTY = "webdriver.chrome.driver"; /** * Used to spawn a new child process when this service is {@link #start() started}. */ private final ProcessBuilder processBuilder; /** * The base URL for the managed server. */ private final URL url; /** * Controls access to {@link #process}. */ private final ReentrantLock lock = new ReentrantLock(); /** * A reference to the current child process. Will be {@code null} whenever * this service is not running. Protected by {@link #lock}. */ private Process process = null; /** * @param executable The chromedriver executable. * @param port Which port to start the chromedriver on. * @throws IOException If an I/O error occurs. */ private ChromeDriverService(File executable, int port) throws IOException { this.processBuilder = new ProcessBuilder( executable.getCanonicalPath(), String.format("--port=%d", port)); url = new URL(String.format("http://localhost:%d", port)); } /** * @return The base URL for the managed chromedriver server. */ public URL getUrl() { return url; } /** * Configures and returns a new {@link ChromeDriverService} using the default * configuration. In this configuration, the service will use the * chromedriver executable identified by the * {@link #CHROME_DRIVER_EXE_PROPERTY} system property. Each service created * by this method will be configured to use a free port on the current * system. * * @return A new ChromeDriverService using the default configuration. */ public static ChromeDriverService createDefaultService() { String defaultPath = findExecutable("chromedriver"); String exePath = System.getProperty(CHROME_DRIVER_EXE_PROPERTY, defaultPath); checkState(exePath != null, "The path to the chromedriver executable must be set by the %s system property", CHROME_DRIVER_EXE_PROPERTY); File exe = new File(exePath); checkState(exe.exists(), "The %s system property defined chromedriver executable does not exist: %s", CHROME_DRIVER_EXE_PROPERTY, exe.getAbsolutePath()); checkState(!exe.isDirectory(), "The %s system property defined chromedriver executable is a directory: %s", CHROME_DRIVER_EXE_PROPERTY, exe.getAbsolutePath()); // TODO(jleyba): Check file.canExecute() once we support Java 1.6 //checkState(exe.canExecute(), // "The %s system property defined chromedriver is not executable: %s", // CHROME_DRIVER_EXE_PROPERTY, exe.getAbsolutePath()); return new Builder() .usingChromeDriverExecutable(exe) .usingAnyFreePort() .build(); } /** * Checks whether the chromedriver child proces is currently running. * * @return Whether the chromedriver child process is still running. */ public boolean isRunning() { lock.lock(); try { if (process == null) { return false; } process.exitValue(); return true; } catch (IllegalThreadStateException e) { return false; } finally { lock.unlock(); } } /** * Starts this service if it is not already running. This method will * block until the server has been fully started and is ready to handle * commands. * * @throws IOException If an error occurs while spawning the child process. * @see #stop() */ public void start() throws IOException { lock.lock(); try { if (process != null) { return; } process = processBuilder.start(); pipe(process.getErrorStream(), System.err); pipe(process.getInputStream(), System.out); URL healthz = new URL(url.toString() + "/healthz"); new UrlChecker().waitUntilAvailable(healthz, 20, SECONDS); } finally { lock.unlock(); } } private static void pipe(final InputStream src, final PrintStream dest) { new Thread(new Runnable() { public void run() { try { byte[] buffer = new byte[1024]; for (int n = 0; n != -1; n = src.read(buffer)) { dest.write(buffer, 0, n); } } catch (IOException e) { // Do nothing. } } }).start(); } /** * Stops this service is it is currently running. This method will attempt to * block until the server has been fully shutdown. * * @see #start() */ public void stop() { lock.lock(); try { if (process == null) { return; } URL killUrl = new URL(url.toString() + "/shutdown"); new UrlChecker().waitUntilUnavailable(killUrl, 3, SECONDS); AsyncExecute.killProcess(process); } catch (MalformedURLException e) { throw new RuntimeException(e); } finally { process = null; lock.unlock(); } } /** * Builder used to configure new {@link ChromeDriverService} instances. */ public static class Builder { private int port = 0; private File exe = null; /** * Sets which chromedriver executable the builder will use. * * @param file The executable to use. * @return A self reference. */ public Builder usingChromeDriverExecutable(File file) { checkNotNull(file); checkArgument(file.exists(), "Specified chromedriver executable does not exist: %s", file.getPath()); checkArgument(!file.isDirectory(), "Specified chromedriver executable is a directory: %s", file.getPath()); // TODO(jleyba): Check file.canExecute() once we support Java 1.6 // checkArgument(file.canExecute(), "File is not executable: %s", file.getPath()); this.exe = file; return this; } /** * Sets which port the chromedriver server should be started on. A value of * 0 indicates that any free port may be used. * * @param port The port to use; must be non-negative. * @return A self reference. */ public Builder usingPort(int port) { checkArgument(port >= 0, "Invalid port number: %d", port); this.port = port; return this; } /** * Configures the chromedriver server to start on any available port. * * @return A self reference. */ public Builder usingAnyFreePort() { this.port = 0; return this; } /** * Creates a new binary to manage the chromedriver server. Before creating * a new binary, the builder will check that either the user defined the * location of the chromedriver executable through * {@link #usingChromeDriverExecutable(File) the API} or with the * {@code webdriver.chrome.driver} system property. * * @return The new binary. */ public ChromeDriverService build() { if (port == 0) { port = PortProber.findFreePort(); } checkState(exe != null, "Path to the chromedriver executable not specified"); try { return new ChromeDriverService(exe, port); } catch (IOException e) { throw new WebDriverException(e); } } } }
package org.xtreemfs.mrc.osdselection; import java.net.InetAddress; import java.util.HashMap; import java.util.List; import java.util.Map; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.logging.Logging.Category; import org.xtreemfs.foundation.util.OutputUtils; import org.xtreemfs.mrc.MRCRequestDispatcher; import org.xtreemfs.mrc.database.DatabaseException; import org.xtreemfs.mrc.database.DatabaseResultSet; import org.xtreemfs.mrc.database.StorageManager; import org.xtreemfs.mrc.database.VolumeInfo; import org.xtreemfs.mrc.metadata.XAttr; import org.xtreemfs.mrc.metadata.XLocList; import org.xtreemfs.mrc.utils.MRCHelper; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.Service; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceDataMap; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceSet; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceType; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.Replica; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.Replicas; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes.VivaldiCoordinates; /** * Volume and policy record. */ public class VolumeOSDFilter { private static final String ATTR_PREFIX = "xtreemfs." + MRCHelper.POLICY_ATTR_PREFIX + "."; private MRCRequestDispatcher master; /** * volume ID */ private String volId; /** * OSD selection policy */ private short[] osdPolicy; /** * replica selection policy */ private short[] replPolicy; /** * map containing instances of all OSD policies */ private Map<Short, OSDSelectionPolicy> policyMap; /** * map containing all known OSDs */ private Map<String, Service> knownOSDMap; public VolumeOSDFilter(MRCRequestDispatcher master, Map<String, Service> knownOSDMap) { this.master = master; this.knownOSDMap = knownOSDMap; } public void init(VolumeInfo volume) throws DatabaseException { this.volId = volume.getId(); this.osdPolicy = volume.getOsdPolicy(); this.replPolicy = volume.getReplicaPolicy(); // initialize the policy map policyMap = new HashMap<Short, OSDSelectionPolicy>(); for (short pol : osdPolicy) { try { if (!policyMap.containsKey(pol)) policyMap.put(pol, master.getPolicyContainer().getOSDSelectionPolicy(pol)); } catch (Exception e) { Logging.logMessage(Logging.LEVEL_ERROR, Category.misc, "could not instantiate OSDSelectionPolicy %d", pol); Logging.logMessage(Logging.LEVEL_ERROR, Category.misc, OutputUtils.stackTraceToString(e)); } } for (short pol : replPolicy) { try { if (!policyMap.containsKey(pol)) policyMap.put(pol, master.getPolicyContainer().getOSDSelectionPolicy(pol)); } catch (Exception e) { Logging.logMessage(Logging.LEVEL_ERROR, Category.misc, "could not instantiate OSDSelectionPolicy %d", pol); Logging.logMessage(Logging.LEVEL_ERROR, Category.misc, OutputUtils.stackTraceToString(e)); } } // get all policy attributes try { DatabaseResultSet<XAttr> xattrs = master.getVolumeManager().getStorageManager(volId) .getXAttrs(1, StorageManager.SYSTEM_UID); // set the while (xattrs.hasNext()) { XAttr xattr = xattrs.next(); if (xattr.getKey().startsWith(ATTR_PREFIX)) setAttribute(xattr.getKey(), xattr.getValue()); } xattrs.destroy(); } catch (Exception exc) { Logging.logMessage(Logging.LEVEL_ERROR, Category.misc, "could not set policy attributes"); Logging.logMessage(Logging.LEVEL_ERROR, Category.misc, OutputUtils.stackTraceToString(exc)); } } public void setAttribute(String key, String value) { assert (key.startsWith(ATTR_PREFIX)); key = key.substring(ATTR_PREFIX.length()); int index = key.indexOf('.'); if (index == -1) for (OSDSelectionPolicy pol : policyMap.values()) pol.setAttribute(key, value); else { short policyId = Short.parseShort(key.substring(0, index)); OSDSelectionPolicy pol = policyMap.get(policyId); if (pol != null) pol.setAttribute(key.substring(index + 1), value); } } public ServiceSet.Builder filterByOSDSelectionPolicy(ServiceSet.Builder knownOSDs, InetAddress clientIP, VivaldiCoordinates clientCoords, XLocList currentXLoc, int numOSDs) { ServiceSet.Builder result = ServiceSet.newBuilder().addAllServices(knownOSDs.getServicesList()); for (short id : osdPolicy) { OSDSelectionPolicy policy = policyMap.get(id); if (policy == null) { Logging.logMessage(Logging.LEVEL_ERROR, Category.proc, this, "could not find OSD selection policy with ID=%d", id); return result; } result = policy.getOSDs(result, clientIP, clientCoords, currentXLoc, numOSDs); } return result; } public ServiceSet.Builder filterByOSDSelectionPolicy(ServiceSet.Builder knownOSDs) { ServiceSet.Builder result = ServiceSet.newBuilder().addAllServices(knownOSDs.getServicesList()); for (short id : osdPolicy) { OSDSelectionPolicy policy = policyMap.get(id); if (policy == null) { Logging.logMessage(Logging.LEVEL_WARN, Category.misc, this, "could not find OSD selection policy with ID %d, will be ignored", id); continue; } result = policy.getOSDs(result); } return result; } public Replicas sortByReplicaSelectionPolicy(InetAddress clientIP, VivaldiCoordinates clientCoords, List<Replica> unsortedRepls, XLocList xLocList) { // head OSD -> replica Map<String, Replica> replMap = new HashMap<String, Replica>(); // get a list of all head OSDs in the XLoc ServiceSet.Builder headOSDServiceSetBuilder = ServiceSet.newBuilder(); for (int i = 0; i < unsortedRepls.size(); i++) { Replica repl = unsortedRepls.get(i); assert (repl.getOsdUuidsCount() > 0); String headOSD = repl.getOsdUuids(0); // store the mapping in a temprorary replica map replMap.put(headOSD, repl); // retrieve the service name from the 'known OSDs' map; if no such // service has been registered, create a dummy service object from // the OSD UUID Service s = knownOSDMap.get(headOSD); if (s == null) s = Service.newBuilder().setData(ServiceDataMap.newBuilder()).setLastUpdatedS(0) .setName("OSD @ " + headOSD).setType(ServiceType.SERVICE_TYPE_OSD).setUuid(headOSD) .setVersion(0).build(); headOSDServiceSetBuilder.addServices(s); } // sort the list of head OSDs according to the policy for (short id : replPolicy) headOSDServiceSetBuilder = policyMap.get(id).getOSDs(headOSDServiceSetBuilder, clientIP, clientCoords, xLocList, headOSDServiceSetBuilder.getServicesCount()); // arrange the resulting list of replicas in the same order as the list // of sorted head OSDs Replicas.Builder sortedReplsBuilder = Replicas.newBuilder(); for (Service headOSD : headOSDServiceSetBuilder.getServicesList()) { Replica r = replMap.get(headOSD.getUuid()); assert (r != null); assert (r.getOsdUuidsCount() > 0); Replica.Builder replBuilder = Replica.newBuilder().setReplicationFlags(r.getReplicationFlags()) .setStripingPolicy(r.getStripingPolicy()); for (int j = 0; j < r.getOsdUuidsCount(); j++) replBuilder.addOsdUuids(r.getOsdUuids(j)); sortedReplsBuilder.addReplicas(replBuilder); } return sortedReplsBuilder.build(); } }
package org.broadinstitute.sting.utils.genotype.vcf; import org.broad.tribble.vcf.*; import org.broadinstitute.sting.gatk.contexts.variantcontext.Allele; import org.broadinstitute.sting.gatk.contexts.variantcontext.Genotype; import org.broadinstitute.sting.gatk.contexts.variantcontext.VariantContext; import org.broadinstitute.sting.utils.GenomeLoc; import org.broadinstitute.sting.utils.MathUtils; import org.broadinstitute.sting.utils.StingException; import org.broadinstitute.sting.utils.Utils; import org.broadinstitute.sting.utils.genotype.CalledGenotype; import org.broadinstitute.sting.utils.pileup.ReadBackedPileup; import java.io.*; import java.util.*; /** * this class writers VCF files */ public class VCFWriter { // the VCF header we're storing private VCFHeader mHeader = null; // the print stream we're writting to BufferedWriter mWriter; private boolean writingVCF40Format; // our genotype sample fields private static final List<VCFGenotypeRecord> mGenotypeRecords = new ArrayList<VCFGenotypeRecord>(); // Properties only used when using VCF4.0 encoding Map<String, VCFFormatHeaderLine.FORMAT_TYPE> typeUsedForFormatString = new HashMap<String, VCFFormatHeaderLine.FORMAT_TYPE>(); Map<String, VCFInfoHeaderLine.INFO_TYPE> typeUsedForInfoFields = new HashMap<String, VCFInfoHeaderLine.INFO_TYPE>(); Map<String, Integer> numberUsedForInfoFields = new HashMap<String, Integer>(); Map<String, Integer> numberUsedForFormatFields = new HashMap<String, Integer>(); // commonly used strings that are in the standard private final String FORMAT_FIELD_SEPARATOR = ":"; private static final String GENOTYPE_FIELD_SEPARATOR = ":"; private static final String FIELD_SEPARATOR = "\t"; private static final String FILTER_CODE_SEPARATOR = ";"; private static final String INFO_FIELD_SEPARATOR = ";"; // default values private static final String UNFILTERED = "."; private static final String PASSES_FILTERS = "0"; private static final String PASSES_FILTERS_VCF_4_0 = "PASS"; private static final String EMPTY_INFO_FIELD = "."; private static final String EMPTY_ID_FIELD = "."; private static final String EMPTY_ALLELE_FIELD = "."; private static final String DOUBLE_PRECISION_FORMAT_STRING = "%.2f"; private static final String MISSING_GENOTYPE_FIELD = "."; /** * create a VCF writer, given a file to write to * * @param location the file location to write to */ public VCFWriter(File location) { this(location, false); } public VCFWriter(File location, boolean useVCF4Format) { this.writingVCF40Format = useVCF4Format; FileOutputStream output; try { output = new FileOutputStream(location); } catch (FileNotFoundException e) { throw new RuntimeException("Unable to create VCF file at location: " + location); } mWriter = new BufferedWriter(new OutputStreamWriter(output)); } /** * create a VCF writer, given a stream to write to * * @param output the file location to write to */ public VCFWriter(OutputStream output) { // use VCF3.3 by default this(output, false); } public VCFWriter(OutputStream output, boolean useVCF4Format) { this.writingVCF40Format = useVCF4Format; mWriter = new BufferedWriter(new OutputStreamWriter(output)); } public void writeHeader(VCFHeader header) { this.mHeader = header; try { // the file format field needs to be written first TreeSet<VCFHeaderLine> nonFormatMetaData = new TreeSet<VCFHeaderLine>(); for ( VCFHeaderLine line : header.getMetaData() ) { if (writingVCF40Format) { if ( line.getKey().equals(VCFHeaderVersion.VCF4_0.getFormatString()) ) { mWriter.write(VCFHeader.METADATA_INDICATOR + VCFHeaderVersion.VCF4_0.getFormatString() + "=" + VCFHeaderVersion.VCF4_0.getVersionString() + "\n"); } else { nonFormatMetaData.add(line); } // Record, if line corresponds to a FORMAT field, which type will be used for writing value if (line.getClass() == VCFFormatHeaderLine.class) { VCFFormatHeaderLine a = (VCFFormatHeaderLine)line; String key = a.getmName(); typeUsedForFormatString.put(key,a.getmType()); int num = a.getmCount(); numberUsedForFormatFields.put(key,num); } else if (line.getClass() == VCFInfoHeaderLine.class) { VCFInfoHeaderLine a = (VCFInfoHeaderLine)line; String key = a.getmName(); typeUsedForInfoFields.put(key,a.getmType()); int num = a.getmCount(); numberUsedForInfoFields.put(key, num); } } else { if ( line.getKey().equals(VCFHeaderVersion.VCF3_3.getFormatString()) ) { mWriter.write(VCFHeader.METADATA_INDICATOR + line.toString() + "\n"); } else if ( line.getKey().equals(VCFHeaderVersion.VCF3_2.getFormatString()) ) { mWriter.write(VCFHeader.METADATA_INDICATOR + VCFHeaderVersion.VCF3_2.getFormatString() + "=" + VCFHeaderVersion.VCF3_2.getVersionString() + "\n"); } else { nonFormatMetaData.add(line); } } } // write the rest of the header meta-data out for ( VCFHeaderLine line : nonFormatMetaData ) mWriter.write(VCFHeader.METADATA_INDICATOR + line + "\n"); // write out the column line StringBuilder b = new StringBuilder(); b.append(VCFHeader.HEADER_INDICATOR); for (VCFHeader.HEADER_FIELDS field : header.getHeaderFields()) b.append(field + FIELD_SEPARATOR); if (header.hasGenotypingData()) { b.append("FORMAT" + FIELD_SEPARATOR); for (String field : header.getGenotypeSamples()) b.append(field + FIELD_SEPARATOR); } mWriter.write(b.toString() + "\n"); mWriter.flush(); // necessary so that writing to an output stream will work } catch (IOException e) { throw new RuntimeException("IOException writing the VCF header", e); } } /** * output a record to the VCF file * * @param record the record to output */ public void add(VCFRecord record) { addRecord(record); } public void addRecord(VCFRecord record) { addRecord(record, VCFGenotypeWriter.VALIDATION_STRINGENCY.STRICT); } public void add(VariantContext vc, byte[] refBases) { if ( mHeader == null ) throw new IllegalStateException("The VCF Header must be written before records can be added"); if (!writingVCF40Format) throw new IllegalStateException("VCFWriter can only support add() method with a variant context if writing VCF4.0. Use VCFWriter(output, true) when constructing object"); String vcfString = toStringEncoding(vc, mHeader, refBases); try { mWriter.write(vcfString + "\n"); mWriter.flush(); // necessary so that writing to an output stream will work } catch (IOException e) { throw new RuntimeException("Unable to write the VCF object to a file"); } } /** * output a record to the VCF file * * @param record the record to output * @param validationStringency the validation stringency */ public void addRecord(VCFRecord record, VCFGenotypeWriter.VALIDATION_STRINGENCY validationStringency) { if ( mHeader == null ) throw new IllegalStateException("The VCF Header must be written before records can be added"); String vcfString = record.toStringEncoding(mHeader); try { mWriter.write(vcfString + "\n"); mWriter.flush(); // necessary so that writing to an output stream will work } catch (IOException e) { throw new RuntimeException("Unable to write the VCF object to a file"); } } /** * attempt to close the VCF file */ public void close() { try { mWriter.flush(); mWriter.close(); } catch (IOException e) { throw new RuntimeException("Unable to close VCFFile"); } } private String toStringEncoding(VariantContext vc, VCFHeader header, byte[] refBases) { StringBuilder builder = new StringBuilder(); // CHROM \t POS \t ID \t REF \t ALT \t QUAL \t FILTER \t INFO GenomeLoc loc = vc.getLocation(); String contig = loc.getContig(); long position = loc.getStart(); String ID = vc.hasAttribute("ID") ? vc.getAttributeAsString("ID") : EMPTY_ID_FIELD; // deal with the reference String referenceFromVC = new String(vc.getReference().getBases()); double qual = vc.hasNegLog10PError() ? vc.getPhredScaledQual() : -1; // TODO- clean up these flags and associated code boolean filtersWereAppliedToContext = true; List<String> allowedGenotypeAttributeKeys = null; boolean filtersWereAppliedToGenotypes = false; String filters = vc.isFiltered() ? Utils.join(";", Utils.sorted(vc.getFilters())) : (filtersWereAppliedToContext ? PASSES_FILTERS_VCF_4_0 : UNFILTERED); Map<Allele, VCFGenotypeEncoding> alleleMap = new HashMap<Allele, VCFGenotypeEncoding>(); alleleMap.put(Allele.NO_CALL, new VCFGenotypeEncoding(VCFGenotypeRecord.EMPTY_ALLELE)); // convenience for lookup List<VCFGenotypeEncoding> vcfAltAlleles = new ArrayList<VCFGenotypeEncoding>(); int refIndex=0, numTrailingBases = 0, numPaddingBases = 0; String paddingBases = new String(""); String trailingBases = new String(""); ArrayList<Allele> originalAlleles = (ArrayList)vc.getAttribute("ORIGINAL_ALLELE_LIST"); // search for reference allele and find trailing and padding at the end. if (originalAlleles != null) { Allele originalReferenceAllele = null; for (refIndex=0; refIndex < originalAlleles.size(); refIndex++) { originalReferenceAllele = originalAlleles.get(refIndex); if (originalReferenceAllele.isReference()) break; } if (originalReferenceAllele == null) throw new IllegalStateException("At least one Allele must be reference"); for ( Allele a : vc.getAlleles() ) { if (a.isNonReference()) continue; String refString = new String(a.getBases()); String originalRef = new String(originalReferenceAllele.getBases()); if (refString.equals("")) { // special case with null reference: // for example, null reference, originalRef = "AC", alt = "AGC". // In this case, we'd have one trailing and one padding base, with alleles as {-,G}. // TEMP fix: assume in this case one trailing base, more general solution would be to // scan through all alleles and look for maximum common subsequence at beginning and at end for all alleles numTrailingBases = 1; } else numTrailingBases = originalRef.indexOf(refString); numPaddingBases = originalRef.length()-refString.length()-numTrailingBases; if (numTrailingBases > 0) { position -= numTrailingBases; trailingBases = originalRef.substring(0,numTrailingBases); } if (numPaddingBases > 0) paddingBases = originalRef.substring(originalRef.length()-numPaddingBases,originalRef.length()); } } else { // no original Allele information: see first if all alleles have a base encoding (ie no deletions) // if so, add one common base to all alleles (reference at this location) boolean hasBasesInAllAlleles = true; for ( Allele a : vc.getAlleles() ) { String alleleString = new String(a.getBases()); if (alleleString.length()==0) { hasBasesInAllAlleles = false; break; } } if (!hasBasesInAllAlleles) { trailingBases = new String(refBases); numTrailingBases = 1; position } } for ( Allele a : vc.getAlleles() ) { VCFGenotypeEncoding encoding; String alleleString = new String(a.getBases()); String s = trailingBases+alleleString+paddingBases; encoding = new VCFGenotypeEncoding(s, true); // overwrite reference string by possibly padded version if (a.isReference()) referenceFromVC = s; else { vcfAltAlleles.add(encoding); } alleleMap.put(a, encoding); } List<String> vcfGenotypeAttributeKeys = new ArrayList<String>(); if ( vc.hasGenotypes() ) { vcfGenotypeAttributeKeys.add(VCFGenotypeRecord.GENOTYPE_KEY); for ( String key : calcVCFGenotypeKeys(vc) ) { if ( allowedGenotypeAttributeKeys == null || allowedGenotypeAttributeKeys.contains(key) ) vcfGenotypeAttributeKeys.add(key); } if ( filtersWereAppliedToGenotypes ) vcfGenotypeAttributeKeys.add(VCFGenotypeRecord.GENOTYPE_FILTER_KEY); } String genotypeFormatString = Utils.join(GENOTYPE_FIELD_SEPARATOR, vcfGenotypeAttributeKeys); List<VCFGenotypeRecord> genotypeObjects = new ArrayList<VCFGenotypeRecord>(vc.getGenotypes().size()); for ( Genotype g : vc.getGenotypesSortedByName() ) { List<VCFGenotypeEncoding> encodings = new ArrayList<VCFGenotypeEncoding>(g.getPloidy()); for ( Allele a : g.getAlleles() ) { encodings.add(alleleMap.get(a)); } VCFGenotypeRecord.PHASE phasing = g.genotypesArePhased() ? VCFGenotypeRecord.PHASE.PHASED : VCFGenotypeRecord.PHASE.UNPHASED; VCFGenotypeRecord vcfG = new VCFGenotypeRecord(g.getSampleName(), encodings, phasing); for ( String key : vcfGenotypeAttributeKeys ) { if ( key.equals(VCFGenotypeRecord.GENOTYPE_KEY) ) continue; Object val; if (g.hasAttribute(key)) val = g.getAttribute(key); else val = new String(MISSING_GENOTYPE_FIELD); // some exceptions if ( key.equals(VCFGenotypeRecord.GENOTYPE_QUALITY_KEY) ) { if ( MathUtils.compareDoubles(g.getNegLog10PError(), Genotype.NO_NEG_LOG_10PERROR) == 0 ) val = MISSING_GENOTYPE_FIELD; else { // TODO - check whether we need to saturate quality to 99 as in VCF3.3 coder. For now allow unbounded values // val = Math.min(g.getPhredScaledQual(), VCFGenotypeRecord.MAX_QUAL_VALUE); val = g.getPhredScaledQual(); } } else if ( key.equals(VCFGenotypeRecord.DEPTH_KEY) && val == null ) { ReadBackedPileup pileup = (ReadBackedPileup)g.getAttribute(CalledGenotype.READBACKEDPILEUP_ATTRIBUTE_KEY); if ( pileup != null ) val = pileup.size(); } else if ( key.equals(VCFGenotypeRecord.GENOTYPE_FILTER_KEY) ) { // VCF 4.0 key for no filters is "." val = g.isFiltered() ? Utils.join(";", Utils.sorted(g.getFilters())) : UNFILTERED; } Object newVal; if (typeUsedForFormatString.containsKey(key)) { VCFFormatHeaderLine.FORMAT_TYPE formatType = typeUsedForFormatString.get(key); if (!val.getClass().equals(String.class)) newVal = formatType.convert(String.valueOf(val)); else newVal = val; } else { newVal = val; } if (numberUsedForFormatFields.containsKey(key)){ int numInFormatField = numberUsedForFormatFields.get(key); if (numInFormatField>1 && val.equals(MISSING_GENOTYPE_FIELD)) { // If we have a missing field but multiple values are expected, we need to construct new string with all fields. // for example for Number =2, string has to be ".,." StringBuilder v = new StringBuilder(MISSING_GENOTYPE_FIELD); for ( int i = 1; i < numInFormatField; i++ ) { v.append(","); v.append(MISSING_GENOTYPE_FIELD); } newVal = v.toString(); } } // assume that if key is absent, given string encoding suffices. String outputValue = formatVCFField(key, newVal); if ( outputValue != null ) vcfG.setField(key, outputValue); } genotypeObjects.add(vcfG); } mGenotypeRecords.clear(); mGenotypeRecords.addAll(genotypeObjects); // info fields Map<String, String> infoFields = new HashMap<String, String>(); for ( Map.Entry<String, Object> elt : vc.getAttributes().entrySet() ) { String key = elt.getKey(); if ( key.equals("ID") ) continue; // Original alleles are not for reporting but only for internal bookkeeping if (key.equals("ORIGINAL_ALLELE_LIST")) continue; String outputValue = formatVCFField(key, elt.getValue()); if ( outputValue != null ) infoFields.put(key, outputValue); } builder.append(contig); builder.append(FIELD_SEPARATOR); builder.append(position); builder.append(FIELD_SEPARATOR); builder.append(ID); builder.append(FIELD_SEPARATOR); builder.append(referenceFromVC); builder.append(FIELD_SEPARATOR); if ( vcfAltAlleles.size() > 0 ) { builder.append(vcfAltAlleles.get(0)); for ( int i = 1; i < vcfAltAlleles.size(); i++ ) { builder.append(","); builder.append(vcfAltAlleles.get(i)); } } else { builder.append(EMPTY_ALLELE_FIELD); } builder.append(FIELD_SEPARATOR); if ( qual == -1 ) builder.append(MISSING_GENOTYPE_FIELD); else builder.append(String.format(DOUBLE_PRECISION_FORMAT_STRING, qual)); builder.append(FIELD_SEPARATOR); builder.append(filters); builder.append(FIELD_SEPARATOR); builder.append(createInfoString(infoFields)); if ( genotypeFormatString != null && genotypeFormatString.length() > 0 ) { addGenotypeData(builder, header, genotypeFormatString, vcfAltAlleles); } return builder.toString(); } /** * add the genotype data * * @param builder the string builder * @param header the header object * @param genotypeFormatString Genotype formatting string * @param vcfAltAlleles alternate alleles at this site */ private void addGenotypeData(StringBuilder builder, VCFHeader header, String genotypeFormatString, List<VCFGenotypeEncoding>vcfAltAlleles) { Map<String, VCFGenotypeRecord> gMap = genotypeListToMap(mGenotypeRecords); StringBuffer tempStr = new StringBuffer(); if ( header.getGenotypeSamples().size() < mGenotypeRecords.size() ) { for ( String sample : gMap.keySet() ) { if ( !header.getGenotypeSamples().contains(sample) ) System.err.println("Sample " + sample + " is a duplicate or is otherwise not present in the header"); else header.getGenotypeSamples().remove(sample); } throw new IllegalStateException("We have more genotype samples than the header specified; please check that samples aren't duplicated"); } tempStr.append(FIELD_SEPARATOR + genotypeFormatString); String[] genotypeFormatStrings = genotypeFormatString.split(":"); for ( String genotype : header.getGenotypeSamples() ) { tempStr.append(FIELD_SEPARATOR); if ( gMap.containsKey(genotype) ) { VCFGenotypeRecord rec = gMap.get(genotype); String genotypeString = rec.toStringEncoding(vcfAltAlleles, genotypeFormatStrings, true); // Override default produced genotype string when there are trailing String[] genotypeStrings = genotypeString.split(":"); int lastUsedPosition = 0; for (int k=genotypeStrings.length-1; k >=1; k // see if string represents an empty field. If not, break. if (!isEmptyField(genotypeStrings[k]) ) { lastUsedPosition = k; break; } } // now reconstruct genotypeString from 0 to lastUsedPosition genotypeString = Utils.join(":",genotypeStrings, 0,lastUsedPosition+1); tempStr.append(genotypeString); gMap.remove(genotype); } else { tempStr.append(VCFGenotypeRecord.stringEncodingForEmptyGenotype(genotypeFormatStrings, true)); } } if ( gMap.size() != 0 ) { for ( String sample : gMap.keySet() ) System.err.println("Sample " + sample + " is being genotyped but isn't in the header."); throw new IllegalStateException("We failed to use all the genotype samples; there must be an inconsistancy between the header and records"); } builder.append(tempStr); } boolean isEmptyField(String field) { // check if given genotype field is empty, ie either ".", or ".,.", or ".,.,.", etc. String[] fields = field.split(","); boolean isEmpty = true; for (int k=0; k < fields.length; k++) { if (!fields[k].matches(".")) { isEmpty = false; break; } } return isEmpty; } /** * create a genotype mapping from a list and their sample names * * @param list a list of genotype samples * @return a mapping of the sample name to VCF genotype record */ private static Map<String, VCFGenotypeRecord> genotypeListToMap(List<VCFGenotypeRecord> list) { Map<String, VCFGenotypeRecord> map = new HashMap<String, VCFGenotypeRecord>(); for (int i = 0; i < list.size(); i++) { VCFGenotypeRecord rec = list.get(i); map.put(rec.getSampleName(), rec); } return map; } /** * create the info string * * @param infoFields a map of info fields * @return a string representing the infomation fields */ protected String createInfoString(Map<String,String> infoFields) { StringBuffer info = new StringBuffer(); boolean isFirst = true; for (Map.Entry<String, String> entry : infoFields.entrySet()) { if ( isFirst ) isFirst = false; else info.append(INFO_FIELD_SEPARATOR); info.append(entry.getKey()); if ( entry.getValue() != null && !entry.getValue().equals("") ) { int numVals = 1; if (this.writingVCF40Format) { String key = entry.getKey(); if (numberUsedForInfoFields.containsKey(key)) { numVals = numberUsedForInfoFields.get(key); } // take care of unbounded encoding // TODO - workaround for "-1" in original INFO header structure if (numVals == VCFInfoHeaderLine.UNBOUNDED || numVals < 0) numVals = 1; } if (numVals > 0) { info.append("="); info.append(entry.getValue()); } } } return info.length() == 0 ? EMPTY_INFO_FIELD : info.toString(); } private static String formatVCFField(String key, Object val) { String result; if ( val == null ) result = VCFGenotypeRecord.getMissingFieldValue(key); else if ( val instanceof Double ) { result = String.format("%.2f", (Double)val); } else if ( val instanceof Boolean ) result = (Boolean)val ? "" : null; // empty string for true, null for false else if ( val instanceof List ) { List list = (List)val; if ( list.size() == 0 ) return formatVCFField(key, null); StringBuffer sb = new StringBuffer(formatVCFField(key, list.get(0))); for ( int i = 1; i < list.size(); i++) { sb.append(","); sb.append(formatVCFField(key, list.get(i))); } result = sb.toString(); } else result = val.toString(); return result; } private static List<String> calcVCFGenotypeKeys(VariantContext vc) { Set<String> keys = new HashSet<String>(); boolean sawGoodQual = false; for ( Genotype g : vc.getGenotypes().values() ) { keys.addAll(g.getAttributes().keySet()); if ( g.hasNegLog10PError() ) sawGoodQual = true; } if ( sawGoodQual ) keys.add(VCFGenotypeRecord.GENOTYPE_QUALITY_KEY); return Utils.sorted(new ArrayList<String>(keys)); } }
package org.openoffice.setup.Util; import org.openoffice.setup.InstallData; import java.io.File; import java.util.Vector; public class InfoDir { private InfoDir() { } static private String copySourceFile(String fileName) { InstallData data = InstallData.getInstance(); File jarFile = data.getJarFilePath(); String destFile = null; if ( jarFile != null ) { String sourceDir = jarFile.getParent(); File sourceFileFile = new File(sourceDir, fileName); String sourceFile = sourceFileFile.getPath(); // String jarFileName = jarFile.getName(); File destDir = new File(data.getInstallRoot(), data.getInstallDir()); File destFileFile = new File(destDir, fileName); destFile = destFileFile.getPath(); boolean success = SystemManager.copy(sourceFile, destFile); } return destFile; } static private void copyInstallDirectoryWithExtension(File destBaseDir, String subDirName, String fileExtension) { InstallData data = InstallData.getInstance(); File sourceDir = data.getInfoRoot(subDirName); if ( sourceDir != null ) { File destDir = new File(destBaseDir, subDirName); destDir.mkdir(); SystemManager.copyAllFiles(sourceDir, destDir, fileExtension); } } static private void copyInstallDirectoryWithExtension(File destBaseDir, String subDirName, String fileExtension, String unixRights) { InstallData data = InstallData.getInstance(); File sourceDir = data.getInfoRoot(subDirName); if ( sourceDir != null ) { File destDir = new File(destBaseDir, subDirName); destDir.mkdir(); SystemManager.copyAllFiles(sourceDir, destDir, fileExtension); SystemManager.setUnixPrivilegesDirectory(destDir, fileExtension, unixRights); } } static private void copyInstallDirectoryDoubleSubdir(File destBaseDir, String dir1, String dir2) { InstallData data = InstallData.getInstance(); File sourceDir1 = data.getInfoRoot(dir1); File sourceDir = new File(sourceDir1, dir2); destBaseDir.mkdir(); File destDir1 = new File(destBaseDir, dir1); destDir1.mkdir(); File destDir = new File(destDir1, dir2); destDir.mkdir(); SystemManager.copyAllFiles(sourceDir, destDir); } static private File createUninstallDir() { InstallData data = InstallData.getInstance(); File baseDir = new File(data.getInstallRoot(), data.getInstallDir()); File uninstallDir = new File(baseDir, data.getUninstallDirName()); uninstallDir.mkdir(); return uninstallDir; } static private void copyGetUidSoFile(File dir) { InstallData data = InstallData.getInstance(); String uidFileSource = data.getGetUidPath(); if ( uidFileSource != null ) { // Copying the "getuid.so" file into installation String fileName = "getuid.so"; File destFile = new File(dir, fileName); String uidFileDest = destFile.getPath(); boolean success = SystemManager.copy(uidFileSource, uidFileDest); data.setGetUidPath(uidFileDest); } } static private void copyJreFile(File dir) { InstallData data = InstallData.getInstance(); String jrefilename = System.getProperty("JRE_FILE"); if ( jrefilename != null ) { // For Solaris, JRE_FILE can already contain the complete path. // Otherwise it contains only the filename File jreFile = new File(jrefilename); if ( ! jreFile.exists()) { jreFile = new File(data.getPackagePath(), jrefilename); } if ( jreFile.exists() ) { String jreFileSource = jreFile.getPath(); File destDir = new File(dir, "jre"); destDir.mkdir(); String onlyFileName = jreFile.getName(); File destFile = new File(destDir, onlyFileName); // In maintenance mode the file already exists if ( ! destFile.exists() ) { String jreFileDest = destFile.getPath(); boolean success = SystemManager.copy(jreFileSource, jreFileDest); } } } } static private void moveAdminFiles(File dir) { InstallData data = InstallData.getInstance(); if ( data.getAdminFileNameReloc() != null ) { File sourceFile = new File(data.getAdminFileNameReloc()); String fileName = sourceFile.getName(); File destFile = new File(dir, fileName); boolean success = SystemManager.copy(sourceFile.getPath(), destFile.getPath()); data.setAdminFileNameReloc(destFile.getPath()); sourceFile.delete(); } if ( data.getAdminFileNameNoReloc() != null ) { File sourceFile = new File(data.getAdminFileNameNoReloc()); String fileName = sourceFile.getName(); File destFile = new File(dir, fileName); boolean success = SystemManager.copy(sourceFile.getPath(), destFile.getPath()); data.setAdminFileNameNoReloc(destFile.getPath()); sourceFile.delete(); } } static private void createInfoFile(File dir) { Vector fileContent = new Vector(); String line = null; InstallData data = InstallData.getInstance(); line = "PackagePath=" + data.getPackagePath(); fileContent.add(line); line = "InstallationPrivileges=" + data.getInstallationPrivileges(); fileContent.add(line); line = "AdminFileReloc=" + data.getAdminFileNameReloc(); fileContent.add(line); line = "AdminFileNoReloc=" + data.getAdminFileNameNoReloc(); fileContent.add(line); line = "InstallationDir=" + data.getInstallDir(); fileContent.add(line); line = "InstallationRoot=" + data.getInstallRoot(); fileContent.add(line); line = "DatabasePath=" + data.getDatabasePath(); fileContent.add(line); line = "GetUidFile=" + data.getGetUidPath(); fileContent.add(line); String infoFileName = "infoFile"; File infoFile = new File(dir, infoFileName); SystemManager.saveCharFileVector(infoFile.getPath(), fileContent); } static private void removeSpecialFiles() { InstallData data = InstallData.getInstance(); File jarFile = data.getJarFilePath(); SystemManager.deleteFile(jarFile); String jarFilePath = jarFile.getParent(); File setupFile = new File(jarFilePath, "setup"); SystemManager.deleteFile(setupFile); if ( ! data.getAdminFileNameReloc().equals("null") ) { SystemManager.deleteFile(new File(data.getAdminFileNameReloc())); } if ( ! data.getAdminFileNameNoReloc().equals("null") ) { SystemManager.deleteFile(new File(data.getAdminFileNameNoReloc())); } if ( ! data.getGetUidPath().equals("null") ) { SystemManager.deleteFile(new File(data.getGetUidPath())); } } static private void removeInforootSubdir(String dir1, String dir2) { InstallData data = InstallData.getInstance(); File subdir1 = data.getInfoRoot(dir1); File subdir2 = new File(subdir1, dir2); if (subdir2 != null) { if ( subdir2.exists() ) { SystemManager.removeDirectory(subdir2); } } } static private void removeInforootSubdir(String dir) { InstallData data = InstallData.getInstance(); File subdir = data.getInfoRoot(dir); if (subdir != null) { if ( subdir.exists() ) { SystemManager.removeDirectory(subdir); } } } static private void removeInforoot() { InstallData data = InstallData.getInstance(); SystemManager.removeDirectory(data.getInfoRoot()); } static public void prepareUninstallation() { // additional tasks for uninstallation String setupPath = copySourceFile("setup"); SystemManager.setUnixPrivileges(setupPath, "775"); InstallData data = InstallData.getInstance(); File jarFile = data.getJarFilePath(); copySourceFile(jarFile.getName()); File uninstallDir = createUninstallDir(); copyInstallDirectoryWithExtension(uninstallDir, "xpd", "xpd"); copyInstallDirectoryWithExtension(uninstallDir, "html", "html"); copyInstallDirectoryWithExtension(uninstallDir, "images", "gif"); copyInstallDirectoryDoubleSubdir(uninstallDir, "html", "images"); copyGetUidSoFile(uninstallDir); copyJreFile(uninstallDir); moveAdminFiles(uninstallDir); createInfoFile(uninstallDir); } static public void removeUninstallationFiles() { // removing selected File removeSpecialFiles(); // removing directories html/images, html and xpd removeInforootSubdir("html", "images"); removeInforootSubdir("html"); removeInforootSubdir("xpd"); removeInforootSubdir("images"); removeInforootSubdir("jre"); removeInforoot(); } }
package railo.runtime.exp; import railo.runtime.Info; import railo.runtime.PageContext; import railo.runtime.dump.DumpData; import railo.runtime.dump.DumpProperties; import railo.runtime.dump.DumpTable; import railo.runtime.op.Caster; import railo.runtime.reflection.Reflector; /** * Box a Native Exception, Native = !PageException */ public final class NativeException extends PageExceptionImpl { private Throwable t; /** * Standart constructor for native Exception class * @param t Throwable */ public NativeException(Throwable t) { super(t,t.getClass().getName()); this.t=t; setStackTrace(t.getStackTrace()); setAdditional("Cause", t.getClass().getName()); } /** * @see railo.runtime.dump.Dumpable#toDumpData(railo.runtime.PageContext, int) */ public DumpData toDumpData(PageContext pageContext, int maxlevel, DumpProperties dp) { DumpData data = super.toDumpData(pageContext, maxlevel,dp); if(data instanceof DumpTable) ((DumpTable)data).setTitle("Railo ["+Info.getVersionAsString()+"] - Error ("+Caster.toClassName(t)+")"); return data; } /** * @see railo.runtime.exp.IPageException#typeEqual(java.lang.String) */ public boolean typeEqual(String type) { if(super.typeEqual(type))return true; return Reflector.isInstaneOfIgnoreCase(t.getClass(),type); } /** * @see railo.runtime.exp.PageExceptionImpl#setAdditional(java.lang.String, java.lang.Object) */ public void setAdditional(String key, Object value) { super.setAdditional(key, value); } }
package model; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * All db interaction code resides here, could be called directly by view, or by * view through intermediary layer of Model. (more about this in QUESTIONS.txt) * * This class is a translator between the ER and Object model and vice versa. * * */ public final class QueryExecuter implements QueryInterpreter { private final static String database = "mediacollection"; private final static String user = "clientapp"; private final static String pass = "qwerty"; private final static String driver = "com.mysql.jdbc.Driver"; private final static String host = "jdbc:mysql://localhost:3306/"; public Connection connection; public Statement statement; public PreparedStatement preparedStatement; public ResultSet resultSet; public Model model; public static void main(String args[]) { try { QueryExecuter qx = new QueryExecuter(new Model()); qx.getAllAlbums(); } catch (SQLException e) { e.printStackTrace(); } } public QueryExecuter(Model model) throws SQLException { this.model = model; try { Class.forName(driver); connection = DriverManager.getConnection(host + database, user, pass); statement = connection.createStatement(); } catch (Exception e) { e.printStackTrace(); } } @Override public void disconnect() { try { if (connection != null) { connection.close(); System.out.println("Connection closed."); } } catch (SQLException e) { } } // TODO @ research @Override public List<Album> getAllAlbums() throws SQLException { List<Album> albums = new ArrayList<Album>(); ResultSet rsetAlbum = null; try { rsetAlbum = statement .executeQuery("select * from Media where Mediatype_Id = 1"); // for every album do... while (rsetAlbum.next()) { ResultSet rsetGenre; ResultSet rsetArtist; ResultSet rsetRating; ResultSet rsetReview; ResultSet rsetUser; ResultSet rsetId = null; Statement stId = connection.createStatement(); Statement stUser = connection.createStatement(); Statement stGenre = connection.createStatement(); Statement stArtist = connection.createStatement(); Statement stRating = connection.createStatement(); Statement stReview = connection.createStatement(); Album album = RowConverter.convertRowToAlbum(rsetAlbum); // get genre. rsetGenre = stGenre .executeQuery("select Name from Genre where Id = " + rsetAlbum.getInt("Genre_Id")); rsetGenre.first(); album.setGenre(rsetGenre.getString("Name")); // get artists. System.out.println("Id is: " + album.getId()); rsetArtist = stArtist .executeQuery("select Name from Contributor inner join Creator where Media_Id = " + album.getId() + " and Creator.id = Contributor.Creator_Id;"); while (rsetArtist.next()) album.AddArtist(rsetArtist.getString("Name")); // get the rating. rsetRating = stRating .executeQuery("select avg(Rating) from rating where Media_Id = " + album.getId() + ";"); while (rsetRating.next()) album.setRating(rsetRating.getFloat(1)); // finally, get reviews.. rsetReview = stReview .executeQuery("select Title, Text, Account_Id from review where Media_Id = " + album.getId() + ";"); while (rsetReview.next()) { Review review = RowConverter.convertRowToReview(rsetReview); rsetUser = stUser .executeQuery("select Name from Account where Id = " + rsetReview.getInt("Account_Id") + ";"); rsetUser.first(); review.setUser(rsetUser.getString("Name")); album.addReview(review); } // ops, need user too.. rsetUser = stUser .executeQuery("select Name from Account where Id = " + rsetAlbum.getInt("Account_Id")); rsetUser.first(); album.setUser(rsetUser.getString("Name")); albums.add(album); // ha-ha listClose(new Statement[] { stId, stUser, stGenre, stArtist, stRating, stReview }, new ResultSet[] { rsetGenre, rsetArtist, rsetRating, rsetReview, rsetUser, rsetId }); } model.setBank(albums.toArray()); for (Album a : albums) { System.out.println(a.toString()); } } finally { closeStatement(statement); closeResultSet(rsetAlbum); } return null; } private void listClose(Statement[] statements, ResultSet[] resultSets) { try { for (int i = 0; i < statements.length; i++) if (null != statements[i]) statements[i].close(); for (int i = 0; i < resultSets.length; i++) if (null != resultSets[i]) resultSets[i].close(); } catch (SQLException e) { e.printStackTrace(); } } // more research... public List<Album> getAllAlbums2() throws SQLException { List<Album> albums = new ArrayList<Album>(); // make statement and result set Statement s = null; Statement sAlbum = null; Statement sArtist = null; Statement sReview = null; Statement sRating = null; ResultSet rAlbum = null; ResultSet rArtist = null; ResultSet rReview = null; ResultSet rRating = null; try { // use statement and result set to fetch info s = connection.createStatement(); sAlbum = connection.createStatement(); sArtist = connection.createStatement(); sReview = connection.createStatement(); sRating = connection.createStatement(); // get info rAlbum = sAlbum.executeQuery("select * " + "from Media " + "where Mediatype_Id = 1"); rArtist = sArtist.executeQuery("select Creator.Name " + "from Contributor, Creator, Media " + "where Contributor.Creator_Id = Media.Id " + "and Media.Mediatype_Id = 1"); rReview = sReview.executeQuery("select * " + "from Review, Media " + "where Review.Media_Id = Media.Id"); rRating = sRating.executeQuery("select * " + "from Rating, Media " + "where Rating.Media_Id = Media.Id"); // loop through result set while (rAlbum.next()) { albums.add(RowConverter.convertRowToAlbum(rAlbum, rArtist, rReview, rRating)); } // System.out.println("Albums"); // return list for (Album a : albums) { System.out.println(a.toString()); } } finally { // closeStatementAndResultSet(s, r); } return null; } public void getGenre() throws SQLException { try { } finally { } } public void getMovie() throws SQLException { List<Movie> movies = new ArrayList<Movie>(); try { // use statement and result set to fetch info statement = connection.createStatement(); resultSet = statement .executeQuery("select * from Media where Mediatype_Id = 2"); // loop through result set while (resultSet.next()) { System.out.println(resultSet.getString("Name")); // movies = rc.convertRowToMovie(resultSet); } // System.out.println("movies"); for (Movie m : movies) { System.out.println(m.toString()); } } finally { } } public List<Director> getDirectors() throws SQLException { List<Director> directors = new ArrayList<Director>(); try { // use statement and result set to fetch info statement = connection.createStatement(); resultSet = statement.executeQuery("...coming soon..."); // loop through result set while (resultSet.next()) { System.out.println(resultSet.getString("Name")); directors = RowConverter.convertRowToDirector(resultSet); } System.out.println("Directors"); for (Director d : directors) { System.out.println(d.toString()); } return directors; } finally { closeStatement(statement); } } public List<Artist> getArtists() throws SQLException { List<Artist> artists = new ArrayList<Artist>(); try { // use statement and result set to fetch info statement = connection.createStatement(); // MMm such good when directors in dat table... resultSet = statement .executeQuery("select Name from Creator, Contributor where Id = Creator_Id"); // loop through result set while (resultSet.next()) { System.out.println(resultSet.getString("Name")); artists = RowConverter.convertRowToArtist(resultSet); } System.out.println("Artists"); for (Artist a : artists) { System.out.println(a.toString()); } return artists; } finally { closeStatement(statement); } } @Override public List<Album> searchByAlbumTitle(String title) { List<Album> resultingAlbum = new ArrayList<Album>(); // make statement and result set // TODO define sql query try { // statement with WHERE clause, prepare it correctly using // PArameters // loop through result set adding objects to list // return list } finally { // close statement and result set } return null; } @Override public List<Artist> searchByArtist(String artist) throws SQLException { List<Artist> resultingArtists = new ArrayList<Artist>(); try { artist = artist.trim(); artist += "%"; // first make sure there is no directors! // Search for designated artist preparedStatement = connection .prepareStatement("select Name from Creator where Name like ?"); preparedStatement.setString(1, artist); resultSet = preparedStatement.executeQuery(); // loop through result set while (resultSet.next()) { // resultingArtists = rc.convertRowToArtist(resultSet); resultingArtists.addAll(RowConverter .convertRowToArtist(resultSet)); } if (resultingArtists.size() > 0) { System.out.println("Found Artists: "); // NOTHING! but it should work... // Char encodin issue? for (Artist a : resultingArtists) { System.out.println(a.toString()); } } return resultingArtists; } finally { // closeStatementAndResultSet(); } } @Override public List<Album> searchByGenre(String genre) { // TODO Auto-generated method stub return null; } @Override public List<Album> searchByRating(int rating) { // TODO Auto-generated method stub return null; } @Override public void insertAlbum(Album album) { // CALLING METHOD: show dialog // CALLING METHOD: supply result as album // make statement // try to execute that statement to db } @Override public void rateAlbum(int rating) { // TODO Auto-generated method stub } // close statement private void closeStatement(Statement s) throws SQLException { if (s != null) { s.close(); } } // close result set private void closeResultSet(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } private void closeFinalAllTheStuff() { } }
package com.bigbluecup.android; import javax.microedition.khronos.egl.EGL10; import com.bigbluecup.android.AgsEngine; import android.content.pm.ActivityInfo; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.os.Bundle; import android.os.Message; public class EngineGlue extends Thread implements CustomGlSurfaceView.Renderer { public static final int MSG_SWITCH_TO_INGAME = 1; public static final int MSG_SHOW_MESSAGE = 2; public static final int MSG_SHOW_TOAST = 3; public static final int MSG_SET_ORIENTATION = 4; public static final int MOUSE_CLICK_LEFT = 1; public static final int MOUSE_CLICK_RIGHT = 2; public int keyboardKeycode = 0; public short mouseMoveX = 0; public short mouseMoveY = 0; public int mouseClick = 0; private int screenPhysicalWidth = 480; private int screenPhysicalHeight = 320; private int screenVirtualWidth = 320; private int screenVirtualHeight = 200; private boolean paused = false; private AudioTrack audioTrack; private byte[] audioBuffer; private int bufferSize = 0; private AgsEngine activity; private String gameFilename = ""; private String baseDirectory = ""; public native void nativeInitializeRenderer(int width, int height); public native void shutdownEngine(); private native boolean startEngine(Object object, String filename, String directory); private native void pauseEngine(); private native void resumeEngine(); public EngineGlue(AgsEngine activity, String filename, String directory) { this.activity = activity; gameFilename = filename; baseDirectory = directory; System.loadLibrary("agsengine"); } public void run() { startEngine(this, gameFilename, baseDirectory); } public void pauseGame() { paused = true; if (audioTrack != null) audioTrack.pause(); pauseEngine(); } public void resumeGame() { if (audioTrack != null) audioTrack.play(); resumeEngine(); paused = false; } public void moveMouse(float x, float y) { // The mouse movement is scaled to the game screen size mouseMoveX = (short) (x * (float)screenVirtualWidth / (float)screenPhysicalWidth); mouseMoveY = (short) (y * (float)screenVirtualHeight / (float)screenPhysicalHeight); } public void clickMouse(int button) { mouseClick = button; } public void keyboardEvent(int keycode, int character, boolean shiftPressed) { keyboardKeycode = keycode | (character << 16) | ((shiftPressed ? 1 : 0) << 30); } private void showMessage(String message) { Bundle data = new Bundle(); data.putString("message", message); sendMessageToActivity(MSG_SHOW_MESSAGE, data); } private void showToast(String message) { Bundle data = new Bundle(); data.putString("message", message); sendMessageToActivity(MSG_SHOW_TOAST, data); } private void sendMessageToActivity(int messageId, Bundle data) { Message m = activity.handler.obtainMessage(); m.what = messageId; if (data != null) m.setData(data); activity.handler.sendMessage(m); } private void createScreen(int width, int height, int color_depth) { screenVirtualWidth = width; screenVirtualHeight = height; sendMessageToActivity(MSG_SWITCH_TO_INGAME, null); int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE }; while (!activity.isInGame) { try { Thread.sleep(100, 0); } catch (InterruptedException e) {} } try { Thread.sleep(300, 0); } catch (InterruptedException e) {} activity.surfaceView.initialize(configSpec, this); } private void swapBuffers() { activity.surfaceView.swapBuffers(); } public void onSurfaceChanged(int width, int height) { setPhysicalScreenResolution(width, height); nativeInitializeRenderer(width, height); } // Called from Allegro private int pollKeyboard() { int result = keyboardKeycode; keyboardKeycode = 0; return result; } private int pollMouseX() { int result = mouseMoveX; mouseMoveX = 0; return result; } private int pollMouseY() { int result = mouseMoveY; mouseMoveY = 0; return result; } private int pollMouseButtons() { int result = mouseClick; mouseClick = 0; return result; } private void blockExecution() { while (paused) { try { Thread.sleep(100, 0); } catch (InterruptedException e) {} } } private void setRotation(int orientation) { Bundle data = new Bundle(); if (orientation == 1) data.putInt("orientation", ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); else if (orientation == 2) data.putInt("orientation", ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); sendMessageToActivity(MSG_SET_ORIENTATION, data); } // Called from Allegro, the buffer is allocated in native code public void initializeSound(byte[] buffer, int bufferSize) { audioBuffer = buffer; this.bufferSize = bufferSize; int sampleRate = 44100; int minBufferSize = AudioTrack.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT); if (minBufferSize < bufferSize * 4) minBufferSize = bufferSize * 4; audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_CONFIGURATION_STEREO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM); float audioVolume = AudioTrack.getMaxVolume(); audioTrack.setStereoVolume(audioVolume, audioVolume); audioTrack.play(); } public void updateSound() { audioTrack.write(audioBuffer, 0, bufferSize); } public void setPhysicalScreenResolution(int width, int height) { screenPhysicalWidth = width; screenPhysicalHeight = height; } }
package model; import gui.init.Init; import java.util.List; import java.util.Set; public class SimpleActions implements Actions { private Turtle myTurtle; private List<Turtle> myTurtles; private Set<Integer> myActiveTurtles; private int width; private int height; public SimpleActions(Turtle turtle) { myTurtle = turtle; width = Init.getXDimension(); height = Init.getYDimension(); } // Turtle commands: @Override public double forward(double distance) { double theta = myTurtle.getDirection(); double delta_x = distance * Math.sin(Math.toRadians(theta)); double delta_y = - distance * Math.cos(Math.toRadians(theta)); // update x coordinate if (delta_x >= 0) { if (myTurtle.getX() + delta_x <= width/2) { myTurtle.setX(myTurtle.getX() + delta_x); } else { myTurtle.setX((myTurtle.getX() + delta_x) % width - width); } } else { if (myTurtle.getX() + delta_x >= - width/2) { myTurtle.setX(myTurtle.getX() + delta_x); } else { myTurtle.setX((myTurtle.getX() + delta_x) % width + width); } } // update y coordinate if (delta_y >= 0) { if (myTurtle.getY() + delta_y <= height/2) { myTurtle.setY(myTurtle.getY() + delta_y); } else { myTurtle.setY((myTurtle.getY() + delta_y) % height - height); } } else { if (myTurtle.getY() + delta_y >= - height/2) { myTurtle.setY(myTurtle.getY() + delta_y); } else { myTurtle.setY((myTurtle.getY() + delta_y) % height + height); } } myTurtle.move.set(myTurtle.move.get()+1); return distance; } @Override public double backward(double distance) { distance = - distance; return - forward(distance); } @Override public double left(double degree) { degree = - degree; return - right(degree); } @Override public double right(double degree) { myTurtle.rotate(degree); return degree; } @Override public double setHeading(double degree) { double theta = myTurtle.getDirection(); theta = degree - theta; return right(theta); } @Override public double setTowards(double x, double y) { double delta_x = x - myTurtle.getX(); double delta_y = y - myTurtle.getY(); if (delta_x == 0) { if (delta_y > 0) { return setHeading(180); } else { return setHeading(0); } } if (delta_y == 0) { if (delta_x < 0) { return setHeading(-90); } else { return setHeading(90); } } double angle_rad = Math.atan(delta_x / delta_y); double angle_deg = Math.toDegrees(angle_rad); if (delta_y < 0) { return setHeading(- angle_deg); } if (delta_x < 0) { return setHeading(- angle_deg - 180); } else { return setHeading(180 - angle_deg); } } @Override public double setPosition(double x, double y) { myTurtle.setX(x); myTurtle.setY(y); myTurtle.move.set(myTurtle.move.get()+1); return Math.sqrt(x * x + y * y); } @Override public int penDown() { myTurtle.setPenDown(); return 1; } @Override public int penUp() { myTurtle.setPenUp(); return 0; } @Override public int showTurtle() { myTurtle.setVisible(); return 1; } @Override public int hideTurtle() { myTurtle.setInvisible(); return 0; } @Override public double home() { return setPosition(0,0); } @Override public double clearScreen() { // here need to add code to erase turtle's trails return home(); } // Turtle Queries: @Override public double xCoordinate() { return myTurtle.getX(); } @Override public double yCoordinate() { return myTurtle.getY(); } @Override public double heading() { return myTurtle.getDirection(); } @Override public int isPenDown() { return myTurtle.getIsPenDown(); } @Override public int isShowing() { return myTurtle.getIsVisible(); } // Display commands: @Override public double setBackground(double index) { // TODO Auto-generated method stub return 0; } @Override public double setPenColor(double index) { // TODO Auto-generated method stub return 0; } @Override public double setPenSize(double pixels) { // TODO Auto-generated method stub return 0; } @Override public double setShape(double index) { // TODO Auto-generated method stub return 0; } @Override public double setPalette(double index, double r, double g, double b) { // TODO Auto-generated method stub return 0; } @Override public double getPenColor() { // TODO Auto-generated method stub return 0; } @Override public double getShape() { // TODO Auto-generated method stub return 0; } @Override public double stamp() { // TODO Auto-generated method stub return 0; } @Override public double clearStamp() { // TODO Auto-generated method stub return 0; } @Override public int id() { // TODO Auto-generated method stub return 0; } @Override public int turtles() { // TODO Auto-generated method stub return 0; } @Override public void setFollowers(Set<Integer> activeTurtles) { // TODO Auto-generated method stub } @Override public Set<Integer> getFollowers() { // TODO Auto-generated method stub return null; } @Override public boolean setActive(int index) { // TODO Auto-generated method stub return false; } }
package io.jenetics.engine; import static java.lang.String.format; import java.util.concurrent.atomic.AtomicInteger; import org.testng.Assert; import org.testng.annotations.Test; import io.jenetics.DoubleChromosome; import io.jenetics.DoubleGene; import io.jenetics.Genotype; import io.jenetics.Phenotype; public class FitnessNullifierTest { @Test public void nullifyFitness() { final int nullifiedGeneration = 3; final int populationSize = 66; final var evalCount = new AtomicInteger(); final var nullifiedPhenotypes = new AtomicInteger(); final Evaluator<DoubleGene, Double> evaluator = population -> { evalCount.incrementAndGet(); nullifiedPhenotypes.set( (int)population.stream() .filter(Phenotype::nonEvaluated) .count() ); if (nullifiedGeneration + 2 == evalCount.get()) { Assert.assertEquals(nullifiedPhenotypes.get(), populationSize); } else if (evalCount.get() > 1) { Assert.assertTrue( nullifiedPhenotypes.get() < populationSize, format( "nullified phenotypes >= population size: %s, >= %s", nullifiedPhenotypes, populationSize ) ); } return population .map(pt -> pt.withFitness(5.0)) .asISeq(); }; final var genotype = Genotype.of(DoubleChromosome.of(0, 1)); final var nullifier = new FitnessNullifier<DoubleGene, Double>(); final Engine<DoubleGene, Double> engine = new Engine.Builder<>(evaluator, genotype) .interceptor(nullifier) .populationSize(populationSize) .build(); engine.stream() .peek(er -> { if (er.generation() == nullifiedGeneration) { Assert.assertTrue(nullifier.nullifyFitness()); Assert.assertFalse(nullifier.nullifyFitness()); } }) .limit(6) .forEach(er -> {}); } }
package org.eclipse.jetty.nosql; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.http.HttpServletRequest; import org.eclipse.jetty.server.session.AbstractSession; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.Logger; public class NoSqlSession extends AbstractSession { private final static Logger __log = Log.getLogger("org.eclipse.jetty.server.session"); private final NoSqlSessionManager _manager; private Set<String> _dirty; private final AtomicInteger _active = new AtomicInteger(); private Object _version; private long _lastSync; public NoSqlSession(NoSqlSessionManager manager, HttpServletRequest request) { super(manager, request); _manager=manager; save(true); _active.incrementAndGet(); } public NoSqlSession(NoSqlSessionManager manager, long created, long accessed, String clusterId, Object version) { super(manager, created,accessed,clusterId); _manager=manager; _version=version; } @Override public Object doPutOrRemove(String name, Object value) { synchronized (this) { Object old = super.doPutOrRemove(name,value); if (_manager.getSavePeriod()==-2) { save(true); } return old; } } @Override public void setAttribute(String name, Object value) { if ( updateAttribute(name,value) ) { if (_dirty==null) { _dirty=new HashSet<String>(); } _dirty.add(name); } } /* * a boolean version of the setAttribute method that lets us manage the _dirty set */ protected boolean updateAttribute (String name, Object value) { Object old=null; synchronized (this) { checkValid(); old=doPutOrRemove(name,value); } if (value==null || !value.equals(old)) { if (old!=null) unbindValue(name,old); if (value!=null) bindValue(name,value); _manager.doSessionAttributeListeners(this,name,old,value); return true; } return false; } @Override protected void checkValid() throws IllegalStateException { super.checkValid(); } @Override protected boolean access(long time) { __log.debug("NoSqlSession:access:active "+_active); if (_active.incrementAndGet()==1) { long period=_manager.getStalePeriod()*1000L; if (period==0) refresh(); else if (period>0) { long stale=time-_lastSync; __log.debug("NoSqlSession:access:stale "+stale); if (stale>period) refresh(); } } return super.access(time); } @Override protected void complete() { super.complete(); if(_active.decrementAndGet()==0) { switch(_manager.getSavePeriod()) { case 0: save(isValid()); break; case 1: if (isDirty()) save(isValid()); break; } } } @Override protected void doInvalidate() throws IllegalStateException { super.doInvalidate(); save(false); } protected void save(boolean activateAfterSave) { synchronized (this) { _version=_manager.save(this,_version,activateAfterSave); _lastSync=getAccessed(); } } protected void refresh() { synchronized (this) { _version=_manager.refresh(this,_version); } } public boolean isDirty() { synchronized (this) { return _dirty!=null && !_dirty.isEmpty(); } } public Set<String> takeDirty() { synchronized (this) { Set<String> dirty=_dirty; if (dirty==null) dirty= new HashSet<String>(); else _dirty=null; return dirty; } } public Object getVersion() { return _version; } }
package net.ceos.project.poi.annotated.core; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.RegionUtil; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import net.ceos.project.poi.annotated.annotation.XlsConfiguration; import net.ceos.project.poi.annotated.annotation.XlsDecorator; import net.ceos.project.poi.annotated.annotation.XlsDecorators; import net.ceos.project.poi.annotated.annotation.XlsElement; import net.ceos.project.poi.annotated.annotation.XlsFreeElement; import net.ceos.project.poi.annotated.annotation.XlsNestedHeader; import net.ceos.project.poi.annotated.annotation.XlsSheet; import net.ceos.project.poi.annotated.definition.ExceptionMessage; import net.ceos.project.poi.annotated.definition.ExtensionFileType; import net.ceos.project.poi.annotated.definition.PropagationType; import net.ceos.project.poi.annotated.definition.TitleOrientationType; import net.ceos.project.poi.annotated.exception.ConfigurationException; import net.ceos.project.poi.annotated.exception.ConverterException; import net.ceos.project.poi.annotated.exception.CustomizedRulesException; import net.ceos.project.poi.annotated.exception.ElementException; import net.ceos.project.poi.annotated.exception.SheetException; public class Engine implements IEngine { /** * Get the runtime class of the object passed as parameter. * * @param object * the object * @return the runtime class * @throws ElementException */ private Class<?> initializeRuntimeClass(final Object object) throws ElementException { Class<?> oC = null; try { /* instance object class */ oC = object.getClass(); } catch (Exception e) { throw new ElementException(ExceptionMessage.ElementException_NullObject.getMessage(), e); } return oC; } /** * Initialize the configuration to apply at the Excel. * * @param oC * the {@link Class<?>} * @return * @throws ConfigurationException */ private void initializeConfigurationData(final XConfigCriteria configCriteria, final Class<?> oC, final boolean insideCollection) throws ConfigurationException { /* Process @XlsConfiguration */ if (oC.isAnnotationPresent(XlsConfiguration.class)) { XlsConfiguration xlsAnnotation = (XlsConfiguration) oC.getAnnotation(XlsConfiguration.class); initializeXlsConfiguration(configCriteria, xlsAnnotation); } else { throw new ConfigurationException( ExceptionMessage.ConfigurationException_XlsConfigurationMissing.getMessage()); } /* Process @XlsSheet */ if (oC.isAnnotationPresent(XlsSheet.class)) { XlsSheet xlsAnnotation = (XlsSheet) oC.getAnnotation(XlsSheet.class); initializeXlsSheet(configCriteria, xlsAnnotation); if(insideCollection && oC.isAnnotationPresent(XlsElement.class)){ /** * if the collection is an attribut inside an object * we get the sheet title name from the element */ XlsElement xlsElement = (XlsElement) oC.getAnnotation(XlsElement.class); if(!xlsElement.parentSheet()){ configCriteria.setTitleSheet(xlsElement.title()); configCriteria.setElement(xlsElement); } } } else { throw new ConfigurationException(ExceptionMessage.ConfigurationException_XlsSheetMissing.getMessage()); } } /** * Add the main xls configuration. * * @param configCriteria * the {@link XConfigCriteria} * @param annotation * the {@link XlsConfiguration} * @return */ private void initializeXlsConfiguration(final XConfigCriteria configCriteria, final XlsConfiguration annotation) { configCriteria.setFileName(StringUtils.isBlank(configCriteria.getFileName()) ? annotation.nameFile() : configCriteria.getFileName()); configCriteria.setExtension( configCriteria.getExtension() == null ? annotation.extensionFile() : configCriteria.getExtension()); configCriteria.setCompleteFileName(configCriteria.getFileName() + configCriteria.getExtension().getExtension()); } /** * Add the sheet configuration. * * @param configCriteria * the {@link XConfigCriteria} * @param annotation * the {@link XlsSheet} * @return */ private void initializeXlsSheet(final XConfigCriteria configCriteria, final XlsSheet annotation) { configCriteria.setTitleSheet(annotation.title()); configCriteria.setPropagation(annotation.propagation()); configCriteria.setCascadeLevel(annotation.cascadeLevel()); configCriteria.setStartRow(annotation.startRow()); configCriteria.setStartCell(annotation.startCell()); configCriteria.setFreezePane(annotation.freezePane()); configCriteria.setGroupElement(annotation.groupElement()); } /** * initialize style cell via annotation {@link XlsDecorators} * * @param objectClass * the object class * @param configCriteria * the {@link XConfigCriteria} * @throws ConfigurationException */ private void initializeCellStyleViaAnnotation(final Class<?> objectClass, final XConfigCriteria configCriteria) throws ConfigurationException { if (objectClass.isAnnotationPresent(XlsDecorators.class)) { XlsDecorators xlsDecorators = (XlsDecorators) objectClass.getAnnotation(XlsDecorators.class); for (XlsDecorator decorator : xlsDecorators.values()) { if (configCriteria.getStylesMap().containsKey(decorator.decoratorName())) { throw new ConfigurationException( ExceptionMessage.ConfigurationException_CellStyleDuplicated.getMessage()); } configCriteria.getStylesMap().put(decorator.decoratorName(), CellStyleHandler.initializeCellStyleByXlsDecorator(configCriteria.getWorkbook(), decorator)); } } } /** * Initialize Workbook. * * @param type * the {@link ExtensionFileType} of workbook * @return the {@link Workbook}. */ private Workbook initializeWorkbook(final ExtensionFileType type) { if (type != null && ExtensionFileType.XLS.getExtension().equals(type.getExtension())) { return new HSSFWorkbook(); } else { return new XSSFWorkbook(); } } /** * Initialize Workbook from FileInputStream. * * @param inputStream * the file input stream * @param type * the type of workbook * @return the {@link Workbook}. * @throws IOException */ private Workbook initializeWorkbook(FileInputStream inputStream, ExtensionFileType type) throws IOException { if (type != null && ExtensionFileType.XLS.getExtension().equals(type.getExtension())) { return new HSSFWorkbook(inputStream); } else { return new XSSFWorkbook(inputStream); } } /** * Initialize Workbook from byte[]. * * @param byteArray * the array of bytes * @param type * the {@link ExtensionFileType} of workbook * @return the {@link Workbook} created * @throws IOException */ private Workbook initializeWorkbook(final byte[] byteArray, final ExtensionFileType type) throws IOException { if (type != null && ExtensionFileType.XLS.getExtension().equals(type.getExtension())) { return new HSSFWorkbook(new ByteArrayInputStream(byteArray)); } else { return new XSSFWorkbook(new ByteArrayInputStream(byteArray)); } } /** * Initialize Sheet. * * @param wb * the {@link Workbook} to use * @param sheetName * the name of the sheet * @return the {@link Sheet} created * @throws SheetException */ private Sheet initializeSheet(final Workbook wb, final String sheetName) throws SheetException { Sheet s = null; try { s = wb.createSheet(sheetName); } catch (Exception e) { throw new SheetException(ExceptionMessage.SheetException_CreationSheet.getMessage(), e); } return s; } /** * Validate if the nested header configuration is valid. * * @param isPH * true if propagation is HORIZONTAL otherwise false to * propagation VERTICAL * @param annotation * the {@link XlsNestedHeader} annotation * @throws ConfigurationException */ private void isValidNestedHeaderConfiguration(final boolean isPH, final XlsNestedHeader annotation) throws ConfigurationException { if (isPH && annotation.startX() == annotation.endX()) { throw new ConfigurationException(ExceptionMessage.ConfigurationException_Conflict.getMessage()); } else if (!isPH && annotation.startY() == annotation.endY()) { throw new ConfigurationException(ExceptionMessage.ConfigurationException_Conflict.getMessage()); } } /** * Apply merge region if necessary. * * @param configCriteria * the {@link XConfigCriteria} * @param r * the {@link Row} * @param idxR * the position of the row * @param idxC * the position of the cell * @param isPH * true if propagation horizontally, false if propagation * vertically * @throws ConfigurationException */ private void applyMergeRegion(final XConfigCriteria configCriteria, Row r, final int idxR, final int idxC, final boolean isPH) throws ConfigurationException { /* Process @XlsNestedHeader */ if (configCriteria.getField().isAnnotationPresent(XlsNestedHeader.class)) { XlsNestedHeader annotation = (XlsNestedHeader) configCriteria.getField() .getAnnotation(XlsNestedHeader.class); /* if row null is necessary to create it */ Row row = r; if (row == null) { /* check if the row already exist */ row = configCriteria.getSheet().getRow(idxR); if (row == null) { /* create a new row */ row = initializeRow(configCriteria.getSheet(), idxR); } } /* validation of configuration */ isValidNestedHeaderConfiguration(isPH, annotation); /* prepare position rows / cells */ int startRow; int endRow; int startCell; int endCell; if (isPH) { startRow = endRow = idxR; startCell = idxC + annotation.startX(); endCell = idxC + annotation.endX(); } else { startRow = idxR + annotation.startY(); endRow = idxR + annotation.endY(); startCell = endCell = idxC; } /* initialize nested header cell */ CellStyleHandler.initializeHeaderCell(configCriteria.getStylesMap(), row, startCell, annotation.title()); /* merge region of the nested header cell */ CellRangeAddress range = new CellRangeAddress(startRow, endRow, startCell, endCell); configCriteria.getSheet().addMergedRegion(range); /* apply the border to the nested header cell */ applyBorderToRegion(configCriteria, range); } } /** * Apply the border to region according the {@link CellStyle} * * @param configCriteria * the {@link XConfigCriteria} * @param range * the {@link CellRangeAddress} */ private void applyBorderToRegion(final XConfigCriteria configCriteria, CellRangeAddress range) { RegionUtil.setBorderBottom( configCriteria.getStylesMap().get(CellStyleHandler.CELL_DECORATOR_HEADER).getBorderBottom(), range, configCriteria.getSheet(), configCriteria.getWorkbook()); RegionUtil.setBorderTop( configCriteria.getStylesMap().get(CellStyleHandler.CELL_DECORATOR_HEADER).getBorderTop(), range, configCriteria.getSheet(), configCriteria.getWorkbook()); RegionUtil.setBorderLeft( configCriteria.getStylesMap().get(CellStyleHandler.CELL_DECORATOR_HEADER).getBorderLeft(), range, configCriteria.getSheet(), configCriteria.getWorkbook()); RegionUtil.setBorderRight( configCriteria.getStylesMap().get(CellStyleHandler.CELL_DECORATOR_HEADER).getBorderRight(), range, configCriteria.getSheet(), configCriteria.getWorkbook()); } /** * Initialize an row. * * @param s * the {@link Sheet} to add the row * @param idxR * position of the new row * @return the {@link Row} created */ private Row initializeRow(final Sheet s, final int idxR) { return s.createRow(idxR); } /** * Initialize the cell position based at the title orientation. * * @param positionCell * the cell position defined at the element * @param orientation * the {@link TitleOrientationType} of the element * @return the cell position */ private int initializeHeaderCellPosition(final int positionCell, final TitleOrientationType orientation) { int idxCell = positionCell - 1; if (TitleOrientationType.LEFT == orientation) { idxCell -= 1; } else if (TitleOrientationType.RIGHT == orientation) { idxCell += 1; } return idxCell; } /** * initialize the row position based at the title orientation. * * @param positionRow * the row position defined at the element * @param orientation * the {@link TitleOrientationType} of the element * @return the row position */ private int initializeHeaderRowPosition(final int positionRow, final TitleOrientationType orientation) { int idxRow = positionRow; if (TitleOrientationType.TOP == orientation) { idxRow -= 1; } else if (TitleOrientationType.BOTTOM == orientation) { idxRow += 1; } return idxRow; } private void initializeCellByField(final XConfigCriteria configCriteria, final XlsFreeElement xlsAnnotation, final Object o, final Field field, final int idxC, final int cL) throws ElementException, ConverterException, CustomizedRulesException { /* validate cascade level */ if (cL <= configCriteria.getCascadeLevel().getCode()) { /* make the field accessible to recover the value */ field.setAccessible(true); Class<?> fT = field.getType(); if (configCriteria.getSheet().getRow(xlsAnnotation.row()) != null) { configCriteria.setRow(configCriteria.getSheet().getRow(xlsAnnotation.row())); } else { configCriteria.setRow(configCriteria.getSheet().createRow(xlsAnnotation.row())); } configCriteria.setField(field); // initialize Element configCriteria.setElement(XlsElementFactory.build(xlsAnnotation)); boolean isAppliedObject = toExcel(configCriteria, o, fT, idxC); if (!isAppliedObject && !fT.isPrimitive()) { throw new ElementException(ExceptionMessage.ElementException_ComplexObject.getMessage()); } } } private int initializeCellByFieldHorizontal(final XConfigCriteria configCriteria, final Object o, final int idxR, final int idxC, final int cL) throws IllegalAccessException, InstantiationException, InvocationTargetException, ConfigurationException, ElementException, CustomizedRulesException, ConverterException, SheetException, NoSuchMethodException { int counter = 0; /* validate cascade level */ if (cL <= configCriteria.getCascadeLevel().getCode()) { /* make the field accessible to recover the value */ configCriteria.getField().setAccessible(true); Class<?> fT = configCriteria.getField().getType(); if (Collection.class.isAssignableFrom(fT)) { //E uma lista entao ha que crear uma sheet nova marshallCollectionEngineT(configCriteria,(Collection<?>) CGen.toCollection(o, configCriteria.getField()),idxC,fT); }else{ boolean isAppliedObject = toExcel(configCriteria, o, fT, idxC); if (!isAppliedObject && !fT.isPrimitive()) { Object nO = configCriteria.getField().get(o); /* manage null objects */ if (nO == null) { nO = fT.newInstance(); } Class<?> oC = nO.getClass(); counter = marshalAsPropagationHorizontal(configCriteria, nO, oC, idxR, idxC - 1, cL + 1); } } } return counter; } private int initializeCellByFieldVertical(final XConfigCriteria configCriteria, final Object o, final Row r, final int idxR, final int idxC, int cL) throws ElementException, ConverterException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, CustomizedRulesException, ConfigurationException { int counter = 0; /* validate cascade level */ if (cL <= configCriteria.getCascadeLevel().getCode()) { /* make the field accessible to recover the value */ configCriteria.getField().setAccessible(true); Class<?> fT = configCriteria.getField().getType(); configCriteria.setRow(r); boolean isAppliedObject = toExcel(configCriteria, o, fT, idxC); if (!isAppliedObject && !fT.isPrimitive()) { Object nO = configCriteria.getField().get(o); /* manage null objects */ if (nO == null) { nO = fT.newInstance(); } Class<?> oC = nO.getClass(); counter = marshalAsPropagationVertical(configCriteria, nO, oC, idxR - 1, idxC - 1, cL + 1); } } return counter; } /** * Apply the base object to cell. * * @param configCriteria * the {@link XConfigCriteria} * @param o * the object * @param fT * the field type * @param idxC * the position of the cell * @return * @throws ElementException * @throws ConverterException * @throws CustomizedRulesException * @throws Exception */ private boolean toExcel(final XConfigCriteria configCriteria, final Object o, final Class<?> fT, final int idxC) throws ElementException, ConverterException, CustomizedRulesException { /* flag which define if the cell was updated or not */ boolean isUpdated; /* initialize cell */ Cell cell; /* * check if the cell to be applied the element is empty otherwise one * exception will be launched */ if (configCriteria.getRow().getCell(idxC) != null) { throw new ElementException(ExceptionMessage.ElementException_OverwriteCell.getMessage()); } switch (fT.getName()) { case CellHandler.OBJECT_DATE: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.dateWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_LOCALDATE: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.localDateWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_LOCALDATETIME: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.localDateTimeWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_STRING: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.stringWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_SHORT: /* falls through */ case CellHandler.PRIMITIVE_SHORT: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.shortWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_INTEGER: /* falls through */ case CellHandler.PRIMITIVE_INTEGER: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.integerWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_LONG: /* falls through */ case CellHandler.PRIMITIVE_LONG: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.longWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_DOUBLE: /* falls through */ case CellHandler.PRIMITIVE_DOUBLE: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.doubleWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_BIGDECIMAL: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.bigDecimalWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_FLOAT: /* falls through */ case CellHandler.PRIMITIVE_FLOAT: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.floatWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_BOOLEAN: /* falls through */ case CellHandler.PRIMITIVE_BOOLEAN: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.booleanWriter(configCriteria, o, cell); break; default: isUpdated = false; break; } if (!isUpdated && fT.isEnum()) { cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.enumWriter(configCriteria, o, cell); } return isUpdated; } private boolean toObject(final Object o, final Class<?> fT, final Field f, final Cell c, final XlsElement xlsAnnotation) throws IllegalAccessException, ConverterException { /* flag which define if the cell was updated or not */ boolean isUpdated; f.setAccessible(true); switch (fT.getName()) { case CellHandler.OBJECT_DATE: CellHandler.dateReader(o, f, c, xlsAnnotation); isUpdated = true; break; case CellHandler.OBJECT_LOCALDATE: CellHandler.localDateReader(o, f, c, xlsAnnotation); isUpdated = true; break; case CellHandler.OBJECT_LOCALDATETIME: CellHandler.localDateTimeReader(o, f, c, xlsAnnotation); isUpdated = true; break; case CellHandler.OBJECT_STRING: CellHandler.stringReader(o, f, c); isUpdated = true; break; case CellHandler.OBJECT_SHORT: /* falls through */ case CellHandler.PRIMITIVE_SHORT: CellHandler.shortReader(o, f, c); isUpdated = true; break; case CellHandler.OBJECT_INTEGER: /* falls through */ case CellHandler.PRIMITIVE_INTEGER: CellHandler.integerReader(o, f, c); isUpdated = true; break; case CellHandler.OBJECT_LONG: /* falls through */ case CellHandler.PRIMITIVE_LONG: CellHandler.longReader(o, f, c); isUpdated = true; break; case CellHandler.OBJECT_DOUBLE: /* falls through */ case CellHandler.PRIMITIVE_DOUBLE: CellHandler.doubleReader(o, f, c, xlsAnnotation); isUpdated = true; break; case CellHandler.OBJECT_BIGDECIMAL: CellHandler.bigDecimalReader(o, f, c, xlsAnnotation); isUpdated = true; break; case CellHandler.OBJECT_FLOAT: /* falls through */ case CellHandler.PRIMITIVE_FLOAT: CellHandler.floatReader(o, f, c); isUpdated = true; break; case CellHandler.OBJECT_BOOLEAN: /* falls through */ case CellHandler.PRIMITIVE_BOOLEAN: CellHandler.booleanReader(o, f, c, xlsAnnotation); isUpdated = true; break; default: isUpdated = false; break; } if (!isUpdated && fT.isEnum()) { CellHandler.enumReader(o, fT, f, c); isUpdated = true; } return isUpdated; } /** * Process the annotation {@link XlsFreeElement} * * @param configCriteria * the {@link XConfigCriteria} * @param o * the object * @param oC * the object class * @param f * the field * @throws ElementException * @throws ConverterException * @throws CustomizedRulesException */ private void processXlsFreeElement(final XConfigCriteria configCriteria, final Object o, final int cL, final Field f) throws ElementException, ConverterException, CustomizedRulesException { if (f.isAnnotationPresent(XlsFreeElement.class)) { XlsFreeElement xlsAnnotation = (XlsFreeElement) f.getAnnotation(XlsFreeElement.class); /* validate the row/cell of the element */ if (xlsAnnotation.row() < 1 || xlsAnnotation.cell() < 1) { throw new ElementException(ExceptionMessage.ElementException_InvalidPosition.getMessage()); } /* header treatment */ if (xlsAnnotation.showTitle()) { /* initialize the row position */ int idxRow = initializeHeaderRowPosition(xlsAnnotation.row(), xlsAnnotation.titleOrientation()); /* initialize the cell position */ int idxCell = initializeHeaderCellPosition(xlsAnnotation.cell(), xlsAnnotation.titleOrientation()); /* obtain/initialize the row */ Row row = configCriteria.getSheet().getRow(idxRow); if (row == null) { row = initializeRow(configCriteria.getSheet(), idxRow); } /* * check if the cell to be applied the element is empty * otherwise one exception will be launched */ if (row.getCell(idxCell) != null) { throw new ElementException(ExceptionMessage.ElementException_OverwriteCell.getMessage()); } CellStyleHandler.initializeHeaderCell(configCriteria.getStylesMap(), row, idxCell, xlsAnnotation.title()); } /* prepare the column width */ if (configCriteria.getResizeActive() && xlsAnnotation.columnWidthInUnits() != 0) { configCriteria.getColumnWidthMap().put(xlsAnnotation.cell() - 1, xlsAnnotation.columnWidthInUnits()); } /* content treatment */ initializeCellByField(configCriteria, xlsAnnotation, o, f, xlsAnnotation.cell() - 1, cL); } } /** * Prepare the propagation horizontal:<br> * 1. initialize sheet <br> * 2. initialize header row <br> * 3. initialize row <br> * * @param configCriteria * the {@link XConfigCriteria} * @return * @throws SheetException */ private int preparePropagationHorizontal(final XConfigCriteria configCriteria) throws SheetException { int idxRow; if (configCriteria.getWorkbook().getNumberOfSheets() == 0 || configCriteria.getWorkbook().getSheet(truncateTitle(configCriteria.getTitleSheet())) == null) { configCriteria.setSheet(initializeSheet(configCriteria.getWorkbook(), configCriteria.getTitleSheet())); idxRow = configCriteria.getStartRow(); configCriteria.setRowHeader(initializeRow(configCriteria.getSheet(), idxRow++)); configCriteria.setRow(initializeRow(configCriteria.getSheet(), idxRow++)); } else { //TOVERIFY se ha que aumentar a 5 pelo nestedheader idxRow =configCriteria.getElement()!=null && configCriteria.getElement().parentSheet() ? configCriteria.getSheet().getLastRowNum() + 3 : configCriteria.getSheet().getLastRowNum() + 1; //idxRow = configCriteria.getSheet().getLastRowNum() + 1; configCriteria.setRowHeader(null); configCriteria.setRow(initializeRow(configCriteria.getSheet(), idxRow++)); } return idxRow; } /** * Prepare the propagation vertical:<br> * 1. initialize sheet <br> * 2. define next cell index value <br> * * @param configCriteria * the {@link XConfigCriteria} * @param idxCell * the cell index * @return * @throws SheetException */ private int preparePropagationVertical(final XConfigCriteria configCriteria, int idxCell) throws SheetException { int indexCell = idxCell; if (configCriteria.getWorkbook().getNumberOfSheets() == 0 || configCriteria.getWorkbook().getSheet(truncateTitle(configCriteria.getTitleSheet())) == null) { configCriteria.setSheet(initializeSheet(configCriteria.getWorkbook(), configCriteria.getTitleSheet())); indexCell = configCriteria.getStartCell(); } else { indexCell += 1; } return indexCell; } private int marshalAsPropagationHorizontal(final XConfigCriteria configCriteria, final Object o, final Class<?> oC, final int idxR, final int idxC, final int cL) throws ConfigurationException, ElementException, CustomizedRulesException, IllegalAccessException, InvocationTargetException, InstantiationException, ConverterException, SheetException, NoSuchMethodException { /* counter related to the number of fields (if new object) */ int counter = -1; int indexCell = idxC; int rem=0; /* get declared fields */ List<Field> fL = Arrays.asList(oC.getDeclaredFields()); //Order by the list by position Collections.sort(fL,new Comparator<Field>(){ public int compare(Field f1,Field f2){ if(f2==null){ return 0; }else if (f1!=null && f2!=null && f1.isAnnotationPresent(XlsElement.class) && f2.isAnnotationPresent(XlsElement.class)) { XlsElement element1 = (XlsElement) f1.getAnnotation(XlsElement.class); XlsElement element2 = (XlsElement) f2.getAnnotation(XlsElement.class); return element1.position() - element2.position(); }else{ return 0; } }}); for (Field f : fL) { /* update field at ConfigCriteria */ configCriteria.setField(f); /* process each field from the object */ if (configCriteria.getRowHeader() != null) { /* calculate index of the cell */ int tmpIdxRow = idxR - 3; /* apply merge region */ applyMergeRegion(configCriteria, null, tmpIdxRow, indexCell, true); } /* Process @XlsElement */ if (f.isAnnotationPresent(XlsElement.class)) { XlsElement xlsAnnotation = (XlsElement) f.getAnnotation(XlsElement.class); /* validate the position of the element */ if (xlsAnnotation.position() < 1) { throw new ElementException(ExceptionMessage.ElementException_InvalidPosition.getMessage()); } /* validate the propagation type & formulas */ if (xlsAnnotation.isFormula() && StringUtils.isNotBlank(xlsAnnotation.formula()) && xlsAnnotation.formula().contains("idy")) { throw new ElementException(ExceptionMessage.ConfigurationException_Conflict.getMessage()); } /* update annotation at ConfigCriteria */ configCriteria.setElement(xlsAnnotation); /* apply customized rules defined at the object */ if (StringUtils.isNotBlank(xlsAnnotation.customizedRules())) { try { CellHandler.applyCustomizedRules(o, xlsAnnotation.customizedRules()); } catch (NoSuchMethodException e) { throw new CustomizedRulesException( ExceptionMessage.CustomizedRulesException_NoSuchMethod.getMessage(), e); } } /* * increment of the counter related to the number of fields (if * new object) */ counter++; int pos= idxC + xlsAnnotation.position(); //if is a list don't generate the head if (configCriteria.getRowHeader() != null && !Collection.class.isAssignableFrom(f.getType())) { pos = pos-rem; /* header treatment */ CellStyleHandler.initializeHeaderCell(configCriteria.getStylesMap(), configCriteria.getRowHeader(), indexCell + xlsAnnotation.position(), xlsAnnotation.title()); rem=0; }else{ rem=rem+1; } /* prepare the column width */ if (configCriteria.getResizeActive() && xlsAnnotation.columnWidthInUnits() != 0) { configCriteria.getColumnWidthMap().put(indexCell + xlsAnnotation.position(), xlsAnnotation.columnWidthInUnits()); } /* content treatment */ indexCell += initializeCellByFieldHorizontal(configCriteria, o, idxR, indexCell + xlsAnnotation.position(), cL); } } for (Field f : fL) { /* update field at ConfigCriteria */ configCriteria.setField(f); /* Process @XlsFreeElement */ processXlsFreeElement(configCriteria, o, cL, f); } /* disable the resize */ configCriteria.setResizeActive(false); return counter; } private int marshalAsPropagationVertical(final XConfigCriteria configCriteria, final Object o, Class<?> oC, final int idxR, final int idxC, final int cL) throws ElementException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, CustomizedRulesException, ConfigurationException, ConverterException, InstantiationException { /* counter related to the number of fields (if new object) */ int counter = -1; int indexCell = idxC; int indexRow = idxR; /* backup base index of the cell */ int baseIdxCell = indexCell; /* get declared fields */ List<Field> fL = Arrays.asList(oC.getDeclaredFields()); Collections.sort(fL,new Comparator<Field>(){ public int compare(Field f1,Field f2){ if(f2==null){ return 0; }else if (f1!=null && f2!=null && f1.isAnnotationPresent(XlsElement.class) && f2.isAnnotationPresent(XlsElement.class)) { XlsElement element1 = (XlsElement) f1.getAnnotation(XlsElement.class); XlsElement element2 = (XlsElement) f2.getAnnotation(XlsElement.class); return element1.position() - element2.position(); }else{ return 0; } }}); for (Field f : fL) { /* process each field from the object */ configCriteria.setField(f); /* restart the index of the cell */ indexCell = baseIdxCell; /* Process @XlsElement */ if (f.isAnnotationPresent(XlsElement.class)) { XlsElement xlsAnnotation = (XlsElement) f.getAnnotation(XlsElement.class); /* validate the position of the element */ if (xlsAnnotation.position() < 1) { throw new ElementException(ExceptionMessage.ElementException_InvalidPosition.getMessage()); } /* validate the propagation type & formulas */ if (xlsAnnotation.isFormula() && StringUtils.isNotBlank(xlsAnnotation.formula()) && xlsAnnotation.formula().contains("idx")) { throw new ElementException(ExceptionMessage.ConfigurationException_Conflict.getMessage()); } /* update annotation at ConfigCriteria */ configCriteria.setElement(xlsAnnotation); /* apply customized rules defined at the object */ if (StringUtils.isNotBlank(xlsAnnotation.customizedRules())) { CellHandler.applyCustomizedRules(o, xlsAnnotation.customizedRules()); } /* * increment of the counter related to the number of fields (if * new object) */ counter++; /* create the row */ Row row = configCriteria.getSheet().getRow(indexRow + xlsAnnotation.position()); if (row == null) { /* header treatment with nested header */ int tmpIdxCell = indexCell - 1; /* initialize row */ row = initializeRow(configCriteria.getSheet(), indexRow + xlsAnnotation.position()); /* apply merge region */ applyMergeRegion(configCriteria, row, indexRow, tmpIdxCell, false); /* header treatment */ CellStyleHandler.initializeHeaderCell(configCriteria.getStylesMap(), row, indexCell, xlsAnnotation.title()); } else { /* header treatment without nested header */ CellStyleHandler.initializeHeaderCell(configCriteria.getStylesMap(), row, indexCell, xlsAnnotation.title()); } /* prepare the column width */ if (configCriteria.getResizeActive() && xlsAnnotation.columnWidthInUnits() != 0) { configCriteria.getColumnWidthMap().put(indexCell + xlsAnnotation.position(), xlsAnnotation.columnWidthInUnits()); } /* increment the cell position */ indexCell++; /* content treatment */ indexRow += initializeCellByFieldVertical(configCriteria, o, row, indexRow + xlsAnnotation.position(), indexCell, cL); } } for (Field f : fL) { /* update field at ConfigCriteria */ configCriteria.setField(f); /* Process @XlsFreeElement */ processXlsFreeElement(configCriteria, o, cL, f); } /* disable the resize */ configCriteria.setResizeActive(false); return counter; } private int unmarshalAsPropagationHorizontal(final XConfigCriteria configCriteria, final Object o, Class<?> oC, final int idxR, final int idxC) throws IllegalAccessException, ConverterException, InstantiationException, ElementException { /* counter related to the number of fields (if new object) */ int counter = -1; int indexCell = idxC; /* get declared fields */ List<Field> fL = Arrays.asList(oC.getDeclaredFields()); for (Field f : fL) { /* process each field from the object */ Class<?> fT = f.getType(); /* Process @XlsElement */ if (f.isAnnotationPresent(XlsElement.class)) { XlsElement xlsAnnotation = (XlsElement) f.getAnnotation(XlsElement.class); /* validate the position of the element */ if (xlsAnnotation.position() < 1) { throw new ElementException(ExceptionMessage.ElementException_InvalidPosition.getMessage()); } /* * increment of the counter related to the number of fields (if * new object) */ counter++; /* content row */ //MAL - ERRO AQUI Row contentRow = configCriteria.getSheet().getRow(idxR + 1); Cell contentCell = contentRow.getCell(indexCell + xlsAnnotation.position()); boolean isAppliedToBaseObject = toObject(o, fT, f, contentCell, xlsAnnotation); if (!isAppliedToBaseObject && !fT.isPrimitive()) { Object subObjbect = fT.newInstance(); Class<?> subObjbectClass = subObjbect.getClass(); int internalCellCounter = unmarshalAsPropagationHorizontal(configCriteria, subObjbect, subObjbectClass, idxR, indexCell + xlsAnnotation.position() - 1); /* add the sub object to the parent object */ f.set(o, subObjbect); /* update the index */ indexCell += internalCellCounter; } } /* Process @XlsFreeElement */ if (f.isAnnotationPresent(XlsFreeElement.class)) { XlsFreeElement xlsFreeAnnotation = (XlsFreeElement) f.getAnnotation(XlsFreeElement.class); /* validate the row/cell of the element */ if (xlsFreeAnnotation.row() < 1 || xlsFreeAnnotation.cell() < 1) { throw new ElementException(ExceptionMessage.ElementException_InvalidPosition.getMessage()); } /* content row */ Row contentRow = configCriteria.getSheet().getRow(xlsFreeAnnotation.row()); Cell contentCell = contentRow.getCell(xlsFreeAnnotation.cell() - 1); // initialize Element XlsElement xlsAnnotation = XlsElementFactory.build(xlsFreeAnnotation); boolean isAppliedToBaseObject = toObject(o, fT, f, contentCell, xlsAnnotation); if (!isAppliedToBaseObject && !fT.isPrimitive()) { throw new ElementException(ExceptionMessage.ElementException_ComplexObject.getMessage()); } } } return counter; } private int unmarshalAsPropagationVertical(final XConfigCriteria configCriteria, final Object o, Class<?> oC, final int idxR, final int idxC) throws IllegalAccessException, ConverterException, InstantiationException, ElementException { /* counter related to the number of fields (if new object) */ int counter = -1; int indexRow = idxR; /* get declared fields */ List<Field> fL = Arrays.asList(oC.getDeclaredFields()); for (Field f : fL) { /* process each field from the object */ Class<?> fT = f.getType(); /* Process @XlsElement */ if (f.isAnnotationPresent(XlsElement.class)) { XlsElement xlsAnnotation = (XlsElement) f.getAnnotation(XlsElement.class); /* validate the position of the element */ if (xlsAnnotation.position() < 1) { throw new ElementException(ExceptionMessage.ElementException_InvalidPosition.getMessage()); } /* * increment of the counter related to the number of fields (if * new object) */ counter++; /* content row */ Row contentRow = configCriteria.getSheet().getRow(indexRow + xlsAnnotation.position()); Cell contentCell = contentRow.getCell(idxC + 1); boolean isAppliedToBaseObject = toObject(o, fT, f, contentCell, xlsAnnotation); if (!isAppliedToBaseObject && !fT.isPrimitive()) { Object subObjbect = fT.newInstance(); Class<?> subObjbectClass = subObjbect.getClass(); int internalCellCounter = unmarshalAsPropagationVertical(configCriteria, subObjbect, subObjbectClass, indexRow + xlsAnnotation.position() - 1, idxC); /* add the sub object to the parent object */ f.set(o, subObjbect); /* update the index */ indexRow += internalCellCounter; } } /* Process @XlsFreeElement */ if (f.isAnnotationPresent(XlsFreeElement.class)) { XlsFreeElement xlsFreeAnnotation = (XlsFreeElement) f.getAnnotation(XlsFreeElement.class); /* validate the row/cell of the element */ if (xlsFreeAnnotation.row() < 1 || xlsFreeAnnotation.cell() < 1) { throw new ElementException(ExceptionMessage.ElementException_InvalidPosition.getMessage()); } /* content row */ Row contentRow = configCriteria.getSheet().getRow(xlsFreeAnnotation.row()); Cell contentCell = contentRow.getCell(xlsFreeAnnotation.cell() - 1); // initialize Element XlsElement xlsAnnotation = XlsElementFactory.build(xlsFreeAnnotation); boolean isAppliedToBaseObject = toObject(o, fT, f, contentCell, xlsAnnotation); if (!isAppliedToBaseObject && !fT.isPrimitive()) { throw new ElementException(ExceptionMessage.ElementException_ComplexObject.getMessage()); } } } return counter; } /** * Generate file output stream. * * @param wb * the {@link Workbook} * @param name * the name * @return * @throws IOException * @throws Exception */ private FileOutputStream workbookFileOutputStream(final Workbook wb, final String name) throws IOException { FileOutputStream output = new FileOutputStream(name); wb.write(output); output.close(); return output; } /** * Generate the byte array. * * @param wb * the {@link Workbook} * @return the byte[] * @throws IOException */ private byte[] workbookToByteAray(final Workbook wb) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { wb.write(bos); } finally { bos.close(); } return bos.toByteArray(); } private void marshalEngine(final XConfigCriteria configCriteria, final Object object) throws ElementException, ConfigurationException, SheetException, IllegalAccessException, InvocationTargetException, InstantiationException, CustomizedRulesException, ConverterException, NoSuchMethodException { if (object == null) { throw new ElementException(ExceptionMessage.ElementException_NullObject.getMessage()); } /* initialize the runtime class of the object */ Class<?> oC = initializeRuntimeClass(object); /* initialize configuration data */ initializeConfigurationData(configCriteria, oC, false); /* initialize Workbook */ configCriteria.setWorkbook(initializeWorkbook(configCriteria.getExtension())); /* initialize style cell via annotations */ initializeCellStyleViaAnnotation(oC, configCriteria); /* initialize style cell via default option */ configCriteria.initializeCellDecorator(); /* initialize Sheet */ configCriteria.setSheet(initializeSheet(configCriteria.getWorkbook(), configCriteria.getTitleSheet())); /* initialize Row & Cell */ int idxRow = configCriteria.getStartRow(); int idxCell = configCriteria.getStartCell(); /* initialize rows according the PropagationType */ if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) { configCriteria.setRowHeader(initializeRow(configCriteria.getSheet(), idxRow++)); configCriteria.setRow(initializeRow(configCriteria.getSheet(), idxRow++)); marshalAsPropagationHorizontal(configCriteria, object, oC, idxRow, idxCell, 0); } else { marshalAsPropagationVertical(configCriteria, object, oC, idxRow, idxCell, 0); } /* apply the freeze pane */ SheetFreezePaneHandler.applyFreezePane(configCriteria); /* apply the elements as group */ SheetGroupElementHandler.applyGroupElements(configCriteria); /* apply the column resize */ configCriteria.applyColumnWidthToSheet(); } private void unmarshalEngine(final XConfigCriteria configCriteria, final Object object, final Class<?> oC) throws SheetException, IllegalAccessException, InstantiationException, ConverterException, ElementException { /* initialize sheet */ if (StringUtils.isBlank(configCriteria.getTitleSheet())) { throw new SheetException(ExceptionMessage.SheetException_CreationSheet.getMessage()); } configCriteria.setSheet(configCriteria.getWorkbook().getSheet(configCriteria.getTitleSheet())); /* initialize index row & cell */ int idxRow = configCriteria.getStartRow(); int idxCell = configCriteria.getStartCell(); if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) { unmarshalAsPropagationHorizontal(configCriteria, object, oC, idxRow, idxCell); } else { unmarshalAsPropagationVertical(configCriteria, object, oC, idxRow, idxCell); } } private void marshalCollectionEngine(final XConfigCriteria configCriteria, final Collection<?> listObject, final boolean insideCollection) throws ElementException, ConfigurationException, SheetException, CustomizedRulesException, IllegalAccessException, InvocationTargetException, InstantiationException, ConverterException, NoSuchMethodException { int idxRow; int idxCell = 0; if (listObject == null || listObject.isEmpty()) { throw new ElementException(ExceptionMessage.ElementException_NullObject.getMessage()); } Object objectRT; try { //TOVERIFY objectRT = listObject.iterator().next(); //objectRT = listObject.getClass().stream().findFirst().get(); } catch (Exception e) { throw new ElementException(ExceptionMessage.ElementException_NullObject.getMessage()); } /* initialize the runtime class of the object */ Class<?> oC = initializeRuntimeClass(objectRT); /* initialize configuration data */ // initializeConfigurationData(configCriteria, oC, insideCollection); // initialize Workbook configCriteria.setWorkbook(initializeWorkbook(configCriteria.getExtension())); // initialize style cell via annotation initializeCellStyleViaAnnotation(oC, configCriteria); // initialize style cell via default option configCriteria.initializeCellDecorator(); marshallCollectionEngineT(configCriteria, listObject, idxCell, oC); } private void marshallCollectionEngineT(final XConfigCriteria configCriteria, final Collection<?> listObject, int idxCell, Class<?> oC) throws SheetException, ConfigurationException, ElementException, CustomizedRulesException, IllegalAccessException, InvocationTargetException, InstantiationException, ConverterException, NoSuchMethodException { int idxRow; @SuppressWarnings("rawtypes") Iterator iterator = listObject.iterator(); while (iterator.hasNext()) { Object object = iterator.next(); /* initialize configuration data */ initializeConfigurationData(configCriteria, object.getClass(), false); // initialize rows according the PropagationType if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) { idxCell = configCriteria.getStartCell(); idxRow = preparePropagationHorizontal(configCriteria); marshalAsPropagationHorizontal(configCriteria, object, object.getClass(), idxRow, idxCell, 0); } else { //parentsheet para fazer idxCell = preparePropagationVertical(configCriteria, idxCell); idxRow = configCriteria.getStartRow(); marshalAsPropagationVertical(configCriteria, object, oC, idxRow, idxCell, 0); } } /* apply the column resize */ configCriteria.applyColumnWidthToSheet(); } @Override public Sheet marshalToSheet(final Object object) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, ElementException, ConfigurationException, SheetException, CustomizedRulesException, ConverterException { /* Initialize a basic ConfigCriteria */ XConfigCriteria configCriteria = new XConfigCriteria(); /* Generate the workbook based at the object passed as parameter */ marshalEngine(configCriteria, object); /* Return the Sheet generated */ return configCriteria.getWorkbook().getSheetAt(0); } @Override public Sheet marshalToSheet(final XConfigCriteria configCriteria, final Object object) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, ElementException, ConfigurationException, SheetException, CustomizedRulesException, ConverterException { /* Generate the workbook based at the object passed as parameter */ marshalEngine(configCriteria, object); /* Return the Sheet generated */ return configCriteria.getWorkbook().getSheetAt(0); } @Override public Workbook marshalToWorkbook(final Object object) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, ElementException, ConfigurationException, SheetException, CustomizedRulesException, ConverterException { /* Initialize a basic ConfigCriteria */ XConfigCriteria configCriteria = new XConfigCriteria(); /* Generate the workbook based at the object passed as parameter */ marshalEngine(configCriteria, object); /* Return the Workbook generated */ return configCriteria.getWorkbook(); } @Override public Workbook marshalToWorkbook(final XConfigCriteria configCriteria, final Object object) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, ElementException, ConfigurationException, SheetException, CustomizedRulesException, ConverterException { /* Generate the workbook from the object passed as parameter */ marshalEngine(configCriteria, object); /* Return the Workbook generated */ return configCriteria.getWorkbook(); } @Override public byte[] marshalToByte(final Object object) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, ElementException, ConfigurationException, SheetException, CustomizedRulesException, ConverterException, IOException { /* Initialize a basic ConfigCriteria */ XConfigCriteria configCriteria = new XConfigCriteria(); /* Generate the workbook from the object passed as parameter */ marshalEngine(configCriteria, object); /* Generate the byte array to return */ return workbookToByteAray(configCriteria.getWorkbook()); } @Override public byte[] marshalToByte(final XConfigCriteria configCriteria, final Object object) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, ElementException, ConfigurationException, SheetException, CustomizedRulesException, ConverterException, IOException { /* Generate the workbook from the object passed as parameter */ marshalEngine(configCriteria, object); /* Generate the byte array to return */ return workbookToByteAray(configCriteria.getWorkbook()); } @Override public void marshalAndSave(final Object object, final String pathFile) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, ElementException, ConfigurationException, SheetException, CustomizedRulesException, ConverterException, IOException { /* Generate the workbook from the object passed as parameter */ XConfigCriteria configCriteria = new XConfigCriteria(); marshalAndSave(configCriteria, object, pathFile); } @Override public void marshalAndSave(final XConfigCriteria configCriteria, final Object object, final String pathFile) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, ElementException, ConfigurationException, SheetException, CustomizedRulesException, ConverterException, IOException { /* Generate the workbook from the object passed as parameter */ marshalEngine(configCriteria, object); /* * check if the path terminate with the file separator, otherwise will * be added to avoid any problem */ String internalPathFile = pathFile; if (!pathFile.endsWith(File.separator)) { internalPathFile = pathFile.concat(File.separator); } /* Save the Workbook at a specified path (received as parameter) */ workbookFileOutputStream(configCriteria.getWorkbook(), internalPathFile + configCriteria.getCompleteFileName()); } @Override public Sheet marshalCollectionToSheet(final Collection<?> listObject) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, ElementException, ConfigurationException, SheetException, CustomizedRulesException, ConverterException { /* Initialize a basic ConfigCriteria */ XConfigCriteria configCriteria = new XConfigCriteria(); /* Generate the workbook based at the list of objects passed as parameter */ marshalCollectionEngine(configCriteria, listObject,false); /* Return the Sheet generated */ return configCriteria.getWorkbook().getSheetAt(0); } @Override public Sheet marshalCollectionToSheet(final XConfigCriteria configCriteria, final Collection<?> listObject) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, ElementException, ConfigurationException, SheetException, CustomizedRulesException, ConverterException { /* Generate the workbook based at the list of objects passed as parameter */ marshalCollectionEngine(configCriteria, listObject,false); /* Return the Sheet generated */ return configCriteria.getWorkbook().getSheetAt(0); } @Override public Workbook marshalCollectionToWorkbook(final Collection<?> listObject) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, ElementException, ConfigurationException, SheetException, CustomizedRulesException, ConverterException { /* Initialize a basic ConfigCriteria */ XConfigCriteria configCriteria = new XConfigCriteria(); /* Generate the workbook based at the object passed as parameter */ marshalCollectionEngine(configCriteria, listObject,false); /* Return the Workbook generated */ return configCriteria.getWorkbook(); } @Override public Workbook marshalCollectionToWorkbook(final XConfigCriteria configCriteria, final Collection<?> listObject) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, ElementException, ConfigurationException, SheetException, CustomizedRulesException, ConverterException { /* Generate the workbook from the object passed as parameter */ marshalCollectionEngine(configCriteria, listObject,false); /* Return the Workbook generated */ return configCriteria.getWorkbook(); } /** * Generate the file from the collection of objects. * * @param listObject * the collection to apply at the file. * @param pathFile * the path where is found the file to read and pass the * information to the object * @throws Exception */ @Override public void marshalAsCollectionAndSave(final Collection<?> listObject, final String pathFile) throws Exception { /* Initialize a basic ConfigCriteria */ XConfigCriteria configCriteria = new XConfigCriteria(); marshalAsCollectionAndSave(configCriteria, listObject, pathFile); } /** * Generate the CSV file, based at {@link XConfigCriteria}, from the * collection of objects. * * @param configCriteria * the {@link XConfigCriteria} to use * @param listObject * the collection to apply at the file. * @param pathFile * the path where is found the file to read and pass the * information to the object * @throws Exception */ @Override public void marshalAsCollectionAndSave(final XConfigCriteria configCriteria, final Collection<?> listObject, final String pathFile) throws Exception { /* Generate the workbook from the object passed as parameter */ marshalCollectionEngine(configCriteria, listObject,false); /* * check if the path terminate with the file separator, otherwise will * be added to avoid any problem */ String internalPathFile = pathFile; if (!pathFile.endsWith(File.separator)) { internalPathFile = pathFile.concat(File.separator); } /* save the Workbook at a specified path (received as parameter) */ workbookFileOutputStream(configCriteria.getWorkbook(), internalPathFile + configCriteria.getCompleteFileName()); } @Override public byte[] marshalCollectionToByte(final Collection<?> listObject) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, ElementException, ConfigurationException, SheetException, CustomizedRulesException, ConverterException, IOException { /* Initialize a basic ConfigCriteria */ XConfigCriteria configCriteria = new XConfigCriteria(); /* Generate the workbook from the object passed as parameter */ marshalCollectionEngine(configCriteria, listObject,false); /* Generate the byte array to return */ return workbookToByteAray(configCriteria.getWorkbook()); } @Override public byte[] marshalCollectionToByte(final XConfigCriteria configCriteria, final Collection<?> listObject) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, ElementException, ConfigurationException, SheetException, CustomizedRulesException, ConverterException, IOException { /* Generate the workbook from the object passed as parameter */ marshalCollectionEngine(configCriteria, listObject,false); /* Generate the byte array to return */ return workbookToByteAray(configCriteria.getWorkbook()); } @Override public byte[] marshalCollectionToByte(final XConfigCriteria configCriteria, final Collection<?> listObject) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, ElementException, ConfigurationException, SheetException, CustomizedRulesException, ConverterException, IOException { /* Generate the workbook from the object passed as parameter */ marshalCollectionEngine(configCriteria, listObject); /* Generate the byte array to return */ return workbookToByteAray(configCriteria.getWorkbook()); } @Override public void unmarshalFromWorkbook(final Object object, final Workbook workbook) throws ElementException, ConfigurationException, IllegalAccessException, InstantiationException, SheetException, ConverterException { /* initialize the runtime class of the object */ Class<?> oC = initializeRuntimeClass(object); /* initialize configuration data */ XConfigCriteria configCriteria = new XConfigCriteria(); initializeConfigurationData(configCriteria, oC, false); /* set workbook */ configCriteria.setWorkbook(workbook); /* Extract from the workbook to the object passed as parameter */ unmarshalEngine(configCriteria, object, oC); } @Override public void unmarshalFromPath(final Object object, final String pathFile) throws ElementException, ConfigurationException, IOException, IllegalAccessException, InstantiationException, SheetException, ConverterException { /* initialize the runtime class of the object */ Class<?> oC = initializeRuntimeClass(object); /* initialize configuration data */ XConfigCriteria configCriteria = new XConfigCriteria(); initializeConfigurationData(configCriteria, oC, false); /* * check if the path terminate with the file separator, otherwise will * be added to avoid any problem */ String internalPathFile = pathFile; if (!pathFile.endsWith(File.separator)) { internalPathFile = pathFile.concat(File.separator); } FileInputStream input = new FileInputStream(internalPathFile + configCriteria.getCompleteFileName()); /* set workbook */ configCriteria.setWorkbook(initializeWorkbook(input, configCriteria.getExtension())); /* Extract from the workbook to the object passed as parameter */ unmarshalEngine(configCriteria, object, oC); } @Override public void unmarshalFromByte(final Object object, final byte[] byteArray) throws ElementException, ConfigurationException, IOException, IllegalAccessException, InstantiationException, SheetException, ConverterException { /* initialize the runtime class of the object */ Class<?> oC = initializeRuntimeClass(object); /* initialize configuration data */ XConfigCriteria configCriteria = new XConfigCriteria(); initializeConfigurationData(configCriteria, oC, false); /* set workbook */ configCriteria.setWorkbook(initializeWorkbook(byteArray, configCriteria.getExtension())); /* Extract from the workbook to the object passed as parameter */ unmarshalEngine(configCriteria, object, oC); } @Override public void marshalAsCollection(final Collection<?> collection) { // TODO Auto-generated method stub } @Override public Collection<?> unmarshalToCollection(final XConfigCriteria configCriteria,final Object object, String excelFilePath) throws ConfigurationException, InstantiationException, IllegalAccessException, InvocationTargetException, ConverterException, ElementException, IOException { //FileInputStream inputStream = new FileInputStream(new File(excelFilePath)); /* initialize configuration data */ initializeConfigurationData(configCriteria, object.getClass(),false); /* * check if the path terminate with the file separator, otherwise will * be added to avoid any problem */ String internalPathFile = excelFilePath; if (!excelFilePath.endsWith(File.separator)) { internalPathFile = excelFilePath.concat(File.separator); } FileInputStream input = new FileInputStream(internalPathFile + configCriteria.getCompleteFileName()); /* set workbook */ configCriteria.setWorkbook(initializeWorkbook(input, configCriteria.getExtension())); Collection<Object> collection = unmarshalTreatementToCollection(object, configCriteria); return collection; } private Collection<Object> unmarshalTreatementToCollection(Object object, XConfigCriteria configCriteria) throws InstantiationException, IllegalAccessException, InvocationTargetException, ConverterException, ElementException, ConfigurationException { /* initialize the runtime class of the object */ Class<?> oC = initializeRuntimeClass(object); initializeConfigurationData(configCriteria, oC, false); Sheet s = configCriteria.getWorkbook().getSheet(truncateTitle(configCriteria.getTitleSheet())); configCriteria.setSheet(s); /* initialize index row & cell */ int idxRow = configCriteria.getStartRow(); int idxCell = configCriteria.getStartCell(); Iterator<Row> iterator = s.iterator(); Collection<Object> collection = new ArrayList<>(); if (PropagationType.PROPAGATION_HORIZONTAL.equals(configCriteria.getPropagation())) { while (iterator.hasNext()) { Object obj=oC.newInstance(); unmarshalAsPropagationHorizontal(configCriteria, obj, oC, idxRow, idxCell); if(obj!=null){ collection.add((Object) obj); idxRow= idxRow+1; }else{ break; } } } else { while (iterator.hasNext()) { unmarshalAsPropagationVertical(configCriteria, object, oC, idxRow, idxCell); if(object!=null){ collection.add((Object) object); idxCell= idxCell+1; }else{ break; } } } return collection; } @Override public FileOutputStream marshalToFileOutputStream(final Object object) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, ElementException, ConfigurationException, SheetException, CustomizedRulesException, ConverterException, IOException { /* Initialize a basic ConfigCriteria */ XConfigCriteria configCriteria = new XConfigCriteria(); /* Generate the workbook from the object passed as parameter */ marshalEngine(configCriteria, object); /* Generate the FileOutputStream to return */ return workbookFileOutputStream(configCriteria.getWorkbook(), configCriteria.getFileName()); } /** * Generate the object from the {@link FileInputStream} passed as parameter. * * @param object * the object to apply at the workbook. * @param stream * the {@link FileInputStream} to read * @return the {@link Object} filled up */ @Override public Object unmarshalFromFileInputStream(final Object object, final FileInputStream stream) throws Exception { /* instance object class */ Class<?> oC = object.getClass(); /* initialize configuration data */ XConfigCriteria configCriteria = new XConfigCriteria(); initializeConfigurationData(configCriteria, oC, false); /* set workbook */ configCriteria.setWorkbook(initializeWorkbook(stream, configCriteria.getExtension())); unmarshalEngine(configCriteria, object, oC); return object; } /** * Method to truncate title of the sheet. * The length max is 31 caracters * @param title * @return */ private String truncateTitle(String title){ return title!=null && title.length()>31 ? title.substring(0,31) : title; } }
package org.jhaws.common.net.client5; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import org.apache.hc.core5.concurrent.FutureCallback; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpConnection; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.Message; import org.apache.hc.core5.http.Methods; import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester; import org.apache.hc.core5.http.nio.AsyncClientEndpoint; import org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer; import org.apache.hc.core5.http.nio.support.BasicRequestProducer; import org.apache.hc.core5.http.nio.support.BasicResponseConsumer; import org.apache.hc.core5.http2.config.H2Config; import org.apache.hc.core5.http2.frame.RawFrame; import org.apache.hc.core5.http2.impl.nio.H2StreamListener; import org.apache.hc.core5.http2.impl.nio.bootstrap.H2RequesterBootstrap; import org.apache.hc.core5.http2.ssl.H2ClientTlsStrategy; import org.apache.hc.core5.io.CloseMode; import org.apache.hc.core5.net.NamedEndpoint; import org.apache.hc.core5.reactor.ssl.SSLSessionVerifier; import org.apache.hc.core5.reactor.ssl.TlsDetails; import org.apache.hc.core5.ssl.SSLContexts; import org.apache.hc.core5.util.Timeout; import org.jhaws.common.lang.StringValue; import org.jsoup.Jsoup; public class Http2Test { public static void main(String[] args) throws Exception { H2Config h2Config = H2Config.custom().setPushEnabled(false).build(); HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap().setH2Config(h2Config) .setTlsStrategy(new H2ClientTlsStrategy(SSLContexts.createSystemDefault(), new SSLSessionVerifier() { @Override public TlsDetails verify(NamedEndpoint endpoint, SSLEngine sslEngine) throws SSLException { // IMPORTANT uncomment the following line when running // Java 9 or older // operation warning // return new TlsDetails(sslEngine.getSession(), // sslEngine.getApplicationProtocol()); return null; } })).setStreamListener(new H2StreamListener() { @Override public void onHeaderInput(HttpConnection connection, int streamId, List<? extends Header> headers) { for (int i = 0; i < headers.size(); i++) { System.out.println( connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i)); } } @Override public void onHeaderOutput(HttpConnection connection, int streamId, List<? extends Header> headers) { for (int i = 0; i < headers.size(); i++) { System.out.println( connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i)); } } @Override public void onFrameInput(HttpConnection connection, int streamId, RawFrame frame) { } @Override public void onFrameOutput(HttpConnection connection, int streamId, RawFrame frame) { } @Override public void onInputFlowControl(HttpConnection connection, int streamId, int delta, int actualSize) { } @Override public void onOutputFlowControl(HttpConnection connection, int streamId, int delta, int actualSize) { } }).create(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { System.out.println("HTTP requester shutting down"); requester.close(CloseMode.GRACEFUL); } }); requester.start(); HttpHost target = new HttpHost("https", "www.youtube.com", 443); StringValue body = new StringValue(); CountDownLatch latch1 = new CountDownLatch(1); { Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofSeconds(5)); AsyncClientEndpoint clientEndpoint = future.get(); clientEndpoint.execute(new BasicRequestProducer(Methods.GET, target, "/"), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() { @Override public void completed(Message<HttpResponse, String> message) { clientEndpoint.releaseAndReuse(); body.set(message.getBody()); latch1.countDown(); } @Override public void failed(Exception ex) { latch1.countDown(); } @Override public void cancelled() { latch1.countDown(); } }); } latch1.await(); Set<String> requestUris = new HashSet<>(); Jsoup.parse(body.get()).select("link").forEach(el -> { String href = el.attr("href"); if (href != null && !href.startsWith(" && (href.startsWith("/") || href.startsWith("https: if (href.startsWith("https: href = href.substring("https: } if (!href.equals("/")) requestUris.add(href); } }); Jsoup.parse(body.get()).select("img").forEach(el -> { String href = el.attr("src"); if (href != null && !href.startsWith(" && (href.startsWith("/") || href.startsWith("https: if (href.startsWith("https: href = href.substring("https: } if (!href.equals("/")) requestUris.add(href); } }); requestUris.forEach(System.out::println); CountDownLatch latch = new CountDownLatch(requestUris.size()); for (String requestUri : requestUris) { Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofSeconds(5)); AsyncClientEndpoint clientEndpoint = future.get(); clientEndpoint.execute(new BasicRequestProducer(Methods.GET, target, requestUri), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), new FutureCallback<Message<HttpResponse, String>>() { @Override public void completed(Message<HttpResponse, String> message) { clientEndpoint.releaseAndReuse(); HttpResponse response = message.getHead(); String body = message.getBody(); System.out.println(requestUri + "->" + response.getCode() + " " + response.getVersion()); System.out.println(body); latch.countDown(); } @Override public void failed(Exception ex) { clientEndpoint.releaseAndDiscard(); System.out.println(requestUri + "->" + ex); latch.countDown(); } @Override public void cancelled() { clientEndpoint.releaseAndDiscard(); System.out.println(requestUri + " cancelled"); latch.countDown(); } }); } latch.await(); System.out.println("Shutting down I/O reactor"); requester.initiateShutdown(); } }
package io.scif.util; import io.scif.FormatException; import io.scif.Metadata; import io.scif.io.RandomAccessOutputStream; import java.util.Arrays; import java.util.Hashtable; import java.util.List; import java.util.Map; import net.imglib2.meta.Axes; import net.imglib2.meta.AxisType; import net.imglib2.meta.CalibratedAxis; /** * A utility class for working with {@link io.scif.Metadata} objects. * * @see io.scif.Metadata * @author Mark Hiner */ public class SCIFIOMetadataTools { // -- Constructor -- private SCIFIOMetadataTools() {} // -- Utility Methods -- Metadata -- /** * Returns true if the provided axes correspond to a complete image plane */ public static boolean wholePlane(final int imageIndex, final Metadata meta, final long[] planeMin, final long[] planeMax) { final boolean wholePlane = wholeRow(imageIndex, meta, planeMin, planeMax); final int yIndex = meta.get(imageIndex).getAxisIndex(Axes.Y); return wholePlane && planeMin[yIndex] == 0 && planeMax[yIndex] == meta.get(imageIndex).getAxisLength(Axes.Y); } /** * Returns true if the provided axes correspond to a complete image row */ public static boolean wholeRow(final int imageIndex, final Metadata meta, final long[] planeMin, final long[] planeMax) { boolean wholeRow = true; final int yIndex = meta.get(imageIndex).getAxisIndex(Axes.Y); for (int i = 0; wholeRow && i < planeMin.length; i++) { if (i == yIndex) continue; if (planeMin[i] != 0 || planeMax[i] != meta.get(imageIndex).getAxisLength(i)) wholeRow = false; } return wholeRow; } /** * Replaces the first values.length of the provided Metadata's planar axes * with the values. */ public static long[] modifyPlanar(final int imageIndex, final Metadata meta, final long... values) { final AxisValue[] axes = new AxisValue[values.length]; final List<CalibratedAxis> axisTypes = meta.get(imageIndex).getAxes(); for (int i = 0; i < axes.length && i < axisTypes.size(); i++) { axes[i] = new AxisValue(axisTypes.get(i).type(), values[i]); } return modifyPlanar(imageIndex, meta, axes); } /** * Iterates over the provided Metadata's planar axes, replacing any instances * of axes with the paired values. */ public static long[] modifyPlanar(final int imageIndex, final Metadata meta, final AxisValue... axes) { final long[] planarAxes = meta.get(imageIndex).getAxesLengthsPlanar(); for (final AxisValue v : axes) { planarAxes[meta.get(imageIndex).getAxisIndex(v.getType())] = v.getLength(); } return planarAxes; } /** * Casts the provided Metadata object to the generic type of this method. * <p> * Usage: To cast a Metadata instance to ConcreteMetadata, use: * <p> * {@code SCIFIOMetadataTools.<ConcreteMetadata>castMeta(meta)} * </p> * </p> */ @SuppressWarnings("unchecked") public static <M extends Metadata> M castMeta(final Metadata meta) { // TODO need to check for safe casting here.. return (M) meta; } /** * Checks whether the given metadata object has the minimum metadata populated * to successfully describe an Image. * * @throws FormatException if there is a missing metadata field, or the * metadata object is uninitialized */ public static void verifyMinimumPopulated(final Metadata src, final RandomAccessOutputStream out) throws FormatException { verifyMinimumPopulated(src, out, 0); } /** * Checks whether the given metadata object has the minimum metadata populated * to successfully describe the nth Image. * * @throws FormatException if there is a missing metadata field, or the * metadata object is uninitialized */ public static void verifyMinimumPopulated(final Metadata src, final RandomAccessOutputStream out, final int imageIndex) throws FormatException { if (src == null) { throw new FormatException("Metadata object is null; " + "call Writer.setMetadata() first"); } if (out == null) { throw new FormatException("RandomAccessOutputStream object is null; " + "call Writer.setSource(<String/File/RandomAccessOutputStream>) first"); } if (src.get(imageIndex).getAxes().size() == 0) { throw new FormatException("Axiscount #" + imageIndex + " is 0"); } } // -- Utility methods -- dimensional axes -- /** * Guesses at a reasonable default planar axis count for the given list of * dimensional axes. * <p> * The heuristic looks for the first index following both {@link Axes#X} and * {@link Axes#Y}. If the list does not contain both {@code X} and {@code Y} * then the guess will equal the total number of axes. * </p> */ public static int guessPlanarAxisCount(final List<CalibratedAxis> axes) { boolean xFound = false, yFound = false; int d; for (d = 0; d < axes.size(); d++) { if (xFound && yFound) break; final AxisType type = axes.get(d).type(); if (type == Axes.X) xFound = true; else if (type == Axes.Y) yFound = true; } return d; } /** * Guesses at a reasonable default interleaved axis count for the given list * of dimensional axes. * <p> * The heuristic looks for the last index preceding both {@link Axes#X} and * {@link Axes#Y}. If the list does not contain either {@code X} or {@code Y} * then the guess will equal the total number of axes. * </p> */ public static int guessInterleavedAxisCount(final List<CalibratedAxis> axes) { for (int d = 0; d < axes.size(); d++) { final AxisType type = axes.get(d).type(); if (type == Axes.X || type == Axes.Y) return d; } return axes.size(); } // -- Utility methods -- original metadata -- /** * Merges the given lists of metadata, prepending the specified prefix for the * destination keys. */ public static void merge(final Map<String, Object> src, final Map<String, Object> dest, final String prefix) { for (final String key : src.keySet()) { dest.put(prefix + key, src.get(key)); } } /** Gets a sorted list of keys from the given hashtable. */ public static String[] keys(final Hashtable<String, Object> meta) { final String[] keys = new String[meta.size()]; meta.keySet().toArray(keys); Arrays.sort(keys); return keys; } // -- Utility class -- /** * Helper class that pairs an AxisType with a length. * * @author Mark Hiner */ public static class AxisValue { private CalibratedAxis type; private long length; public AxisValue(final AxisType type, final long length) { this.type = FormatTools.createAxis(type); this.length = length; } public long getLength() { return length; } public void setLength(final long length) { this.length = length; } public AxisType getType() { return type.type(); } public void setType(final CalibratedAxis type) { this.type = type; } } }
package de.otto.edison.jobs.repository; import de.otto.edison.jobs.domain.JobInfo; import de.otto.edison.jobs.domain.JobInfoBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Clock; import java.time.OffsetDateTime; import java.util.List; import java.util.stream.Collectors; import static de.otto.edison.jobs.domain.JobInfo.JobStatus.DEAD; import static de.otto.edison.jobs.domain.JobMessage.jobMessage; import static de.otto.edison.jobs.domain.Level.INFO; import static java.lang.String.format; import static java.time.OffsetDateTime.now; public class StopDeadJobs implements JobCleanupStrategy { public static final String JOB_DEAD_MESSAGE = "Job didn't receive updates for a while, considering it dead"; private static final Logger LOG = LoggerFactory.getLogger(StopDeadJobs.class); private final int stopJobAfterSeconds; private final Clock clock; public StopDeadJobs(final int stopJobAfterSeconds, final Clock clock) { this.stopJobAfterSeconds = stopJobAfterSeconds; this.clock = clock; LOG.info(format("Mark old as stopped after %s seconds of inactivity.", stopJobAfterSeconds)); } @Override public void doCleanUp(JobRepository repository) { OffsetDateTime now = now(clock); OffsetDateTime timeToMarkJobAsStopped = now.minusSeconds(stopJobAfterSeconds); LOG.info(format("JobCleanup: Looking for jobs older than %s ", timeToMarkJobAsStopped)); List<JobInfo> deadJobs = repository.findAll() .stream() .filter(job -> (!job.isStopped() && job.getLastUpdated().isBefore(timeToMarkJobAsStopped))) .collect(Collectors.toList()); for (JobInfo deadJob : deadJobs) { LOG.info("Marking job as dead: {}",deadJob); JobInfo jobInfo = JobInfoBuilder .copyOf(deadJob) .withStopped(now) .withLastUpdated(now) .withStatus(DEAD) .addMessage(jobMessage(INFO, JOB_DEAD_MESSAGE)) .build(); repository.createOrUpdate(jobInfo); } } }
package imagej.build; import imagej.build.minimaven.BuildEnvironment; import imagej.build.minimaven.MavenProject; import java.io.File; import java.io.PrintStream; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.Set; import java.util.Stack; import java.util.TreeSet; /** * TODO * * @author Johannes Schindelin */ public class MiniMaven { private final static String usage = "Usage: MiniMaven [command]\n" + "\tSupported commands: compile, run, compile-and-run, clean, get-dependencies"; public static void main(String[] args) throws Exception { PrintStream err = System.err; BuildEnvironment env = new BuildEnvironment(err, "true".equals(getSystemProperty("minimaven.download.automatically", "true")), "true".equals(getSystemProperty("minimaven.verbose", "false")), false); MavenProject root = env.parse(new File("pom.xml"), null); String command = args.length == 0 ? "compile-and-run" : args[0]; String artifactId = getSystemProperty("artifactId", root.getArtifactId().equals("pom-ij-base") ? "ij-app" : root.getArtifactId()); MavenProject pom = findPOM(root, artifactId); if (pom == null) pom = root; if (command.equals("compile") || command.equals("build") || command.equals("compile-and-run")) { pom.build(); if (command.equals("compile-and-run")) command = "run"; else return; } else if (command.equals("jar") || command.equals("jars")) { if (!pom.getBuildFromSource()) { System.err.println("Cannot build " + pom + " from source"); System.exit(1); } pom.buildJar(); if (command.equals("jars")) pom.copyDependencies(pom.getTarget(), true); return; } if (command.equals("clean")) pom.clean(); else if (command.equals("get") || command.equals("get-dependencies")) pom.downloadDependencies(); else if (command.equals("run")) { String mainClass = getSystemProperty("mainClass", pom.getMainClass()); if (mainClass == null) { err.println("No main class specified in pom " + pom.getCoordinate()); System.exit(1); } String[] paths = pom.getClassPath(false).split(File.pathSeparator); URL[] urls = new URL[paths.length]; for (int i = 0; i < urls.length; i++) urls[i] = new URL("file:" + paths[i] + (paths[i].endsWith(".jar") ? "" : "/")); URLClassLoader classLoader = new URLClassLoader(urls); // needed for sezpoz Thread.currentThread().setContextClassLoader(classLoader); Class<?> clazz = classLoader.loadClass(mainClass); Method main = clazz.getMethod("main", new Class[] { String[].class }); main.invoke(null, new Object[] { new String[0] }); } else if (command.equals("classpath")) err.println(pom.getClassPath(false)); else if (command.equals("list")) { Set<MavenProject> result = new TreeSet<MavenProject>(); Stack<MavenProject> stack = new Stack<MavenProject>(); stack.push(pom.getRoot()); while (!stack.empty()) { pom = stack.pop(); if (result.contains(pom) || !pom.getBuildFromSource()) continue; result.add(pom); for (MavenProject child : pom.getChildren()) stack.push(child); } for (MavenProject pom2 : result) System.err.println(pom2); } else err.println("Unhandled command: " + command + "\n" + usage); } protected static MavenProject findPOM(MavenProject root, String artifactId) { if (artifactId == null || artifactId.equals(root.getArtifactId())) return root; for (MavenProject child : root.getChildren()) { MavenProject pom = findPOM(child, artifactId); if (pom != null) return pom; } return null; } protected static String getSystemProperty(String key, String defaultValue) { String result = System.getProperty(key); return result == null ? defaultValue : result; } }
package io.branch.referral; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.SocketException; import java.net.UnknownHostException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class RemoteInterface { public static final String NO_TAG_VALUE = "no_tag"; public static final int NO_CONNECTIVITY_STATUS = -1009; private static final String SDK_VERSION = "1.2.2"; private HttpClient getGenericHttpClient() { int timeout = 3000; HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, timeout); HttpConnectionParams.setSoTimeout(httpParams, timeout); return new DefaultHttpClient(httpParams); } private ServerResponse processEntityForJSON (HttpEntity entity, int statusCode, String tag, boolean log) { ServerResponse result = new ServerResponse(tag, statusCode); try { if (entity != null) { InputStream instream = entity.getContent(); BufferedReader rd = new BufferedReader(new InputStreamReader(instream)); String line = rd.readLine(); if (log) PrefHelper.Debug("BranchSDK", "returned " + line); if (line != null) { try { JSONObject jsonObj = new JSONObject(line); result.setPost(jsonObj); } catch (JSONException ex) { try { JSONArray jsonArray = new JSONArray(line); result.setPost(jsonArray); } catch (JSONException ex2) { if (log) PrefHelper.Debug(getClass().getSimpleName(), "JSON exception: " + ex2.getMessage()); } } } } } catch (IOException ex) { if (log) PrefHelper.Debug(getClass().getSimpleName(), "IO exception: " + ex.getMessage()); } return result; } public ServerResponse make_restful_get(String url, String tag) { return make_restful_get(url, tag, true); } public ServerResponse make_restful_get(String url, String tag, boolean log) { try { if (url.indexOf('?') == -1) { url += "?sdk=android" + SDK_VERSION; } else { url += "&sdk=android" + SDK_VERSION; } if (log) PrefHelper.Debug("BranchSDK", "getting " + url); HttpGet request = new HttpGet(url); HttpResponse response = getGenericHttpClient().execute(request); return processEntityForJSON(response.getEntity(), response.getStatusLine().getStatusCode(), tag, log); } catch (ClientProtocolException ex) { if (log) PrefHelper.Debug(getClass().getSimpleName(), "Client protocol exception: " + ex.getMessage()); } catch (SocketException ex) { if (log) PrefHelper.Debug(getClass().getSimpleName(), "Http connect exception: " + ex.getMessage()); return new ServerResponse(tag, NO_CONNECTIVITY_STATUS); } catch (UnknownHostException ex) { if (log) PrefHelper.Debug(getClass().getSimpleName(), "Http connect exception: " + ex.getMessage()); return new ServerResponse(tag, NO_CONNECTIVITY_STATUS); } catch (IOException ex) { if (log) PrefHelper.Debug(getClass().getSimpleName(), "IO exception: " + ex.getMessage()); return new ServerResponse(tag, 500); } return null; } public ServerResponse make_restful_post(JSONObject body, String url, String tag) { return make_restful_post(body, url, tag, true); } public ServerResponse make_restful_post(JSONObject body, String url, String tag, boolean log) { try { body.put("sdk", "android" + SDK_VERSION); if (log) { PrefHelper.Debug("BranchSDK", "posting to " + url); PrefHelper.Debug("BranchSDK", "Post value = " + body.toString()); } HttpPost request = new HttpPost(url); request.setEntity(new ByteArrayEntity(body.toString().getBytes("UTF8"))); request.setHeader("Content-type", "application/json"); HttpResponse response = getGenericHttpClient().execute(request); return processEntityForJSON(response.getEntity(), response.getStatusLine().getStatusCode(), tag, log); } catch (SocketException ex) { if (log) PrefHelper.Debug(getClass().getSimpleName(), "Http connect exception: " + ex.getMessage()); return new ServerResponse(tag, NO_CONNECTIVITY_STATUS); } catch (UnknownHostException ex) { if (log) PrefHelper.Debug(getClass().getSimpleName(), "Http connect exception: " + ex.getMessage()); return new ServerResponse(tag, NO_CONNECTIVITY_STATUS); } catch (Exception ex) { if (log) PrefHelper.Debug(getClass().getSimpleName(), "Exception: " + ex.getMessage()); return new ServerResponse(tag, 500); } } }
package org.xwiki.rendering.internal.parser; import static org.hamcrest.CoreMatchers.any; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.when; import java.io.Reader; import java.util.Collections; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.xwiki.component.internal.ContextComponentManagerProvider; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.EntityReferenceSerializer; import org.xwiki.rendering.block.Block; import org.xwiki.rendering.block.XDOM; import org.xwiki.rendering.listener.MetaData; import org.xwiki.rendering.parser.ContentParser; import org.xwiki.rendering.parser.Parser; import org.xwiki.rendering.syntax.Syntax; import org.xwiki.test.annotation.ComponentList; import org.xwiki.test.mockito.MockitoComponentMockingRule; /** * Unit tests for {@link org.xwiki.rendering.internal.parser.DefaultContentParser}. * * @version $Id$ * @since 6.0M2 */ @ComponentList(ContextComponentManagerProvider.class) public class DefaultContentParserTest { @Rule public final MockitoComponentMockingRule<ContentParser> mocker = new MockitoComponentMockingRule<ContentParser>(DefaultContentParser.class); @Rule public ExpectedException thrown = ExpectedException.none(); private static final DocumentReference DOCUMENT_REFERENCE = new DocumentReference("wiki", "space", "page"); private static final String SOURCE = "wiki:space.page"; @Before public void configure() throws Exception { Parser parser = mocker.registerMockComponent(Parser.class, Syntax.PLAIN_1_0.toIdString()); when(parser.parse(argThat(any(Reader.class)))).thenReturn(new XDOM(Collections.<Block>emptyList())); EntityReferenceSerializer<String> serializer = mocker.getInstance(EntityReferenceSerializer.TYPE_STRING); when(serializer.serialize(DOCUMENT_REFERENCE)).thenReturn(SOURCE); } @Test public void testNoMetadataSource() throws Exception { XDOM xdom = mocker.getComponentUnderTest().parse("", Syntax.PLAIN_1_0); assertThat(xdom.getMetaData().getMetaData(MetaData.SOURCE), nullValue()); } @Test public void testAddingMetadataSource() throws Exception { XDOM xdom = mocker.getComponentUnderTest().parse("", Syntax.PLAIN_1_0, DOCUMENT_REFERENCE); assertThat((String) xdom.getMetaData().getMetaData(MetaData.SOURCE), equalTo(SOURCE)); } @Test public void testMissingParserException() throws Exception { thrown.expect(MissingParserException.class); thrown.expectMessage("Failed to find a parser for syntax [XWiki 2.1]"); thrown.expectCause(any(ComponentLookupException.class)); mocker.getComponentUnderTest().parse("", Syntax.XWIKI_2_1, DOCUMENT_REFERENCE); } }
/** * Generated with Acceleo */ package org.wso2.developerstudio.eclipse.gmf.esb.parts.impl; // Start of user code for imports import java.util.ArrayList; import java.util.List; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent; import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent; import org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart; import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent; import org.eclipse.emf.eef.runtime.impl.parts.CompositePropertiesEditionPart; import org.eclipse.emf.eef.runtime.ui.parts.PartComposer; import org.eclipse.emf.eef.runtime.ui.parts.sequence.BindingCompositionSequence; import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionSequence; import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionStep; import org.eclipse.emf.eef.runtime.ui.utils.EditingUtils; import org.eclipse.emf.eef.runtime.ui.widgets.ReferencesTable; import org.eclipse.emf.eef.runtime.ui.widgets.ReferencesTable.ReferencesTableListener; import org.eclipse.emf.eef.runtime.ui.widgets.SWTUtils; import org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableContentProvider; import org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableSettings; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Text; import org.wso2.developerstudio.eclipse.gmf.esb.parts.EsbViewsRepository; import org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlStatementPropertiesEditionPart; import org.wso2.developerstudio.eclipse.gmf.esb.presentation.EEFPropertyViewUtil; import org.wso2.developerstudio.eclipse.gmf.esb.providers.EsbMessages; // End of user code public class SqlStatementPropertiesEditionPartImpl extends CompositePropertiesEditionPart implements ISWTPropertiesEditionPart, SqlStatementPropertiesEditionPart { protected Text queryString; protected ReferencesTable parameters; protected List<ViewerFilter> parametersBusinessFilters = new ArrayList<ViewerFilter>(); protected List<ViewerFilter> parametersFilters = new ArrayList<ViewerFilter>(); protected Button resultsEnabled; protected ReferencesTable results; protected List<ViewerFilter> resultsBusinessFilters = new ArrayList<ViewerFilter>(); protected List<ViewerFilter> resultsFilters = new ArrayList<ViewerFilter>(); /** * Default constructor * @param editionComponent the {@link IPropertiesEditionComponent} that manage this part * */ public SqlStatementPropertiesEditionPartImpl(IPropertiesEditionComponent editionComponent) { super(editionComponent); } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart# * createFigure(org.eclipse.swt.widgets.Composite) * */ public Composite createFigure(final Composite parent) { view = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 3; view.setLayout(layout); createControls(view); return view; } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart# * createControls(org.eclipse.swt.widgets.Composite) * */ public void createControls(Composite view) { CompositionSequence sqlStatementStep = new BindingCompositionSequence(propertiesEditionComponent); CompositionStep propertiesStep = sqlStatementStep.addStep(EsbViewsRepository.SqlStatement.Properties.class); propertiesStep.addStep(EsbViewsRepository.SqlStatement.Properties.queryString); propertiesStep.addStep(EsbViewsRepository.SqlStatement.Properties.parameters); propertiesStep.addStep(EsbViewsRepository.SqlStatement.Properties.resultsEnabled); propertiesStep.addStep(EsbViewsRepository.SqlStatement.Properties.results); composer = new PartComposer(sqlStatementStep) { @Override public Composite addToPart(Composite parent, Object key) { if (key == EsbViewsRepository.SqlStatement.Properties.class) { return createPropertiesGroup(parent); } if (key == EsbViewsRepository.SqlStatement.Properties.queryString) { return createQueryStringText(parent); } if (key == EsbViewsRepository.SqlStatement.Properties.parameters) { return createParametersAdvancedTableComposition(parent); } if (key == EsbViewsRepository.SqlStatement.Properties.resultsEnabled) { return createResultsEnabledCheckbox(parent); } if (key == EsbViewsRepository.SqlStatement.Properties.results) { return createResultsAdvancedTableComposition(parent); } return parent; } }; composer.compose(view); } protected Composite createPropertiesGroup(Composite parent) { Group propertiesGroup = new Group(parent, SWT.NONE); propertiesGroup.setText(EsbMessages.SqlStatementPropertiesEditionPart_PropertiesGroupLabel); GridData propertiesGroupData = new GridData(GridData.FILL_HORIZONTAL); propertiesGroupData.horizontalSpan = 3; propertiesGroup.setLayoutData(propertiesGroupData); GridLayout propertiesGroupLayout = new GridLayout(); propertiesGroupLayout.numColumns = 3; propertiesGroup.setLayout(propertiesGroupLayout); return propertiesGroup; } /** * @generated NOT */ protected Composite createQueryStringText(Composite parent) { createDescription(parent, EsbViewsRepository.SqlStatement.Properties.queryString, EsbMessages.SqlStatementPropertiesEditionPart_QueryStringLabel); queryString = SWTUtils.createScrollableText(parent, SWT.BORDER); GridData queryStringData = new GridData(GridData.FILL_HORIZONTAL); queryString.setLayoutData(queryStringData); queryString.addFocusListener(new FocusAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent) * */ @Override @SuppressWarnings("synthetic-access") public void focusLost(FocusEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(SqlStatementPropertiesEditionPartImpl.this, EsbViewsRepository.SqlStatement.Properties.queryString, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, queryString.getText())); } }); queryString.addKeyListener(new KeyAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent) * */ @Override @SuppressWarnings("synthetic-access") public void keyPressed(KeyEvent e) { if (e.character == SWT.CR) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(SqlStatementPropertiesEditionPartImpl.this, EsbViewsRepository.SqlStatement.Properties.queryString, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, queryString.getText())); } } }); queryString.addKeyListener(new KeyListener() { @Override public void keyReleased(KeyEvent e) { if (!EEFPropertyViewUtil.isReservedKeyCombination(e)) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(SqlStatementPropertiesEditionPartImpl.this, EsbViewsRepository.SqlStatement.Properties.queryString, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, queryString.getText())); } } @Override public void keyPressed(KeyEvent e) { } }); EditingUtils.setID(queryString, EsbViewsRepository.SqlStatement.Properties.queryString); EditingUtils.setEEFtype(queryString, "eef::Text"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.SqlStatement.Properties.queryString, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createQueryStringText // End of user code return parent; } /** * @param container * */ protected Composite createParametersAdvancedTableComposition(Composite parent) { this.parameters = new ReferencesTable(getDescription(EsbViewsRepository.SqlStatement.Properties.parameters, EsbMessages.SqlStatementPropertiesEditionPart_ParametersLabel), new ReferencesTableListener() { public void handleAdd() { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(SqlStatementPropertiesEditionPartImpl.this, EsbViewsRepository.SqlStatement.Properties.parameters, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.ADD, null, null)); parameters.refresh(); } public void handleEdit(EObject element) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(SqlStatementPropertiesEditionPartImpl.this, EsbViewsRepository.SqlStatement.Properties.parameters, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.EDIT, null, element)); parameters.refresh(); } public void handleMove(EObject element, int oldIndex, int newIndex) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(SqlStatementPropertiesEditionPartImpl.this, EsbViewsRepository.SqlStatement.Properties.parameters, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.MOVE, element, newIndex)); parameters.refresh(); } public void handleRemove(EObject element) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(SqlStatementPropertiesEditionPartImpl.this, EsbViewsRepository.SqlStatement.Properties.parameters, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.REMOVE, null, element)); parameters.refresh(); } public void navigateTo(EObject element) { } }); for (ViewerFilter filter : this.parametersFilters) { this.parameters.addFilter(filter); } this.parameters.setHelpText(propertiesEditionComponent.getHelpContent(EsbViewsRepository.SqlStatement.Properties.parameters, EsbViewsRepository.SWT_KIND)); this.parameters.createControls(parent); this.parameters.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (e.item != null && e.item.getData() instanceof EObject) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(SqlStatementPropertiesEditionPartImpl.this, EsbViewsRepository.SqlStatement.Properties.parameters, PropertiesEditionEvent.CHANGE, PropertiesEditionEvent.SELECTION_CHANGED, null, e.item.getData())); } } }); GridData parametersData = new GridData(GridData.FILL_HORIZONTAL); parametersData.horizontalSpan = 3; this.parameters.setLayoutData(parametersData); this.parameters.setLowerBound(0); this.parameters.setUpperBound(-1); parameters.setID(EsbViewsRepository.SqlStatement.Properties.parameters); parameters.setEEFType("eef::AdvancedTableComposition"); //$NON-NLS-1$ // Start of user code for createParametersAdvancedTableComposition // End of user code return parent; } protected Composite createResultsEnabledCheckbox(Composite parent) { resultsEnabled = new Button(parent, SWT.CHECK); resultsEnabled.setText(getDescription(EsbViewsRepository.SqlStatement.Properties.resultsEnabled, EsbMessages.SqlStatementPropertiesEditionPart_ResultsEnabledLabel)); resultsEnabled.addSelectionListener(new SelectionAdapter() { /** * {@inheritDoc} * * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) * */ public void widgetSelected(SelectionEvent e) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(SqlStatementPropertiesEditionPartImpl.this, EsbViewsRepository.SqlStatement.Properties.resultsEnabled, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new Boolean(resultsEnabled.getSelection()))); } }); GridData resultsEnabledData = new GridData(GridData.FILL_HORIZONTAL); resultsEnabledData.horizontalSpan = 2; resultsEnabled.setLayoutData(resultsEnabledData); EditingUtils.setID(resultsEnabled, EsbViewsRepository.SqlStatement.Properties.resultsEnabled); EditingUtils.setEEFtype(resultsEnabled, "eef::Checkbox"); //$NON-NLS-1$ SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.SqlStatement.Properties.resultsEnabled, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$ // Start of user code for createResultsEnabledCheckbox // End of user code return parent; } /** * @param container * */ protected Composite createResultsAdvancedTableComposition(Composite parent) { this.results = new ReferencesTable(getDescription(EsbViewsRepository.SqlStatement.Properties.results, EsbMessages.SqlStatementPropertiesEditionPart_ResultsLabel), new ReferencesTableListener() { public void handleAdd() { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(SqlStatementPropertiesEditionPartImpl.this, EsbViewsRepository.SqlStatement.Properties.results, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.ADD, null, null)); results.refresh(); } public void handleEdit(EObject element) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(SqlStatementPropertiesEditionPartImpl.this, EsbViewsRepository.SqlStatement.Properties.results, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.EDIT, null, element)); results.refresh(); } public void handleMove(EObject element, int oldIndex, int newIndex) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(SqlStatementPropertiesEditionPartImpl.this, EsbViewsRepository.SqlStatement.Properties.results, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.MOVE, element, newIndex)); results.refresh(); } public void handleRemove(EObject element) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(SqlStatementPropertiesEditionPartImpl.this, EsbViewsRepository.SqlStatement.Properties.results, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.REMOVE, null, element)); results.refresh(); } public void navigateTo(EObject element) { } }); for (ViewerFilter filter : this.resultsFilters) { this.results.addFilter(filter); } this.results.setHelpText(propertiesEditionComponent.getHelpContent(EsbViewsRepository.SqlStatement.Properties.results, EsbViewsRepository.SWT_KIND)); this.results.createControls(parent); this.results.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (e.item != null && e.item.getData() instanceof EObject) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(SqlStatementPropertiesEditionPartImpl.this, EsbViewsRepository.SqlStatement.Properties.results, PropertiesEditionEvent.CHANGE, PropertiesEditionEvent.SELECTION_CHANGED, null, e.item.getData())); } } }); GridData resultsData = new GridData(GridData.FILL_HORIZONTAL); resultsData.horizontalSpan = 3; this.results.setLayoutData(resultsData); this.results.setLowerBound(0); this.results.setUpperBound(-1); results.setID(EsbViewsRepository.SqlStatement.Properties.results); results.setEEFType("eef::AdvancedTableComposition"); //$NON-NLS-1$ // Start of user code for createResultsAdvancedTableComposition // End of user code return parent; } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent) * */ public void firePropertiesChanged(IPropertiesEditionEvent event) { // Start of user code for tab synchronization // End of user code } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlStatementPropertiesEditionPart#getQueryString() * */ public String getQueryString() { return queryString.getText(); } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlStatementPropertiesEditionPart#setQueryString(String newValue) * */ public void setQueryString(String newValue) { if (newValue != null) { queryString.setText(newValue); } else { queryString.setText(""); //$NON-NLS-1$ } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.SqlStatement.Properties.queryString); if (eefElementEditorReadOnlyState && queryString.isEnabled()) { queryString.setEnabled(false); queryString.setToolTipText(EsbMessages.SqlStatement_ReadOnly); } else if (!eefElementEditorReadOnlyState && !queryString.isEnabled()) { queryString.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlStatementPropertiesEditionPart#initParameters(EObject current, EReference containingFeature, EReference feature) */ public void initParameters(ReferencesTableSettings settings) { if (current.eResource() != null && current.eResource().getResourceSet() != null) this.resourceSet = current.eResource().getResourceSet(); ReferencesTableContentProvider contentProvider = new ReferencesTableContentProvider(); parameters.setContentProvider(contentProvider); parameters.setInput(settings); boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.SqlStatement.Properties.parameters); if (eefElementEditorReadOnlyState && parameters.isEnabled()) { parameters.setEnabled(false); parameters.setToolTipText(EsbMessages.SqlStatement_ReadOnly); } else if (!eefElementEditorReadOnlyState && !parameters.isEnabled()) { parameters.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlStatementPropertiesEditionPart#updateParameters() * */ public void updateParameters() { parameters.refresh(); } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlStatementPropertiesEditionPart#addFilterParameters(ViewerFilter filter) * */ public void addFilterToParameters(ViewerFilter filter) { parametersFilters.add(filter); if (this.parameters != null) { this.parameters.addFilter(filter); } } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlStatementPropertiesEditionPart#addBusinessFilterParameters(ViewerFilter filter) * */ public void addBusinessFilterToParameters(ViewerFilter filter) { parametersBusinessFilters.add(filter); } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlStatementPropertiesEditionPart#isContainedInParametersTable(EObject element) * */ public boolean isContainedInParametersTable(EObject element) { return ((ReferencesTableSettings)parameters.getInput()).contains(element); } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlStatementPropertiesEditionPart#getResultsEnabled() * */ public Boolean getResultsEnabled() { return Boolean.valueOf(resultsEnabled.getSelection()); } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlStatementPropertiesEditionPart#setResultsEnabled(Boolean newValue) * */ public void setResultsEnabled(Boolean newValue) { if (newValue != null) { resultsEnabled.setSelection(newValue.booleanValue()); } else { resultsEnabled.setSelection(false); } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.SqlStatement.Properties.resultsEnabled); if (eefElementEditorReadOnlyState && resultsEnabled.isEnabled()) { resultsEnabled.setEnabled(false); resultsEnabled.setToolTipText(EsbMessages.SqlStatement_ReadOnly); } else if (!eefElementEditorReadOnlyState && !resultsEnabled.isEnabled()) { resultsEnabled.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlStatementPropertiesEditionPart#initResults(EObject current, EReference containingFeature, EReference feature) */ public void initResults(ReferencesTableSettings settings) { if (current.eResource() != null && current.eResource().getResourceSet() != null) this.resourceSet = current.eResource().getResourceSet(); ReferencesTableContentProvider contentProvider = new ReferencesTableContentProvider(); results.setContentProvider(contentProvider); results.setInput(settings); boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.SqlStatement.Properties.results); if (eefElementEditorReadOnlyState && results.isEnabled()) { results.setEnabled(false); results.setToolTipText(EsbMessages.SqlStatement_ReadOnly); } else if (!eefElementEditorReadOnlyState && !results.isEnabled()) { results.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlStatementPropertiesEditionPart#updateResults() * */ public void updateResults() { results.refresh(); } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlStatementPropertiesEditionPart#addFilterResults(ViewerFilter filter) * */ public void addFilterToResults(ViewerFilter filter) { resultsFilters.add(filter); if (this.results != null) { this.results.addFilter(filter); } } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlStatementPropertiesEditionPart#addBusinessFilterResults(ViewerFilter filter) * */ public void addBusinessFilterToResults(ViewerFilter filter) { resultsBusinessFilters.add(filter); } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlStatementPropertiesEditionPart#isContainedInResultsTable(EObject element) * */ public boolean isContainedInResultsTable(EObject element) { return ((ReferencesTableSettings)results.getInput()).contains(element); } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart#getTitle() * */ public String getTitle() { return EsbMessages.SqlStatement_Part_Title; } // Start of user code additional methods // End of user code }
package org.nuxeo.ecm.platform.userworkspace.web.ejb; import static org.jboss.seam.ScopeType.SESSION; import javax.ejb.Remove; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.Destroy; import org.jboss.seam.annotations.Factory; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.annotations.Startup; import org.jboss.seam.core.Events; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.platform.ui.web.api.NavigationContext; import org.nuxeo.ecm.platform.userworkspace.api.UserWorkspaceManagerActions; import org.nuxeo.ecm.platform.userworkspace.api.UserWorkspaceService; import org.nuxeo.ecm.platform.userworkspace.constants.UserWorkspaceConstants; import org.nuxeo.ecm.webapp.helpers.EventNames; import org.nuxeo.runtime.api.Framework; /** * Personal user workspace manager actions bean. * * @author btatar * */ @Name("userWorkspaceManagerActions") @Scope(SESSION) @Startup public class UserWorkspaceManagerActionsBean implements UserWorkspaceManagerActions { private static final long serialVersionUID = 1828552026739219850L; private static final Log log = LogFactory.getLog(UserWorkspaceManagerActions.class); private static final String DOCUMENT_VIEW = "view_documents"; private static final String DASHBOARD_VIEW = "user_dashboard"; private boolean showingPersonalWorkspace; private boolean initialized; private DocumentModel lastAccessedDocument; //Rux INA-252: very likely cause of passivation error private transient UserWorkspaceService userWorkspaceService; //Rux INA-252: another cause of passivation error @In(required = true) private transient NavigationContext navigationContext; @In(required = true) private transient CoreSession documentManager; public void initialize() { log.info("Initializing user workspace manager actions bean"); try { //Rux INA-252: use a getter //userWorkspaceService = Framework.getLocalService(UserWorkspaceService.class); showingPersonalWorkspace = false; initialized = true; } catch (Exception e) { log.error( "There was an error while trying to get UserWorkspaceService", e); } } @Destroy @Remove public void destroy() { userWorkspaceService = null; log.debug("Removing user workspace actions bean"); } private UserWorkspaceService getUserWorkspaceService() { if (userWorkspaceService != null) { return userWorkspaceService; } userWorkspaceService = Framework.getLocalService(UserWorkspaceService.class); return userWorkspaceService; } public DocumentModel getCurrentUserPersonalWorkspace() throws ClientException { if (!initialized) { initialize(); } return getUserWorkspaceService().getCurrentUserPersonalWorkspace(documentManager, navigationContext.getCurrentDocument()); } public String navigateToCurrentUserPersonalWorkspace() throws ClientException { if (!initialized) { initialize(); } String returnView = DOCUMENT_VIEW; //Rux INA-221: separated links for going to workspaces DocumentModel currentUserPersonalWorkspace = getCurrentUserPersonalWorkspace(); DocumentModel currentDocument = navigationContext.getCurrentDocument(); if (!isShowingPersonalWorkspace() && currentDocument != null && currentDocument.getPath().segment(0) != null) { lastAccessedDocument = navigationContext.getCurrentDocument(); } navigationContext.setCurrentDocument(currentUserPersonalWorkspace); showingPersonalWorkspace = true; Events.instance().raiseEvent(EventNames.GO_HOME); return returnView; } //Rux INA-221: create a new method for the 2 separated links public String navigateToOverallWorkspace() throws ClientException { if (!initialized) { initialize(); } String returnView = DOCUMENT_VIEW; if (lastAccessedDocument != null) { navigationContext.setCurrentDocument(lastAccessedDocument); } else if (navigationContext.getCurrentDomain() != null) { navigationContext.setCurrentDocument(navigationContext.getCurrentDomain()); } else { returnView = DASHBOARD_VIEW; } showingPersonalWorkspace = false; Events.instance().raiseEvent(EventNames.GO_HOME); return returnView; } @Factory(value="isInsidePersonalWorkspace", scope=ScopeType.EVENT) public boolean isShowingPersonalWorkspace() { if (!initialized) { initialize(); } DocumentModel currentDoc = navigationContext.getCurrentDocument(); if (currentDoc==null || currentDoc.getPath().segmentCount()<2) { return false; } String secondSegment = currentDoc.getPath().segment(1); showingPersonalWorkspace = secondSegment != null && secondSegment.startsWith(UserWorkspaceConstants.USERS_PERSONAL_WORKSPACES_ROOT); return showingPersonalWorkspace; } public void setShowingPersonalWorkspace(boolean showingPersonalWorkspace) { this.showingPersonalWorkspace = showingPersonalWorkspace; } public boolean isInitialized() { return initialized; } public void setInitialized(boolean initialized) { this.initialized = initialized; } }
package fr.openwide.core.jpa.more.business.link.service; import io.mola.galimatias.GalimatiasParseException; import java.io.IOException; import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.net.ssl.SSLHandshakeException; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HTTP; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import com.google.common.collect.ImmutableList; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import fr.openwide.core.jpa.exception.SecurityServiceException; import fr.openwide.core.jpa.exception.ServiceException; import fr.openwide.core.jpa.more.business.link.model.ExternalLinkErrorType; import fr.openwide.core.jpa.more.business.link.model.ExternalLinkStatus; import fr.openwide.core.jpa.more.business.link.model.ExternalLinkWrapper; import fr.openwide.core.spring.config.CoreConfigurer; @Service("externalLinkCheckerService") public class ExternalLinkCheckerServiceImpl implements IExternalLinkCheckerService { private static final Logger LOGGER = LoggerFactory.getLogger(ExternalLinkCheckerServiceImpl.class); @Autowired private IExternalLinkWrapperService externalLinkWrapperService; @Autowired private ConfigurableApplicationContext applicationContext; @Autowired private CoreConfigurer configurer; private CloseableHttpClient httpClient = null; /** * we can put here some URLs known to fail. Otherwise, it's better to do it directly in the application. */ private List<Pattern> ignorePatterns = Lists.newArrayList( ); private int batchSize; private int minDelayBetweenTwoChecks; @PostConstruct private void initialize() { RequestConfig requestConfig = RequestConfig.custom() .setMaxRedirects(configurer.getExternalLinkCheckerMaxRedirects()) .setSocketTimeout(configurer.getExternalLinkCheckerTimeout()) .setConnectionRequestTimeout(configurer.getExternalLinkCheckerTimeout()) .setConnectTimeout(configurer.getExternalLinkCheckerTimeout()) .setStaleConnectionCheckEnabled(true) .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY) .build(); httpClient = HttpClientBuilder.create() .setUserAgent(configurer.getExternalLinkCheckerUserAgent()) .setDefaultRequestConfig(requestConfig) .setDefaultHeaders(Lists.newArrayList( new BasicHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE), new BasicHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"), new BasicHeader("Accept-Language", "fr,en;q=0.8,fr-fr;q=0.6,en-us;q=0.4,en-gb;q=0.2") )) .build(); batchSize = configurer.getExternalLinkCheckerBatchSize(); minDelayBetweenTwoChecks = configurer.getExternalLinkCheckerMinDelayBetweenTwoChecksInDays(); } @PreDestroy private void destroy() { if (httpClient != null) { try { httpClient.close(); } catch (IOException e) { LOGGER.error("Unable to close the HTTP client", e); } } } // Public methods @Override public void checkBatch() throws ServiceException, SecurityServiceException { List<ExternalLinkWrapper> links = externalLinkWrapperService.listNextCheckingBatch( batchSize, minDelayBetweenTwoChecks); runTasksInParallel(createTasksByDomain(links), 10, TimeUnit.HOURS); } @Override public void checkLink(final ExternalLinkWrapper link) throws ServiceException, SecurityServiceException { try { io.mola.galimatias.URL url = io.mola.galimatias.URL.parse(link.getUrl()); checkLinksWithSameUrl(url, ImmutableList.of(link)); } catch (GalimatiasParseException e) { markAsInvalid(link); } } @Override public void checkLinksWithSameUrl(io.mola.galimatias.URL url, Collection<ExternalLinkWrapper> links) throws ServiceException, SecurityServiceException { StatusLine httpStatus = null; ExternalLinkErrorType errorType = null; // Special casing the ignore patterns for (Pattern pattern : ignorePatterns) { if (pattern.matcher(url.toHumanString()).matches()) { markAsIgnored(links); return; } } URI uri; try { uri = url.toJavaURI(); } catch (URISyntaxException e) { // java.net.URI is buggy and doesn't support domain names with underscores. As galimatias already check // the URL format, if we are here, it's probably because java.net.URI doesn't handle this case very well // so we simply ignore the link instead of marking it as dead. markAsIgnored(links); return; } // Check the URL and update the links try { // We try a HEAD request httpStatus = sendRequest(new HttpHead(uri)); if (httpStatus != null && httpStatus.getStatusCode() != HttpStatus.SC_OK) { // If the result of the HEAD request is not OK, we try a GET request // Using HttpStatus.SC_METHOD_NOT_ALLOWED looked like a clever trick but a lot of sites return // 400 or 500 errors for HEAD requests httpStatus = sendRequest(new HttpGet(uri)); } if (httpStatus == null) { errorType = ExternalLinkErrorType.UNKNOWN_HTTPCLIENT_ERROR; } else if (httpStatus.getStatusCode() != HttpStatus.SC_OK) { errorType = ExternalLinkErrorType.HTTP; } } catch (IllegalArgumentException e) { errorType = ExternalLinkErrorType.INVALID_IDN; } catch (SocketTimeoutException e) { errorType = ExternalLinkErrorType.TIMEOUT; } catch (SSLHandshakeException e) { // certificate not supported by Java: we ignore the links markAsIgnored(links); return; } catch (IOException e) { errorType = ExternalLinkErrorType.IO; } if (errorType == null) { markAsOnline(links); } else { markAsOfflineOrDead(links, errorType, httpStatus); } } // Private methods private Collection<Callable<Void>> createTasksByDomain(List<ExternalLinkWrapper> links) throws ServiceException, SecurityServiceException { Collection<Callable<Void>> tasks = Lists.newArrayList(); Map<String, Multimap<io.mola.galimatias.URL, Long>> domainToUrlToIds = Maps.newLinkedHashMap(); for (ExternalLinkWrapper link : links) { try { // there's no need to normalize the URL further as galimatias already normalizes the host and it's the // only part we can normalize. io.mola.galimatias.URL url = io.mola.galimatias.URL.parse(link.getUrl()); String domain = url.host().toHumanString(); Multimap<io.mola.galimatias.URL, Long> urlToIds = domainToUrlToIds.get(domain); if (urlToIds == null) { urlToIds = LinkedListMultimap.create(); domainToUrlToIds.put(domain, urlToIds); } urlToIds.put(url, link.getId()); } catch (Exception e) { // if we cannot parse the URI, there's no need to go further, we mark it as invalid and we ignore it markAsInvalid(link); } } for (Multimap<io.mola.galimatias.URL, Long> urlToIds : domainToUrlToIds.values()) { tasks.add(new ExternalLinkCheckByDomainTask(applicationContext, urlToIds.asMap())); } return tasks; } private void markAsInvalid(ExternalLinkWrapper link) throws ServiceException, SecurityServiceException { link.setLastCheckDate(new Date()); link.setStatus(ExternalLinkStatus.DEAD_LINK); link.setLastErrorType(ExternalLinkErrorType.URI_SYNTAX); externalLinkWrapperService.update(link); } private void markAsIgnored(Collection<ExternalLinkWrapper> links) throws ServiceException, SecurityServiceException { Date checkDate = new Date(); for (ExternalLinkWrapper link : links) { link.setLastCheckDate(checkDate); link.setConsecutiveFailures(0); link.setStatus(ExternalLinkStatus.IGNORED); externalLinkWrapperService.update(link); } } private void markAsOnline(Collection<ExternalLinkWrapper> links) throws ServiceException, SecurityServiceException { Date checkDate = new Date(); for (ExternalLinkWrapper link : links) { link.setLastCheckDate(checkDate); link.setConsecutiveFailures(0); link.setStatus(ExternalLinkStatus.ONLINE); link.setLastStatusCode(HttpStatus.SC_OK); link.setFailureAudit(null); externalLinkWrapperService.update(link); } } private void markAsOfflineOrDead(Collection<ExternalLinkWrapper> links, final ExternalLinkErrorType errorType, final StatusLine httpStatus) throws ServiceException, SecurityServiceException { Date checkDate = new Date(); for (ExternalLinkWrapper link : links) { link.setLastCheckDate(checkDate); link.setLastErrorType(errorType); int consecutiveFailures = link.getConsecutiveFailures() + 1; link.setConsecutiveFailures(consecutiveFailures); Integer statusCode; if (httpStatus != null) { statusCode = httpStatus.getStatusCode(); } else { statusCode = null; } link.setLastStatusCode(statusCode); ExternalLinkStatus status; if (link.getConsecutiveFailures() >= configurer.getExternalLinkCheckerRetryAttemptsLimit()) { status = ExternalLinkStatus.DEAD_LINK; } else { status = ExternalLinkStatus.OFFLINE; } link.setStatus(status); // Failure audit StringBuilder failureAuditBuilder = new StringBuilder(); String failureAudit = link.getFailureAudit(); if (StringUtils.hasText(failureAudit)) { failureAuditBuilder.append(failureAudit).append("\n"); } failureAuditBuilder.append( new ToStringBuilder(link, ToStringStyle.SHORT_PREFIX_STYLE) .append("checkDate", checkDate) .append("errorType", errorType) .append("consecutiveFailures", consecutiveFailures) .append("statusCode", statusCode) .append("status", status) .build() ); link.setFailureAudit(failureAuditBuilder.toString()); externalLinkWrapperService.update(link); } } private StatusLine sendRequest(HttpRequestBase request) throws IOException { CloseableHttpResponse response = null; try { response = httpClient.execute(request); return response.getStatusLine(); } finally { if (request != null) { request.reset(); } if (response != null) { try { response.close(); } catch (IOException e) { LOGGER.error("Unable to close the HTTP response", e); } } } } private void runTasksInParallel(Collection<? extends Callable<Void>> tasks, long timeout, TimeUnit timeoutUnit) throws ServiceException { final int threadPoolSize = configurer.getExternalLinkCheckerThreadPoolSize(); final ThreadPoolExecutor executor = new ThreadPoolExecutor( threadPoolSize, threadPoolSize, 100, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); executor.prestartAllCoreThreads(); try { List<Future<Void>> futures = executor.invokeAll(tasks, timeout, timeoutUnit); for (Future<Void> future : futures) { future.get(); // Check that no error has occurred } } catch (Exception e) { throw new ServiceException("Interrupted request", e); } finally { try { executor.shutdown(); } catch (Exception e) { LOGGER.warn("An error occurred while shutting down threads", e); } } } public void addIgnorePattern(Pattern ignorePattern) { this.ignorePatterns.add(ignorePattern); } }
package com.thinkbiganalytics.nifi.v1.rest.model; import com.thinkbiganalytics.nifi.rest.model.NiFiAllowableValue; import com.thinkbiganalytics.nifi.rest.model.NiFiPropertyDescriptor; import com.thinkbiganalytics.nifi.rest.model.NiFiPropertyDescriptorTransform; import org.apache.nifi.web.api.dto.AllowableValueDTO; import org.apache.nifi.web.api.dto.PropertyDescriptorDTO; import org.apache.nifi.web.api.entity.AllowableValueEntity; import java.util.List; import java.util.stream.Collectors; import javax.annotation.Nonnull; /** * Transforms {@link NiFiPropertyDescriptor} objects for NiFi v1.0. */ public class NiFiPropertyDescriptorTransformV1 implements NiFiPropertyDescriptorTransform { @Override public Boolean isSensitive(@Nonnull final PropertyDescriptorDTO propertyDescriptorDTO) { return propertyDescriptorDTO.isSensitive(); } /** * Transforms the specified {@link AllowableValueDTO} to a {@link NiFiAllowableValue}. * * @param dto the allowable value DTO * @return the NiFi allowable value */ @Nonnull public NiFiAllowableValue toNiFiAllowableValue(@Nonnull final AllowableValueDTO dto) { final NiFiAllowableValue nifi = new NiFiAllowableValue(); nifi.setDisplayName(dto.getDisplayName()); nifi.setValue(dto.getValue()); nifi.setDescription(dto.getDescription()); return nifi; } @Nonnull @Override public NiFiPropertyDescriptor toNiFiPropertyDescriptor(@Nonnull final PropertyDescriptorDTO dto) { final NiFiPropertyDescriptor nifi = new NiFiPropertyDescriptor(); nifi.setName(dto.getName()); nifi.setDisplayName(dto.getDisplayName()); nifi.setDescription(dto.getDescription()); nifi.setDefaultValue(dto.getDefaultValue()); nifi.setRequired(dto.isRequired()); nifi.setSensitive(dto.isSensitive()); nifi.setDynamic(dto.isDynamic()); nifi.setSupportsEl(dto.getSupportsEl()); nifi.setIdentifiesControllerService(dto.getIdentifiesControllerService()); final List<AllowableValueEntity> allowableValues = dto.getAllowableValues(); if (allowableValues != null) { nifi.setAllowableValues( allowableValues.stream().filter(allowableValueEntity -> allowableValueEntity.getAllowableValue() != null && allowableValueEntity.getAllowableValue().getValue() != null) .map(AllowableValueEntity::getAllowableValue) .map(this::toNiFiAllowableValue) .collect(Collectors.toList())); } return nifi; } }
package com.google.cloud.tools.eclipse.appengine.localserver.server; import com.google.cloud.tools.appengine.api.AppEngineException; import com.google.cloud.tools.appengine.api.devserver.AppEngineDevServer; import com.google.cloud.tools.appengine.api.devserver.DefaultRunConfiguration; import com.google.cloud.tools.appengine.api.devserver.DefaultStopConfiguration; import com.google.cloud.tools.appengine.cloudsdk.CloudSdk; import com.google.cloud.tools.appengine.cloudsdk.CloudSdkAppEngineDevServer; import com.google.cloud.tools.appengine.cloudsdk.process.ProcessExitListener; import com.google.cloud.tools.appengine.cloudsdk.process.ProcessOutputLineListener; import com.google.cloud.tools.appengine.cloudsdk.process.ProcessStartListener; import com.google.cloud.tools.eclipse.appengine.localserver.Activator; import com.google.cloud.tools.eclipse.appengine.localserver.server.LocalAppEngineServerBehaviour.DevAppServerOutputListener; import com.google.cloud.tools.eclipse.appengine.localserver.server.LocalAppEngineServerBehaviour.LocalAppEngineExitListener; import com.google.cloud.tools.eclipse.appengine.localserver.server.LocalAppEngineServerBehaviour.LocalAppEngineStartListener; import com.google.cloud.tools.eclipse.sdk.ui.MessageConsoleWriterOutputLineListener; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.ui.console.MessageConsoleStream; import org.eclipse.wst.server.core.IModule; import org.eclipse.wst.server.core.IServer; import org.eclipse.wst.server.core.model.IModuleResource; import org.eclipse.wst.server.core.model.IModuleResourceDelta; import org.eclipse.wst.server.core.model.ServerBehaviourDelegate; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * A {@link ServerBehaviourDelegate} for App Engine Server executed via the Java App Management * Client Library. */ public class LocalAppEngineServerBehaviour extends ServerBehaviourDelegate { private static final Logger logger = Logger.getLogger(LocalAppEngineServerBehaviour.class.getName()); private LocalAppEngineStartListener localAppEngineStartListener; private LocalAppEngineExitListener localAppEngineExitListener; private AppEngineDevServer devServer; private Process devProcess; private DevAppServerOutputListener serverOutputListener; public LocalAppEngineServerBehaviour () { localAppEngineStartListener = new LocalAppEngineStartListener(); localAppEngineExitListener = new LocalAppEngineExitListener(); serverOutputListener = new DevAppServerOutputListener(); } @Override public void stop(boolean force) { int serverState = getServer().getServerState(); if (serverState == IServer.STATE_STOPPED) { return; } // If the server seems to be running, and we haven't already tried to stop it, // then try to shut it down nicely if (devServer != null && (!force || serverState != IServer.STATE_STOPPING)) { setServerState(IServer.STATE_STOPPING); // TODO: when available configure the host and port specified in the server DefaultStopConfiguration stopConfig = new DefaultStopConfiguration(); try { devServer.stop(stopConfig); } catch (AppEngineException ex) { logger.log(Level.WARNING, "Error terminating server: " + ex.getMessage(), ex); } } else { // we've already given it a chance logger.info("forced stop: destroying associated processes"); if (devProcess != null) { devProcess.destroy(); devProcess = null; } devServer = null; setServerState(IServer.STATE_STOPPED); } } /** * Convenience method allowing access to protected method in superclass. */ @Override protected IModuleResourceDelta[] getPublishedResourceDelta(IModule[] module) { return super.getPublishedResourceDelta(module); } /** * Convenience method allowing access to protected method in superclass. */ @Override protected IModuleResource[] getResources(IModule[] module) { return super.getResources(module); } @Override public IStatus canStop() { int serverState = getServer().getServerState(); if ((serverState != IServer.STATE_STOPPING) && (serverState != IServer.STATE_STOPPED)) { return Status.OK_STATUS; } else { return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Stop in progress"); } } /** * Returns runtime base directory. Uses temp directory. */ public IPath getRuntimeBaseDirectory() { return getTempDirectory(false); } /** * @return the directory at which module will be published. */ public IPath getModuleDeployDirectory(IModule module) { return getRuntimeBaseDirectory().append(module.getName()); } /** * Convenience accessor to protected member in superclass. */ public final void setModulePublishState2(IModule[] module, int state) { setModulePublishState(module, state); } /** * Starts the development server. * * @param runnables the path to directories that contain configuration files like appengine-web.xml * @param stream the stream to send development server process output to */ void startDevServer(List<File> runnables, MessageConsoleStream stream) { setServerState(IServer.STATE_STARTING); // Create dev app server instance initializeDevServer(stream); // Create run configuration DefaultRunConfiguration devServerRunConfiguration = new DefaultRunConfiguration(); devServerRunConfiguration.setAppYamls(runnables); // FIXME: workaround bug when running on a Java8 JVM devServerRunConfiguration.setJvmFlags(Arrays.asList("-Dappengine.user.timezone=UTC")); // Run server try { devServer.run(devServerRunConfiguration); } catch (AppEngineException ex) { Activator.logError("Error starting server: " + ex.getMessage()); stop(true); } } /** * Starts the development server in debug mode. * * @param runnables the path to directories that contain configuration files like appengine-web.xml * @param stream the stream to send development server process output to * @param debugPort the port to attach a debugger to if launch is in debug mode */ void startDebugDevServer(List<File> runnables, MessageConsoleStream stream, int debugPort) { setServerState(IServer.STATE_STARTING); // Create dev app server instance initializeDevServer(stream); // Create run configuration DefaultRunConfiguration devServerRunConfiguration = new DefaultRunConfiguration(); devServerRunConfiguration.setAppYamls(runnables); // todo: make this a configurable option, but default to // 1 instance to simplify debugging devServerRunConfiguration.setMaxModuleInstances(1); List<String> jvmFlags = new ArrayList<String>(); // FIXME: workaround bug when running on a Java8 JVM jvmFlags.add("-Dappengine.user.timezone=UTC"); if (debugPort <= 0 || debugPort > 65535) { throw new IllegalArgumentException("Debug port is set to " + debugPort + ", should be between 1-65535"); } jvmFlags.add("-Xdebug"); jvmFlags.add("-Xrunjdwp:transport=dt_socket,server=n,suspend=y,quiet=y,address=" + debugPort); devServerRunConfiguration.setJvmFlags(jvmFlags); // Run server try { devServer.run(devServerRunConfiguration); } catch (AppEngineException ex) { Activator.logError("Error starting server: " + ex.getMessage()); stop(true); } } private void initializeDevServer(MessageConsoleStream stream) { MessageConsoleWriterOutputLineListener outputListener = new MessageConsoleWriterOutputLineListener(stream); // dev_appserver output goes to stderr CloudSdk cloudSdk = new CloudSdk.Builder() .addStdOutLineListener(outputListener) .addStdErrLineListener(outputListener) .addStdErrLineListener(serverOutputListener) .startListener(localAppEngineStartListener) .exitListener(localAppEngineExitListener) .async(true) .build(); devServer = new CloudSdkAppEngineDevServer(cloudSdk); } /** * A {@link ProcessExitListener} for the App Engine server. */ public class LocalAppEngineExitListener implements ProcessExitListener { @Override public void onExit(int exitCode) { logger.log(Level.FINE, "Process exit: code=" + exitCode); devServer = null; devProcess = null; setServerState(IServer.STATE_STOPPED); } } /** * A {@link ProcessStartListener} for the App Engine server. */ public class LocalAppEngineStartListener implements ProcessStartListener { @Override public void onStart(Process process) { logger.log(Level.FINE, "New Process: " + process); devProcess = process; } } /** * An output listener that monitors for well-known key dev_appserver output and affects server * state changes. */ public class DevAppServerOutputListener implements ProcessOutputLineListener { @Override public void onOutputLine(String line) { if (line.endsWith("Dev App Server is now running")) { // App Engine Standard (v1) setServerState(IServer.STATE_STARTED); } else if (line.endsWith(".Server:main: Started")) { // App Engine Flexible (v2) setServerState(IServer.STATE_STARTED); } else if (line.equals("Traceback (most recent call last):")) { // An error occurred setServerState(IServer.STATE_STOPPED); } } } }
package org.eclipse.che.plugin.languageserver.ide.editor; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import org.eclipse.che.ide.api.editor.document.Document; import org.eclipse.che.ide.api.editor.events.DocumentChangedEvent; import org.eclipse.che.ide.api.editor.events.DocumentChangedHandler; import org.eclipse.che.ide.api.editor.events.DocumentChangingEvent; import org.eclipse.che.ide.api.editor.events.DocumentChangingHandler; import org.eclipse.che.ide.api.editor.reconciler.DirtyRegion; import org.eclipse.che.ide.api.editor.reconciler.ReconcilingStrategy; import org.eclipse.che.ide.api.editor.text.Region; import org.eclipse.che.ide.api.editor.text.TextPosition; import org.eclipse.che.plugin.languageserver.ide.editor.sync.TextDocumentSynchronize; import org.eclipse.che.plugin.languageserver.ide.editor.sync.TextDocumentSynchronizeFactory; import org.eclipse.lsp4j.ServerCapabilities; import org.eclipse.lsp4j.TextDocumentSyncKind; import org.eclipse.lsp4j.TextDocumentSyncOptions; import org.eclipse.lsp4j.jsonrpc.messages.Either; /** * Responsible for document synchronization * * @author Evgen Vidolob */ public class LanguageServerReconcileStrategy implements ReconcilingStrategy { private final TextDocumentSynchronize synchronize; private int version = 0; private TextPosition lastEventStart; private TextPosition lastEventEnd; @Inject public LanguageServerReconcileStrategy( TextDocumentSynchronizeFactory synchronizeFactory, @Assisted ServerCapabilities serverCapabilities) { Either<TextDocumentSyncKind, TextDocumentSyncOptions> sync = serverCapabilities.getTextDocumentSync(); TextDocumentSyncKind documentSync = null; // sync may be null if (sync != null) { if (sync.isLeft()) { documentSync = sync.getLeft(); } else { documentSync = sync.getRight().getChange(); } } synchronize = synchronizeFactory.getSynchronize(documentSync); } @Override public void setDocument(Document document) { document .getDocumentHandle() .getDocEventBus() .addHandler( DocumentChangedEvent.TYPE, new DocumentChangedHandler() { @Override public void onDocumentChanged(DocumentChangedEvent event) { synchronize.syncTextDocument( event.getDocument().getDocument(), lastEventStart, lastEventEnd, event.getRemoveCharCount(), event.getText(), ++version); } }); document .getDocumentHandle() .getDocEventBus() .addHandler( DocumentChangingEvent.TYPE, new DocumentChangingHandler() { @Override public void onDocumentChanging(DocumentChangingEvent event) { lastEventStart = event.getDocument().getDocument().getPositionFromIndex(event.getOffset()); lastEventEnd = event .getDocument() .getDocument() .getPositionFromIndex(event.getOffset() + event.getRemoveCharCount()); } }); } @Override public void reconcile(DirtyRegion dirtyRegion, Region subRegion) { doReconcile(); } public void doReconcile() { // TODO use DocumentHighlight to add additional highlight for file } @Override public void reconcile(Region partition) { doReconcile(); } @Override public void closeReconciler() {} }
package io.sniffy.servlet; import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap; import io.sniffy.Constants; import io.sniffy.configuration.SniffyConfiguration; import io.sniffy.registry.ConnectionsRegistry; import javax.servlet.*; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.net.MalformedURLException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; * <url-pattern>/*</url-pattern> * </filter-mapping> * } * </pre> * * @since 3.1 */ public class SniffyFilter implements Filter { private final static String SNIFFY_REQUEST_PROCESSOR_REQUEST_ATTRIBUTE_NAME = "io.sniffy.servlet.SniffyRequestProcessor"; public static final String HEADER_CORS_HEADERS = "Access-Control-Expose-Headers"; public static final String HEADER_NUMBER_OF_QUERIES = "Sniffy-Sql-Queries"; public static final String HEADER_TIME_TO_FIRST_BYTE = "Sniffy-Time-To-First-Byte"; public static final String HEADER_REQUEST_DETAILS = "Sniffy-Request-Details"; public static final String SNIFFER_URI_PREFIX = "sniffy/" + Constants.MAJOR_VERSION + "." + Constants.MINOR_VERSION + "." + Constants.PATCH_VERSION; public static final String JAVASCRIPT_URI = SNIFFER_URI_PREFIX + "/sniffy.min.js"; public static final String JAVASCRIPT_SOURCE_URI = SNIFFER_URI_PREFIX + "/sniffy.js"; public static final String JAVASCRIPT_MAP_URI = SNIFFER_URI_PREFIX + "/sniffy.map"; public static final String REQUEST_URI_PREFIX = SNIFFER_URI_PREFIX + "/request/"; public static final String SNIFFY = "sniffy"; public static final String SNIFFY_ENABLED_HEADER = "Sniffy-Enabled"; protected static final String THREAD_LOCAL_DISCOVERED_ADDRESSES = "discoveredAddresses"; protected static final String THREAD_LOCAL_DISCOVERED_DATA_SOURCES = "discoveredDataSources"; protected boolean injectHtml = false; protected boolean enabled = true; protected Pattern excludePattern = null; protected final Map<String, RequestStats> cache = new ConcurrentLinkedHashMap.Builder<String, RequestStats>(). maximumWeightedCapacity(200). build(); protected SniffyServlet sniffyServlet = new SniffyServlet(cache); protected ServletContext servletContext; // TODO: log via slf4j if available public SniffyFilter() { enabled = SniffyConfiguration.INSTANCE.isFilterEnabled(); injectHtml = SniffyConfiguration.INSTANCE.isInjectHtml(); try { String excludePattern = SniffyConfiguration.INSTANCE.getExcludePattern(); if (null != excludePattern) { this.excludePattern = Pattern.compile(excludePattern); } } catch (PatternSyntaxException e) { // TODO: log me maybe? } } public void init(FilterConfig filterConfig) throws ServletException { try { String injectHtml = filterConfig.getInitParameter("inject-html"); if (null != injectHtml) { this.injectHtml = Boolean.parseBoolean(injectHtml); } String enabled = filterConfig.getInitParameter("enabled"); if (null != enabled) { this.enabled = Boolean.parseBoolean(enabled); } String excludePattern = filterConfig.getInitParameter("exclude-pattern"); if (null != excludePattern) { this.excludePattern = Pattern.compile(excludePattern); // TODO: can throw exception } String faultToleranceCurrentRequest = filterConfig.getInitParameter("fault-tolerance-current-request"); if (null != faultToleranceCurrentRequest) { ConnectionsRegistry.INSTANCE.setThreadLocal(Boolean.parseBoolean(faultToleranceCurrentRequest)); } sniffyServlet.init(new FilterServletConfigAdapter(filterConfig, "sniffy")); servletContext = filterConfig.getServletContext(); } catch (Exception e) { e.printStackTrace(); enabled = false; } } public void doFilter(final ServletRequest request, ServletResponse response, final FilterChain chain) throws IOException, ServletException { // issues/275 - Sniffy filter is called twice in case of request forwarding Object existingRequestProcessorAttribute = request.getAttribute(SNIFFY_REQUEST_PROCESSOR_REQUEST_ATTRIBUTE_NAME); if (null != existingRequestProcessorAttribute) { chain.doFilter(request, response); return; } HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; // if disabled, run chain and return if (!isSniffyFilterEnabled(request, httpServletRequest, httpServletResponse)) { chain.doFilter(request, response); return; } // Copy fault tolerance testing settings from session to thread local storage if (ConnectionsRegistry.INSTANCE.isThreadLocal()) { copyFaultToleranceTestingFromSession((HttpServletRequest) request); } // process Sniffy REST calls if (null != sniffyServlet) { try { sniffyServlet.service(request, response); if (response.isCommitted()) return; } catch (Exception e) { if (null != servletContext) servletContext.log("Exception in SniffyServlet; calling original chain", e); chain.doFilter(request, response); return; } } // create request decorator SniffyRequestProcessor sniffyRequestProcessor; try { sniffyRequestProcessor = new SniffyRequestProcessor(this, httpServletRequest, httpServletResponse); request.setAttribute(SNIFFY_REQUEST_PROCESSOR_REQUEST_ATTRIBUTE_NAME, sniffyRequestProcessor); } catch (Exception e) { if (null != servletContext) servletContext.log("Exception in SniffyRequestProcessor initialization; calling original chain", e); chain.doFilter(request, response); return; } try { sniffyRequestProcessor.process(chain); } finally { // Clean fault tolerance testing settings thread local storage cleanThreadLocalFaultToleranceSettings(); } } private static void cleanThreadLocalFaultToleranceSettings() { if (ConnectionsRegistry.INSTANCE.isThreadLocal()) { ConnectionsRegistry.INSTANCE.setThreadLocalDiscoveredAddresses( new ConcurrentHashMap<Map.Entry<String, Integer>, ConnectionsRegistry.ConnectionStatus>() ); ConnectionsRegistry.INSTANCE.setThreadLocalDiscoveredDataSources( new ConcurrentHashMap<Map.Entry<String, String>, ConnectionsRegistry.ConnectionStatus>() ); } } private static void copyFaultToleranceTestingFromSession(HttpServletRequest request) { HttpSession session = request.getSession(); Map<Map.Entry<String,Integer>, ConnectionsRegistry.ConnectionStatus> discoveredAddresses = (Map<Map.Entry<String,Integer>, ConnectionsRegistry.ConnectionStatus>) session.getAttribute(THREAD_LOCAL_DISCOVERED_ADDRESSES); if (null == discoveredAddresses) { discoveredAddresses = new ConcurrentHashMap<Map.Entry<String,Integer>, ConnectionsRegistry.ConnectionStatus>(); session.setAttribute(THREAD_LOCAL_DISCOVERED_ADDRESSES, discoveredAddresses); } ConnectionsRegistry.INSTANCE.setThreadLocalDiscoveredAddresses(discoveredAddresses); Map<Map.Entry<String,String>, ConnectionsRegistry.ConnectionStatus> discoveredDataSources = (Map<Map.Entry<String,String>, ConnectionsRegistry.ConnectionStatus>) session.getAttribute(THREAD_LOCAL_DISCOVERED_DATA_SOURCES); if (null == discoveredDataSources) { discoveredDataSources = new ConcurrentHashMap<Map.Entry<String,String>, ConnectionsRegistry.ConnectionStatus>(); session.setAttribute(THREAD_LOCAL_DISCOVERED_DATA_SOURCES, discoveredDataSources); } ConnectionsRegistry.INSTANCE.setThreadLocalDiscoveredDataSources(discoveredDataSources); } private boolean isSniffyFilterEnabled(ServletRequest request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws MalformedURLException { boolean sniffyEnabled = enabled; // override by request header String sniffyEnabledHeader = httpServletRequest.getHeader(SNIFFY_ENABLED_HEADER); if (null != sniffyEnabledHeader) { sniffyEnabled = Boolean.parseBoolean(sniffyEnabledHeader); } // override by request parameter/cookie value if provided String sniffyEnabledParam = request.getParameter(SNIFFY); if (null != sniffyEnabledParam) { sniffyEnabled = Boolean.parseBoolean(sniffyEnabledParam); setSessionCookie(httpServletResponse, SNIFFY, String.valueOf(sniffyEnabled)); } else { sniffyEnabledParam = readCookie(httpServletRequest, SNIFFY); if (null != sniffyEnabledParam) { sniffyEnabled = Boolean.parseBoolean(sniffyEnabledParam); } } return sniffyEnabled; } private void setSessionCookie(HttpServletResponse httpServletResponse, String name, String value) throws MalformedURLException { Cookie cookie = new Cookie(name, value); cookie.setPath("/"); httpServletResponse.addCookie(cookie); } private String readCookie(HttpServletRequest httpServletRequest, String name) { Cookie[] cookies = httpServletRequest.getCookies(); if (null != cookies) for (Cookie cookie : cookies) { if (name.equals(cookie.getName())) { return cookie.getValue(); } } return null; } public void destroy() { // TODO: implement some cleanup here if required } public boolean isInjectHtml() { return injectHtml; } public void setInjectHtml(boolean injectHtml) { this.injectHtml = injectHtml; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } }
//$HeadURL$ package org.deegree.securityproxy.service.commons.responsefilter.clipping; import static org.apache.commons.io.IOUtils.closeQuietly; import static org.apache.commons.io.IOUtils.write; import static org.deegree.securityproxy.service.commons.responsefilter.ResponseFilterUtils.copyBufferedStream; import static org.deegree.securityproxy.service.commons.responsefilter.ResponseFilterUtils.isException; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.deegree.securityproxy.authentication.ows.raster.GeometryFilterInfo; import org.deegree.securityproxy.authentication.ows.raster.RasterUser; import org.deegree.securityproxy.filter.StatusCodeResponseBodyWrapper; import org.deegree.securityproxy.request.OwsRequest; import org.deegree.securityproxy.responsefilter.ResponseFilterException; import org.deegree.securityproxy.responsefilter.ResponseFilterManager; import org.deegree.securityproxy.responsefilter.logging.ResponseClippingReport; import org.deegree.securityproxy.service.commons.responsefilter.clipping.exception.ClippingException; import org.deegree.securityproxy.service.commons.responsefilter.clipping.geometry.GeometryRetriever; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTWriter; public abstract class AbstractClippingResponseFilterManager implements ResponseFilterManager { public static final String REQUEST_AREA_HEADER_KEY = "request_area"; public static final String NOT_A_CORRECT_REQUEST_MSG = "Request was not a GetCoverage- or GetMap-Request - clipping not required."; public static final String SERVICE_EXCEPTION_MSG = "Response is a ServiceException."; public static final int DEFAULT_STATUS_CODE = 500; public static final String DEFAULT_BODY = "Clipping failed!"; private static final Logger LOG = Logger.getLogger( AbstractClippingResponseFilterManager.class ); protected final String exceptionBody; protected final int exceptionStatusCode; @Autowired private GeometryRetriever geometryRetriever; @Autowired private ImageClipper imageClipper; /** * Instantiates a new {@link AbstractClippingResponseFilterManager} with default exception body (DEFAULT_BODY) and * status code (DEFAULT_STATUS_CODE). */ public AbstractClippingResponseFilterManager() { this.exceptionBody = DEFAULT_BODY; this.exceptionStatusCode = DEFAULT_STATUS_CODE; } /** * Instantiates a new {@link AbstractClippingResponseFilterManager} with the passed exception body and status code. * * @param pathToExceptionFile * if null or not available, the default exception body (DEFAULT_BODY) is used * @param exceptionStatusCode * the exception status code */ public AbstractClippingResponseFilterManager( String pathToExceptionFile, int exceptionStatusCode ) { this.exceptionBody = readExceptionBodyFromFile( pathToExceptionFile ); this.exceptionStatusCode = exceptionStatusCode; } @Override public ResponseClippingReport filterResponse( StatusCodeResponseBodyWrapper servletResponse, OwsRequest request, Authentication auth ) throws ResponseFilterException { checkParameters( servletResponse, request ); if ( canBeFiltered( request ) ) { LOG.info( "Apply filter for response of request " + request ); try { if ( isException( servletResponse ) ) { LOG.debug( "Response contains an exception!" ); copyBufferedStream( servletResponse ); return new ResponseClippingReport( SERVICE_EXCEPTION_MSG ); } Geometry clippingGeometry = retrieveGeometryUseForClipping( auth, request ); return processClippingAndAddHeaderInfo( servletResponse, clippingGeometry ); } catch ( ParseException e ) { LOG.error( "Calculating clipped result image failed!", e ); writeExceptionBodyAndSetExceptionStatusCode( servletResponse ); return new ResponseClippingReport( "" + e.getMessage() ); } catch ( IOException e ) { LOG.error( "Calculating clipped result image failed!", e ); writeExceptionBodyAndSetExceptionStatusCode( servletResponse ); return new ResponseClippingReport( "" + e.getMessage() ); } } LOG.debug( "Request was not a GetCoverage request. Will be ignored by this filter manager!" ); copyBufferedStream( servletResponse ); return new ResponseClippingReport( NOT_A_CORRECT_REQUEST_MSG ); } @Override public boolean canBeFiltered( OwsRequest request ) { checkIfRequestEqualsNull( request ); return isCorrectRequestType( request ) && isCorrectRequest( request ); } /** * @param request * never <code>null</code> * @return true if request is from the supported type */ protected abstract boolean isCorrectRequestType( OwsRequest request ); /** * @param owsRequest * never <code>null</code> * @return true if request is a capabilities request */ protected abstract boolean isCorrectRequest( OwsRequest owsRequest ); /** * * @param request * never <code>null</code> * @return layer name */ protected abstract String retrieveLayerName( OwsRequest request ); private void checkIfRequestEqualsNull( OwsRequest request ) { if ( request == null ) throw new IllegalArgumentException( "Request must not be null!" ); } private void checkParameters( HttpServletResponse servletResponse, OwsRequest request ) { if ( servletResponse == null ) throw new IllegalArgumentException( "Parameter servletResponse may not be null!" ); if ( request == null ) throw new IllegalArgumentException( "Parameter request may not be null!" ); if ( !isCorrectRequestType( request ) ) throw new IllegalArgumentException( "OwsRequest of class " + request.getClass().getCanonicalName() + " is not supported!" ); } private ResponseClippingReport processClippingAndAddHeaderInfo( StatusCodeResponseBodyWrapper servletResponse, Geometry clippingGeometry ) throws IOException { try { InputStream imageAsStream = servletResponse.getBufferedStream(); ByteArrayOutputStream destination = new ByteArrayOutputStream(); ResponseClippingReport clippedImageReport = imageClipper.calculateClippedImage( imageAsStream, clippingGeometry, destination ); addHeaderInfoIfNoFailureOccurred( servletResponse, clippedImageReport ); // required to set the header (must be set BEFORE any data is written to the response) destination.writeTo( servletResponse.getRealOutputStream() ); return clippedImageReport; } catch ( ClippingException e ) { writeExceptionBodyAndSetExceptionStatusCode( servletResponse ); return new ResponseClippingReport( "" + e.getMessage() ); } } private void writeExceptionBodyAndSetExceptionStatusCode( StatusCodeResponseBodyWrapper servletResponse ) { try { OutputStream destination = servletResponse.getRealOutputStream(); writeExceptionBodyAndSetExceptionStatusCode( servletResponse, destination ); } catch ( IOException e ) { LOG.error( "An error occurred during writing the exception response!", e ); } } private void writeExceptionBodyAndSetExceptionStatusCode( StatusCodeResponseBodyWrapper servletResponse, OutputStream destination ) throws IOException { servletResponse.setStatus( exceptionStatusCode ); write( exceptionBody, destination ); } private Geometry retrieveGeometryUseForClipping( Authentication auth, OwsRequest wcsRequest ) throws IllegalArgumentException, ParseException { RasterUser wcsUser = retrieveWcsUser( auth ); List<GeometryFilterInfo> geometryFilterInfos = wcsUser.getWcsGeometryFilterInfos(); String coverageName = retrieveLayerName( wcsRequest ); return geometryRetriever.retrieveGeometry( coverageName, geometryFilterInfos ); } private RasterUser retrieveWcsUser( Authentication auth ) { Object principal = auth.getPrincipal(); if ( !( principal instanceof RasterUser ) ) { throw new IllegalArgumentException( "Principal is not a WcsUser!" ); } return (RasterUser) principal; } private void addHeaderInfoIfNoFailureOccurred( StatusCodeResponseBodyWrapper servletResponse, ResponseClippingReport clippedImageReport ) { if ( noFailureOccured( clippedImageReport ) ) { WKTWriter writer = new WKTWriter(); String requestAreaWkt = writer.write( clippedImageReport.getReturnedVisibleArea() ); LOG.debug( "Add header '" + REQUEST_AREA_HEADER_KEY + "': " + requestAreaWkt ); servletResponse.addHeader( REQUEST_AREA_HEADER_KEY, requestAreaWkt ); } } private boolean noFailureOccured( ResponseClippingReport clippedImageReport ) { return clippedImageReport.getFailure() == null && clippedImageReport.getReturnedVisibleArea() != null; } protected String readExceptionBodyFromFile( String pathToExceptionFile ) { LOG.info( "Reading exception body from " + pathToExceptionFile ); if ( pathToExceptionFile != null && pathToExceptionFile.length() > 0 ) { InputStream exceptionAsStream = null; try { File exceptionFile = new File( pathToExceptionFile ); exceptionAsStream = new FileInputStream( exceptionFile ); return IOUtils.toString( exceptionAsStream ); } catch ( FileNotFoundException e ) { LOG.warn( "Could not read exception message from file: File not found! Defaulting to " + DEFAULT_BODY ); } catch ( IOException e ) { LOG.warn( "Could not read exception message from file. Defaulting to " + DEFAULT_BODY + "Reason: " + e.getMessage() ); } finally { closeQuietly( exceptionAsStream ); } } return DEFAULT_BODY; } }
package me.stefvanschie.buildinggame.commands.subcommands; import java.util.HashMap; import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import me.stefvanschie.buildinggame.Main; import me.stefvanschie.buildinggame.commands.commandutils.CommandResult; import me.stefvanschie.buildinggame.commands.commandutils.SubCommand; import me.stefvanschie.buildinggame.events.player.create.Bounds; import me.stefvanschie.buildinggame.managers.arenas.ArenaManager; import me.stefvanschie.buildinggame.managers.messages.MessageManager; import me.stefvanschie.buildinggame.utils.Arena; import me.stefvanschie.buildinggame.utils.plot.Plot; public class SetBounds extends SubCommand { HashMap<String, Plot> editingPlot = new HashMap<String, Plot>(); HashMap<String, Arena> editingArena = new HashMap<String, Arena>(); Map<String, Location> previousLocation = new HashMap<String, Location>(); @Override public CommandResult onCommand(Player player, String[] args) { if (args.length < 2) { MessageManager.getInstance().send(player, ChatColor.RED + "Please specify the arena and plot"); return CommandResult.ARGUMENTEXCEPTION; } Arena arena = ArenaManager.getInstance().getArena(args[0]); if (arena == null) { MessageManager.getInstance().send(player, ChatColor.RED + "That's not a valid arena"); return CommandResult.ERROR; } try { Integer.parseInt(args[1]); } catch (NumberFormatException nfe) { MessageManager.getInstance().send(player, ChatColor.RED + "That's not a valid plot"); return CommandResult.ERROR; } int ID = Integer.parseInt(args[1]); Plot plot = arena.getPlot(ID); if (plot == null) { MessageManager.getInstance().send(player, ChatColor.RED + "That's not a valid plot"); return CommandResult.ERROR; } ItemStack wand = new ItemStack(Material.STICK, 1); ItemMeta wandItemMeta = wand.getItemMeta(); wandItemMeta.setDisplayName(ChatColor.LIGHT_PURPLE + "Wand"); wand.setItemMeta(wandItemMeta); player.getInventory().setItemInHand(wand); editingPlot.put(player.getName(), plot); editingArena.put(player.getName(), arena); MessageManager.getInstance().send(player, ChatColor.GREEN + "Please click on one corner"); Bukkit.getPluginManager().registerEvents(new Bounds(player, arena, plot), Main.getInstance()); return CommandResult.SUCCES; } @Override public String getName() { return "setbounds"; } @Override public String[] getAliases() { return null; } @Override public String getInfo() { return "Set the boundaries of a plot (inclusive)"; } @Override public String getPermission() { return "bg.setbounds"; } }
package imagej.build.minimaven; import imagej.build.minimaven.JavaCompiler.CompileError; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.jar.Attributes.Name; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import javax.xml.parsers.ParserConfigurationException; import org.scijava.util.FileUtils; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * This class represents a parsed pom.xml file. * * Every pom.xml file is parsed into an instance of this class; the tree of projects shares * a {@link BuildEnvironment} instance. * * @author Johannes Schindelin */ public class MavenProject extends DefaultHandler implements Comparable<MavenProject> { protected final BuildEnvironment env; protected boolean buildFromSource, built; protected File directory, target; protected String sourceDirectory = "src/main/java"; protected MavenProject parent; protected MavenProject[] children; protected Coordinate coordinate = new Coordinate(), parentCoordinate; protected Map<String, String> properties = new HashMap<String, String>(); protected List<String> modules = new ArrayList<String>(); protected List<Coordinate> dependencies = new ArrayList<Coordinate>(); protected Set<String> repositories = new TreeSet<String>(); protected String sourceVersion, targetVersion, mainClass; protected boolean includeImplementationBuild; protected String packaging = "jar"; private static enum BooleanState { UNKNOWN, YES, NO }; private BooleanState upToDate = BooleanState.UNKNOWN, jarUpToDate = BooleanState.UNKNOWN; // only used during parsing protected String prefix = ""; protected Coordinate latestDependency = new Coordinate(); protected boolean isCurrentProfile; protected String currentPluginName; private static Name CREATED_BY = new Name("Created-By"); protected MavenProject addModule(String name) throws IOException, ParserConfigurationException, SAXException { return addChild(env.parse(new File(new File(directory, name), "pom.xml"), this)); } protected MavenProject addChild(MavenProject child) { MavenProject[] newChildren = new MavenProject[children.length + 1]; System.arraycopy(children, 0, newChildren, 0, children.length); newChildren[children.length] = child; children = newChildren; return child; } protected MavenProject(final BuildEnvironment miniMaven, File directory, MavenProject parent) { env = miniMaven; this.directory = directory; this.parent = parent; if (parent != null) { coordinate.groupId = parent.coordinate.groupId; coordinate.version = parent.coordinate.version; parentCoordinate = parent.coordinate; includeImplementationBuild = parent.includeImplementationBuild; } } public void clean() throws IOException, ParserConfigurationException, SAXException { if ("pom".equals(getPackaging())) { for (final MavenProject child : getChildren()) { child.clean(); } return; } if (!buildFromSource) return; for (MavenProject child : getDependencies(true, env.downloadAutomatically)) if (child != null) child.clean(); if (target.isDirectory()) BuildEnvironment.rmRF(target); else if (target.exists()) target.delete(); File jar = getTarget(); if (jar.exists()) jar.delete(); } public void downloadDependencies() throws IOException, ParserConfigurationException, SAXException { getDependencies(true, true, "test"); download(); } protected void download() throws FileNotFoundException { if (buildFromSource || target.exists()) return; download(coordinate, true); } protected void download(Coordinate dependency, boolean quiet) throws FileNotFoundException { for (String url : getRoot().getRepositories()) try { if (env.debug) { env.err.println("Trying to download from " + url); } env.downloadAndVerify(url, dependency, quiet); return; } catch (Exception e) { if (env.verbose) e.printStackTrace(); } throw new FileNotFoundException("Could not download " + dependency.getJarName()); } public boolean upToDate(boolean includingJar) throws IOException, ParserConfigurationException, SAXException { if (includingJar) { if (jarUpToDate == BooleanState.UNKNOWN) { jarUpToDate = checkUpToDate(true) ? BooleanState.YES : BooleanState.NO; } return jarUpToDate == BooleanState.YES; } if (upToDate == BooleanState.UNKNOWN) { upToDate = checkUpToDate(false) ? BooleanState.YES : BooleanState.NO; } return upToDate == BooleanState.YES; } public boolean checkUpToDate(boolean includingJar) throws IOException, ParserConfigurationException, SAXException { if (!buildFromSource) return true; for (MavenProject child : getDependencies(true, env.downloadAutomatically, "test")) if (child != null && !child.upToDate(includingJar)) { if (env.verbose) { env.err.println(getArtifactId() + " not up-to-date because of " + child.getArtifactId()); } return false; } File source = getSourceDirectory(); List<String> notUpToDates = new ArrayList<String>(); long lastModified = addRecursively(notUpToDates, source, ".java", target, ".class", false); int count = notUpToDates.size(); // ugly work-around for Bio-Formats: EFHSSF.java only contains commented-out code if (count == 1 && notUpToDates.get(0).endsWith("poi/hssf/dev/EFHSSF.java")) { count = 0; } if (count > 0) { if (env.verbose) { final StringBuilder files = new StringBuilder(); int counter = 0; for (String item : notUpToDates) { if (counter > 3) { files.append(", ..."); break; } else if (counter > 0) { files.append(", "); } files.append(item); } env.err.println(getArtifactId() + " not up-to-date because " + count + " source files are not up-to-date (" + files + ")"); } return false; } long lastModified2 = updateRecursively(new File(source.getParentFile(), "resources"), target, true); if (lastModified < lastModified2) lastModified = lastModified2; if (includingJar) { File jar = getTarget(); if (!jar.exists() || jar.lastModified() < lastModified) { if (env.verbose) { env.err.println(getArtifactId() + " not up-to-date because " + jar + " is not up-to-date"); } return false; } } return true; } public File getSourceDirectory() { String sourcePath = getSourcePath(); File file = new File(sourcePath); if (file.isAbsolute()) return file; return new File(directory, sourcePath); } public String getSourcePath() { return expand(sourceDirectory); } protected void addToJarRecursively(JarOutputStream out, File directory, String prefix) throws IOException { for (File file : directory.listFiles()) if (file.isFile()) { // For backwards-compatibility with the Fiji Updater, let's not include pom.properties files in the Updater itself if (file.getAbsolutePath().endsWith("/Fiji_Updater/target/classes/META-INF/maven/sc.fiji/Fiji_Updater/pom.properties")) continue; out.putNextEntry(new ZipEntry(prefix + file.getName())); BuildEnvironment.copy(new FileInputStream(file), out, false); } else if (file.isDirectory()) addToJarRecursively(out, file, prefix + file.getName() + "/"); } /** * Builds the artifact and installs it and its dependencies into ${imagej.app.directory}. * * If the property <tt>imagej.app.directory</tt> does not point to a valid directory, the * install step is skipped. * * @throws CompileError * @throws IOException * @throws ParserConfigurationException * @throws SAXException */ public void buildAndInstall() throws CompileError, IOException, ParserConfigurationException, SAXException { final String ijDirProperty = expand(getProperty(BuildEnvironment.IMAGEJ_APP_DIRECTORY)); if (ijDirProperty == null) { throw new IOException(BuildEnvironment.IMAGEJ_APP_DIRECTORY + " does not point to an ImageJ.app/ directory!"); } buildAndInstall(new File(ijDirProperty), false); } /** * Builds the project an its dependencies, and installs them into the given ImageJ.app/ directory structure. * * If the property <tt>imagej.app.directory</tt> does not point to a valid directory, the * install step is skipped. * * @param ijDir the ImageJ.app/ directory * * @throws CompileError * @throws IOException * @throws ParserConfigurationException * @throws SAXException */ public void buildAndInstall(final File ijDir) throws CompileError, IOException, ParserConfigurationException, SAXException { buildAndInstall(ijDir, false); } /** * Builds the project an its dependencies, and installs them into the given ImageJ.app/ directory structure. * * If the property <tt>imagej.app.directory</tt> does not point to a valid directory, the * install step is skipped. * * @param ijDir the ImageJ.app/ directory * @param forceBuild recompile even if the artifact is up-to-date * * @throws CompileError * @throws IOException * @throws ParserConfigurationException * @throws SAXException */ public void buildAndInstall(final File ijDir, final boolean forceBuild) throws CompileError, IOException, ParserConfigurationException, SAXException { if ("pom".equals(getPackaging())) { env.err.println("Looking at children of " + getArtifactId()); for (final MavenProject child : getChildren()) { child.buildAndInstall(ijDir, forceBuild); } return; } build(true, forceBuild); for (final MavenProject project : getDependencies(true, false, "test", "provided", "system")) { project.copyToImageJAppDirectory(ijDir, true); } copyToImageJAppDirectory(ijDir, true); } /** * Builds the artifact. * * @throws CompileError * @throws IOException * @throws ParserConfigurationException * @throws SAXException */ public void buildJar() throws CompileError, IOException, ParserConfigurationException, SAXException { build(true, false); } /** * Compiles the project. * * @throws CompileError * @throws IOException * @throws ParserConfigurationException * @throws SAXException */ public void build() throws CompileError, IOException, ParserConfigurationException, SAXException { build(false); } /** * Compiles the project and optionally builds the .jar artifact. * * @param makeJar build a .jar file * * @throws CompileError * @throws IOException * @throws ParserConfigurationException * @throws SAXException */ public void build(boolean makeJar) throws CompileError, IOException, ParserConfigurationException, SAXException { build(makeJar, false); } /** * Compiles the project and optionally builds the .jar artifact. * * @param makeJar build a .jar file * @param forceBuild for recompilation even if the artifact is up-to-date * * @throws CompileError * @throws IOException * @throws ParserConfigurationException * @throws SAXException */ public void build(boolean makeJar, boolean forceBuild) throws CompileError, IOException, ParserConfigurationException, SAXException { if (!forceBuild && upToDate(makeJar)) { return; } if (!buildFromSource || built) return; boolean forceFullBuild = false; for (MavenProject child : getDependencies(true, env.downloadAutomatically, "test")) if (child != null && !child.upToDate(makeJar)) { child.build(makeJar); forceFullBuild = true; } // do not build aggregator projects File source = getSourceDirectory(); if (!source.exists() && !new File(source.getParentFile(), "resources").exists()) return; target.mkdirs(); List<String> arguments = new ArrayList<String>(); // classpath String classPath = getClassPath(true); MavenProject pom2 = this; while (pom2 != null && pom2.sourceVersion == null) pom2 = pom2.parent; if (pom2 != null) { arguments.add("-source"); arguments.add(pom2.sourceVersion); } pom2 = this; while (pom2 != null && pom2.targetVersion == null) pom2 = pom2.parent; if (pom2 != null) { arguments.add("-target"); arguments.add(pom2.targetVersion); } arguments.add("-classpath"); arguments.add(classPath); // output directory arguments.add("-d"); arguments.add(target.getPath()); // the files int count = arguments.size(); addRecursively(arguments, source, ".java", target, ".class", !forceFullBuild); count = arguments.size() - count; if (count > 0) { env.err.println("Compiling " + count + " files in " + directory); if (env.verbose) { env.err.println(arguments.toString()); env.err.println("using the class path: " + classPath); } String[] array = arguments.toArray(new String[arguments.size()]); if (env.javac != null) env.javac.call(array, env.verbose); } updateRecursively(new File(source.getParentFile(), "resources"), target, false); File pom = new File(directory, "pom.xml"); if (pom.exists()) { File targetFile = new File(target, "META-INF/maven/" + coordinate.groupId + "/" + coordinate.artifactId + "/pom.xml"); targetFile.getParentFile().mkdirs(); BuildEnvironment.copyFile(pom, targetFile); } final String manifestClassPath = getManifestClassPath(); File file = new File(target, "META-INF/MANIFEST.MF"); Manifest manifest = null; if (file.exists()) manifest = new Manifest(new FileInputStream(file)); else { manifest = new Manifest(); manifest.getMainAttributes().put(Name.MANIFEST_VERSION, "1.0"); file.getParentFile().mkdirs(); } final java.util.jar.Attributes main = manifest.getMainAttributes(); if (mainClass != null) main.put(Name.MAIN_CLASS, mainClass); main.put(CREATED_BY , "MiniMaven"); if (includeImplementationBuild && !getArtifactId().equals("Fiji_Updater")) main.put(new Name("Implementation-Build"), env.getImplementationBuild(directory)); manifest.write(new FileOutputStream(file)); if (makeJar) { JarOutputStream out = new JarOutputStream(new FileOutputStream(getTarget())); addToJarRecursively(out, target, ""); out.close(); } built = true; } protected long addRecursively(List<String> list, File directory, String extension, File targetDirectory, String targetExtension, boolean includeUpToDates) { long lastModified = 0; if (list == null) return lastModified; File[] files = directory.listFiles(); if (files == null) return lastModified; for (File file : files) if (file.isDirectory()) { long lastModified2 = addRecursively(list, file, extension, new File(targetDirectory, file.getName()), targetExtension, includeUpToDates); if (lastModified < lastModified2) lastModified = lastModified2; } else { String name = file.getName(); if (!name.endsWith(extension) || name.equals("package-info.java")) continue; File targetFile = new File(targetDirectory, name.substring(0, name.length() - extension.length()) + targetExtension); long lastModified2 = file.lastModified(); if (lastModified < lastModified2) lastModified = lastModified2; if (includeUpToDates || !targetFile.exists() || targetFile.lastModified() < lastModified2) list.add(file.getPath()); } return lastModified; } protected long updateRecursively(File source, File target, boolean dryRun) throws IOException { long lastModified = 0; File[] list = source.listFiles(); if (list == null) return lastModified; for (File file : list) { File targetFile = new File(target, file.getName()); if (file.isDirectory()) { long lastModified2 = updateRecursively(file, targetFile, dryRun); if (lastModified < lastModified2) lastModified = lastModified2; } else if (file.isFile()) { long lastModified2 = file.lastModified(); if (lastModified < lastModified2) lastModified = lastModified2; if (dryRun || (targetFile.exists() && targetFile.lastModified() >= lastModified2)) continue; targetFile.getParentFile().mkdirs(); BuildEnvironment.copyFile(file, targetFile); } } return lastModified; } public Coordinate getCoordinate() { return coordinate; } public String getGroupId() { return coordinate.groupId; } public String getArtifactId() { return coordinate.artifactId; } public String getVersion() { return coordinate.version; } public String getJarName() { return coordinate.getJarName(); } public String getMainClass() { return mainClass; } public String getPackaging() { return packaging; } public File getTarget() { if (!buildFromSource) return target; return new File(new File(directory, "target"), getJarName()); } public File getDirectory() { return directory; } public boolean getBuildFromSource() { return buildFromSource; } public String getClassPath(boolean forCompile) throws IOException, ParserConfigurationException, SAXException { StringBuilder builder = new StringBuilder(); builder.append(target); if (env.debug) env.err.println("Get classpath for " + coordinate + " for " + (forCompile ? "compile" : "runtime")); for (MavenProject pom : getDependencies(true, env.downloadAutomatically, "test", forCompile ? "runtime" : "provided")) { if (env.debug) env.err.println("Adding dependency " + pom.coordinate + " to classpath"); builder.append(File.pathSeparator).append(pom.getTarget()); } return builder.toString(); } private final void deleteVersions(final File directory, final String filename, final File excluding) { final File[] versioned = FileUtils.getAllVersions(directory, filename); if (versioned == null) return; for (final File file : versioned) { if (file.equals(excluding)) continue; if (!file.getName().equals(filename)) env.err.println("Warning: deleting '" + file + "'"); if (!file.delete()) env.err.println("Warning: could not delete '" + file + "'"); } } /** * Copies the current artifact and all its dependencies into an ImageJ.app/ directory structure. * * In the ImageJ.app/ directory structure, plugin .jar files live in the plugins/ subdirectory * while libraries not providing any plugins should go to jars/. * * @param ijDir the ImageJ.app/ directory * @throws IOException */ private void copyToImageJAppDirectory(final File ijDir, boolean deleteOtherVersions) throws IOException { if ("pom".equals(getPackaging())) return; final File source = getTarget(); if (!source.exists()) throw new IOException("Artifact does not exist: " + source); final File targetDir = new File(ijDir, isImageJ1Plugin(source) ? "plugins" : "jars"); final File target = new File(targetDir, getArtifactId() + ("Fiji_Updater".equals(getArtifactId()) ? "" : "-" + getVersion()) + ".jar"); if (!targetDir.exists()) { if (!targetDir.mkdirs()) { throw new IOException("Could not make directory " + targetDir); } } else if (target.exists() && target.lastModified() >= source.lastModified()) { if (deleteOtherVersions) deleteVersions(targetDir, target.getName(), target); return; } if (deleteOtherVersions) deleteVersions(targetDir, target.getName(), null); BuildEnvironment.copyFile(source, target); } /** * Determines whether a .jar file contains ImageJ 1.x plugins. * * The test is simple: does it contain a <tt>plugins.config</tt> file? * * @param file the .jar file * @return whether it contains at least one ImageJ 1.x plugin. */ private static boolean isImageJ1Plugin(File file) { String name = file.getName(); if (name.indexOf('_') < 0 || !file.exists()) return false; if (file.isDirectory()) return new File(file, "src/main/resources/plugins.config").exists(); if (name.endsWith(".jar")) try { JarFile jar = new JarFile(file); for (JarEntry entry : Collections.list(jar.entries())) if (entry.getName().equals("plugins.config")) { jar.close(); return true; } jar.close(); } catch (Throwable t) { // obviously not a plugin... } return false; } /** * Copy the runtime dependencies * * @param directory where to copy the files to * @param onlyNewer whether to copy the files only if the sources are newer * @throws IOException * @throws ParserConfigurationException * @throws SAXException */ public void copyDependencies(File directory, boolean onlyNewer) throws IOException, ParserConfigurationException, SAXException { for (MavenProject pom : getDependencies(true, env.downloadAutomatically, "test", "provided")) { File file = pom.getTarget(); File destination = new File(directory, pom.coordinate.artifactId + ".jar"); if (file.exists() && (!onlyNewer || (!destination.exists() || destination.lastModified() < file.lastModified()))) BuildEnvironment.copyFile(file, destination); } } public Set<MavenProject> getDependencies() throws IOException, ParserConfigurationException, SAXException { return getDependencies(false, env.downloadAutomatically); } public Set<MavenProject> getDependencies(boolean excludeOptionals, boolean downloadAutomatically, String... excludeScopes) throws IOException, ParserConfigurationException, SAXException { Set<MavenProject> set = new TreeSet<MavenProject>(); getDependencies(set, excludeOptionals, downloadAutomatically, excludeScopes); return set; } public void getDependencies(Set<MavenProject> result, boolean excludeOptionals, boolean downloadAutomatically, String... excludeScopes) throws IOException, ParserConfigurationException, SAXException { for (Coordinate dependency : dependencies) { if (excludeOptionals && dependency.optional) continue; String scope = expand(dependency.scope); if (scope != null && excludeScopes != null && arrayContainsString(excludeScopes, scope)) continue; Coordinate expanded = expand(dependency); MavenProject pom = findPOM(expanded, !env.verbose, false); String systemPath = expand(dependency.systemPath); if (pom == null && systemPath != null) { File file = new File(systemPath); if (file.exists()) { result.add(env.fakePOM(file, expanded)); continue; } } // make sure that snapshot .pom files are updated once a day if (!env.offlineMode && downloadAutomatically && pom != null && pom.coordinate.version != null && (pom.coordinate.version.startsWith("[") || pom.coordinate.version.endsWith("-SNAPSHOT")) && pom.directory.getPath().startsWith(BuildEnvironment.mavenRepository.getPath())) { if (maybeDownloadAutomatically(pom.coordinate, !env.verbose, downloadAutomatically)) { if (pom.coordinate.version.startsWith("[")) pom.coordinate.setSnapshotVersion(VersionPOMHandler.parse(new File(pom.directory.getParentFile(), "maven-metadata-version.xml"))); else pom.coordinate.setSnapshotVersion(SnapshotPOMHandler.parse(new File(pom.directory, "maven-metadata-snapshot.xml"))); dependency.setSnapshotVersion(pom.coordinate.getVersion()); } } if (pom == null && downloadAutomatically) try { pom = findPOM(expanded, !env.verbose, downloadAutomatically); } catch (IOException e) { env.err.println("Failed to download dependency " + expanded.artifactId + " of " + getArtifactId()); throw e; } if (pom == null || result.contains(pom)) continue; result.add(pom); try { pom.getDependencies(result, env.downloadAutomatically, excludeOptionals, excludeScopes); } catch (IOException e) { env.err.println("Problems downloading the dependencies of " + getArtifactId()); throw e; } } } protected boolean arrayContainsString(String[] array, String key) { for (String string : array) if (string.equals(key)) return true; return false; } // expands ${<property-name>} public Coordinate expand(Coordinate dependency) { boolean optional = dependency.optional; String scope = expand(dependency.scope); String groupId = expand(dependency.groupId); String artifactId = expand(dependency.artifactId); String version = expand(dependency.version); String classifier = expand(dependency.classifier); String systemPath = expand(dependency.systemPath); return new Coordinate(groupId, artifactId, version, scope, optional, systemPath, classifier); } public String expand(String string) { if (string == null) return null; String result = string; for (;;) { int dollarCurly = result.indexOf("${"); if (dollarCurly < 0) return result; int endCurly = result.indexOf("}", dollarCurly + 2); if (endCurly < 0) throw new RuntimeException("Invalid string: " + string); String property = getProperty(result.substring(dollarCurly + 2, endCurly)); if (property == null) { if (dollarCurly == 0 && endCurly == result.length() - 1) return null; property = ""; } result = result.substring(0, dollarCurly) + property + result.substring(endCurly + 1); } } /** * Returns the (possibly project-specific) value of a property. * * System properties override project-specific properties to allow the user * to overrule a setting by specifying it on the command-line. * * @param key the name of the property * @return the value of the property */ public String getProperty(String key) { final String systemProperty = System.getProperty(key); if (systemProperty != null) return systemProperty; if (properties.containsKey(key)) return properties.get(key); if (key.equals("project.basedir")) return directory.getPath(); if (key.equals("rootdir")) { File directory = this.directory; for (;;) { final File parent = directory.getParentFile(); if (parent == null || !new File(parent, "pom.xml").exists()) { return directory.getPath(); } directory = parent; } } if (parent == null) { // hard-code a few variables if (key.equals("bio-formats.groupId")) return "loci"; if (key.equals("bio-formats.version")) return "4.4-SNAPSHOT"; if (key.equals("imagej.groupId")) return "imagej"; return null; } return parent.getProperty(key); } public MavenProject[] getChildren() { if (children == null) return new MavenProject[0]; return children; } public MavenProject getRoot() { MavenProject result = this; while (result.parent != null) result = result.parent; return result; } protected Set<String> getRepositories() { Set<String> result = new TreeSet<String>(); getRepositories(result); return result; } protected void getRepositories(Set<String> result) { // add a default to the root if (parent == null) { result.add("http://repo1.maven.org/maven2/"); result.add("http://maven.imagej.net/content/repositories/releases/"); result.add("http://maven.imagej.net/content/repositories/snapshots/"); } result.addAll(repositories); for (MavenProject child : getChildren()) if (child != null) child.getRepositories(result); } public MavenProject findPOM(Coordinate dependency, boolean quiet, boolean downloadAutomatically) throws IOException, ParserConfigurationException, SAXException { if (dependency.version == null && "aopalliance".equals(dependency.artifactId)) dependency.version = "1.0"; if (dependency.version == null && "provided".equals(dependency.scope)) return null; if (dependency.artifactId.equals(expand(coordinate.artifactId)) && dependency.groupId.equals(expand(coordinate.groupId)) && dependency.version.equals(expand(coordinate.version))) return this; // fall back to Fiji's modules/, $HOME/.m2/repository/ and Fiji's jars/ and plugins/ directories String key = dependency.getKey(); if (env.localPOMCache.containsKey(key)) { MavenProject result = env.localPOMCache.get(key); // may be null if (result == null || BuildEnvironment.compareVersion(dependency.getVersion(), result.coordinate.getVersion()) <= 0) return result; } MavenProject pom = findInMultiProjects(dependency); if (pom != null) return pom; if (env.ignoreMavenRepositories) { if (!quiet && !dependency.optional) env.err.println("Skipping artifact " + dependency.artifactId + " (for " + coordinate.artifactId + "): not in jars/ nor plugins/"); return cacheAndReturn(key, null); } String path = BuildEnvironment.mavenRepository.getPath() + "/" + dependency.groupId.replace('.', '/') + "/" + dependency.artifactId + "/"; if (dependency.version == null) { env.err.println("Skipping invalid dependency (version unset): " + dependency); return null; } if (dependency.version.startsWith("[") && dependency.snapshotVersion == null) try { if (!maybeDownloadAutomatically(dependency, quiet, downloadAutomatically)) return null; if (dependency.version.startsWith("[")) dependency.snapshotVersion = VersionPOMHandler.parse(new File(path, "maven-metadata-version.xml")); } catch (FileNotFoundException e) { /* ignore */ } path += dependency.getVersion() + "/"; if (dependency.version.endsWith("-SNAPSHOT")) try { if (!maybeDownloadAutomatically(dependency, quiet, downloadAutomatically)) { return null; } if (dependency.version.endsWith("-SNAPSHOT")) dependency.setSnapshotVersion(SnapshotPOMHandler.parse(new File(path, "maven-metadata-snapshot.xml"))); } catch (FileNotFoundException e) { /* ignore */ } File file = new File(path, dependency.getPOMName()); if (!file.exists()) { if (downloadAutomatically) { if (!maybeDownloadAutomatically(dependency, quiet, downloadAutomatically)) return null; } else { if (!quiet && !dependency.optional) env.err.println("Skipping artifact " + dependency.artifactId + " (for " + coordinate.artifactId + "): not found"); if (!downloadAutomatically && env.downloadAutomatically) return null; return cacheAndReturn(key, null); } } MavenProject result = env.parse(new File(path, dependency.getPOMName()), null, dependency.classifier); if (result != null) { if (result.target.getName().endsWith("-SNAPSHOT.jar")) { result.coordinate.version = dependency.version; result.target = new File(result.directory, dependency.getJarName()); } if (result.parent == null) result.parent = getRoot(); if (result.packaging.equals("jar") && !new File(path, dependency.getJarName()).exists()) { if (downloadAutomatically) download(dependency, quiet); else { env.localPOMCache.remove(key); return null; } } } else if (!quiet && !dependency.optional) env.err.println("Artifact " + dependency.artifactId + " not found" + (downloadAutomatically ? "" : "; consider 'get-dependencies'")); return result; } protected MavenProject findInMultiProjects(Coordinate dependency) throws IOException, ParserConfigurationException, SAXException { env.parseMultiProjects(); String key = dependency.getKey(); MavenProject result = env.localPOMCache.get(key); if (result != null && BuildEnvironment.compareVersion(dependency.getVersion(), result.coordinate.getVersion()) <= 0) return result; return null; } protected MavenProject cacheAndReturn(String key, MavenProject pom) { env.localPOMCache.put(key, pom); return pom; } protected boolean maybeDownloadAutomatically(Coordinate dependency, boolean quiet, boolean downloadAutomatically) { if (!downloadAutomatically || env.offlineMode) return true; try { download(dependency, quiet); } catch (Exception e) { if (!quiet && !dependency.optional) { e.printStackTrace(env.err); env.err.println("Could not download " + dependency.artifactId + ": " + e.getMessage()); } String key = dependency.getKey(); env.localPOMCache.put(key, null); return false; } return true; } protected String findLocallyCachedVersion(String path) throws IOException { File file = new File(path, "maven-metadata-local.xml"); if (!file.exists()) { String[] list = new File(path).list(); return list != null && list.length > 0 ? list[0] : null; } BufferedReader reader = new BufferedReader(new FileReader(file)); for (;;) { String line = reader.readLine(); if (line == null) throw new RuntimeException("Could not determine version for " + path); int tag = line.indexOf("<version>"); if (tag < 0) continue; reader.close(); int endTag = line.indexOf("</version>"); return line.substring(tag + "<version>".length(), endTag); } } // XML parsing @Override public void endDocument() { if (!properties.containsKey("project.groupId")) properties.put("project.groupId", coordinate.groupId); if (!properties.containsKey("project.version")) properties.put("project.version", coordinate.getVersion()); } @Override public void startElement(String uri, String name, String qualifiedName, Attributes attributes) { prefix += ">" + qualifiedName; if (env.debug) env.err.println("start(" + uri + ", " + name + ", " + qualifiedName + ", " + toString(attributes) + ")"); } @Override public void endElement(String uri, String name, String qualifiedName) { if (prefix.equals(">project>dependencies>dependency") || (isCurrentProfile && prefix.equals(">project>profiles>profile>dependencies>dependency"))) { if (env.debug) env.err.println("Adding dependendency " + latestDependency + " to " + this); if (coordinate.artifactId.equals("javassist") && latestDependency.artifactId.equals("tools")) latestDependency.optional = false; dependencies.add(latestDependency); latestDependency = new Coordinate(); } if (prefix.equals(">project>profiles>profile")) isCurrentProfile = false; prefix = prefix.substring(0, prefix.length() - 1 - qualifiedName.length()); if (env.debug) env.err.println("end(" + uri + ", " + name + ", " + qualifiedName + ")"); } @Override public void characters(char[] buffer, int offset, int length) { String string = new String(buffer, offset, length); if (env.debug) env.err.println("characters: " + string + " (prefix: " + prefix + ")"); String prefix = this.prefix; if (isCurrentProfile) prefix = ">project" + prefix.substring(">project>profiles>profile".length()); if (prefix.equals(">project>groupId")) coordinate.groupId = string; else if (prefix.equals(">project>artifactId")) coordinate.artifactId = string; else if (prefix.equals(">project>version")) coordinate.version = string; else if (prefix.equals(">project>packaging")) packaging = string; else if (prefix.equals(">project>modules")) buildFromSource = true; // might not be building a target else if (prefix.equals(">project>modules>module")) modules.add(string); else if (prefix.startsWith(">project>properties>")) properties.put(prefix.substring(">project>properties>".length()), string); else if (prefix.equals(">project>dependencies>dependency>groupId")) latestDependency.groupId = string; else if (prefix.equals(">project>dependencies>dependency>artifactId")) latestDependency.artifactId = string; else if (prefix.equals(">project>dependencies>dependency>version")) latestDependency.version = string; else if (prefix.equals(">project>dependencies>dependency>scope")) latestDependency.scope = string; else if (prefix.equals(">project>dependencies>dependency>optional")) latestDependency.optional = string.equalsIgnoreCase("true"); else if (prefix.equals(">project>dependencies>dependency>systemPath")) latestDependency.systemPath = string; else if (prefix.equals(">project>dependencies>dependency>classifier")) latestDependency.classifier = string; else if (prefix.equals(">project>profiles>profile>id")) { isCurrentProfile = (!System.getProperty("os.name").equals("Mac OS X") && "javac".equals(string)) || (coordinate.artifactId.equals("javassist") && (string.equals("jdk16") || string.equals("default-tools"))); if (env.debug) env.err.println((isCurrentProfile ? "Activating" : "Ignoring") + " profile " + string); } else if (!isCurrentProfile && prefix.equals(">project>profiles>profile>activation>file>exists")) isCurrentProfile = new File(directory, string).exists(); else if (!isCurrentProfile && prefix.equals(">project>profiles>profile>activation>activeByDefault")) isCurrentProfile = "true".equalsIgnoreCase(string); else if (!isCurrentProfile && prefix.equals(">project>profiles>profile>activation>property>name")) { boolean negate = false; if (string.startsWith("!")) { negate = true; string = string.substring(1); } isCurrentProfile = negate ^ (expand("${" + string + "}") != null); } else if (prefix.equals(">project>repositories>repository>url")) repositories.add(string); else if (prefix.equals(">project>build>sourceDirectory")) sourceDirectory = string; else if (prefix.startsWith(">project>parent>")) { if (parentCoordinate == null) parentCoordinate = new Coordinate(); if (prefix.equals(">project>parent>groupId")) { if (coordinate.groupId == null) coordinate.groupId = string; if (parentCoordinate.groupId == null) parentCoordinate.groupId = string; else checkParentTag("groupId", parentCoordinate.groupId, string); } else if (prefix.equals(">project>parent>artifactId")) { if (parentCoordinate.artifactId == null) parentCoordinate.artifactId = string; else checkParentTag("artifactId", parentCoordinate.artifactId, string); } else if (prefix.equals(">project>parent>version")) { if (coordinate.version == null) coordinate.version = string; if (parentCoordinate.version == null) parentCoordinate.version = string; else checkParentTag("version", parentCoordinate.version, string); } } else if (prefix.equals(">project>build>plugins>plugin>artifactId")) { currentPluginName = string; if (string.equals("buildnumber-maven-plugin")) includeImplementationBuild = true; } else if (prefix.equals(">project>build>plugins>plugin>configuration>source") && "maven-compiler-plugin".equals(currentPluginName)) sourceVersion = string; else if (prefix.equals(">project>build>plugins>plugin>configuration>target") && "maven-compiler-plugin".equals(currentPluginName)) targetVersion = string; else if (prefix.equals(">project>build>plugins>plugin>configuration>archive>manifest>mainClass") && "maven-jar-plugin".equals(currentPluginName)) mainClass = string; /* This would be needed to compile clojure.jar. However, it does not work because we do not support the antrun plugin else if (prefix.equals(">project>build>plugins>plugin>executions>execution>configuration>sources>source") && "build-helper-maven-plugin".equals(currentPluginName)) sourceDirectory = string; */ else if (env.debug) env.err.println("Ignoring " + prefix); } protected void checkParentTag(String tag, String string1, String string2) { String expanded1 = expand(string1); String expanded2 = expand(string2); if ((expanded1 == null && expanded2 != null) || (expanded1 != null && !expanded1.equals(expanded2))) env.err.println("Warning: " + tag + " mismatch in " + directory + "'s parent: " + string1 + " != " + string2); } public String toString(Attributes attributes) { StringBuilder builder = new StringBuilder(); builder.append("[ "); for (int i = 0; i < attributes.getLength(); i++) builder.append(attributes.getQName(i)) . append("='").append(attributes.getValue(i)) . append("' "); builder.append("]"); return builder.toString(); } @Override public int compareTo(MavenProject other) { int result = coordinate.artifactId.compareTo(other.coordinate.artifactId); if (result != 0) return result; if (coordinate.groupId != null && other.coordinate.groupId != null) result = coordinate.groupId.compareTo(other.coordinate.groupId); if (result != 0) return result; return BuildEnvironment.compareVersion(coordinate.getVersion(), other.coordinate.getVersion()); } @Override public String toString() { StringBuilder builder = new StringBuilder(); append(builder, ""); return builder.toString(); } public void append(StringBuilder builder, String indent) { builder.append(indent + coordinate.getKey() + "\n"); if (children != null) for (MavenProject child : getChildren()) if (child == null) builder.append(indent).append(" (null)\n"); else child.append(builder, indent + " "); } }
package com.google.mbdebian.springboot.playground.microservices.tutorial; import com.netflix.zuul.ZuulFilter; public class MyZuulFilter extends ZuulFilter { @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 1; } @Override public boolean shouldFilter() { return true; } @Override public Object run() { // This is where you execute the logic of your filter System.out.println("[MyZuulFilter] This request has passed through the custom Zuul Filter..."); return null; } }
package org.jasig.portal.layout; /** * An implementation of Aggregated User Layout Interface defining common operations on user layout nodes, * that is channels and folders * * @author <a href="mailto:mvi@immagic.com">Michael Ivanov</a> * @version 1.0 */ import java.util.Collections; import java.util.Enumeration; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Vector; import javax.xml.parsers.DocumentBuilderFactory; import org.jasig.portal.IUserLayoutStore; import org.jasig.portal.PortalException; import org.jasig.portal.UserProfile; import org.jasig.portal.layout.restrictions.IUserLayoutRestriction; import org.jasig.portal.layout.restrictions.PriorityRestriction; import org.jasig.portal.layout.restrictions.RestrictionTypes; import org.jasig.portal.layout.restrictions.UserLayoutRestriction; import org.jasig.portal.layout.restrictions.UserLayoutRestrictionFactory; import org.jasig.portal.security.IPerson; import org.jasig.portal.utils.CommonUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; public class AggregatedUserLayoutImpl implements IAggregatedUserLayoutManager { private IAggregatedUserLayoutStore layoutStore; private Hashtable layout; private UserProfile userProfile; private String lostFolderId = IALFolderDescription.LOST_FOLDER_ID; private IPerson person; // Boolean flags for marking nodes //private boolean addTargetsAllowed = false; //private boolean moveTargetsAllowed = false; private IALNodeDescription addTargetsNodeDesc; private String moveTargetsNodeId; private int restrictionMask = 0; private boolean autoCommit = false; // the tag names constants private static final String LAYOUT = "layout"; private static final String LAYOUT_FRAGMENT = "layout_fragment"; private static final String FOLDER = "folder"; private static final String CHANNEL = "channel"; private static final String PARAMETER = "parameter"; private static final String RESTRICTION = "restriction"; // The names for marking nodes private static final String ADD_TARGET = "add_target"; private static final String MOVE_TARGET = "move_target"; // Channel and folder perfixes //private static final String CHANNEL_PREFIX="n"; //private static final String FOLDER_PREFIX="s"; // The priority coefficient for changing priority values through an user interface public final int PRIORITY_COEFF = 100; // root folder id public static final String ROOT_FOLDER_ID="userLayoutRootNode"; private String rootNodeId=ROOT_FOLDER_ID; public AggregatedUserLayoutImpl( IPerson person, UserProfile userProfile ) { this.person = person; this.userProfile = userProfile; layout = new Hashtable(); autoCommit = false; } public AggregatedUserLayoutImpl( IPerson person, UserProfile userProfile, IUserLayoutStore layoutStore ) throws Exception { this ( person, userProfile ); this.layoutStore = (IAggregatedUserLayoutStore) layoutStore; this.loadUserLayout(); } /** * A factory method to create an empty <code>IUserLayoutNodeDescription</code> instance * * @param nodeType a node type value * @return an <code>IUserLayoutNodeDescription</code> instance * @exception PortalException if the error occurs. */ public IUserLayoutNodeDescription createNodeDescription( int nodeType ) throws PortalException { switch ( nodeType ) { case IUserLayoutNodeDescription.FOLDER: return new ALFolderDescription(); case IUserLayoutNodeDescription.CHANNEL: return new ALChannelDescription(); default: return null; } } /** * Sets a layout manager to auto-commit mode that allows to update the database immediately * @param autoCommit a boolean value */ public void setAutoCommit (boolean autoCommit) { this.autoCommit = autoCommit; } /** * Sets the internal representation of the UserLayout. * The user layout root node always has ID="root" * @param layout a <code>Hashtable</code> object containing the UserLayout data * @exception PortalException if an error occurs */ public void setUserLayout(Hashtable layout) throws PortalException { this.layout = layout; } public int getLayoutId() { return userProfile.getLayoutId(); } /** * Returns an Id of a parent user layout node. * The user layout root node always has ID="root" * * @param nodeId a <code>String</code> value * @return a <code>String</code> value * @exception PortalException if an error occurs */ public String getParentId(String nodeId) throws PortalException { return getLayoutNode(nodeId).getParentNodeId(); } /** * Returns the list of child node Ids for a given node. * * @param nodeId a <code>String</code> value * @return a <code>List</code> of <code>String</code> child node Ids. * @exception PortalException if an error occurs */ public List getChildIds(String nodeId) throws PortalException { //return getLayoutFolder(nodeId).getChildNodes(); List childIds = Collections.synchronizedList(new LinkedList()); String firstChildId = getLayoutFolder(nodeId).getFirstChildNodeId(); for ( String nextNodeId = firstChildId; nextNodeId != null; ) { childIds.add(nextNodeId); nextNodeId = getLayoutNode(nextNodeId).getNextNodeId(); } return childIds; } /** * Determine an Id of a previous sibling node. * * @param nodeId a <code>String</code> node ID * @return a <code>String</code> Id value of a previous sibling node, or <code>null</code> if this is the first sibling. * @exception PortalException if an error occurs */ public String getPreviousSiblingId(String nodeId) throws PortalException { return getLayoutNode(nodeId).getPreviousNodeId(); } /** * Determine an Id of a next sibling node. * * @param nodeId a <code>String</code> node ID * @return a <code>String</code> Id value of a next sibling node, or <code>null</code> if this is the last sibling. * @exception PortalException if an error occurs */ public String getNextSiblingId(String nodeId) throws PortalException { return getLayoutNode(nodeId).getNextNodeId(); } /** * Checks the restriction specified by the parameters below * @param nodeId a <code>String</code> node ID * @param restrictionType a restriction type * @param restrictionPath a <code>String</code> restriction path * @param propertyValue a <code>String</code> property value to be checked * @return a boolean value * @exception PortalException if an error occurs */ protected boolean checkRestriction(String nodeId, int restrictionType, String restrictionPath, String propertyValue) throws PortalException { ALNode node = getLayoutNode(nodeId); return (node!=null)?checkRestriction(node,restrictionType,restrictionPath,propertyValue):true; } /** * Checks the local restriction specified by the parameters below * @param nodeId a <code>String</code> node ID * @param restrictionType a restriction type * @param propertyValue a <code>String</code> property value to be checked * @return a boolean value * @exception PortalException if an error occurs */ protected boolean checkRestriction(String nodeId, int restrictionType, String propertyValue ) throws PortalException { return checkRestriction(nodeId, restrictionType, null, propertyValue); } /** * Checks the restriction specified by the parameters below * @param node a <code>ALNode</code> node to be checked * @param restrictionType a restriction type * @param restrictionPath a <code>String</code> restriction path * @param propertyValue a <code>String</code> property value to be checked * @return a boolean value * @exception PortalException if an error occurs */ protected boolean checkRestriction(ALNode node, int restrictionType, String restrictionPath, String propertyValue) throws PortalException { IUserLayoutRestriction restriction = node.getRestriction(UserLayoutRestriction.getRestrictionName(restrictionType,restrictionPath)); if ( restriction != null ) return restriction.checkRestriction(propertyValue); return true; } /** * Moves the nodes to the lost folder if they don't satisfy their restrictions * @exception PortalException if an error occurs */ protected void moveWrongNodesToLostFolder() throws PortalException { moveWrongNodesToLostFolder(rootNodeId,0); } /** * Moves the nodes to the lost folder if they don't satisfy their restrictions * @param nodeId a <code>String</code> node ID * @param depth a depth of the given node * @exception PortalException if an error occurs */ private void moveWrongNodesToLostFolder(String nodeId, int depth) throws PortalException { ALNode node = getLayoutNode(nodeId); // Checking restrictions on the node Vector restrictions = node.getRestrictionsByPath(""); for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); // check other restrictions except priority and depth if ( ( restriction.getRestrictionType() & (RestrictionTypes.DEPTH_RESTRICTION | RestrictionTypes.PRIORITY_RESTRICTION )) == 0 && !restriction.checkRestriction(node) ) { moveNodeToLostFolder(nodeId); break; } } // Checking the depth restriction if ( !checkRestriction(nodeId,RestrictionTypes.DEPTH_RESTRICTION,depth+"") ) { moveNodeToLostFolder(nodeId); } // Checking children related restrictions on the children if they exist restrictions = node.getRestrictionsByPath("children"); boolean isFolder = (node.getNodeType() == IUserLayoutNodeDescription.FOLDER ); if ( isFolder ) { for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); for ( String nextId = ((ALFolder)node).getFirstChildNodeId(); nextId != null; ) { ALNode nextNode = getLayoutNode(nextId); String tmpNodeId = nextNode.getNextNodeId(); if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 && !restriction.checkRestriction(nextNode) ) { moveNodeToLostFolder(nextId); } nextId = tmpNodeId; } } } // Checking parent related restrictions on the parent if it exists String parentNodeId = node.getParentNodeId(); if ( parentNodeId != null ) { restrictions = node.getRestrictionsByPath("parent"); ALNode parentNode = getLayoutNode(parentNodeId); for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 && !restriction.checkRestriction(parentNode) ) { moveNodeToLostFolder(nodeId); break; } } } if ( isFolder ) { ++depth; String firstChildId = ((ALFolder)node).getFirstChildNodeId(); for ( String nextId = firstChildId; nextId != null; ) { ALNode tmpNode = getLayoutNode(nextId); String tmpNodeId = tmpNode.getNextNodeId(); if ( nextId.equals(firstChildId) ) { while ( !changeSiblingNodesOrder(firstChildId) ) moveNodeToLostFolder(getLastSiblingNode(firstChildId).getId()); } moveWrongNodesToLostFolder(nextId,depth); nextId = tmpNodeId; } } } /** * Checks the local restriction specified by the parameters below * @param node a <code>ALNode</code> node to be checked * @param restrictionType a restriction type * @param propertyValue a <code>String</code> property value to be checked * @return a boolean value * @exception PortalException if an error occurs */ protected boolean checkRestriction(ALNode node, int restrictionType, String propertyValue ) throws PortalException { return checkRestriction(node, restrictionType, null, propertyValue); } /** * Checks the necessary restrictions while adding a new node * @param nodeDesc a <code>IALNodeDescription</code> node description of a new node to be added * @param parentId a <code>String</code> parent node ID * @param nextSiblingId a <code>String</code> next sibling node ID * @return a boolean value * @exception PortalException if an error occurs */ private boolean checkAddRestrictions( IALNodeDescription nodeDesc, String parentId, String nextSiblingId ) throws PortalException { String newNodeId = nodeDesc.getId(); ALNode newNode = null; if ( newNodeId == null ) { if ( nodeDesc instanceof IALChannelDescription ) newNode = new ALChannel((IALChannelDescription)nodeDesc); else newNode = new ALFolder((IALFolderDescription)nodeDesc); } else newNode = getLayoutNode(newNodeId); ALNode parentNode = getLayoutNode(parentId); if ( !(parentNode.getNodeType()==IUserLayoutNodeDescription.FOLDER ) ) throw new PortalException ("The target parent node should be a folder!"); //if ( checkRestriction(parentNode,RestrictionTypes.IMMUTABLE_RESTRICTION,"false") ) { if ( !parentNode.getNodeDescription().isImmutable() ) { // Checking children related restrictions Vector restrictions = parentNode.getRestrictionsByPath("children"); for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 && !restriction.checkRestriction(newNode) ) return false; } // Checking parent related restrictions restrictions = newNode.getRestrictionsByPath("parent"); for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 && !restriction.checkRestriction(parentNode) ) return false; } // Considering two cases if the node is new or it is already in the user layout if ( newNodeId != null ) { // Checking depth restrictions for the node and all its descendants (if there are any) if ( !checkDepthRestrictions(newNodeId,parentId) ) return false; } else return checkRestriction(newNode,RestrictionTypes.DEPTH_RESTRICTION,(getDepth(parentId)+1)+""); // Checking sibling nodes order return changeSiblingNodesPriorities(newNode,parentId,nextSiblingId,false); } else return false; } /** * Checks the necessary restrictions while moving a node * @param nodeId a <code>String</code> node ID of a node to be moved * @param newParentId a <code>String</code> new parent node ID * @param nextSiblingId a <code>String</code> next sibling node ID * @return a boolean value * @exception PortalException if an error occurs */ private boolean checkMoveRestrictions( String nodeId, String newParentId, String nextSiblingId ) throws PortalException { ALNode node = getLayoutNode(nodeId); ALNode oldParentNode = getLayoutNode(node.getParentNodeId()); ALNode newParentNode = getLayoutNode(newParentId); /*if ( checkRestriction(oldParentNode,RestrictionTypes.IMMUTABLE_RESTRICTION,"false") && checkRestriction(newParentNode,RestrictionTypes.IMMUTABLE_RESTRICTION,"false") ) {*/ if ( !oldParentNode.getNodeDescription().isImmutable() && !newParentNode.getNodeDescription().isImmutable() ) { if ( !oldParentNode.equals(newParentNode) ) { // Checking children related restrictions Vector restrictions = newParentNode.getRestrictionsByPath("children"); for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 && !restriction.checkRestriction(node) ) return false; } // Checking parent related restrictions restrictions = node.getRestrictionsByPath("parent"); for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 && !restriction.checkRestriction(newParentNode) ) return false; } // Checking depth restrictions for the node and all its descendants if ( !checkDepthRestrictions(nodeId,newParentId) ) return false; } // Checking sibling nodes order return changeSiblingNodesPriorities(node,newParentId,nextSiblingId,false); } else return false; } /** * Checks the necessary restrictions while deleting a node * @param nodeId a <code>String</code> node ID of a node to be deleted * @return a boolean value * @exception PortalException if an error occurs */ private boolean checkDeleteRestrictions( String nodeId ) throws PortalException { ALNode node = getLayoutNode(nodeId); if ( node == null ) return true; //if ( checkRestriction(node.getParentNodeId(),RestrictionTypes.IMMUTABLE_RESTRICTION,"false") ) { if ( !getLayoutNode(node.getParentNodeId()).getNodeDescription().isImmutable() ) { // Checking the unremovable restriction on the node to be deleted //return checkRestriction(nodeId,RestrictionTypes.UNREMOVABLE_RESTRICTION,"false"); return !node.getNodeDescription().isUnremovable(); } else return false; } /** * Recursively checks the depth restrictions beginning with a given node * @param nodeId a <code>String</code> node ID * @param newParentId a <code>String</code> new parent node ID * @return a boolean value * @exception PortalException if an error occurs */ private boolean checkDepthRestrictions(String nodeId,String newParentId) throws PortalException { if ( nodeId == null ) return true; int nodeDepth = getDepth(nodeId); int parentDepth = getDepth(newParentId); if ( nodeDepth == parentDepth+1 ) return true; return checkDepthRestrictions(nodeId,newParentId,nodeDepth); } /** * Recursively checks the depth restrictions beginning with a given node * @param nodeId a <code>String</code> node ID * @param newParentId a <code>String</code> new parent node ID * @param parentDepth a parent depth * @return a boolean value * @exception PortalException if an error occurs */ private boolean checkDepthRestrictions(String nodeId,String newParentId,int parentDepth) throws PortalException { ALNode node = getLayoutNode(nodeId); // Checking restrictions for the node if ( !checkRestriction(nodeId,RestrictionTypes.DEPTH_RESTRICTION,(parentDepth+1)+"") ) return false; if ( node.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { for ( String nextId = ((ALFolder)node).getFirstChildNodeId(); nextId != null; nextId = node.getNextNodeId() ) { node = getLayoutNode(nextId); if ( !checkDepthRestrictions(nextId,node.getParentNodeId(),parentDepth+1) ) return false; } } return true; } /** * Gets the tree depth for a given node * @param nodeId a <code>String</code> node ID * @return a depth value * @exception PortalException if an error occurs */ private int getDepth(String nodeId) throws PortalException { int depth = 0; for ( String parentId = nodeId; parentId != null; parentId = getLayoutNode(parentId).getParentNodeId(), depth++ ); return depth; } /** * Moves the node to the lost folder * @param nodeId a <code>String</code> node ID * @return a boolean value * @exception PortalException if an error occurs */ private boolean moveNodeToLostFolder(String nodeId) throws PortalException { ALFolder lostFolder = getLayoutFolder(lostFolderId); if ( lostFolder == null ) { lostFolder = ALFolder.createLostFolder(); } System.out.println ( "LOST FOLDER node id: " + nodeId ); System.out.println ( "LOST FOLDER parent id: " + getLayoutNode(nodeId).getParentNodeId() ); System.out.println ( "LOST FOLDER next id: " + getLayoutNode(nodeId).getNextNodeId() ); System.out.println ( "LOST FOLDER prev id: " + getLayoutNode(nodeId).getPreviousNodeId() ); // Moving the node to the lost folder return moveNode(nodeId,lostFolder.getId(),null); } /** * Gets the restriction specified by the parameters below * @param node a <code>ALNode</code> node * @param restrictionType a restriction type * @param restrictionPath a <code>String</code> restriction path * @return a <code>IUserLayoutRestriction</code> instance * @exception PortalException if an error occurs */ private static IUserLayoutRestriction getRestriction( ALNode node, int restrictionType, String restrictionPath ) throws PortalException { return node.getRestriction(UserLayoutRestriction.getRestrictionName(restrictionType,restrictionPath)); } /** * Return a priority restriction for the given node. * @return a <code>PriorityRestriction</code> object * @exception PortalException if an error occurs */ public static PriorityRestriction getPriorityRestriction( ALNode node ) throws PortalException { PriorityRestriction priorRestriction = getPriorityRestriction(node,null); if ( priorRestriction == null ) { priorRestriction = (PriorityRestriction) UserLayoutRestrictionFactory.createRestriction(RestrictionTypes.PRIORITY_RESTRICTION,"0-"+java.lang.Integer.MAX_VALUE,null); } return priorRestriction; } /** * Return a priority restriction for the given node. * @return a <code>PriorityRestriction</code> object * @exception PortalException if an error occurs */ private static PriorityRestriction getPriorityRestriction( ALNode node, String restrictionPath ) throws PortalException { return (PriorityRestriction) getRestriction(node,RestrictionTypes.PRIORITY_RESTRICTION,restrictionPath); } /** * Change if it's possible priority values for all the sibling nodes * @param node a <code>String</code> a node from the sibling line * @return a boolean value * @exception PortalException if an error occurs */ protected boolean changeSiblingNodesPriorities ( String nodeId ) throws PortalException { ALNode firstNode = getFirstSiblingNode(nodeId); String parentId = firstNode.getParentNodeId(); for ( String id = firstNode.getId(); id != null; ) { ALNode node = getLayoutNode(id); String nextId = node.getNextNodeId(); if ( !changeSiblingNodesPriorities(node,parentId,nextId,false) ) return false; id = nextId; } return true; } /** * Change if it's possible priority values for all the sibling nodes after trying to add a new node * @param node a <code>String</code> a node to be added * @param parentNodeId a <code>String</code> parent node ID * @param nextNodeId a <code>String</code> next sibling node ID * @param justCheck a boolean * @return a boolean value * @exception PortalException if an error occurs */ protected boolean changeSiblingNodesPriorities(ALNode node, String parentNodeId, String nextNodeId, boolean justCheck ) throws PortalException { ALNode firstNode = null, nextNode = null; String firstNodeId = null; int priority = 0, nextPriority = 0, prevPriority = 0, range[] = null, prevRange[] = null, nextRange[] = null; PriorityRestriction priorityRestriction = null; ALFolder parent = getLayoutFolder(parentNodeId); String nodeId = node.getId(); if ( parentNodeId != null ) { firstNodeId = parent.getFirstChildNodeId(); // if the node is equal the first node in the sibling line we get the next node if ( nodeId.equals(firstNodeId) ) firstNodeId = node.getNextNodeId(); if ( firstNodeId == null ) return true; } else return false; firstNode = getLayoutNode(firstNodeId); if ( nextNodeId != null ) { nextNode = getLayoutNode(nextNodeId); nextPriority = nextNode.getPriority(); priorityRestriction = getPriorityRestriction(nextNode); nextRange = priorityRestriction.getRange(); } priority = node.getPriority(); priorityRestriction = getPriorityRestriction(node); range = priorityRestriction.getRange(); // If we add a new node to the beginning of the sibling line if ( firstNodeId.equals(nextNodeId) ) { if ( range[1] <= nextRange[0] ) return false; if ( priority > nextPriority ) return true; if ( range[1] > nextPriority ) { if ( !justCheck ) node.setPriority(range[1]); return true; } if ( (nextPriority+1) <= range[1] && (nextPriority+1) >= range[0] ) { if ( !justCheck ) node.setPriority(nextPriority+1); return true; } } // If we add a new node to the end of the sibling line if ( nextNode == null ) { // Getting the last node ALNode lastNode = null; for ( String nextId = firstNodeId; nextId != null; ) { lastNode = getLayoutNode(nextId); nextId = lastNode.getNextNodeId(); } // if the node to be added is equal the last node in the sibling line if ( nodeId.equals(lastNode.getId()) ) lastNode = getLayoutNode(lastNode.getPreviousNodeId()); int lastPriority = lastNode.getPriority(); PriorityRestriction lastPriorityRestriction = getPriorityRestriction(lastNode); int[] lastRange = lastPriorityRestriction.getRange(); if ( range[0] >= lastRange[1] ) return false; if ( priority < lastPriority ) return true; if ( range[0] < lastPriority ) { if ( !justCheck ) node.setPriority(range[0]); return true; } if ( (lastPriority-1) <= range[1] && (lastPriority-1) >= range[0] ) { if ( !justCheck ) node.setPriority(lastPriority-1); return true; } } // If we add a new node in a general case if ( nextNode != null && !nextNode.equals(firstNode) ) { // Getting the last node ALNode prevNode = getLayoutNode(nextNode.getPreviousNodeId()); prevPriority = prevNode.getPriority(); PriorityRestriction lastPriorityRestriction = getPriorityRestriction(prevNode); prevRange = lastPriorityRestriction.getRange(); if ( range[1] <= nextRange[0] || range[0] >= prevRange[1] ) return false; if ( priority < prevPriority && priority > nextPriority ) return true; int maxPossibleLowValue = Math.max(range[0],nextPriority+1); int minPossibleHighValue = Math.min(range[1],prevPriority-1); if ( minPossibleHighValue >= maxPossibleLowValue ) { if ( !justCheck ) node.setPriority(minPossibleHighValue); return true; } // the general case } //Vector ranges = new Vector(); Vector priorities = null; if ( !justCheck ) priorities = new Vector(); int tmpPriority = Integer.MAX_VALUE, value; // Fill out the vector by priority values for ( String nextId = firstNodeId; nextId != null; ) { ALNode curNode = getLayoutNode(nextId); // if the node to be added/moved is equal to the current node (it's in the same sibling line) if ( nextId.equals(node.getId()) ) { nextId = curNode.getNextNodeId(); continue; } int[] curRange = (nextId.equals(nextNodeId))?nextRange:getPriorityRestriction(curNode).getRange(); if ( (value = Math.min(curRange[1],tmpPriority-1)) < tmpPriority ) { if ( !justCheck ) priorities.add(new Integer(value)); tmpPriority = value; } else return false; //ranges.add(new int[] { curRange[0], value }); // This is a strange line: if (!nextNodeId.equals(nextId)) nextId = node.getNextNodeId(); nextId = curNode.getNextNodeId(); } if ( !justCheck ) { // Setting priority values to the sibling nodes int i = 0; for ( String nextId = firstNodeId; nextId != null; i++ ) { ALNode curNode = getLayoutNode(nextId); // if the node to be added/moved is equal to the current node (it's in the same sibling line) if ( nextId.equals(node.getId()) ) { nextId = curNode.getNextNodeId(); i continue; } int prior = ((Integer)priorities.get(i)).intValue(); if (nextId.equals(nextNodeId)) nextNode.setPriority(prior); else curNode.setPriority(prior); nextId = curNode.getNextNodeId(); } } // ssss return true; } /** * Change the sibling nodes order depending on their priority values * @param firstNodeId a <code>String</code> first node ID in the sibling line * @return a boolean value * @exception PortalException if an error occurs */ protected boolean changeSiblingNodesOrder(String firstNodeId) throws PortalException { ALNode firstNode = getLayoutNode(firstNodeId); String parentNodeId = firstNode.getParentNodeId(); boolean rightOrder = true; ALNode node = null; for ( String nextNodeId = firstNodeId; nextNodeId != null; ) { node = getLayoutNode(nextNodeId); nextNodeId = node.getNextNodeId(); if ( nextNodeId != null ) { ALNode nextNode = getLayoutNode(nextNodeId); if ( node.getPriority() <= nextNode.getPriority() ) { rightOrder = false; break; } } } if ( rightOrder ) return true; // Check if the current order is right if ( changeSiblingNodesPriorities(firstNodeId) ) return true; // Choosing more suitable order of the nodes in the sibling line ALNode lastNode = getLastSiblingNode(node.getId()); String lastNodeId = lastNode.getId(); for ( String prevNodeId = lastNodeId; prevNodeId != null; ) { for ( String nodeId = lastNodeId; nodeId != null; ) { if ( !nodeId.equals(prevNodeId) ) { if ( moveNode(prevNodeId,parentNodeId,nodeId) ) if ( changeSiblingNodesPriorities(firstNodeId) ) return true; } nodeId = getLayoutNode(nodeId).getPreviousNodeId(); } // Checking the last place in the sibling line if ( moveNode(prevNodeId,parentNodeId,null) ) if ( changeSiblingNodesPriorities(firstNodeId) ) return true; prevNodeId = getLayoutNode(prevNodeId).getPreviousNodeId(); } return false; } /** * Return a cache key, uniqly corresponding to the composition and the structure of the user layout. * * @return a <code>String</code> value * @exception PortalException if an error occurs */ public String getCacheKey() throws PortalException { return null; } /** * Output a tree of a user layout (with appropriate markings) defined by a particular node into * a <code>ContentHandler</code> * @param contentHandler a <code>ContentHandler</code> value * @exception PortalException if an error occurs */ public void getUserLayout(ContentHandler contentHandler) throws PortalException { getUserLayout(rootNodeId,contentHandler); } private void createMarkingLeaf(ContentHandler contentHandler, String leafName, String parentNodeId, String nextNodeId) throws PortalException { try { AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute("","parentID","parentID","CDATA",parentNodeId); attributes.addAttribute("","nextID","nextID","CDATA",CommonUtils.nvl(nextNodeId)); contentHandler.startElement("",leafName,leafName,attributes); contentHandler.endElement("",leafName,leafName); } catch ( SAXException saxe ) { throw new PortalException(saxe.getMessage()); } } private void createMarkingLeaf(Document document, String leafName, String parentNodeId, String nextNodeId, Node node) throws PortalException { try { Element markingLeaf = document.createElement(leafName); markingLeaf.setAttribute("parentID",parentNodeId); markingLeaf.setAttribute("nextID",nextNodeId); node.appendChild(markingLeaf); } catch ( Exception saxe ) { throw new PortalException(saxe.getMessage()); } } /** * Output subtree of a user layout (with appropriate markings) defined by a particular node into * a <code>ContentHandler</code> * * @param nodeId a <code>String</code> a node determining a user layout subtree. * @param ch a <code>ContentHandler</code> value * @exception PortalException if an error occurs */ public void getUserLayout(String nodeId,ContentHandler contentHandler) throws PortalException { IALFolderDescription folderDescription = null; IALChannelDescription channelDescription = null; if ( contentHandler != null && nodeId != null ) { try { ALNode node = getLayoutNode(nodeId); AttributesImpl attributes = new AttributesImpl(); // If we have a folder if ( node.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { // Start document if we have the root node if (nodeId.equals(rootNodeId)) contentHandler.startDocument(); if (nodeId.equals(rootNodeId)) contentHandler.startElement("",LAYOUT,LAYOUT,new AttributesImpl()); ALFolder folder = (ALFolder) node; folderDescription = (IALFolderDescription) node.getNodeDescription(); attributes.addAttribute("","ID","ID","ID",nodeId); attributes.addAttribute("","type","type","CDATA", IUserLayoutFolderDescription.folderTypeNames[folderDescription.getFolderType()]); attributes.addAttribute("","hidden","hidden","CDATA",CommonUtils.boolToStr(folderDescription.isHidden())); attributes.addAttribute("","unremovable","unremovable","CDATA",CommonUtils.boolToStr(folderDescription.isUnremovable())); attributes.addAttribute("","immutable","immutable","CDATA",CommonUtils.boolToStr(folderDescription.isImmutable())); attributes.addAttribute("","name","name","CDATA",folderDescription.getName()); //String tagName = (nodeId.equals(rootNodeId))?LAYOUT:FOLDER; contentHandler.startElement("",FOLDER,FOLDER,attributes); // Loop for all children String firstChildId = folder.getFirstChildNodeId(); for ( String nextNodeId = firstChildId; nextNodeId != null; ) { // if necessary we add marking nodes if ( !node.getNodeDescription().isHidden() && !getLayoutNode(nextNodeId).getNodeDescription().isHidden() ) { if ( addTargetsNodeDesc != null && canAddNode(addTargetsNodeDesc,nodeId,nextNodeId) ) createMarkingLeaf(contentHandler,ADD_TARGET,nodeId,nextNodeId); if ( moveTargetsNodeId != null && canMoveNode(moveTargetsNodeId,nodeId,nextNodeId) ) createMarkingLeaf(contentHandler,MOVE_TARGET,nodeId,nextNodeId); } getUserLayout(nextNodeId,contentHandler); nextNodeId = getLayoutNode(nextNodeId).getNextNodeId(); } // if necessary we add marking nodes at the end of the sibling line if ( !node.getNodeDescription().isHidden() ) { if ( addTargetsNodeDesc != null && canAddNode(addTargetsNodeDesc,nodeId,null) ) createMarkingLeaf(contentHandler,ADD_TARGET,nodeId,null); if ( moveTargetsNodeId != null && canMoveNode(moveTargetsNodeId,nodeId,null) ) createMarkingLeaf(contentHandler,MOVE_TARGET,nodeId,null); } // Putting restrictions to the content handler if ( restrictionMask > 0 ) bindRestrictions(folderDescription,contentHandler); contentHandler.endElement("",FOLDER,FOLDER); // Start document if we have the root node if (nodeId.equals(rootNodeId)) contentHandler.endElement("",LAYOUT,LAYOUT); if (nodeId.equals(rootNodeId)) contentHandler.endDocument(); // If we have a channel } else { channelDescription = (IALChannelDescription) node.getNodeDescription(); attributes.addAttribute("","ID","ID","ID",nodeId); attributes.addAttribute("","typeID","typeID","CDATA",channelDescription.getChannelTypeId()); attributes.addAttribute("","hidden","hidden","CDATA",CommonUtils.boolToStr(channelDescription.isHidden())); attributes.addAttribute("","editable","editable","CDATA",CommonUtils.boolToStr(channelDescription.isEditable())); attributes.addAttribute("","unremovable","unremovable","CDATA",CommonUtils.boolToStr(channelDescription.isUnremovable())); attributes.addAttribute("","immutable","immutable","CDATA",CommonUtils.boolToStr(channelDescription.isImmutable())); attributes.addAttribute("","name","name","CDATA",channelDescription.getName()); attributes.addAttribute("","description","description","CDATA",channelDescription.getDescription()); attributes.addAttribute("","title","title","CDATA",channelDescription.getTitle()); attributes.addAttribute("","class","class","CDATA",channelDescription.getClassName()); attributes.addAttribute("","chanID","chanID","CDATA",channelDescription.getChannelPublishId()); attributes.addAttribute("","fname","fname","CDATA",channelDescription.getFunctionalName()); attributes.addAttribute("","timeout","timeout","CDATA",String.valueOf(channelDescription.getTimeout())); attributes.addAttribute("","hasHelp","hasHelp","CDATA",CommonUtils.boolToStr(channelDescription.hasHelp())); attributes.addAttribute("","hasAbout","hasAbout","CDATA",CommonUtils.boolToStr(channelDescription.hasAbout())); contentHandler.startElement("",CHANNEL,CHANNEL,attributes); if ( channelDescription.hasParameters() ) { Enumeration paramNames = channelDescription.getParameterNames(); while ( paramNames.hasMoreElements() ) { String name = (String) paramNames.nextElement(); String value = channelDescription.getParameterValue(name); AttributesImpl paramAttrs = new AttributesImpl(); paramAttrs.addAttribute("","name","name","CDATA",name); paramAttrs.addAttribute("","value","value","CDATA",value); paramAttrs.addAttribute("","override","override","CDATA", channelDescription.canOverrideParameter(name)?"yes":"no"); contentHandler.startElement("",PARAMETER,PARAMETER,paramAttrs); contentHandler.endElement("",PARAMETER,PARAMETER); } } // Putting restrictions to the content handler if ( restrictionMask > 0 ) bindRestrictions(channelDescription,contentHandler); contentHandler.endElement("",CHANNEL,CHANNEL); } } catch ( SAXException saxe ) { throw new PortalException(saxe.getMessage()); } } } private void bindRestrictions( IALNodeDescription nodeDesc, ContentHandler contentHandler ) throws SAXException { Hashtable restrictions = nodeDesc.getRestrictions(); for ( Enumeration e = restrictions.keys(); e.hasMoreElements(); ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction ) e.nextElement(); if ( ( restriction.getRestrictionType() & restrictionMask ) > 0 ) { AttributesImpl paramAttrs = new AttributesImpl(); paramAttrs.addAttribute("","path","path","CDATA",restriction.getRestrictionPath()); // we have to re-scale the priority restriction for the UI if ( ( restriction.getRestrictionType() & RestrictionTypes.PRIORITY_RESTRICTION ) > 0 ) { PriorityRestriction priorRestriction = (PriorityRestriction) restriction; paramAttrs.addAttribute("","value","value","CDATA",((int)priorRestriction.getMinValue()/PRIORITY_COEFF)+"-"+ ((int)priorRestriction.getMaxValue()/PRIORITY_COEFF)); } else paramAttrs.addAttribute("","value","value","CDATA",restriction.getRestrictionExpression()); paramAttrs.addAttribute("","type","type","CDATA",restriction.getRestrictionType()+""); contentHandler.startElement("",RESTRICTION,RESTRICTION,paramAttrs); contentHandler.endElement("",RESTRICTION,RESTRICTION); } } } private ALNode getLayoutNode(String nodeId) { try { return (ALNode)layout.get(nodeId); } catch ( Exception e ) { return null; } } private ALFolder getLayoutFolder(String folderId) { try { return (ALFolder)layout.get(folderId); } catch (Exception e ) { return null; } } private ALNode getLastSiblingNode ( String nodeId ) { ALNode node = null; for ( String nextId = nodeId; nextId != null; ) { node = getLayoutNode(nextId); nextId = node.getNextNodeId(); } return node; } private ALNode getFirstSiblingNode ( String nodeId ) { ALNode node = null; for ( String prevId = nodeId; prevId != null; ) { node = getLayoutNode(prevId); prevId = node.getPreviousNodeId(); } return node; } /** * Build the DOM consistent of folders and channels using the internal representation * @param domLayout a <code>Document</code> a user layout document. * @param node a <code>Element</code> a node that will be used as a root for the tree construction * @param nodeId a <code>String</code> a nodeId from the user layout internal representation * @exception PortalException if an error occurs */ private void appendDescendants(Document domLayout,Node node, String nodeId) throws PortalException { ALNode layoutNode = getLayoutNode(nodeId); IALNodeDescription nodeDesc = layoutNode.getNodeDescription(); Element markingMoveLeaf = null, markingAddLeaf = null; Element newNode = domLayout.createElement((layoutNode.getNodeType()==IUserLayoutNodeDescription.FOLDER)?FOLDER:CHANNEL); layoutNode.addNodeAttributes(newNode); String parentId = layoutNode.getParentNodeId(); String nextId = layoutNode.getNextNodeId(); // If the node is the first node in the sibling line if ( parentId != null && layoutNode.getPreviousNodeId() == null ) { if ( !layoutNode.getNodeDescription().isHidden() && !getLayoutNode(parentId).getNodeDescription().isHidden() ) { if ( addTargetsNodeDesc != null && canAddNode(addTargetsNodeDesc,parentId,nodeId) ) createMarkingLeaf(domLayout,ADD_TARGET,parentId,nodeId,node); if ( moveTargetsNodeId != null && canMoveNode(moveTargetsNodeId,parentId,nodeId) ) createMarkingLeaf(domLayout,MOVE_TARGET,parentId,nodeId,node); } } // Appending a new node node.appendChild(newNode); if ( parentId != null ) { boolean isNodeMarkable = false; if ( nextId != null && !getLayoutNode(nextId).getNodeDescription().isHidden() ) isNodeMarkable = true; else if ( nextId == null ) isNodeMarkable = true; if ( isNodeMarkable && !getLayoutNode(parentId).getNodeDescription().isHidden() ) { if ( addTargetsNodeDesc != null && canAddNode(addTargetsNodeDesc,parentId,nextId) ) createMarkingLeaf(domLayout,ADD_TARGET,parentId,nextId,node); if ( moveTargetsNodeId != null && canMoveNode(moveTargetsNodeId,parentId,nextId) ) createMarkingLeaf(domLayout,MOVE_TARGET,parentId,nextId,node); } } // Adding restrictions to the node nodeDesc.addRestrictionChildren(newNode,domLayout); if ( layoutNode.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { // Loop for all children String firstChildId = ((ALFolder)layoutNode).getFirstChildNodeId(); for ( String nextNodeId = firstChildId; nextNodeId != null; ) { appendDescendants(domLayout,newNode,nextNodeId); nextNodeId = getLayoutNode(nextNodeId).getNextNodeId(); } } else if ( layoutNode.getNodeType() == IUserLayoutNodeDescription.CHANNEL ) { ALChannelDescription channelDesc = (ALChannelDescription) nodeDesc; // Adding channel parameters channelDesc.addParameterChildren(newNode,domLayout); } } public Document getUserLayoutDOM() throws PortalException { try { Document domLayout = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element layoutNode = domLayout.createElement(LAYOUT); domLayout.appendChild(layoutNode); // Build the DOM appendDescendants(domLayout,layoutNode,rootNodeId); return domLayout; } catch ( Exception e ) { e.printStackTrace(); throw new PortalException ("Couldn't create the DOM representation: " + e ); } } private void setUserLayoutDOM( Node n, String parentNodeId ) throws PortalException { Element node = (Element) n; NodeList childNodes = node.getChildNodes(); IALNodeDescription nodeDesc = ALNode.createUserLayoutNodeDescription(node); String nodeId = node.getAttribute("ID"); nodeDesc.setId(nodeId); nodeDesc.setName(node.getAttribute("name")); nodeDesc.setFragmentId(node.getAttribute("fragmentID")); nodeDesc.setHidden(CommonUtils.strToBool(node.getAttribute("hidden"))); nodeDesc.setImmutable(CommonUtils.strToBool(node.getAttribute("immutable"))); nodeDesc.setUnremovable(CommonUtils.strToBool(node.getAttribute("unremovable"))); nodeDesc.setHidden(CommonUtils.strToBool(node.getAttribute("hidden"))); ALNode layoutNode = null; IALChannelDescription channelDesc = null; if (nodeDesc instanceof IALChannelDescription) channelDesc = (IALChannelDescription) nodeDesc; // Getting parameters and restrictions for ( int i = 0; i < childNodes.getLength(); i++ ) { Node childNode = childNodes.item(i); String nodeName = childNode.getNodeName(); NamedNodeMap attributes = childNode.getAttributes(); if ( PARAMETER.equals(nodeName) && channelDesc != null ) { Node paramNameNode = attributes.getNamedItem("name"); String paramName = (paramNameNode!=null)?paramNameNode.getFirstChild().getNodeValue():null; Node paramValueNode = attributes.getNamedItem("value"); String paramValue = (paramValueNode!=null)?paramValueNode.getFirstChild().getNodeValue():null; Node overParamNode = attributes.getNamedItem("override"); String overParam = (overParamNode!=null)?overParamNode.getFirstChild().getNodeValue():null; if ( paramName != null ) { channelDesc.setParameterValue(paramName, paramValue); channelDesc.setParameterOverride(paramName, "yes".equalsIgnoreCase(overParam)?true:false); } } else if ( RESTRICTION.equals(nodeName) ) { Node restrPathNode = attributes.getNamedItem("path"); String restrPath = (restrPathNode!=null)?restrPathNode.getFirstChild().getNodeValue():null; Node restrValueNode = attributes.getNamedItem("value"); String restrValue = (restrValueNode!=null)?restrValueNode.getFirstChild().getNodeValue():null; Node restrTypeNode = attributes.getNamedItem("type"); String restrType = (restrTypeNode!=null)?restrTypeNode.getFirstChild().getNodeValue():"0"; if ( restrValue != null ) { IUserLayoutRestriction restriction = UserLayoutRestrictionFactory.createRestriction(CommonUtils.parseInt(restrType),restrValue,restrPath); nodeDesc.addRestriction(restriction); } } } if ( channelDesc != null ) { channelDesc.setChannelPublishId(node.getAttribute("chanID")); channelDesc.setChannelTypeId(node.getAttribute("typeID")); channelDesc.setClassName(node.getAttribute("class")); channelDesc.setDescription(node.getAttribute("description")); channelDesc.setEditable(CommonUtils.strToBool(node.getAttribute("editable"))); channelDesc.setHasAbout(CommonUtils.strToBool(node.getAttribute("hasAbout"))); channelDesc.setHasHelp(CommonUtils.strToBool(node.getAttribute("hasHelp"))); channelDesc.setFunctionalName(node.getAttribute("fname")); channelDesc.setTimeout(Long.parseLong(node.getAttribute("timeout"))); channelDesc.setTitle(node.getAttribute("title")); // Adding to the layout layoutNode = new ALChannel(channelDesc); } else { layoutNode = new ALFolder((IALFolderDescription)nodeDesc); } // Setting priority value layoutNode.setPriority(CommonUtils.parseInt(node.getAttribute("priority"),0)); ALFolder parentFolder = getLayoutFolder(parentNodeId); // Binding the current node to the parent child list and parentNodeId to the current node if ( parentFolder != null ) { //parentFolder.addChildNode(nodeDesc.getId()); layoutNode.setParentNodeId(parentNodeId); } Element nextNode = (Element) node.getNextSibling(); Element prevNode = (Element) node.getPreviousSibling(); if ( nextNode != null && isNodeFolderOrChannel(nextNode) ) layoutNode.setNextNodeId(nextNode.getAttribute("ID")); if ( prevNode != null && isNodeFolderOrChannel(prevNode) ) layoutNode.setPreviousNodeId(prevNode.getAttribute("ID") ); // Setting the first child node ID if ( layoutNode.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { String id = ((Element)node.getFirstChild()).getAttribute("ID"); if ( id != null && id.length() > 0 ) ((ALFolder)layoutNode).setFirstChildNodeId(id); } // Putting the LayoutNode object into the layout layout.put(nodeDesc.getId(), layoutNode); // Recurrence for all children for ( int i = 0; i < childNodes.getLength() && (layoutNode.getNodeType()==IUserLayoutNodeDescription.FOLDER); i++ ) { Element childNode = (Element) childNodes.item(i); if ( isNodeFolderOrChannel ( childNode ) ) setUserLayoutDOM ( childNode, nodeDesc.getId() ); } } public void setUserLayoutDOM( Document domLayout ) throws PortalException { layout.clear(); Element rootNode = (Element) domLayout.getDocumentElement().getFirstChild(); ALFolder rootFolder = new ALFolder((IALFolderDescription)ALNode.createUserLayoutNodeDescription(rootNode)); rootFolder.setFirstChildNodeId(((Element)rootNode.getFirstChild()).getAttribute("ID")); layout.put(ROOT_FOLDER_ID,rootFolder); NodeList childNodes = rootNode.getChildNodes(); for ( int i = 0; i < childNodes.getLength(); i++ ) setUserLayoutDOM ( childNodes.item(i), rootNodeId ); } private boolean isNodeFolderOrChannel ( Element node ) { String nodeName = node.getNodeName(); return ( FOLDER.equals(nodeName) || CHANNEL.equals(nodeName) ); } public void setLayoutStore(IUserLayoutStore layoutStore ) { this.layoutStore = (IAggregatedUserLayoutStore) layoutStore; } public void loadUserLayout() throws PortalException { try { if ( layoutStore != null ) { layout = (Hashtable) layoutStore.getAggregatedUserLayout(person,userProfile); // Checking restrictions and move "wrong" nodes to the lost folder moveWrongNodesToLostFolder(); } } catch ( Exception e ) { e.printStackTrace(); throw new PortalException(e.getMessage()); } } public void saveUserLayout() throws PortalException { try { layoutStore.setAggregatedUserLayout(this.person,this.userProfile,this.layout); } catch ( Exception e ) { e.printStackTrace(); throw new PortalException(e.getMessage()); } } public IUserLayoutNodeDescription getNode(String nodeId) throws PortalException { return getLayoutNode(nodeId).getNodeDescription(); } public synchronized boolean moveNode(String nodeId, String parentId,String nextSiblingId) throws PortalException { // Checking restrictions if the parent is not the lost folder if ( !parentId.equals(IALFolderDescription.LOST_FOLDER_ID) ) if ( !canMoveNode(nodeId,parentId,nextSiblingId) ) return false; ALNode node = getLayoutNode(nodeId); ALFolder targetFolder = getLayoutFolder(parentId); ALFolder sourceFolder = getLayoutFolder(node.getParentNodeId()); String sourcePrevNodeId = node.getPreviousNodeId(); String sourceNextNodeId = node.getNextNodeId(); ALNode targetNextNode = getLayoutNode(nextSiblingId); ALNode targetPrevNode = null, sourcePrevNode = null, sourceNextNode = null; String prevSiblingId = null; // If the nextNode != null we calculate the prev node from it otherwise we have to run to the last node in the sibling line if ( targetNextNode != null ) targetPrevNode = getLayoutNode(targetNextNode.getPreviousNodeId()); else targetPrevNode = getLastSiblingNode(targetFolder.getFirstChildNodeId()); if ( targetPrevNode != null ) { targetPrevNode.setNextNodeId(nodeId); prevSiblingId = targetPrevNode.getId(); } // Changing the previous node id for the new next sibling node if ( targetNextNode != null ) targetNextNode.setPreviousNodeId(nodeId); if ( nodeId.equals(sourceFolder.getFirstChildNodeId()) ) { // Set the new first child node ID to the source folder sourceFolder.setFirstChildNodeId(node.getNextNodeId()); } if ( CommonUtils.nvl(targetFolder.getFirstChildNodeId()).equals(nextSiblingId) ) { // Set the new first child node ID to the target folder targetFolder.setFirstChildNodeId(nodeId); } // Set the new next node ID for the source previous node if ( sourcePrevNodeId != null ) { sourcePrevNode = getLayoutNode(sourcePrevNodeId); sourcePrevNode.setNextNodeId(sourceNextNodeId); } // Set the new previous node ID for the source next node if ( sourceNextNodeId != null ) { sourceNextNode = getLayoutNode(sourceNextNodeId); sourceNextNode.setPreviousNodeId(sourcePrevNodeId); } node.setParentNodeId(parentId); node.setNextNodeId(nextSiblingId); node.setPreviousNodeId(prevSiblingId); // TO UPDATE THE APPROPRIATE INFO IN THE DB // TO BE DONE !!!!!!!!!!! boolean result = false; if ( autoCommit ) { if ( sourcePrevNode != null ) result &= layoutStore.updateUserLayoutNode(person,userProfile,sourcePrevNode); if ( sourceNextNode != null ) result &= layoutStore.updateUserLayoutNode(person,userProfile,sourceNextNode); if ( targetPrevNode != null ) result &= layoutStore.updateUserLayoutNode(person,userProfile,targetPrevNode); if ( targetNextNode != null ) result &= layoutStore.updateUserLayoutNode(person,userProfile,targetNextNode); result &= layoutStore.updateUserLayoutNode(person,userProfile,targetFolder); result &= layoutStore.updateUserLayoutNode(person,userProfile,sourceFolder); // Changing the node being moved result &= layoutStore.updateUserLayoutNode(person,userProfile,node); return result; } return true; } public synchronized boolean deleteNode(String nodeId) throws PortalException { if ( nodeId == null ) return false; ALNode node = getLayoutNode(nodeId); if ( node == null ) return false; // Checking restrictions if ( !canDeleteNode(nodeId) ) { System.out.println ( "The node with ID = '" + nodeId + "' cannot be deleted" ); return false; } // Deleting the node from the parent ALFolder parentFolder = getLayoutFolder(node.getParentNodeId()); boolean result = false; //parentNode.deleteChildNode(nodeId); if ( nodeId.equals(parentFolder.getFirstChildNodeId()) ) { // Set the new first child node ID to the source folder parentFolder.setFirstChildNodeId(node.getNextNodeId()); // Update it in the database if ( autoCommit ) result = layoutStore.updateUserLayoutNode(person,userProfile,parentFolder); } // Changing the next node id for the previous sibling node // and the previous node for the next sibling node String prevSiblingId = node.getPreviousNodeId(); String nextSiblingId = node.getNextNodeId(); if ( prevSiblingId != null ) { ALNode prevNode = getLayoutNode(prevSiblingId); prevNode.setNextNodeId(nextSiblingId); if ( autoCommit ) result = layoutStore.updateUserLayoutNode(person,userProfile,prevNode); } if ( nextSiblingId != null ) { ALNode nextNode = getLayoutNode(nextSiblingId); nextNode.setPreviousNodeId(prevSiblingId); if ( autoCommit ) result = layoutStore.updateUserLayoutNode(person,userProfile,nextNode); } // DELETE THE NODE FROM THE DB if ( autoCommit ) result = layoutStore.deleteUserLayoutNode(person,userProfile,node); // Deleting the nodefrom the hashtable and returning the result value result = (layout.remove(nodeId)!=null) && ((autoCommit)?result:true); System.out.println( "Deleting result: " + result ); return ( result ); } public synchronized IUserLayoutNodeDescription addNode(IUserLayoutNodeDescription nodeDesc, String parentId,String nextSiblingId) throws PortalException { // Checking restrictions if ( !canAddNode(nodeDesc,parentId,nextSiblingId) ) return null; ALFolder parentFolder = getLayoutFolder(parentId); ALNode nextNode = getLayoutNode(nextSiblingId); ALNode prevNode = null; // If the nextNode != null we calculate the prev node from it otherwise we have to run to the last node in the sibling line if ( nextNode != null ) prevNode = getLayoutNode(nextNode.getPreviousNodeId()); else prevNode = getLastSiblingNode(parentFolder.getFirstChildNodeId()); ALNode layoutNode=ALNode.createALNode(nodeDesc); // Setting the parent node ID layoutNode.setParentNodeId(parentId); if ( prevNode != null ) layoutNode.setPreviousNodeId(prevNode.getId()); if ( nextNode != null ) layoutNode.setNextNodeId(nextSiblingId); // Add the new node to the database and get the node with a new node ID layoutNode = layoutStore.addUserLayoutNode(person,userProfile,layoutNode); String nodeId = layoutNode.getId(); // Putting the new node into the hashtable layout.put(nodeId,layoutNode); if ( prevNode != null ) prevNode.setNextNodeId(nodeId); if ( nextNode != null ) nextNode.setPreviousNodeId(nodeId); // Setting new child node ID to the parent node if ( nextSiblingId != null && nextSiblingId.equals(parentFolder.getFirstChildNodeId()) ) parentFolder.setFirstChildNodeId(nodeId); // TO UPDATE ALL THE NEIGHBOR NODES IN THE DATABASE if ( nextNode != null ) layoutStore.updateUserLayoutNode(person,userProfile,nextNode); if ( prevNode != null ) layoutStore.updateUserLayoutNode(person,userProfile,prevNode); // Update the parent node layoutStore.updateUserLayoutNode(person,userProfile,parentFolder); return layoutNode.getNodeDescription(); } private void changeDescendantsBooleanProperties (IALNodeDescription nodeDesc,IALNodeDescription oldNodeDesc, String nodeId) throws PortalException { changeDescendantsBooleanProperties(nodeDesc.isHidden()==oldNodeDesc.isHidden(),nodeDesc.isImmutable()==oldNodeDesc.isImmutable(), nodeDesc.isUnremovable()==oldNodeDesc.isUnremovable(),nodeDesc,nodeId); } private void changeDescendantsBooleanProperties (boolean hiddenValuesMatch, boolean immutableValuesMatch, boolean unremovableValuesMatch, IALNodeDescription nodeDesc, String nodeId) throws PortalException { ALNode node = getLayoutNode(nodeId); if ( node.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { // Loop for all children String firstChildId = ((ALFolder)node).getFirstChildNodeId(); for ( String nextNodeId = firstChildId; nextNodeId != null; ) { ALNode currentNode = getLayoutNode(nextNodeId); // Checking the hidden property if it's changed if ( !hiddenValuesMatch ) { // Checking the hidden node restriction boolean canChange = checkRestriction(currentNode,RestrictionTypes.HIDDEN_RESTRICTION,CommonUtils.boolToStr(nodeDesc.isHidden())); // Checking the hidden parent node related restriction canChange &= checkRestriction(currentNode.getParentNodeId(),RestrictionTypes.HIDDEN_RESTRICTION,"children",CommonUtils.boolToStr(nodeDesc.isHidden())); // Checking the hidden children node related restrictions if ( currentNode.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { ALFolder folder = (ALFolder) node; //Loop for all children for ( String nextId = folder.getFirstChildNodeId(); nextId != null; nextId = getLayoutNode(nextId).getNextNodeId() ) canChange &= checkRestriction(nextId,RestrictionTypes.HIDDEN_RESTRICTION,"parent",CommonUtils.boolToStr(nodeDesc.isHidden())); } // Changing the hidden value if canChange is true if ( canChange ) currentNode.getNodeDescription().setHidden(nodeDesc.isHidden()); } // Checking the immutable property if it's changed if ( !immutableValuesMatch ) { // Checking the immutable node restriction boolean canChange = checkRestriction(currentNode,RestrictionTypes.IMMUTABLE_RESTRICTION,CommonUtils.boolToStr(nodeDesc.isImmutable())); // Checking the immutable parent node related restriction canChange &= checkRestriction(currentNode.getParentNodeId(),RestrictionTypes.IMMUTABLE_RESTRICTION,"children",CommonUtils.boolToStr(nodeDesc.isImmutable())); // Checking the immutable children node related restrictions if ( currentNode.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { ALFolder folder = (ALFolder) node; //Loop for all children for ( String nextId = folder.getFirstChildNodeId(); nextId != null; nextId = getLayoutNode(nextId).getNextNodeId() ) canChange &= checkRestriction(nextId,RestrictionTypes.IMMUTABLE_RESTRICTION,"parent",CommonUtils.boolToStr(nodeDesc.isImmutable())); } // Changing the immutable value if canChange is true if ( canChange ) currentNode.getNodeDescription().setImmutable(nodeDesc.isImmutable()); } // Checking the unremovable property if it's changed if ( !unremovableValuesMatch ) { // Checking the unremovable node restriction boolean canChange = checkRestriction(currentNode,RestrictionTypes.UNREMOVABLE_RESTRICTION,CommonUtils.boolToStr(nodeDesc.isUnremovable())); // Checking the unremovable parent node related restriction canChange &= checkRestriction(currentNode.getParentNodeId(),RestrictionTypes.UNREMOVABLE_RESTRICTION,"children",CommonUtils.boolToStr(nodeDesc.isUnremovable())); // Checking the unremovable children node related restrictions if ( currentNode.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { ALFolder folder = (ALFolder) node; //Loop for all children for ( String nextId = folder.getFirstChildNodeId(); nextId != null; nextId = getLayoutNode(nextId).getNextNodeId() ) canChange &= checkRestriction(nextId,RestrictionTypes.UNREMOVABLE_RESTRICTION,"parent",CommonUtils.boolToStr(nodeDesc.isImmutable())); } // Changing the unremovable value if canChange is true if ( canChange ) currentNode.getNodeDescription().setUnremovable(nodeDesc.isUnremovable()); } /// Recurrence changeDescendantsBooleanProperties(hiddenValuesMatch,immutableValuesMatch,unremovableValuesMatch,nodeDesc,nextNodeId); nextNodeId = currentNode.getNextNodeId(); } } } public synchronized boolean updateNode(IUserLayoutNodeDescription nodeDesc) throws PortalException { // Checking restrictions if ( !canUpdateNode(nodeDesc) ) return false; ALNode node = getLayoutNode(nodeDesc.getId()); IALNodeDescription oldNodeDesc = node.getNodeDescription(); // We have to change all the boolean properties on descendants changeDescendantsBooleanProperties((IALNodeDescription)nodeDesc,oldNodeDesc,nodeDesc.getId()); node.setNodeDescription((IALNodeDescription)nodeDesc); // Update the node into the database if ( autoCommit ) return layoutStore.updateUserLayoutNode(person,userProfile,node); else return true; } public boolean canAddNode(IUserLayoutNodeDescription nodeDesc, String parentId, String nextSiblingId) throws PortalException { return checkAddRestrictions((IALNodeDescription)nodeDesc,parentId,nextSiblingId); } public boolean canMoveNode(String nodeId, String parentId, String nextSiblingId) throws PortalException { return checkMoveRestrictions(nodeId,parentId,nextSiblingId); } public boolean canDeleteNode(String nodeId) throws PortalException { return checkDeleteRestrictions(nodeId); } public boolean canUpdateNode(IUserLayoutNodeDescription nodeDescription) throws PortalException { IALNodeDescription nodeDesc=(IALNodeDescription)nodeDescription; String nodeId = nodeDesc.getId(); if ( nodeId == null ) return false; ALNode node = getLayoutNode(nodeId); IALNodeDescription currentNodeDesc = node.getNodeDescription(); // If the node Ids do no match to each other then return false if ( !nodeId.equals(currentNodeDesc.getId()) ) return false; // Checking the immutable node restriction //if ( checkRestriction(node,RestrictionTypes.IMMUTABLE_RESTRICTION,"true") ) if ( currentNodeDesc.isImmutable() ) return false; // Checking the immutable parent node related restriction if ( getRestriction(getLayoutNode(node.getParentNodeId()),RestrictionTypes.IMMUTABLE_RESTRICTION,"children") != null && checkRestriction(node.getParentNodeId(),RestrictionTypes.IMMUTABLE_RESTRICTION,"children","true") ) return false; // Checking the immutable children node related restrictions if ( node.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { ALFolder folder = (ALFolder) node; //Loop for all children for ( String nextId = folder.getFirstChildNodeId(); nextId != null; nextId = getLayoutNode(nextId).getNextNodeId() ) if ( getRestriction(getLayoutNode(nextId),RestrictionTypes.IMMUTABLE_RESTRICTION,"parent") != null && checkRestriction(nextId,RestrictionTypes.IMMUTABLE_RESTRICTION,"parent","true") ) return false; } // if a new node description doesn't contain any restrictions the old restrictions will be used if ( nodeDesc.getRestrictions() == null ) nodeDesc.setRestrictions(currentNodeDesc.getRestrictions()); Hashtable rhash = nodeDesc.getRestrictions(); // Setting the new node description to the node node.setNodeDescription(nodeDesc); // Checking restrictions for the node if ( rhash != null ) { for ( Enumeration enum = rhash.elements(); enum.hasMoreElements(); ) if ( !((IUserLayoutRestriction)enum.nextElement()).checkRestriction(node) ) { node.setNodeDescription(currentNodeDesc); return false; } } // Checking parent related restrictions for the children Vector restrictions = getLayoutNode(node.getParentNodeId()).getRestrictionsByPath("children"); for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); if ( !restriction.checkRestriction(node) ) { node.setNodeDescription(currentNodeDesc); return false; } } // Checking child related restrictions for the parent if ( node.getNodeType() == IUserLayoutNodeDescription.FOLDER ) { for ( String nextId = ((ALFolder)node).getFirstChildNodeId(); nextId != null; ) { ALNode child = getLayoutNode(nextId); restrictions = child.getRestrictionsByPath("parent"); for ( int i = 0; i < restrictions.size(); i++ ) { IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i); if ( !restriction.checkRestriction(node) ) { node.setNodeDescription(currentNodeDesc); return false; } } nextId = child.getNextNodeId(); } } return true; } public void markAddTargets(IUserLayoutNodeDescription nodeDesc) { addTargetsNodeDesc = (IALNodeDescription)nodeDesc; //addTargetsAllowed = (nodeDesc!=null); } public void markMoveTargets(String nodeId) throws PortalException { moveTargetsNodeId = nodeId; //moveTargetsAllowed = (getLayoutNode(nodeId)!=null); } /** * Sets a restriction mask that logically multiplies one of the types from <code>RestrictionTypes</code> and * is responsible for filtering restrictions for the layout output to ContentHandler or DOM * @param restrictionMask a restriction mask */ public void setRestrictionMask (int restrictionMask) { this.restrictionMask = restrictionMask; } public boolean addLayoutEventListener(LayoutEventListener l){ return false; } public boolean removeLayoutEventListener(LayoutEventListener l){ return false; } /** * Returns an id of the root folder. * * @return a <code>String</code> value */ public String getRootFolderId() { return ROOT_FOLDER_ID; } }
//package declaration package model.objects.painting; //import declarations import java.awt.Color; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import control.ContorlPicture; import control.ControlPaintSelectin; import control.tabs.CTabSelection; import view.forms.Console; import view.forms.Message; import view.forms.Page; import view.tabs.Insert; import view.tabs.Debug; import model.objects.PictureOverview; import model.objects.history.HistorySession; import model.objects.painting.po.POInsertion; import model.objects.painting.po.PaintObject; import model.objects.painting.po.PaintObjectImage; import model.objects.painting.po.PaintObjectPen; import model.objects.painting.po.PaintObjectWriting; import model.objects.painting.po.diag.PODiagramm; import model.objects.painting.po.geo.POArch; import model.objects.painting.po.geo.POArchFilled; import model.objects.painting.po.geo.POCurve; import model.objects.painting.po.geo.POLine; import model.objects.painting.po.geo.PORectangle; import model.objects.painting.po.geo.POTriangle; import model.objects.painting.po.geo.POTriangleFilled; import model.objects.painting.po.geo.PoRectangleFilled; import model.objects.pen.Pen; import model.objects.pen.normal.BallPen; import model.objects.pen.normal.Pencil; import model.objects.pen.special.PenSelection; import model.settings.Constants; import model.settings.Status; import model.util.DPoint; import model.util.Util; import model.util.adt.list.SecureList; import model.util.adt.list.SecureListSort; import model.util.paint.Utils; /** * Picture class which contains all the not selected and selected painted items * contained in two lists of PaintObjects. * * It handles the creation, changing and removing of PaintObjects, selection * methods, * * @author Julius Huelsmann * @version %I%, %U% */ public final class Picture implements Serializable { /** * Default serial version UID for being able to identify the list's * version if saved to the disk and check whether it is possible to * load it or whether important features have been added so that the * saved file is out-dated. */ private static final long serialVersionUID = 29882073145378042L; /** * List of PaintObjects into which all non-selected paintObjects are added * sorted by their x coordinate. */ private SecureListSort<PaintObject> ls_po_sortedByX; /** * List of PaintObjects which contains all currently selected items. * These items have to be saved somewhere outside the first list because * they can be transformed or removed. */ private SecureList<PaintObject> ls_poSelected; /** * Current PaintObjectPen which can be altered and afterwards inserted into * the list of PaintObjects sorted by X. * * If an image is inserted from clipboard or an existing PaintObjectPen is * transformed into an image, that can be done directly e.g. by using the * addPaintObjectImage method. This can not be done with the PaintObjectPens * because their creation is a continued process (the user draws a line; * first the PaintObjectPen has to be created, afterwards points are added * to the PaintObjectPen. When the user released the mouse, the paintObject * is added to list of paintObjects and the PaintObjectPen po_current is * reset to null. */ private PaintObjectPen po_current; /** * The currently selected pen with which the current PaintObjectPen is * painted to the screen. Because of this, pen_current is copied and * afterwards given to new created PaintObject. */ private Pen pen_current; /** * Current id of following PaintObject. Is given to the PaintObjectPen and * increased afterwards. If the user removes PaintObjects the id is not * decreased; there may occur gaps in id. */ private int currentId; /** * The history. */ private HistorySession history; /** * Empty utility class constructor because the Picture instance has to exist * in process of initialization of Picture attributes. */ public Picture() { } /** * Initialization method of class Picture. Calls the reload() method which * creates a new instance of sorted PaintObject list and sets up the * currentID. */ public void initialize(HistorySession _history) { this.history = _history; reload(); } /** * The reload method creates a new instance of sorted PaintObject list and * sets up the currentID. This method is called in initialization process * and if the user creates a new page or loads a file that does only consist * of images (e.g. in PNG of PDF format). */ public void reload() { // initialize both lists ordered by this.ls_po_sortedByX = new SecureListSort<PaintObject>(); // save current id this.currentId = 0; //initialize the standard pen and the standard operation id in //controller class for pen1 selected. Status.applyStandardPen(this); } /** * Increases id and returns the next id for being able to create * PaintObjects. From outside the Picture class without using the create. * method. Is mainly used for testing purpose. * * @return the next id. */ public synchronized int getIncreaseCID() { currentId++; return currentId - 1; } /** * Method for creating a new PaintObjectImage which is not directly added to * a list but returned to the demanding method. * * @param _bi * the BufferedImage of which the new created PaintObjectImage * consists * * @return the new created PaintObjectImage. */ public PaintObjectImage createPOI(final BufferedImage _bi) { return new PaintObjectImage(getIncreaseCID(), _bi, this); } /** * Method for creating a new PaintObjectWriting which is not directly added * to a list but returned to the demanding method. * * * @param _pen * the pen which will print the new created PaintObjectWriting * * @return the new created PaintObjectWriting */ public PaintObjectWriting createPOW(final Pen _pen) { return new PaintObjectWriting(this, getIncreaseCID(), _pen); } /** * adds a new PaintObject to list. */ public void addPaintObjectWrinting() { if (po_current != null) { if (!(po_current instanceof POCurve)) { // throw error message and kill program. Status.getLogger().severe("Es soll ein neues pen objekt" + " geadded werden, obwohl das Alte nicht null ist " + "also nicht gefinished wurde.\n" + "Programm wird beendet."); ls_po_sortedByX.insertSorted(po_current, po_current.getSnapshotBounds().x, SecureList.ID_NO_PREDECESSOR); } } if (!(po_current instanceof POCurve)) { // create new PaintObject and insert it into list of po_current = new PaintObjectWriting(this, currentId, pen_current); // increase current id currentId++; // set uncommitted changes. Status.setUncommittedChanges(true); } } /** * adds a new PaintObject to list. * * @param _bi * the BufferedImage which is to be transformed into ImagePO. */ public void addPaintObjectImage(final BufferedImage _bi) { if (po_current != null) { // throw error message and kill program. Status.getLogger().severe("Es soll ein neues pen objekt" + " geadded werden, obwohl das Alte nicht null ist " + "also nicht gefinished wurde.\n" + "Programm wird beendet."); ls_po_sortedByX.insertSorted(po_current, po_current.getSnapshotBounds().x, SecureList.ID_NO_PREDECESSOR); } if (_bi == null) { Status.getLogger().warning("nothing on clipboard."); } else { // create new PaintObject and insert it into list of PaintObjectImage poi = new PaintObjectImage(currentId, _bi, this); ls_po_sortedByX.insertSorted(poi, poi.getSnapshotBounds().x, SecureList.ID_NO_PREDECESSOR); // increase current id currentId++; // set uncommitted changes. Status.setUncommittedChanges(true); } } /** * Add the paintObject. */ public void addPaintObject(final Insert _tab_insert) { int casus = -1; // switch index of operation switch (Status.getIndexOperation()) { case Constants.CONTROL_PAINTING_INDEX_I_G_LINE: addPaintObject(new POLine(currentId, pen_current, this)); break; case Constants.CONTROL_PAINTING_INDEX_I_G_CURVE: casus = Constants.PEN_ID_MATHS_SILENT; case Constants.CONTROL_PAINTING_INDEX_I_G_CURVE_2: if (casus == -1) { casus = Constants.PEN_ID_MATHS_SILENT_2; } Pen pen; if (pen_current instanceof BallPen) { pen = new BallPen(casus, pen_current.getThickness(), pen_current.getClr_foreground()); } else if (pen_current instanceof PenSelection) { pen = new PenSelection(); } else if (pen_current instanceof Pencil) { pen = new Pencil(casus, pen_current.getThickness(), pen_current.getClr_foreground()); } else { Status.getLogger().warning("fehler stiftz noch nicht hinzu"); // throw exception throw new Error("Fehler: stift noch nicht hinzugefuegt."); } addPaintObject(new POCurve(casus, pen, casus, this)); break; case Constants.CONTROL_PAINTING_INDEX_I_G_RECTANGLE: addPaintObject(new PORectangle(currentId, pen_current, this)); break; case Constants.CONTROL_PAINTING_INDEX_I_G_TRIANGLE: addPaintObject(new POTriangle(currentId, pen_current, this)); break; case Constants.CONTROL_PAINTING_INDEX_I_G_ARCH_FILLED: addPaintObject(new POArchFilled(currentId, pen_current, this)); break; case Constants.CONTROL_PAINTING_INDEX_I_G_RECTANGLE_FILLED: addPaintObject(new PoRectangleFilled(currentId, pen_current, this)); break; case Constants.CONTROL_PAINTING_INDEX_I_G_TRIANGLE_FILLED: addPaintObject(new POTriangleFilled(currentId, pen_current, this)); break; case Constants.CONTROL_PAINTING_INDEX_I_G_ARCH: addPaintObject(new POArch(currentId, pen_current, this)); break; case Constants.CONTROL_PAINTING_INDEX_I_D_DIA: String srows = _tab_insert.getJtf_amountRows().getText(); int rows = 0; try { rows = Integer.parseInt(srows); } catch (Exception e) { Message.showMessage(Message.MESSAGE_ID_INFO, "enter valid row"); } String slines = _tab_insert.getJtf_amountLines().getText(); int lines = 0; try { lines = Integer.parseInt(slines); } catch (Exception e) { Message.showMessage(Message.MESSAGE_ID_INFO, "enter valid column"); } addPaintObject(new PODiagramm(currentId, pen_current, lines, rows, this)); break; case Constants.CONTROL_PAINTING_INDEX_PAINT_2: case Constants.CONTROL_PAINTING_INDEX_PAINT_1: addPaintObject(new PaintObjectWriting(this, currentId, pen_current)); break; default: Status.getLogger().warning("unknown index operation"); } } /** * adds a new PaintObject to list. * * @param _po * the PaintObjectPen. */ private void addPaintObject(final PaintObjectPen _po) { if (po_current != null) { if (!(po_current instanceof POCurve)) { // throw error message and kill program. Status.getLogger().severe("Es soll ein neues pen objekt" + " geadded werden, obwohl das Alte nicht null ist " + "also nicht gefinished wurde.\n" + "Programm wird beendet."); ls_po_sortedByX.insertSorted(po_current, po_current.getSnapshotBounds().x, SecureList.ID_NO_PREDECESSOR); } } if (!(po_current instanceof POCurve) || !(_po instanceof POCurve)) { // create new PaintObject and insert it into list of po_current = _po; // increase current id currentId++; // set uncommitted changes. Status.setUncommittedChanges(true); } } /** * return the color of the pixel at given location. The location is the * location in the bufferedImage which is not adapted at the zoomed click * size. * * @param _pxX * coordinate of normal-sized BufferedImage. * @param _pxY * coordinate of normal-sized BufferedImage. * * @param _bi * The BufferedImage which pixel is checked. * * @return the RGB integer of the color at given coordinate. */ public int getColorPX(final int _pxX, final int _pxY, final BufferedImage _bi) { return _bi.getRGB(_pxX, _pxY); } /** * repaint the items that are in a rectangle to the (view) page (e.g. if the * JLabel is moved)).. * * @param _x * the x coordinate * @param _y * the y coordinate * @param _width * the width * @param _height * the height * @param _graphicX * the graphics x * @param _graphiY * the graphics y. * @param _bi * the bufferedImage * @return the graphics */ public synchronized BufferedImage updateRectangle( final int _x, final int _y, final int _width, final int _height, final int _graphicX, final int _graphiY, final BufferedImage _bi, final ContorlPicture _controlPicture) { BufferedImage ret = emptyRectangle( _x, _y, _width, _height, _graphicX, _graphiY, _bi); // if the graphical user interface is not set up yet. if (ret == null) { return new BufferedImage(_width, _height, BufferedImage.TYPE_INT_ARGB); } ret = repaintRectangle(_x, _y, _width, _height, _graphicX, _graphiY, ret, false); return ret; } /** * repaint the items that are in a rectangle to the (view) page (e.g. if the * JLabel is moved)).. * * @param _x * the x coordinate * @param _y * the y coordinate * @param _width * the width * @param _height * the height * @param _graphicX * the graphics x * @param _graphiY * the graphics y. * @param _bi * the BufferedImage * @return the graphics */ public synchronized BufferedImage emptyRectangle(final int _x, final int _y, final int _width, final int _height, final int _graphicX, final int _graphiY, final BufferedImage _bi) { // check whether the rectangle concerns the blue border of the // image which is not to be emptied and then repainted. // If that's the case, the rectangle width or height are decreased. int rectWidth = _width, rectHeight = _height; if (_x + _width > Status.getImageShowSize().width) { rectWidth = Status.getImageShowSize().width - _x; } if (_y + _height > Status.getImageShowSize().height) { rectHeight = Status.getImageShowSize().height - _y; } BufferedImage bi = _bi; // alle die in Frage kommen neu laden. if (ls_po_sortedByX == null || bi == null) { bi = new BufferedImage(_width, _height, BufferedImage.TYPE_INT_ARGB); // return _bi; } final int maxRGB = 255; PaintBI.fillRectangleQuick(bi, new Color(maxRGB, maxRGB, maxRGB, 0), new Rectangle(_graphicX, _graphiY, rectWidth, rectHeight)); return bi; } /** * Repaint a rectangle without clearing the screen. The state of the list of * paintObjects is not changed by this process. * * @param _x * the x coordinate of the repainted rectangle * @param _y * the y coordinate * @param _width * the width * @param _height * the height * * @param _bi * the BufferedImage * @param _final * whether to paint finally to BufferedImage or not. * * @return the BufferedImage with painted PaintObjects on it. */ public synchronized BufferedImage repaintRectangle( final int _x, final int _y, final int _width, final int _height, final int _xBi, final int _yBi, final BufferedImage _bi, final boolean _final) { // If the sorted list of PaintObjects has not been initialized yet, // the list is empty or the given bufferedImage is equal to NULL // return the given BufferedImage because there is nothing to do if (ls_po_sortedByX == null || ls_po_sortedByX.isEmpty() || _bi == null) { return _bi; } // Start a transaction. That means that after the transaction has // been terminated, the current item of the list is reset. final int id_closedAction = ls_po_sortedByX.startClosedAction("repaintRectangle", SecureList.ID_NO_PREDECESSOR); final int id_transaction = ls_po_sortedByX.startTransaction("repaintRectangle", SecureList.ID_NO_PREDECESSOR); // Initialize new list into which the Items are inserted that are inside // the specified rectangle. List is sorted by id for painting the // items chronologically. SecureListSort<PaintObject> ls_poChronologic = new SecureListSort<PaintObject>(); // reset value for debugging and speed testing. Status.setCounter_paintedPoints(0); // initialize start value go to the list's beginning and calculate // values such as the stretch factors (which occur because of // zooming in and out). boolean behindRectangle = false; ls_po_sortedByX.toFirst(id_closedAction, id_transaction); /** * Stretch factor by width and height. */ final double factorW, factorH; if (_final) { factorW = 1; factorH = 1; } else { factorW = 1.0 * Status.getImageSize().width / Status.getImageShowSize().width; factorH = 1.0 * Status.getImageSize().width / Status.getImageShowSize().width; } /** * The location of the page end needed for checking roughly whether a * paintObject may be inside the repaint rectangle. */ final int xLocationRepaintEnd = (int) (factorW * (_x + _width)), yLocationRepaintEnd = (int) (factorH * (_y + _height)); /** * The repaint rectangle. */ final Rectangle r_selection = new Rectangle( (int) (factorW * _x), (int) (factorH * _y), (int) (factorW * _width), (int) (factorH * _height)); /* * Find out which items are inside the given repaint rectangle and * insert them into the list of paintObjects. */ while (!ls_po_sortedByX.isEmpty() && !ls_po_sortedByX.isBehind() && !behindRectangle) { // if the current item is not initialized only perform the // next operation. if (ls_po_sortedByX.getItem() != null) { // check whether the current PaintObject is in the given // rectangle by the coordinate by which the list is sorted. // if that is not the case the element is behind the specified // rectangle. if (ls_po_sortedByX.getItem().getSnapshotBounds().x <= xLocationRepaintEnd) { // Firstly check whether the current PaintObject may be // inside the given rectangle by the other // coordinate (by which the list is not sorted). // Secondly, if (1) is the case, perform a second // check which is exact; that means it // only succeeds if there really are pixels // printed inside selected rectangle. // If one of the two above mentioned tests return false // there may occur PaintObjects that are inside the // rectangle // but are found behind the current item inside the list // (because the list can only be sorted by one parameter) // Thus it is necessary to use this second if clause. if (ls_po_sortedByX.getItem().getSnapshotBounds().y <= yLocationRepaintEnd && ls_po_sortedByX.getItem().isInSelectionImage( r_selection)) { ls_poChronologic.insertSorted(ls_po_sortedByX.getItem(), ls_po_sortedByX.getItem().getElementId(), SecureList.ID_NO_PREDECESSOR); } } else { // if the current element starts behind the rectangle // in coordinate by which the list is sorted, // no PaintObject inserted after this element inside the // can be printed. behindRectangle = true; } } else { // log severe error because of unnecessary PaintObject inside // list. Status.getLogger().severe( "Error. Null PaintObject inside" + " the list of sorted paintObjects."); } ls_po_sortedByX.next(id_closedAction, id_transaction); } /* * Go through the sorted list of items and paint them */ ls_poChronologic.toFirst(SecureList.ID_NO_PREDECESSOR, SecureList.ID_NO_PREDECESSOR); int counter = 0; try{ while (!ls_poChronologic.isBehind() && !ls_poChronologic.isEmpty()) { ls_poChronologic.getItem().paint(_bi, _final, _bi, // _x, _y, // _paintLocationX, // _paintLocationY, -_x + _xBi, -_y + _yBi, // Page.getInstance().getJlbl_painting().getBi(), // Page.getInstance().getJlbl_painting().getLocation().x, // Page.getInstance().getJlbl_painting().getLocation().y, r_selection); counter++; ls_poChronologic.next(SecureList.ID_NO_PREDECESSOR, SecureList.ID_NO_PREDECESSOR); } } catch(Exception e) { e.printStackTrace(); } //log repainting action in console. if (counter > 0) { Console.log(counter + " Item painted in rectanlge (" + _x + ", " + _y + ", " + _width + ", " + _height + "). Final: " + _final, Console.ID_INFO_UNIMPORTANT, getClass(), "repaintRectangle"); } // print logging method Status.getLogger().info("Painted " + Status.getCounter_paintedPoints() + "pixel points for this operation."); //finish transaction and finish closed action; adjust the current //element to its state before the list transaction. ls_po_sortedByX.finishTransaction(id_transaction); ls_po_sortedByX.finishClosedAction(id_closedAction); return _bi; } /** * adds a Point to current PaintObject. * * @param _pnt * the point which is to be added. */ public void changePaintObject(final DPoint _pnt, final Page _page, final ContorlPicture _cPicture) { if (po_current == null) { // throw error message and kill program. Status.getLogger().warning( "Es soll ein nicht existentes Objekt veraendert werden.\n" + "Programm wird beendet."); } if (_pnt.getX() > Status.getImageSize().getWidth() || _pnt.getX() < 0 || _pnt.getY() > Status.getImageSize().getHeight() || _pnt.getY() < 0) { return; } if (!(po_current instanceof POCurve) && po_current instanceof PaintObjectWriting) { PaintObjectWriting pow = (PaintObjectWriting) po_current; pow.getPoints().toLast(); if (pow.getPoints().isEmpty()) { // add point to PaintObject pow.addPoint(_pnt); } else { pow.addPoint(_pnt); if (pen_current instanceof PenSelection) { ((PenSelection) pow.getPen()).resetCurrentBorderValue(); } } } else if (po_current instanceof POInsertion || po_current instanceof POLine) { POInsertion pow = (POInsertion) po_current; if (pow.getPnt_first() != null && pow.getPnt_last() != null) { _cPicture.refreshPaint(); } po_current.addPoint(_pnt); } else if (po_current instanceof POCurve) { POCurve pow = (POCurve) po_current; pow.addPoint(_pnt); _cPicture.refreshPaint(); } if (pen_current instanceof PenSelection) { BufferedImage bi_transformed = Util .getEmptyBISelection(); bi_transformed = po_current.paint( bi_transformed, false, bi_transformed, _page.getJlbl_painting().getLocation().x, _page.getJlbl_painting().getLocation().y, null); _page.getJlbl_selectionBG() .setIcon(new javax.swing.ImageIcon(bi_transformed)); } else { BufferedImage bi_transformed = _cPicture.getBi(); if (po_current instanceof POCurve) { bi_transformed = ((PaintObjectWriting) po_current).paint( _cPicture.getBi(), false, _cPicture.getBi(), _page.getJlbl_painting().getLocation().x, _page.getJlbl_painting().getLocation().y, null); } else if (po_current instanceof PaintObjectWriting && !(po_current instanceof POCurve)) { bi_transformed = ((PaintObjectWriting) po_current).paintLast( bi_transformed, _page.getJlbl_painting().getLocation().x, _page.getJlbl_painting().getLocation().y); } else { _cPicture .refreshRectangle( po_current.getSnapshotBounds().x, po_current.getSnapshotBounds().y, po_current.getSnapshotBounds().width, po_current.getSnapshotBounds().height); bi_transformed = po_current.paint(_cPicture.getBi(), false, _cPicture.getBi(), _page .getJlbl_painting().getLocation().x, _page .getJlbl_painting().getLocation().y, null); } _cPicture.setBi(bi_transformed); } // set uncommitted changes. Status.setUncommittedChanges(true); } /** * @return the paintObject. */ public PaintObjectWriting abortPaintObject(ContorlPicture _controlPic) { PaintObjectWriting pow = null; // PaintObjectWriting pow = new PaintObjectWriting(-1, pen_current); // List<DPoint> ls_points = null; // pow. if (pen_current instanceof PenSelection) { _controlPic .paintSelection(po_current, (PenSelection) pen_current); } pen_current.abort(); if (po_current instanceof PaintObjectWriting) { pow = (PaintObjectWriting) po_current; } po_current = null; return pow; } /** * Finishes current PaintObject. */ public void finish(final Debug _po) { if (po_current == null) { // throw error message and kill program. Status.getLogger().severe( "Es soll ein nicht existentes Objekt beendet werden.\n" + "Programm wird beendet."); } else { //add a new history item that indicates an add operation. history.addHistoryItem( history.createAddItem(po_current.clone(), po_current.clone())); // insert into sorted lists sorted by x and y positions. final Rectangle b = po_current.getSnapshotBounds(); if (po_current instanceof POCurve) { POCurve pc = (POCurve) po_current; pc.setReady(); } else { ls_po_sortedByX.insertSorted(po_current, b.x, SecureList.ID_NO_PREDECESSOR); new PictureOverview(_po).add(po_current); // reset current instance of PaintObject po_current = null; } // setChanged(); // notifyObservers(bi_normalSize); if (!(pen_current instanceof PenSelection)) { // set uncommitted changes. Status.setUncommittedChanges(true); } } } /** * sets the pen the first time a picture is created (thus do not notify the * history of uncommitted changes). * * @param _pen * the new pen. */ public void initializePen(final Pen _pen) { if (_pen instanceof BallPen) { this.pen_current = new BallPen(_pen.getId_operation(), // this.pen = new PenKuli(Constants.PEN_ID_POINT, _pen.getThickness(), _pen.getClr_foreground()); } else if (_pen instanceof PenSelection) { this.pen_current = new PenSelection(); } else if (_pen instanceof Pencil) { this.pen_current = new Pencil(_pen.getId_operation(), _pen.getThickness(), _pen.getClr_foreground()); } else { // alert user. Status.showMessageDialog( "PROGRAMMIERFEHLER @ paintobjectwriting: " + "Stift noch nicht hinzugefuegt."); // throw exception new java.lang.Error("Fehler: stift noch nicht hinzugefuegt.") .printStackTrace(); } } /** * sets the pen both to Picture (for the following PaintObjects) and to the * current PaintObject (which should be null). * * @param _pen * the new pen. */ public void changePen(final Pen _pen) { // set in picture this.pen_current = _pen; // set in current paint object. if (po_current != null && po_current instanceof PaintObjectWriting) { po_current.setPen(pen_current); } // set uncommitted changes. Status.setUncommittedChanges(true); } /** * Paint the selected BufferedImages to a new BufferedImage which has got * the size of the selection. This method is used for copying the * paintObjects as images to clipboard. * * @return the painted BufferedImage. */ public BufferedImage paintSelectedBI(final Rectangle _recSelection) { if (_recSelection == null) { Status.getLogger().warning("the selection square does not exist!"); return null; } BufferedImage bi = new BufferedImage(_recSelection.width + 1, _recSelection.height + 1, BufferedImage.TYPE_INT_ARGB); //start transaction and closed action. final int transaction = getLs_po_sortedByX() .startTransaction("paint selected bi", SecureList.ID_NO_PREDECESSOR); final int closedAction = getLs_po_sortedByX() .startClosedAction("paint selected bi", SecureList.ID_NO_PREDECESSOR); ls_poSelected.toFirst(transaction, closedAction); while (!ls_poSelected.isEmpty() && !ls_poSelected.isBehind()) { PaintObject po = ls_poSelected.getItem(); if (po instanceof PaintObjectWriting) { PaintObjectWriting pow = (PaintObjectWriting) po; // TODO: zoom, scroll adjust? pow.paint(bi, false, bi, -_recSelection.x, -_recSelection.y, null); } else if (po instanceof PaintObjectImage) { PaintObjectImage poi = (PaintObjectImage) po; poi.paint(bi, false, bi, -_recSelection.x, -_recSelection.y, null); } else { Status.getLogger().warning("unknown kind of PaintObject" + po); } ls_poSelected.next(transaction, closedAction); } //close transaction and closed action. getLs_po_sortedByX().finishTransaction( transaction); getLs_po_sortedByX().finishClosedAction( closedAction); return bi; } /** * save the picture. * * @param _wsLoc * the path of the location. * * @param _x the location of the PaintLabel. * @param _y the location of the PaintLabel. */ public void saveIMAGE(final String _wsLoc, final int _x, final int _y) { BufferedImage bi; if (Status.isExportAlpha()) { bi = Util.getEmptyBITransparent(); } else { bi = Util.getEmptyBIWhite(); } bi = Utils.getBackgroundExport(bi, 0, 0, Status.getImageSize().width, Status.getImageSize().height, 0, 0); bi = repaintRectangle(-_x + 0, -_y + 0, Status.getImageSize().width, Status.getImageSize().height, -_x + 0, -_y + 0, bi, true); try { ImageIO.write(bi, Status.getSaveFormat(), new File(_wsLoc + Status.getSaveFormat())); } catch (IOException e) { e.printStackTrace(); } } /** * save the picture. * @return the BufferedImage. */ public BufferedImage calculateImage() { BufferedImage bi; if (Status.isExportAlpha()) { bi = Util.getEmptyBITransparent(); } else { bi = Util.getEmptyBIWhite(); } bi = Utils.getBackgroundExport(bi, 0, 0, Status.getImageSize().width, Status.getImageSize().height, 0, 0); bi = repaintRectangle( 0, 0, // -Page.getInstance().getJlbl_painting().getLocation().x + 0, // -Page.getInstance().getJlbl_painting().getLocation().y + 0, Status.getImageSize().width, Status.getImageSize().height, 0, 0, bi, true); return bi; } /** * save the picture. Method for different use of the software. Only used * for transforming image by using main method parameters in start class. * * @param _wsLoc * the path of the location. */ public void saveQuickPNG(final String _wsLoc) { ls_po_sortedByX.toFirst(SecureList.ID_NO_PREDECESSOR, SecureList.ID_NO_PREDECESSOR); Rectangle r = ls_po_sortedByX.getItem().getSnapshotBounds(); BufferedImage bi = new BufferedImage(r.width, r.height, BufferedImage.TYPE_INT_ARGB); for (int i = 0; i < r.width; i++) { for (int j = 0; j < r.height; j++) { bi.setRGB(i, j, new Color(0, 0, 0, 0).getRGB()); } } bi = ls_po_sortedByX.getItem().paint(bi, true, bi, 0, 0, null); try { ImageIO.write(bi, "png", new File(_wsLoc)); } catch (IOException e) { e.printStackTrace(); } } /** * save the picture. * * @param _wsLoc * the path of the location. */ public void savePicture(final String _wsLoc) { try { FileOutputStream fos = new FileOutputStream(new File(_wsLoc)); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(ls_po_sortedByX); oos.flush(); oos.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } /** * save the picture. * * @param _wsLoc * the path of the location. */ public void loadPicture(final String _wsLoc) { try { FileInputStream fos = new FileInputStream(new File(_wsLoc)); ObjectInputStream oos = new ObjectInputStream(fos); @SuppressWarnings("unchecked") SecureListSort<PaintObject> p = (SecureListSort<PaintObject>) oos.readObject(); ls_po_sortedByX = p; oos.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * Empty each paintObject. */ public void emptyImage() { ls_po_sortedByX = new SecureListSort<PaintObject>(); ls_poSelected = new SecureList<PaintObject>(); } /** * darken image. * * @param _poi * the PaintObjectImage which is altered */ public void darken(final PaintObjectImage _poi) { BufferedImage bi_snapshot = _poi.getSnapshot(); for (int i = 0; i < bi_snapshot.getWidth(); i++) { for (int j = 0; j < bi_snapshot.getHeight(); j++) { final int minus = 30; Color c = new Color(bi_snapshot.getRGB(i, j)); int red = c.getRed() - minus; int blue = c.getBlue() - minus; int green = c.getGreen() - minus; if (red < 0) { red = 0; } if (green < 0) { green = 0; } if (blue < 0) { blue = 0; } bi_snapshot.setRGB(i, j, new Color(red, green, blue).getRGB()); } } } /** * transform white to alpha. * * @param _poi * the PaintObjectImage which is altered */ public void transformToAlpha(final PaintObjectImage _poi) { BufferedImage bi_snapshot = _poi.getSnapshot(); for (int i = 0; i < bi_snapshot.getWidth(); i++) { for (int j = 0; j < bi_snapshot.getHeight(); j++) { Color c = new Color(bi_snapshot.getRGB(i, j)); int red = c.getRed(); int blue = c.getBlue(); int green = c.getGreen(); final int maxRGB = 255; final double multiplyer = 1.5; final int five = 5; int gesamt = maxRGB - (red + green + blue) / (2 + 1); gesamt *= multiplyer; if (gesamt > maxRGB) { gesamt = maxRGB - 1; } red = red * 2 + five; green = green * 2 + five; blue = blue * 2 + five; if (red > maxRGB) { red = maxRGB; } if (green > maxRGB) { green = maxRGB; } if (blue > maxRGB) { blue = maxRGB; } bi_snapshot.setRGB(i, j, new Color(red, green, blue, gesamt).getRGB()); } } } /** * Transform all PaintObjectImages to alpha. */ public void transformWhiteToAlpha() { if (ls_po_sortedByX != null) { //start transaction and closed action. final int transaction = getLs_po_sortedByX() .startTransaction("transformWhiteToAlpha", SecureList.ID_NO_PREDECESSOR); final int closedAction = getLs_po_sortedByX() .startClosedAction("transformWhiteToAlpha", SecureList.ID_NO_PREDECESSOR); ls_po_sortedByX.toFirst(transaction, closedAction); while (!ls_po_sortedByX.isBehind() && !ls_po_sortedByX.isEmpty()) { if (ls_po_sortedByX.getItem() instanceof PaintObjectImage) { whiteToAlpha((PaintObjectImage) ls_po_sortedByX.getItem()); } ls_po_sortedByX.next(transaction, closedAction); } //close transaction and closed action. getLs_po_sortedByX().finishTransaction( transaction); getLs_po_sortedByX().finishClosedAction( closedAction); } } /** * transform white pixel to alpha pixel. * * @param _poi * the PaintObjectImage which is altered */ private void whiteToAlpha(final PaintObjectImage _poi) { BufferedImage bi_snapshot = _poi.getSnapshot(); for (int i = 0; i < bi_snapshot.getWidth(); i++) { for (int j = 0; j < bi_snapshot.getHeight(); j++) { Color c = new Color(bi_snapshot.getRGB(i, j), true); int red = c.getRed(); int blue = c.getBlue(); int green = c.getGreen(); int alpha; final int upTo = 240; if (red + green + blue >= (2 + 1) * upTo) { alpha = 0; System.out.println("hier"); } else { final int maxAlpha = 255; alpha = maxAlpha; } bi_snapshot.setRGB(i, j, new Color(red, green, blue, alpha).getRGB()); } } _poi.setImage(bi_snapshot); } /** * transform image to gray image. * * @param _poi * the PaintObjectImage which is altered */ public void blackWhite(final PaintObjectImage _poi) { BufferedImage bi_snapshot = _poi.getSnapshot(); for (int i = 0; i < bi_snapshot.getWidth(); i++) { for (int j = 0; j < bi_snapshot.getHeight(); j++) { Color c = new Color(bi_snapshot.getRGB(i, j)); int red = c.getRed(); int blue = c.getBlue(); int green = c.getGreen(); int gesamt = (red + green + blue) / (2 + 1); bi_snapshot.setRGB(i, j, new Color(gesamt, gesamt, gesamt).getRGB()); } } } /* * Selection methods. */ /** * create selected List. */ public void createSelected() { if (ls_poSelected == null) { ls_poSelected = new SecureList<PaintObject>(); } else { if (!ls_poSelected.isEmpty()) { Status.getLogger().warning( "creating new selection list but list is not empty."); } } } /** * insert into selected list. * * @param _po * the paintObject to be inserted. */ public synchronized void insertIntoSelected(final PaintObject _po, final Debug _paintObjects) { // deactivates to change operations of selected items if (ls_poSelected == null) { Status.getLogger().warning("insert into null list"); } else if (_po != null) { // CTabSelection.activateOp(); // if (_po instanceof PaintObjectWriting) { // PaintObjectWriting pow = (PaintObjectWriting) _po; // CTabSelection.getInstance().change(ls_poSelected.isEmpty(), // pow.getPen().getId_operation(), // pow.getPen().getClr_foreground().getRGB()); ls_poSelected.insertAfterHead(_po, SecureList.ID_NO_PREDECESSOR); new PictureOverview(_paintObjects).addSelected(_po); } } /** * Finish paintObjectSelection: go through the list of selected paint * objects and tell the paintObjects selection interface controller * the color and the pen. */ public synchronized void finishSelection(CTabSelection _ctabSelection) { // deactivates to change operations of selected items if (ls_poSelected == null) { Status.getLogger().warning("finish selection list which is" + " null."); } else { //start transaction and closedAction. final int transaction = ls_poSelected.startTransaction( "finishSelection", SecureList.ID_NO_PREDECESSOR); final int closedAction = ls_poSelected.startClosedAction( "finishSelection", SecureList.ID_NO_PREDECESSOR); ls_poSelected.toFirst(transaction, closedAction); _ctabSelection.activateOp(); while (!ls_poSelected.isBehind()) { if (ls_poSelected.getItem() instanceof PaintObjectWriting) { PaintObjectWriting pow = (PaintObjectWriting) ls_poSelected.getItem(); _ctabSelection.change(ls_poSelected.isEmpty(), pow.getPen().getId_operation(), pow.getPen().getClr_foreground().getRGB()); } ls_poSelected.next(transaction, closedAction); } //finish actions. ls_poSelected.finishClosedAction(closedAction); ls_poSelected.finishTransaction(transaction); } } public SecureList<PaintObject> cloneSecureListPaintObject( final SecureList<PaintObject> _slpo) { SecureList<PaintObject> sl_new = new SecureList<PaintObject>(); if (_slpo != null) { _slpo.toFirst(SecureList.ID_NO_PREDECESSOR, SecureList.ID_NO_PREDECESSOR); while (!_slpo.isBehind() && !_slpo.isEmpty()) { sl_new.insertBehind(_slpo.getItem().clone(), SecureList.ID_NO_PREDECESSOR); _slpo.next(SecureList.ID_NO_PREDECESSOR, SecureList.ID_NO_PREDECESSOR); } } return sl_new; } /** * Move selected items. * * @param _dX * the x difference from current position * @param _dY * the y difference from current position */ public synchronized void moveSelected(final int _dX, final int _dY) { if (ls_poSelected == null) { return; } SecureList<PaintObject> sl_oldMove = cloneSecureListPaintObject(ls_poSelected); // add a new history item that indicates an add operation. //start transaction and closed action. final int transaction = getLs_po_sortedByX() .startTransaction("stretch image", SecureList.ID_NO_PREDECESSOR); final int closedAction = getLs_po_sortedByX() .startClosedAction("stretch image", SecureList.ID_NO_PREDECESSOR); ls_poSelected.toFirst(transaction, closedAction); while (!ls_poSelected.isBehind()) { if (ls_poSelected.getItem() instanceof PaintObjectWriting) { PaintObjectWriting pow = (PaintObjectWriting) ls_poSelected .getItem(); pow = movePaintObjectWriting(pow, _dX, _dY); } else if (ls_poSelected.getItem() instanceof PaintObjectImage) { PaintObjectImage p = (PaintObjectImage) ls_poSelected.getItem(); p.move(new Point(_dX, _dY)); } else if (ls_poSelected.getItem() instanceof POLine) { POLine p = (POLine) ls_poSelected.getItem(); moveLine(p, _dX, _dY); } else { Status.getLogger().warning("unknown kind of PaintObject?"); } ls_poSelected.next(transaction, closedAction); } SecureList<PaintObject> sl_newMoved = cloneSecureListPaintObject(ls_poSelected); history.addHistoryItem(history.createMoveItem( sl_oldMove, sl_newMoved)); //close transaction and closed action. getLs_po_sortedByX().finishTransaction( transaction); getLs_po_sortedByX().finishClosedAction( closedAction); } /** * * Move PaintObject items. * * @param _pow * PaintObjectWriting * @param _dX * the x difference from current position * @param _dY * the y difference from current position * @return the PaintObjectWriting */ public static PaintObjectWriting movePaintObjectWriting( final PaintObjectWriting _pow, final int _dX, final int _dY) { _pow.getPoints().toFirst(); _pow.adjustSnapshotBounds(_dX, _dY); while (!_pow.getPoints().isBehind()) { _pow.getPoints().getItem() .setX(_pow.getPoints().getItem().getX() + _dX); _pow.getPoints().getItem() .setY(_pow.getPoints().getItem().getY() + _dY); _pow.getPoints().next(); } return _pow; } /** * * Move PaintObject items. * * @param _pow * PaintObjectWriting * @param _dX * the x difference from current position * @param _dY * the y difference from current position * @return the PaintObjectWriting */ public static POLine moveLine(final POLine _pow, final int _dX, final int _dY) { _pow.getPnt_first().setX(_pow.getPnt_first().getX() + _dX); _pow.getPnt_first().setY(_pow.getPnt_first().getY() + _dY); _pow.getPnt_last().setX(_pow.getPnt_last().getX() + _dX); _pow.getPnt_last().setY(_pow.getPnt_last().getY() + _dY); return _pow; } /** * Paint the selected items to the selection JLabel. * * @return whether there is something to be painted or not. */ public boolean paintSelected(Page _page, final ContorlPicture _cp, final ControlPaintSelectin _cps) { // If the list of PaintObjects has not been initialized yet or // the list is empty return that there is nothing to do if (ls_poSelected == null || ls_poSelected.isEmpty()) { return false; } // Start a transaction. That means that after the transaction has // been terminated, the current item of the list is reset. final int id_transaction = getLs_po_sortedByX() .startTransaction("paintSelected", SecureList.ID_NO_PREDECESSOR); final int id_closedAction = getLs_po_sortedByX() .startClosedAction("paintSelected", SecureList.ID_NO_PREDECESSOR); // Initialize new list into which the Items are inserted that are inside // the specified rectangle. List is sorted by id for painting the // items chronologically. SecureListSort<PaintObject> ls_poChronologic = new SecureListSort<PaintObject>(); // reset value for debugging and speed testing. Status.setCounter_paintedPoints(0); ls_poSelected.toFirst(id_transaction, id_closedAction); Rectangle r_max = null; while (!ls_poSelected.isEmpty() && !ls_poSelected.isBehind()) { // if the current item is not initialized only perform the // next operation. if (ls_poSelected.getItem() != null) { // create new Rectangle consisting of the bounds of the current // paitnObject otherwise adjust the existing bounds if (r_max == null) { Rectangle b = ls_poSelected.getItem().getSnapshotBounds(); r_max = new Rectangle(b.x, b.y, b.width + b.x, b.height + b.y); } else { Rectangle b = ls_poSelected.getItem().getSnapshotBounds(); r_max.x = Math.min(r_max.x, b.x); r_max.y = Math.min(r_max.y, b.y); r_max.width = Math.max(r_max.width, b.x + b.width); r_max.height = Math.max(r_max.height, b.y + b.height); } //insert the current element into the list containing //the selected items by sorted by time of insertion //indicated by their index. ls_poChronologic.insertSorted(ls_poSelected.getItem(), ls_poSelected.getItem().getElementId(), SecureList.ID_NO_PREDECESSOR); } else { // log severe error because of unnecessary PaintObject inside // list. Status.getLogger().severe( "Error. Null PaintObject inside" + " the list of sorted paintObjects."); } ls_poSelected.next(id_closedAction, id_transaction); } /* * Go through the sorted list of items and paint them */ ls_poChronologic.toFirst(SecureList.ID_NO_PREDECESSOR, SecureList.ID_NO_PREDECESSOR); BufferedImage verbufft = Util.getEmptyBISelection(); BufferedImage verbufft2 = Util.getEmptyBISelection(); int counter = 0; while (!ls_poChronologic.isBehind() && !ls_poChronologic.isEmpty()) { if (ls_poChronologic.getItem() instanceof PaintObjectWriting) { PaintObjectWriting pow = (PaintObjectWriting) ls_poChronologic .getItem(); pow.enableSelected(); } // paint the object. ls_poChronologic.getItem().paint(verbufft2, false, verbufft, _page.getJlbl_painting().getLocation().x, _page.getJlbl_painting().getLocation().y, null); if (ls_poChronologic.getItem() instanceof PaintObjectWriting) { PaintObjectWriting pow = (PaintObjectWriting) ls_poChronologic .getItem(); pow.disableSelected(); } counter++; ls_poChronologic.next(SecureList.ID_NO_PREDECESSOR, SecureList.ID_NO_PREDECESSOR); } //log repainting action in console. if (counter > 0) { Console.log(counter + " Item painted in rectanlge (" + r_max + ").", Console.ID_INFO_UNIMPORTANT, getClass(), "repaintRectangle"); } // print logging method Status.getLogger().info("Painted " + Status.getCounter_paintedPoints() + "pixel points for this operation. (paint selected)"); //finish transaction and finish closed action; adjust the current //element to its state before the list transaction. ls_po_sortedByX.finishTransaction(id_transaction); ls_po_sortedByX.finishClosedAction(id_closedAction); _page.getJlbl_selectionPainting() .setIcon(new ImageIcon(verbufft)); if (r_max != null) { Rectangle realRect = new Rectangle(r_max.x, r_max.y, r_max.width - r_max.x, r_max.height - r_max.y); // adapt the rectangle to the currently used zoom factor. final double cZoomFactorWidth = 1.0 * Status.getImageSize().width / Status.getImageShowSize().width; final double cZoomFactorHeight = 1.0 * Status.getImageSize().height / Status.getImageShowSize().height; realRect.x = (int) (1.0 * realRect.x / cZoomFactorWidth); realRect.width = (int) (1.0 * realRect.width / cZoomFactorWidth); realRect.y = (int) (1.0 * realRect.y / cZoomFactorHeight); realRect.height = (int) (1.0 * realRect.height / cZoomFactorHeight); realRect.x += _page.getJlbl_painting().getLocation().x; realRect.y += _page.getJlbl_painting().getLocation().y; _cp.refreshRectangle(realRect.x, realRect.y, realRect.width, realRect.height); _cps.setR_selection(realRect, _page.getJlbl_painting().getLocation()); _cp.paintEntireSelectionRect(realRect); return true; } return false; } /** * Paint the selected items to the selection JLabel. * NOT USED ANYMORE * * @return whether there is something to be painted or not. */ public boolean paintSelectedOld(Page _page, final ContorlPicture _cp, final ControlPaintSelectin _cps) { _page.getJlbl_selectionPainting().setLocation(0, 0); BufferedImage verbufft = Util.getEmptyBISelection(); BufferedImage verbufft2 = Util.getEmptyBISelection(); //start transaction and closed action. final int transaction = getLs_po_sortedByX() .startTransaction("paintSelected", SecureList.ID_NO_PREDECESSOR); final int closedAction = getLs_po_sortedByX() .startClosedAction("paintSelected", SecureList.ID_NO_PREDECESSOR); ls_poSelected.toFirst(transaction, closedAction); Rectangle r_max = null; while (!ls_poSelected.isEmpty() && !ls_poSelected.isBehind()) { if (ls_poSelected.getItem() != null) { // create new Rectangle consisting of the bounds of the current // paitnObject otherwise adjust the existing bounds if (r_max == null) { Rectangle b = ls_poSelected.getItem().getSnapshotBounds(); r_max = new Rectangle(b.x, b.y, b.width + b.x, b.height + b.y); } else { Rectangle b = ls_poSelected.getItem().getSnapshotBounds(); r_max.x = Math.min(r_max.x, b.x); r_max.y = Math.min(r_max.y, b.y); r_max.width = Math.max(r_max.width, b.x + b.width); r_max.height = Math.max(r_max.height, b.y + b.height); } if (ls_poSelected.getItem() instanceof PaintObjectWriting) { PaintObjectWriting pow = (PaintObjectWriting) ls_poSelected .getItem(); pow.enableSelected(); } // paint the object. ls_poSelected.getItem().paint(verbufft2, false, verbufft, _page.getJlbl_painting().getLocation().x, _page.getJlbl_painting().getLocation().y, null); if (ls_poSelected.getItem() instanceof PaintObjectWriting) { PaintObjectWriting pow = (PaintObjectWriting) ls_poSelected .getItem(); pow.disableSelected(); } } ls_poSelected.next(transaction, closedAction); } //close transaction and closed action. getLs_po_sortedByX().finishTransaction( transaction); getLs_po_sortedByX().finishClosedAction( closedAction); _page.getJlbl_selectionPainting() .setIcon(new ImageIcon(verbufft)); if (r_max != null) { Rectangle realRect = new Rectangle(r_max.x, r_max.y, r_max.width - r_max.x, r_max.height - r_max.y); // adapt the rectangle to the currently used zoom factor. final double cZoomFactorWidth = 1.0 * Status.getImageSize().width / Status.getImageShowSize().width; final double cZoomFactorHeight = 1.0 * Status.getImageSize().height / Status.getImageShowSize().height; realRect.x = (int) (1.0 * realRect.x / cZoomFactorWidth); realRect.width = (int) (1.0 * realRect.width / cZoomFactorWidth); realRect.y = (int) (1.0 * realRect.y / cZoomFactorHeight); realRect.height = (int) (1.0 * realRect.height / cZoomFactorHeight); realRect.x += _page.getJlbl_painting().getLocation().x; realRect.y += _page.getJlbl_painting().getLocation().y; _cp.refreshRectangle(realRect.x, realRect.y, realRect.width, realRect.height); _cps.setR_selection(realRect, _page.getJlbl_painting().getLocation()); _cp.paintEntireSelectionRect(realRect); return true; } return false; } /** * Paint the selected items to the selection JLabel. * * @return whether there is something to be painted or not. */ public boolean paintSelectedInline( ControlPaintSelectin _controlPaintSelection, final Page _page, final ContorlPicture _controlPic) { // it occurred that the start point equal to 0. Why? int px, py; if (_controlPaintSelection.getPnt_start() == null) { px = 0; py = 0; } else { px = (int) (_controlPaintSelection.getPnt_start().getX() - _page.getJlbl_painting().getLocation().getX()); py = (int) (_controlPaintSelection.getPnt_start().getY() - _page.getJlbl_painting().getLocation().getY()); } //reset the point which shaves the shift of the selection //because now the shift that has been done is applied. _controlPaintSelection.resetPntStartLocationLabel(); _page.getJlbl_selectionPainting().setLocation(0, 0); BufferedImage verbufft = Util.getEmptyBISelection(); BufferedImage verbufft2 = Util.getEmptyBISelection(); //start transaction and closed action. final int transaction = getLs_po_sortedByX() .startTransaction("paintSelectedInline", SecureList.ID_NO_PREDECESSOR); final int closedAction = getLs_po_sortedByX() .startClosedAction("paintSelectedInline", SecureList.ID_NO_PREDECESSOR); ls_poSelected.toFirst(transaction, closedAction); Rectangle r_max = null; while (!ls_poSelected.isEmpty() && !ls_poSelected.isBehind()) { if (ls_poSelected.getItem() != null) { // create new Rectangle consisting of the bounds of the current // paitnObject otherwise adjust the existing bounds if (r_max == null) { Rectangle b = ls_poSelected.getItem().getSnapshotBounds(); r_max = new Rectangle(b.x, b.y, b.width + b.x, b.height + b.y); } else { Rectangle b = ls_poSelected.getItem().getSnapshotBounds(); r_max.x = Math.min(r_max.x, b.x); r_max.y = Math.min(r_max.y, b.y); r_max.width = Math.max(r_max.width, b.x + b.width); r_max.height = Math.max(r_max.height, b.y + b.height); } if (ls_poSelected.getItem() instanceof PaintObjectWriting) { PaintObjectWriting pow = (PaintObjectWriting) ls_poSelected .getItem(); pow.enableSelected(); } // paint the object. ls_poSelected.getItem().paint( verbufft2, false, verbufft, _page.getJlbl_painting().getLocation().x - px, _page.getJlbl_painting().getLocation().y - py, null); if (ls_poSelected.getItem() instanceof PaintObjectWriting) { PaintObjectWriting pow = (PaintObjectWriting) ls_poSelected .getItem(); pow.disableSelected(); } } ls_poSelected.next(transaction, closedAction); } //close transaction and closed action. getLs_po_sortedByX().finishTransaction( transaction); getLs_po_sortedByX().finishClosedAction( closedAction); _page.getJlbl_selectionPainting() .setIcon(new ImageIcon(verbufft)); if (r_max != null) { Rectangle realRect = new Rectangle(r_max.x, r_max.y, r_max.width - r_max.x, r_max.height - r_max.y); // adapt the rectangle to the currently used zoom factor. final double cZoomFactorWidth = 1.0 * Status.getImageSize().width / Status.getImageShowSize().width; final double cZoomFactorHeight = 1.0 * Status.getImageSize().height / Status.getImageShowSize().height; realRect.x = (int) (1.0 * realRect.x / cZoomFactorWidth); realRect.width = (int) (1.0 * realRect.width / cZoomFactorWidth); realRect.y = (int) (1.0 * realRect.y / cZoomFactorHeight); realRect.height = (int) (1.0 * realRect.height / cZoomFactorHeight); realRect.x += _page.getJlbl_painting().getLocation().x; realRect.y += _page.getJlbl_painting().getLocation().y; _controlPic .refreshRectangle(realRect.x, realRect.y, realRect.width, realRect.height); _controlPaintSelection.setR_selection(realRect, _page.getJlbl_painting().getLocation()); _controlPic .paintEntireSelectionRect(realRect); return true; } return false; } /** * release selected elements to normal list. */ public synchronized void releaseSelected( final ControlPaintSelectin _controlPaintSelection, final CTabSelection _controlTabSelection, final Debug _paintObjects, final int _xLocationPaint, final int _yLocationPaint) { // adjust the bounds of the selected items to the performed // scrolling if (_controlPaintSelection.getOldPaintLabelLocation() != null) { int oldX = (int) _controlPaintSelection .getOldPaintLabelLocation().getX(); int oldY = (int) _controlPaintSelection .getOldPaintLabelLocation().getY(); int newX = (int) _xLocationPaint; int newY = (int) _yLocationPaint; moveSelected(oldX - newX, oldY - newY); _controlPaintSelection.setOldPaintLabelLocation(null); } // deactivates to change operations of selected items _controlTabSelection.deactivateOp(); if (ls_poSelected == null) { Status.getLogger().info("o selected elements"); return; } //create new transaction int transaction = ls_poSelected.startTransaction( "picture release selected", SecureList.ID_NO_PREDECESSOR); //pass the list. ls_poSelected.toFirst(transaction, SecureList.ID_NO_PREDECESSOR); while (!ls_poSelected.isEmpty()) { PaintObject po = ls_poSelected.getItem(); if (po == null) { Status.getLogger().warning("error: empty list item"); } new PictureOverview(_paintObjects).removeSelected(po); if (po instanceof PaintObjectWriting) { PaintObjectWriting pow = (PaintObjectWriting) po; new PictureOverview(_paintObjects).add(pow); ls_po_sortedByX.insertSorted(pow, pow.getSnapshotBounds().x, SecureList.ID_NO_PREDECESSOR); } else if (po instanceof PaintObjectImage) { PaintObjectImage poi = (PaintObjectImage) po; new PictureOverview(_paintObjects).add(poi); ls_po_sortedByX.insertSorted(poi, poi.getSnapshotBounds().x, SecureList.ID_NO_PREDECESSOR); } else if (ls_poSelected.getItem() instanceof POLine) { POLine p = (POLine) ls_poSelected.getItem(); p.recalculateSnapshotBounds(); new PictureOverview(_paintObjects).add(p); ls_po_sortedByX.insertSorted(p, p.getSnapshotBounds().x, SecureList.ID_NO_PREDECESSOR); } else if (po != null) { Status.getLogger().warning("unknown kind of PaintObject" + po); } ls_poSelected.remove(transaction); ls_poSelected.toFirst(transaction, SecureList.ID_NO_PREDECESSOR); } //finish transaction and destroy list of selected items. ls_poSelected.finishTransaction(transaction); ls_poSelected = null; } /** * release selected elements to normal list. */ public synchronized void deleteSelected( final Debug _pos, CTabSelection _cts) { if (ls_poSelected == null) { Status.getLogger().info("o selected elements"); return; } //create new transaction int transaction = ls_poSelected.startTransaction( "picture delete selected", SecureList.ID_NO_PREDECESSOR); //pass the list. ls_poSelected.toFirst(transaction, SecureList.ID_NO_PREDECESSOR); while (!ls_poSelected.isEmpty()) { if (ls_poSelected.getItem() == null) { Status.getLogger().warning("error: empty list item"); } new PictureOverview(_pos).removeSelected(ls_poSelected.getItem()); ls_poSelected.remove(transaction); ls_poSelected.toFirst(transaction, SecureList.ID_NO_PREDECESSOR); } // deactivates to change operations of selected items _cts.deactivateOp(); //finish transaction and destroy list of selected items. ls_poSelected.finishTransaction(transaction); ls_poSelected = null; } /* * save and load */ /** * load an image to the picture. and write it into bi_resized. * * @param _wsLoc * the location of the image * @return the size of the image */ public DPoint load(final String _wsLoc) { BufferedImage bi_normalSize; try { BufferedImage bi_unnormalSchaizz = ImageIO.read(new File(_wsLoc)); bi_normalSize = new BufferedImage(bi_unnormalSchaizz.getWidth(), bi_unnormalSchaizz.getHeight(), BufferedImage.TYPE_INT_ARGB); for (int x = 0; x < bi_unnormalSchaizz.getWidth(); x++) { for (int y = 0; y < bi_unnormalSchaizz.getHeight(); y++) { bi_normalSize.setRGB(x, y, bi_unnormalSchaizz.getRGB(x, y)); } } Status.setImageSize(new Dimension(bi_normalSize.getWidth(), bi_normalSize.getHeight())); Status.setImageShowSize(new Dimension(bi_normalSize.getWidth(), bi_normalSize.getHeight())); if (ls_po_sortedByX == null) { createSelected(); } //create new transaction int transaction = ls_po_sortedByX.startTransaction( "load", SecureList.ID_NO_PREDECESSOR); ls_po_sortedByX.toFirst(transaction, SecureList.ID_NO_PREDECESSOR); PaintObjectImage poi_current = createPOI(bi_normalSize); ls_po_sortedByX.insertSorted(poi_current, poi_current.getSnapshotBounds().x, transaction); //finish transaction and destroy list of selected items. ls_po_sortedByX.finishTransaction(transaction); } catch (IOException e) { Util.handleException( "Error opening image: File not found", "Error opening image file " + _wsLoc + ".\nThe input file can not be opened.", e, null); } return new DPoint(Status.getImageSize().getWidth(), Status .getImageSize().getHeight()); } /* * getter and setter methods */ /** * @return the pen_current */ public Pen getPen_current() { return pen_current; } /** * @return the ls_po_sortedByX */ public SecureListSort<PaintObject> getLs_po_sortedByX() { return ls_po_sortedByX; } /** * @param _ls_po_sortedByX * the ls_po_sortedByX to set */ public void setLs_po_sortedByX( final SecureListSort<PaintObject> _ls_po_sortedByX) { this.ls_po_sortedByX = _ls_po_sortedByX; } /** * @return the ls_poSelected */ public SecureList<PaintObject> getLs_poSelected() { return ls_poSelected; } /** * Returns whether the current paint object is equal to zero; thus the * Picture is ready for creating a new PaintObject. * * Used because there are PaintObjects (such as POCurve) that need multiple * mouse presses, and releases. * * Thus the Controller class for the painting has to check whether there is * a paintObejct ready if the 'new' PaintObject would be of one of the above * mentioned types. * * @return whether the current paintObject does not exist. */ public boolean isPaintObjectReady() { return (po_current == null); } /** * Set the pen after the user clicked at a pen button. Thus clone the pen * and change its color afterwards to the last used one. * * @param _pen * the pen * @param _id * whether pen 1 or pen 2. */ public void userSetPen(final Pen _pen, final int _id) { Pen pen = Pen.clonePen(_pen); if (_id == 1) { pen.setClr_foreground(Status.getPenSelected1().getClr_foreground()); Status.setPenSelected1(pen); } else if (_id == 2) { pen.setClr_foreground(Status.getPenSelected2().getClr_foreground()); Status.setPenSelected2(pen); } else { Status.getLogger().severe("wrong identifier: " + _id); } } /** * Return whether some PaintObjects are selected or not. * @return whether there is something selected or not. */ public boolean isSelected() { return !(ls_poSelected == null || ls_poSelected.isEmpty()); } /** * @return the history */ public HistorySession getHistory() { return history; } /** * @param _history the history to set */ public void setHistory(final HistorySession _history) { this.history = _history; } }
package org.jasig.portal.layout.dlm; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jasig.portal.PortalException; import org.jasig.portal.layout.IUserLayoutStore; import org.jasig.portal.layout.UserLayoutStoreFactory; import org.jasig.portal.security.IPerson; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Looks for, applies against the ilf, and updates accordingly within the plf * the set of parameter edits made against channels incorporated from fragments. * * @version $Revision$ $Date$ * @since uPortal 2.6 */ public class ParameterEditManager { public static final String RCS_ID = "@(#) $Header$"; private static final Log LOG = LogFactory.getLog(ParameterEditManager.class); private static RDBMDistributedLayoutStore dls = null; /** * Hands back the single instance of RDBMDistributedLayoutStore. There is * already a method for aquiring a single instance of the configured layout * store so we delegate over there so that all references refer to the same * instance. This method is solely for convenience so that we don't have to * keep calling UserLayoutStoreFactory and casting the resulting class. */ private static RDBMDistributedLayoutStore getDLS() { if ( dls == null ) { IUserLayoutStore uls = null; uls = UserLayoutStoreFactory.getUserLayoutStoreImpl(); dls = (RDBMDistributedLayoutStore) uls; } return dls; } /** Get the parm edit set if any from the plf and process each edit command removing any that fail from the set so that the set is self cleaning. * @throws Exception */ static void applyAndUpdateParmEditSet( Document plf, Document ilf, IntegrationResult result ) { Element pSet = null; try { pSet = getParmEditSet( plf, null, false ); } catch( Exception e ) { LOG.error("Exception occurred while getting user's DLM " + "paramter-edit-set.", e); } if ( pSet == null ) return; NodeList edits = pSet.getChildNodes(); for( int i=edits.getLength()-1; i>=0; i { if ( applyEdit( (Element) edits.item(i), ilf ) == false ) { pSet.removeChild( edits.item(i) ); result.changedPLF = true; } else { result.changedILF = true; } } if ( pSet.getChildNodes().getLength() == 0 ) { plf.getDocumentElement().removeChild( pSet ); result.changedPLF = true; } } /** * Attempt to apply a single channel parameter edit command and return true * if it succeeds or false otherwise. If the edit is disallowed or the * target element no longer exists in the document the edit command fails * and returns false. * @throws Exception */ private static boolean applyEdit( Element edit, Document ilf ) { String nodeID = edit.getAttribute( Constants.ATT_TARGET ); Element channel = ilf.getElementById( nodeID ); if ( channel == null ) return false; // now get the name of the parameter to be edited and find that element String parmName = edit.getAttribute( Constants.ATT_NAME ); String parmValue = edit.getAttribute( Constants.ATT_USER_VALUE ); NodeList ilfParms = channel.getChildNodes(); Element targetParm = null; for(int i=0; i<ilfParms.getLength(); i++) { Element ilfParm = (Element) ilfParms.item(i); if (ilfParm.getAttribute(Constants.ATT_NAME).equals(parmName)) { targetParm = ilfParm; break; } } if (targetParm == null) // parameter not found so we are free to set { Element parameter = ilf.createElement("parameter"); parameter.setAttribute("name", parmName); parameter.setAttribute("value", parmValue); parameter.setAttribute("override", "yes"); channel.appendChild(parameter); return true; } /* TODO Add support for fragments to set dlm:editAllowed attribute for * channel parameters. (2005.11.04 mboyd) * * In the commented code below, the check for editAllowed will never be * seen on a parameter element in the * current database schema approach used by DLM. This is because * parameters are second class citizens of the layout structure. They * are not found in the up_layout_struct table but only in the * up_layout_param table. DLM functionality like dlm:editAllowed, * dlm:moveAllowed, dlm:deleteAllowed, and dlm:addChildAllowed were * implemented without schema changes by adding these as parameters to * structural elements and upon loading any parameter that begins with * 'dlm:' is placed as an attribute on the containing structural * element. So any channel parameter entry with dlm:editAllowed has that * value placed as an attribute on the containing channel not on the * parameter that was meant to have it. * * The only solution would be to add special dlm:parm children below * channels that would get the editAllowed value and then when creating * the DOM don't create those as child elements but use them to set the * attribute on the corresponding parameter by having the name of the * dlm:parm element be the name of the parameter to which it is to be * related. * * The result of this lack of functionality is that fragments can't * mark any channel parameters as dlm:editAllowed='false' thereby * further restricting which channel parameters can be edited beyond * what the channel definition specifies during publishing. */ //Attr editAllowed = targetParm.getAttributeNode( Constants.ATT_EDIT_ALLOWED ); //if ( editAllowed != null && editAllowed.getNodeValue().equals("false")) // return false; // target parm found. See if channel definition will still allow changes. Attr override = targetParm.getAttributeNode( Constants.ATT_OVERRIDE ); if ( override != null && !override.getNodeValue().equals(Constants.CAN_OVERRIDE)) return false; // now see if the change is still needed if (targetParm.getAttribute(Constants.ATT_VALUE).equals(parmValue)) return false; // user's edit same as fragment or chan def targetParm.setAttribute("value", parmValue); return true; } /** * Get the parameter edits set if any stored in the root of the document or * create it if passed-in create flag is true. */ private static Element getParmEditSet( Document plf, IPerson person, boolean create ) throws PortalException { Node root = plf.getDocumentElement(); Node child = root.getFirstChild(); while( child != null ) { if ( child.getNodeName().equals( Constants.ELM_PARM_SET ) ) return (Element) child; child = child.getNextSibling(); } if ( create == false ) return null; String ID = null; try { ID = getDLS().getNextStructDirectiveId( person ); } catch (Exception e) { throw new PortalException( "Exception encountered while " + "generating new parameter edit set node " + "Id for userId=" + person.getID(), e ); } Element parmSet = plf.createElement( Constants.ELM_PARM_SET ); parmSet.setAttribute( Constants.ATT_TYPE, Constants.ELM_PARM_SET ); parmSet.setAttribute( Constants.ATT_ID, ID ); parmSet.setIdAttribute(Constants.ATT_ID, true); root.appendChild( parmSet ); return parmSet; } /** * Create and append a parameter edit directive to parameter edits set for * applying a user specified value to a named parameter of the incorporated * channel represented by the passed-in target id. If one already exists * for that node and that name then the value of the existing edit is * changed to the passed-in value. */ public static synchronized void addParmEditDirective( Element compViewChannelNode, String targetId, String name, String value, IPerson person ) throws PortalException { Document plf = (Document) person.getAttribute( Constants.PLF ); Element parmSet = getParmEditSet( plf, person, true ); NodeList edits = parmSet.getChildNodes(); Element existingEdit = null; for(int i=0; i<edits.getLength(); i++) { Element edit = (Element) edits.item(i); if (edit.getAttribute(Constants.ATT_TARGET).equals(targetId) && edit.getAttribute(Constants.ATT_NAME).equals(name)) { existingEdit = edit; break; } } if (existingEdit == null) // existing one not found, create a new one { addParmEditDirective(targetId, name, value, person, plf, parmSet); return; } existingEdit.setAttribute(Constants.ATT_USER_VALUE, value); } /** This method does the actual work of adding a newly created parameter edit and adding it to the parameter edits set. */ private static void addParmEditDirective( String targetID, String name, String value, IPerson person, Document plf, Element parmSet ) throws PortalException { String ID = null; try { ID = getDLS().getNextStructDirectiveId( person ); } catch (Exception e) { throw new PortalException( "Exception encountered while " + "generating new parameter edit node " + "Id for userId=" + person.getID(), e ); } Element parm = plf.createElement( Constants.ELM_PARM_EDIT ); parm.setAttribute( Constants.ATT_TYPE, Constants.ELM_PARM_EDIT ); parm.setAttribute( Constants.ATT_ID, ID ); parm.setIdAttribute(Constants.ATT_ID, true); parm.setAttributeNS( Constants.NS_URI, Constants.ATT_TARGET, targetID ); parm.setAttribute( Constants.ATT_NAME, name ); parm.setAttribute( Constants.ATT_USER_VALUE, value ); parmSet.appendChild( parm ); } /** * Remove a parameter edit directive from the parameter edits set for * applying user specified values to a named parameter of an incorporated * channel represented by the passed-in target id. If one doesn't exists * for that node and that name then this call returns without any effects. */ public static void removeParmEditDirective( String targetId, String name, IPerson person ) throws PortalException { Document plf = (Document) person.getAttribute( Constants.PLF ); Element parmSet = getParmEditSet( plf, person, false ); if (parmSet == null) return; // no set so no edit to remove NodeList edits = parmSet.getChildNodes(); Element existingEdit = null; for(int i=0; i<edits.getLength(); i++) { Element edit = (Element) edits.item(i); if (edit.getAttribute(Constants.ATT_TARGET).equals(targetId) && edit.getAttribute(Constants.ATT_NAME).equals(name)) { parmSet.removeChild(edit); break; } } if (parmSet.getChildNodes().getLength() == 0) // no more edits, remove { Node parent = parmSet.getParentNode(); parent.removeChild(parmSet); } } }
package com.jayway.jsonpath; import org.junit.Test; import static com.jayway.jsonpath.internal.filter.FilterCompiler.compile; import static org.assertj.core.api.Assertions.assertThat; public class FilterCompilerTest { @Test public void valid_filters_compile() { assertThat(compile("[?(@)]").toString()).isEqualTo("[?(@)]"); assertThat(compile("[?(@)]").toString()).isEqualTo("[?(@)]"); assertThat(compile("[?(@.firstname)]").toString()).isEqualTo("[?(@['firstname'])]"); assertThat(compile("[?($.firstname)]").toString()).isEqualTo("[?($['firstname'])]"); assertThat(compile("[?(@['firstname'])]").toString()).isEqualTo("[?(@['firstname'])]"); assertThat(compile("[?($['firstname'].lastname)]").toString()).isEqualTo("[?($['firstname']['lastname'])]"); assertThat(compile("[?($['firstname']['lastname'])]").toString()).isEqualTo("[?($['firstname']['lastname'])]"); assertThat(compile("[?($['firstname']['lastname'].*)]").toString()).isEqualTo("[?($['firstname']['lastname'][*])]"); assertThat(compile("[?($['firstname']['num_eq'] == 1)]").toString()).isEqualTo("[?($['firstname']['num_eq'] == 1)]"); assertThat(compile("[?($['firstname']['num_gt'] > 1.1)]").toString()).isEqualTo("[?($['firstname']['num_gt'] > 1.1)]"); assertThat(compile("[?($['firstname']['num_lt'] < 11.11)]").toString()).isEqualTo("[?($['firstname']['num_lt'] < 11.11)]"); assertThat(compile("[?($['firstname']['str_eq'] == 'hej')]").toString()).isEqualTo("[?($['firstname']['str_eq'] == 'hej')]"); assertThat(compile("[?($['firstname']['str_eq'] == '')]").toString()).isEqualTo("[?($['firstname']['str_eq'] == '')]"); assertThat(compile("[?($['firstname']['str_eq'] == null)]").toString()).isEqualTo("[?($['firstname']['str_eq'] == null)]"); assertThat(compile("[?($['firstname']['str_eq'] == true)]").toString()).isEqualTo("[?($['firstname']['str_eq'] == true)]"); assertThat(compile("[?($['firstname']['str_eq'] == false)]").toString()).isEqualTo("[?($['firstname']['str_eq'] == false)]"); assertThat(compile("[?(@.firstname && @.lastname)]").toString()).isEqualTo("[?(@['firstname'] && @['lastname'])]"); assertThat(compile("[?((@.firstname || @.lastname) && @.and)]").toString()).isEqualTo("[?((@['firstname'] || @['lastname']) && @['and'])]"); assertThat(compile("[?((@.a || @.b || @.c) && @.x)]").toString()).isEqualTo("[?((@['a'] || @['b'] || @['c']) && @['x'])]"); assertThat(compile("[?((@.a && @.b && @.c) || @.x)]").toString()).isEqualTo("[?((@['a'] && @['b'] && @['c']) || @['x'])]"); assertThat(compile("[?((@.a && @.b || @.c) || @.x)]").toString()).isEqualTo("[?(((@['a'] && @['b']) || @['c']) || @['x'])]"); assertThat(compile("[?((@.a && @.b) || (@.c && @.d))]").toString()).isEqualTo("[?((@['a'] && @['b']) || (@['c'] && @['d']))]"); assertThat(compile("[?(@.a IN [1,2,3])]").toString()).isEqualTo("[?(@['a'] IN [1,2,3])]"); assertThat(compile("[?(@.a IN {'foo':'bar'})]").toString()).isEqualTo("[?(@['a'] IN {'foo':'bar'})]"); assertThat(compile("[?(@.value<'7')]").toString()).isEqualTo("[?(@['value'] < '7')]"); assertThat(compile("[?(@.message == 'it\\\\')]").toString()).isEqualTo("[?(@['message'] == 'it\\\\')]"); assertThat(compile("[?(@.message.min() > 10)]").toString()).isEqualTo("[?(@['message'].min() > 10)]"); assertThat(compile("[?(@.message.min()==10)]").toString()).isEqualTo("[?(@['message'].min() == 10)]"); assertThat(compile("[?(10 == @.message.min())]").toString()).isEqualTo("[?(10 == @['message'].min())]"); assertThat(compile("[?(((@)))]").toString()).isEqualTo("[?(@)]"); assertThat(compile("[?(@.name =~ /.*?/i)]").toString()).isEqualTo("[?(@['name'] =~ /.*?/i)]"); assertThat(compile("[?(@.name =~ /.*?/)]").toString()).isEqualTo("[?(@['name'] =~ /.*?/)]"); assertThat(compile("[?($[\"firstname\"][\"lastname\"])]").toString()).isEqualTo("[?($[\"firstname\"][\"lastname\"])]"); assertThat(compile("[?($[\"firstname\"].lastname)]").toString()).isEqualTo("[?($[\"firstname\"]['lastname'])]"); assertThat(compile("[?($[\"firstname\", \"lastname\"])]").toString()).isEqualTo("[?($[\"firstname\",\"lastname\"])]"); assertThat(compile("[?(((@.a && @.b || @.c)) || @.x)]").toString()).isEqualTo("[?(((@['a'] && @['b']) || @['c']) || @['x'])]"); } @Test public void string_quote_style_is_serialized() { assertThat(compile("[?('apa' == 'apa')]").toString()).isEqualTo("[?('apa' == 'apa')]"); assertThat(compile("[?('apa' == \"apa\")]").toString()).isEqualTo("[?('apa' == \"apa\")]"); } @Test public void string_can_contain_path_chars() { assertThat(compile("[?(@[')]@$)]'] == ')]@$)]')]").toString()).isEqualTo("[?(@[')]@$)]'] == ')]@$)]')]"); assertThat(compile("[?(@[\")]@$)]\"] == \")]@$)]\")]").toString()).isEqualTo("[?(@[\")]@$)]\"] == \")]@$)]\")]"); } @Test(expected = InvalidPathException.class) public void invalid_path_when_string_literal_is_unquoted() { compile("[?(@.foo == x)]"); } @Test public void or_has_lower_priority_than_and() { assertThat(compile("[?(@.category == 'fiction' && @.author == 'Evelyn Waugh' || @.price > 15)]").toString()) .isEqualTo("[?((@['category'] == 'fiction' && @['author'] == 'Evelyn Waugh') || @['price'] > 15)]"); } @Test public void invalid_filters_does_not_compile() { assertInvalidPathException("[?(@))]"); assertInvalidPathException("[?(@ FOO 1)]"); assertInvalidPathException("[?(@ || )]"); assertInvalidPathException("[?(@ == 'foo )]"); assertInvalidPathException("[?(@ == 1' )]"); assertInvalidPathException("[?(@.foo bar == 1)]"); assertInvalidPathException("[?(@.i == 5 @.i == 8)]"); assertInvalidPathException("[?(!5)]"); assertInvalidPathException("[?(!'foo')]"); } private void assertInvalidPathException(String filter){ try { compile(filter); throw new AssertionError("Expected " + filter + " to throw InvalidPathException"); } catch (InvalidPathException e){ //e.printStackTrace(); } } }
package com.imcode.imcms.api; /** * This exception is thrown from almost all methods in the service classes. It is thrown when the current logged * in user dosen't have the apropiate rights to do that operation. See the message for futher information. */ public class NoPermissionException extends RuntimeException { public NoPermissionException( String message ) { super( message ); } }
package com.taobao.zeus.socket.master; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.hadoop.hive.ql.parse.HiveParser.booleanValue_return; import org.jboss.netty.channel.Channel; import org.quartz.SchedulerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.taobao.zeus.broadcast.alarm.MailAlarm; import com.taobao.zeus.broadcast.alarm.SMSAlarm; import com.taobao.zeus.client.ZeusException; import com.taobao.zeus.model.DebugHistory; import com.taobao.zeus.model.FileDescriptor; import com.taobao.zeus.model.JobDescriptor; import com.taobao.zeus.model.JobHistory; import com.taobao.zeus.model.JobStatus; import com.taobao.zeus.model.JobStatus.TriggerType; import com.taobao.zeus.model.Profile; import com.taobao.zeus.mvc.Controller; import com.taobao.zeus.mvc.Dispatcher; import com.taobao.zeus.schedule.mvc.AddJobListener; import com.taobao.zeus.schedule.mvc.DebugInfoLog; import com.taobao.zeus.schedule.mvc.DebugListener; import com.taobao.zeus.schedule.mvc.JobController; import com.taobao.zeus.schedule.mvc.JobFailListener; import com.taobao.zeus.schedule.mvc.JobSuccessListener; import com.taobao.zeus.schedule.mvc.ScheduleInfoLog; import com.taobao.zeus.schedule.mvc.StopScheduleJobListener; import com.taobao.zeus.schedule.mvc.ZeusJobException; import com.taobao.zeus.schedule.mvc.event.DebugFailEvent; import com.taobao.zeus.schedule.mvc.event.DebugSuccessEvent; import com.taobao.zeus.schedule.mvc.event.Events; import com.taobao.zeus.schedule.mvc.event.JobFailedEvent; import com.taobao.zeus.schedule.mvc.event.JobLostEvent; import com.taobao.zeus.schedule.mvc.event.JobMaintenanceEvent; import com.taobao.zeus.schedule.mvc.event.JobSuccessEvent; import com.taobao.zeus.socket.SocketLog; import com.taobao.zeus.socket.master.MasterWorkerHolder.HeartBeatInfo; import com.taobao.zeus.socket.master.reqresp.MasterExecuteJob; import com.taobao.zeus.socket.protocol.Protocol.ExecuteKind; import com.taobao.zeus.socket.protocol.Protocol.Response; import com.taobao.zeus.socket.protocol.Protocol.Status; import com.taobao.zeus.store.GroupBean; import com.taobao.zeus.store.JobBean; import com.taobao.zeus.store.mysql.persistence.JobPersistence; import com.taobao.zeus.store.mysql.persistence.JobPersistenceOld; import com.taobao.zeus.util.CronExpParser; import com.taobao.zeus.util.DateUtil; import com.taobao.zeus.util.Environment; import com.taobao.zeus.util.Tuple; import com.taobao.zeus.util.ZeusDateTool; public class Master { private MasterContext context; private static Logger log = LoggerFactory.getLogger(Master.class); public Master(final MasterContext context) { this.context = context; GroupBean root = context.getGroupManager().getGlobeGroupBean(); if (Environment.isPrePub()) { // stop listener context.getDispatcher().addDispatcherListener( new StopScheduleJobListener()); } context.getDispatcher().addDispatcherListener( new AddJobListener(context, this)); context.getDispatcher().addDispatcherListener( new JobFailListener(context)); context.getDispatcher().addDispatcherListener( new DebugListener(context)); context.getDispatcher().addDispatcherListener( new JobSuccessListener(context)); Map<String, JobBean> allJobBeans = root.getAllSubJobBeans(); for (String id : allJobBeans.keySet()) { context.getDispatcher().addController( new JobController(context, this, id)); } context.getDispatcher().forwardEvent(Events.Initialize); context.setMaster(this); private void checkTimeOver() { for (MasterWorkerHolder w : context.getWorkers().values()) { checkScheduleTimeOver(w); //TODO // checkManualTimeOver(w); // checkDebugTimeOver(w); } } private void checkDebugTimeOver(MasterWorkerHolder w) { for (Map.Entry<String, Boolean> entry : w.getDebugRunnings().entrySet()) { if (entry.getValue() != null && entry.getValue()) { continue; } String historyId = entry.getKey(); DebugHistory his = context.getDebugHistoryManager() .findDebugHistory(historyId); long maxTime; FileDescriptor fd; try { fd = context.getFileManager().getFile(his.getFileId()); Profile pf = context.getProfileManager().findByUid( fd.getOwner()); String maxTimeString = pf.getHadoopConf().get( "zeus.job.maxtime"); if (maxTimeString == null || maxTimeString.trim().isEmpty()) { continue; } maxTime = Long.parseLong(maxTimeString); if (maxTime < 0) { continue; } } catch (Exception e) { continue; } long runTime = (System.currentTimeMillis() - his.getStartTime() .getTime()) / 1000 / 60; if (runTime > maxTime) { if (timeOverAlarm(null, fd, runTime, maxTime, 2, null)) { w.getDebugRunnings().replace(historyId, false, true); } } } } private void checkManualTimeOver(MasterWorkerHolder w) { for (Map.Entry<String, Boolean> entry : w.getManualRunnings() .entrySet()) { if (entry.getValue() != null && entry.getValue()) { continue; } String historyId = entry.getKey(); JobHistory his = context.getJobHistoryManager().findJobHistory( historyId); JobDescriptor jd = context.getGroupManager() .getJobDescriptor(his.getJobId()).getX(); long maxTime; try { String maxTimeString = jd.getProperties().get( "zeus.job.maxtime"); if (maxTimeString == null || maxTimeString.trim().isEmpty()) { continue; } maxTime = Long.parseLong(maxTimeString); if (maxTime < 0) { continue; } } catch (Exception e) { continue; } long runTime = (System.currentTimeMillis() - his.getStartTime() .getTime()) / 1000 / 60; if (runTime > maxTime) { if (timeOverAlarm(his, null, runTime, maxTime, 1, jd)) { w.getManualRunnings().replace(historyId, false, true); } } } } private void checkScheduleTimeOver(MasterWorkerHolder w) { for (Map.Entry<String, Boolean> entry : w.getRunnings().entrySet()) { if (entry.getValue() != null && entry.getValue()) { continue; } String jobId = entry.getKey(); JobDescriptor jd = context.getGroupManager() .getJobDescriptor(jobId).getX(); String maxTimeString = jd.getProperties().get("zeus.job.maxtime"); long maxTime; try { if (maxTimeString == null || maxTimeString.trim().isEmpty()) { continue; } maxTime = Long.parseLong(maxTimeString); if (maxTime < 0) { continue; } } catch (Exception e) { continue; } JobHistory his = context.getJobHistoryManager().findJobHistory( context.getGroupManager().getJobStatus(jobId) .getHistoryId()); if (his != null && his.getStartTime() != null) { long runTime = (System.currentTimeMillis() - his.getStartTime() .getTime()) / 1000 / 60; if (runTime > maxTime) { log.info("send the timeOverAlarm of job: " + jobId); if (timeOverAlarm(his, null, runTime, maxTime, 0, jd)) { w.getRunnings().replace(jobId, false, true); } } } } } private boolean timeOverAlarm(final JobHistory his, FileDescriptor fd, long runTime, long maxTime, int type, JobDescriptor jd) { final MailAlarm mailAlarm = (MailAlarm) context.getApplicationContext() .getBean("mailAlarm"); SMSAlarm smsAlarm = (SMSAlarm) context.getApplicationContext().getBean( "smsAlarm"); final StringBuffer title = new StringBuffer("["); switch (type) { case 0: title.append("").append("] jobID=").append(his.getJobId()); break; case 1: title.append("").append("] jobID=").append(his.getJobId()); break; case 2: title.append("").append("] ").append(fd.getName()); } final StringBuffer content = new StringBuffer(title); if(jd != null){ content.append("\nJOB").append(jd.getName()); Map<String, String> properties=jd.getProperties(); if(properties != null){ String plevel=properties.get("run.priority.level"); if("1".equals(plevel)){ content.append("\nJob: ").append("low"); }else if("2".equals(plevel)){ content.append("\nJob: ").append("middle"); }else if("3".equals(plevel)){ content.append("\nJob: ").append("high"); } } content.append("\nJOBOwner").append(jd.getOwner()); } content.append("\n").append(runTime).append("") .append("\n").append(maxTime).append(""); if(his != null){ content.append("\n\n").append(his.getLog().getContent().replaceAll("\\n", "<br/>")); } try { if (type == 2) { } else { new Thread() { @Override public void run() { try { Thread.sleep(6000); mailAlarm .alarm(his.getId(), title.toString(), content.toString() .replace("\n", "<br/>")); } catch (Exception e) { log.error("send run timeover mail alarm failed", e); } } }.start(); if (type == 0) { String priorityLevel = "3"; if(jd != null){ priorityLevel = jd.getProperties().get("run.priority.level"); } if(priorityLevel == null || !priorityLevel.trim().equals("1")){ Calendar now = Calendar.getInstance(); int hour = now.get(Calendar.HOUR_OF_DAY); int day = now.get(Calendar.DAY_OF_WEEK); if (day == Calendar.SATURDAY || day == Calendar.SUNDAY || hour < 9 || hour > 18) { smsAlarm.alarm(his.getId(), title.toString(),content.toString(), null); //mailAlarm.alarm(his.getId(), title.toString(),content.toString(), null); } } } } return true; } catch (Exception e) { log.error("send run timeover alarm failed", e); return false; } } public void workerDisconnectProcess(Channel channel) { MasterWorkerHolder holder = context.getWorkers().get(channel); if (holder != null) { context.getWorkers().remove(channel); final List<JobHistory> hiss = new ArrayList<JobHistory>(); Map<String, Tuple<JobDescriptor, JobStatus>> map = context .getGroupManager().getJobDescriptor( holder.getRunnings().keySet()); for (String key : map.keySet()) { JobStatus js = map.get(key).getY(); if (js.getHistoryId() != null) { hiss.add(context.getJobHistoryManager().findJobHistory( js.getHistoryId())); } js.setStatus(com.taobao.zeus.model.JobStatus.Status.FAILED); context.getGroupManager().updateJobStatus(js); } new Thread() { @Override public void run() { try { Thread.sleep(30000); } catch (InterruptedException e) { } for (JobHistory his : hiss) { String jobId = his.getJobId(); JobHistory history = new JobHistory(); history.setJobId(jobId); history.setToJobId(his.getToJobId()); history.setTriggerType(his.getTriggerType()); history.setIllustrate("worker"); history.setOperator(his.getOperator()); context.getJobHistoryManager().addJobHistory(history); Master.this.run(history); } }; }.start(); } } public void debug(DebugHistory debug) { JobElement element = new JobElement(debug.getId(), debug.getHost()); debug.setStatus(com.taobao.zeus.model.JobStatus.Status.RUNNING); debug.setStartTime(new Date()); context.getDebugHistoryManager().updateDebugHistory(debug); debug.getLog().appendZeus( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " "); context.getDebugHistoryManager().updateDebugHistoryLog(debug.getId(), debug.getLog().getContent()); context.getDebugQueue().offer(element); System.out.println("offer debug queue :" +context.getDebugQueue().size()+ " element :"+element.getJobID()); } public JobHistory run(JobHistory history) { String jobId = history.getJobId(); int priorityLevel = 3; try{ JobDescriptor jd = context.getGroupManager().getJobDescriptor(jobId).getX(); String priorityLevelStr = jd.getProperties().get("run.priority.level"); if(priorityLevelStr!=null){ priorityLevel = Integer.parseInt(priorityLevelStr); } }catch(Exception ex){ priorityLevel = 3; } JobElement element = new JobElement(jobId, history.getExecuteHost(), priorityLevel); history.setStatus(com.taobao.zeus.model.JobStatus.Status.RUNNING); if (history.getTriggerType() == TriggerType.MANUAL_RECOVER) { for (JobElement e : new ArrayList<JobElement>(context.getQueue())) { if (e.getJobID().equals(jobId)) { history.getLog().appendZeus(""); history.setStartTime(new Date()); history.setEndTime(new Date()); history.setStatus(com.taobao.zeus.model.JobStatus.Status.FAILED); break; } } for (Channel key : context.getWorkers().keySet()) { MasterWorkerHolder worker = context.getWorkers().get(key); if (worker.getRunnings().containsKey(jobId)) { history.getLog().appendZeus(""); history.setStartTime(new Date()); history.setEndTime(new Date()); history.setStatus(com.taobao.zeus.model.JobStatus.Status.FAILED); break; } } } if (history.getStatus() == com.taobao.zeus.model.JobStatus.Status.RUNNING) { history.getLog().appendZeus( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(new Date()) + " "); context.getJobHistoryManager().updateJobHistoryLog(history.getId(), history.getLog().getContent()); if (history.getTriggerType() == TriggerType.MANUAL) { element.setJobID(history.getId()); context.getManualQueue().offer(element); } else { JobStatus js = context.getGroupManager().getJobStatus( history.getJobId()); js.setStatus(com.taobao.zeus.model.JobStatus.Status.RUNNING); js.setHistoryId(history.getId()); context.getGroupManager().updateJobStatus(js); context.getQueue().offer(element); } } context.getJobHistoryManager().updateJobHistory(history); context.getJobHistoryManager().updateJobHistoryLog(history.getId(), history.getLog().getContent()); return history; } //actionaction public void runScheduleJobToAction(List<JobPersistenceOld> jobDetails, Date now, SimpleDateFormat df2, Map<Long, JobPersistence> actionDetails, String currentDateStr){ for(JobPersistenceOld jobDetail : jobDetails){ //ScheduleType: 0 ; 1; 2 if(jobDetail.getScheduleType() != null && jobDetail.getScheduleType()==0){ try{ String jobCronExpression = jobDetail.getCronExpression(); String cronDate= df2.format(now); List<String> lTime = new ArrayList<String>(); if(jobCronExpression != null && jobCronExpression.trim().length() > 0){ boolean isCronExp = false; try{ isCronExp = CronExpParser.Parser(jobCronExpression, cronDate, lTime); }catch(Exception ex){ isCronExp = false; } if (!isCronExp) { log.error("Cron," + cronDate + ";cron" + jobCronExpression); } for (int i = 0; i < lTime.size(); i++) { String actionDateStr = ZeusDateTool.StringToDateStr(lTime.get(i), "yyyy-MM-dd HH:mm:ss", "yyyyMMddHHmmss"); String actionCronExpr = ZeusDateTool.StringToDateStr(lTime.get(i), "yyyy-MM-dd HH:mm:ss", "s m H d M") + " ?"; JobPersistence actionPer = new JobPersistence(); actionPer.setId(Long.parseLong(actionDateStr)*10000+jobDetail.getId());//update action id actionPer.setToJobId(jobDetail.getId()); actionPer.setAuto(jobDetail.getAuto()); actionPer.setConfigs(jobDetail.getConfigs()); actionPer.setCronExpression(actionCronExpr);//update action cron expression actionPer.setCycle(jobDetail.getCycle()); String jobDependencies = jobDetail.getDependencies(); actionPer.setDependencies(jobDependencies); actionPer.setJobDependencies(jobDependencies); actionPer.setDescr(jobDetail.getDescr()); actionPer.setGmtCreate(jobDetail.getGmtCreate()); actionPer.setGmtModified(new Date()); actionPer.setGroupId(jobDetail.getGroupId()); actionPer.setHistoryId(jobDetail.getHistoryId()); actionPer.setHost(jobDetail.getHost()); actionPer.setLastEndTime(jobDetail.getLastEndTime()); actionPer.setLastResult(jobDetail.getLastResult()); actionPer.setName(jobDetail.getName()); actionPer.setOffset(jobDetail.getOffset()); actionPer.setOwner(jobDetail.getOwner()); actionPer.setPostProcessers(jobDetail.getPostProcessers()); actionPer.setPreProcessers(jobDetail.getPreProcessers()); actionPer.setReadyDependency(jobDetail.getReadyDependency()); actionPer.setResources(jobDetail.getResources()); actionPer.setRunType(jobDetail.getRunType()); actionPer.setScheduleType(jobDetail.getScheduleType()); actionPer.setScript(jobDetail.getScript()); actionPer.setStartTime(jobDetail.getStartTime()); actionPer.setStartTimestamp(jobDetail.getStartTimestamp()); actionPer.setStatisStartTime(jobDetail.getStatisStartTime()); actionPer.setStatisEndTime(jobDetail.getStatisEndTime()); actionPer.setStatus(jobDetail.getStatus()); actionPer.setTimezone(jobDetail.getTimezone()); try { //System.out.println("JobId: " + jobDetail.getId()+"; ActionId: " +actionPer.getId()); log.info("JobId: " + jobDetail.getId()+"; ActionId: " +actionPer.getId()); //if(actionPer.getId()>Long.parseLong(currentDateStr)){ context.getGroupManager().saveJob(actionPer); // System.out.println("success"); log.info("success"); actionDetails.put(actionPer.getId(),actionPer); } catch (ZeusException e) { // System.out.println("failed"); log.error("JobId:" + jobDetail.getId() + " Action" +actionPer.getId() + "", e); } } } }catch(Exception ex){ log.error("Action",ex); } } if(jobDetail.getScheduleType() != null && jobDetail.getScheduleType()==2){ try{ if(jobDetail.getDependencies()==null || jobDetail.getDependencies().trim().length()==0){ Date date = null; try { date = DateUtil.timestamp2Date(jobDetail.getStartTimestamp(), DateUtil.getDefaultTZStr()); //System.out.println(date); } catch (ParseException e) { date = new Date(); log.error("parse job start timestamp to date failed,", e); } SimpleDateFormat dfTime=new SimpleDateFormat("HHmmss"); SimpleDateFormat dfDate=new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat dfMinute=new SimpleDateFormat("mmss"); String currentDate = dfDate.format(new Date()); String startTime = dfTime.format(date); String startMinute = dfMinute.format(date); if(jobDetail.getCycle().equals("day")){ Date newStartDate = ZeusDateTool.StringToDate(currentDate+startTime, "yyyyMMddHHmmss"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(newStartDate.getTime()); calendar.add(Calendar.DATE, -1); calendar.getTime(); Date statisStartTime = calendar.getTime(); calendar.add(Calendar.MINUTE, 60*23+59); Date statisEndTime = calendar.getTime(); JobPersistence actionPer = new JobPersistence(); actionPer.setId(Long.parseLong(currentDate+startTime)*10000+jobDetail.getId());//update action id actionPer.setToJobId(jobDetail.getId()); actionPer.setAuto(jobDetail.getAuto()); actionPer.setConfigs(jobDetail.getConfigs()); actionPer.setCronExpression(jobDetail.getCronExpression()); actionPer.setCycle(jobDetail.getCycle()); String jobDependencies = jobDetail.getDependencies(); actionPer.setDependencies(jobDependencies); actionPer.setJobDependencies(jobDependencies); actionPer.setDescr(jobDetail.getDescr()); actionPer.setGmtCreate(jobDetail.getGmtCreate()); actionPer.setGmtModified(new Date()); actionPer.setGroupId(jobDetail.getGroupId()); actionPer.setHistoryId(jobDetail.getHistoryId()); actionPer.setHost(jobDetail.getHost()); actionPer.setLastEndTime(jobDetail.getLastEndTime()); actionPer.setLastResult(jobDetail.getLastResult()); actionPer.setName(jobDetail.getName()); actionPer.setOffset(jobDetail.getOffset()); actionPer.setOwner(jobDetail.getOwner()); actionPer.setPostProcessers(jobDetail.getPostProcessers()); actionPer.setPreProcessers(jobDetail.getPreProcessers()); actionPer.setReadyDependency(jobDetail.getReadyDependency()); actionPer.setResources(jobDetail.getResources()); actionPer.setRunType(jobDetail.getRunType()); actionPer.setScheduleType(jobDetail.getScheduleType()); actionPer.setScript(jobDetail.getScript()); actionPer.setStartTime(newStartDate); actionPer.setStartTimestamp(newStartDate.getTime()); actionPer.setStatisStartTime(statisStartTime); actionPer.setStatisEndTime(statisEndTime); actionPer.setStatus(jobDetail.getStatus()); actionPer.setTimezone(jobDetail.getTimezone()); try { //System.out.println("JobId: " + jobDetail.getId()+"; ActionId: " +actionPer.getId()); //if(actionPer.getId()>Long.parseLong(currentDateStr)){ context.getGroupManager().saveJob(actionPer); System.out.println("success"); actionDetails.put(actionPer.getId(),actionPer); } catch (ZeusException e) { System.out.println("failed"); log.error("JobId:" + jobDetail.getId() + " Action" +actionPer.getId() + "", e); } } if(jobDetail.getCycle().equals("hour")){ for (int i = 0; i < 24; i++) { String startHour = String.valueOf(i); if(startHour.trim().length()<2){ startHour = "0"+startHour; } Date newStartDate = ZeusDateTool.StringToDate(currentDate+startHour+startMinute, "yyyyMMddHHmmss"); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(newStartDate.getTime()); calendar.add(Calendar.HOUR, -1); calendar.getTime(); Date statisStartTime = calendar.getTime(); calendar.add(Calendar.MINUTE, 59); Date statisEndTime = calendar.getTime(); JobPersistence actionPer = new JobPersistence(); actionPer.setId(Long.parseLong(currentDate+startHour+startMinute)*10000+jobDetail.getId());//update action id actionPer.setToJobId(jobDetail.getId()); actionPer.setAuto(jobDetail.getAuto()); actionPer.setConfigs(jobDetail.getConfigs()); actionPer.setCronExpression(jobDetail.getCronExpression()); actionPer.setCycle(jobDetail.getCycle()); String jobDependencies = jobDetail.getDependencies(); actionPer.setDependencies(jobDependencies); actionPer.setJobDependencies(jobDependencies); actionPer.setDescr(jobDetail.getDescr()); actionPer.setGmtCreate(jobDetail.getGmtCreate()); actionPer.setGmtModified(new Date()); actionPer.setGroupId(jobDetail.getGroupId()); actionPer.setHistoryId(jobDetail.getHistoryId()); actionPer.setHost(jobDetail.getHost()); actionPer.setLastEndTime(jobDetail.getLastEndTime()); actionPer.setLastResult(jobDetail.getLastResult()); actionPer.setName(jobDetail.getName()); actionPer.setOffset(jobDetail.getOffset()); actionPer.setOwner(jobDetail.getOwner()); actionPer.setPostProcessers(jobDetail.getPostProcessers()); actionPer.setPreProcessers(jobDetail.getPreProcessers()); actionPer.setReadyDependency(jobDetail.getReadyDependency()); actionPer.setResources(jobDetail.getResources()); actionPer.setRunType(jobDetail.getRunType()); actionPer.setScheduleType(jobDetail.getScheduleType()); actionPer.setScript(jobDetail.getScript()); actionPer.setStartTime(newStartDate); actionPer.setStartTimestamp(newStartDate.getTime()); actionPer.setStatisStartTime(statisStartTime); actionPer.setStatisEndTime(statisEndTime); actionPer.setStatus(jobDetail.getStatus()); actionPer.setTimezone(jobDetail.getTimezone()); try { System.out.println("JobId: " + jobDetail.getId()+"; ActionId: " +actionPer.getId()); //if(actionPer.getId()>Long.parseLong(currentDateStr)){ context.getGroupManager().saveJob(actionPer); System.out.println("success"); actionDetails.put(actionPer.getId(),actionPer); } catch (ZeusException e) { System.out.println("failed"); log.error("JobId:" + jobDetail.getId() + " Action" +actionPer.getId() + "", e); } } } } }catch(Exception ex){ log.error("Action",ex); } } } } //action public void runDependencesJobToAction(List<JobPersistenceOld> jobDetails, Map<Long, JobPersistence> actionDetails,String currentDateStr, int loopCount){ int noCompleteCount = 0; loopCount ++; // System.out.println("loopCount"+loopCount); for(JobPersistenceOld jobDetail : jobDetails){ //ScheduleType: 0 ; 1; 2 if((jobDetail.getScheduleType() != null && jobDetail.getScheduleType()==1) || (jobDetail.getScheduleType() != null && jobDetail.getScheduleType()==2)){ try{ String jobDependencies = jobDetail.getDependencies(); String actionDependencies = ""; if(jobDependencies != null && jobDependencies.trim().length()>0){ Map<String,List<JobPersistence>> dependActionList = new HashMap<String,List<JobPersistence>>(); String[] dependStrs = jobDependencies.split(","); for(String deps : dependStrs){ List<JobPersistence> dependActions = new ArrayList<JobPersistence>(); Iterator<JobPersistence> actionIt = actionDetails.values().iterator(); while(actionIt.hasNext()){ JobPersistence action = actionIt.next(); if(action.getToJobId().toString().equals(deps)){ dependActions.add(action); } } dependActionList.put(deps, dependActions); if(loopCount > 40){ if(!jobDetail.getConfigs().contains("sameday")){ if(dependActionList.get(deps).size()==0){ List<JobPersistence> lastJobActions = context.getGroupManager().getLastJobAction(deps); if(lastJobActions != null && lastJobActions.size()>0){ actionDetails.put(lastJobActions.get(0).getId(),lastJobActions.get(0)); dependActions.add(lastJobActions.get(0)); dependActionList.put(deps, dependActions); }else{ break; } } } } } boolean isComplete = true; String actionMostDeps = ""; for(String deps : dependStrs){ if(dependActionList.get(deps).size()==0){ isComplete = false; noCompleteCount ++; break; } if(actionMostDeps.trim().length()==0){ actionMostDeps = deps; } if(dependActionList.get(deps).size()>dependActionList.get(actionMostDeps).size()){ actionMostDeps = deps; }else if(dependActionList.get(deps).size()==dependActionList.get(actionMostDeps).size()){ if(dependActionList.get(deps).get(0).getId()<dependActionList.get(actionMostDeps).get(0).getId()){ actionMostDeps = deps; } } } if(!isComplete){ continue; }else{ List<JobPersistence> actions = dependActionList.get(actionMostDeps); if(actions != null && actions.size()>0){ for(JobPersistence actionModel : actions){ actionDependencies = String.valueOf(actionModel.getId()); for(String deps : dependStrs){ if(!deps.equals(actionMostDeps)){ List<JobPersistence> actionOthers = dependActionList.get(deps); Long actionOtherId = actionOthers.get(0).getId(); for(JobPersistence actionOtherModel : actionOthers){ if(Math.abs((actionOtherModel.getId()-actionModel.getId()))<Math.abs((actionOtherId-actionModel.getId()))){ actionOtherId = actionOtherModel.getId(); } } if(actionDependencies.trim().length()>0){ actionDependencies += ","; } actionDependencies += String.valueOf((actionOtherId/10000)*10000 + Long.parseLong(deps)); } } //action JobPersistence actionPer = new JobPersistence(); actionPer.setId((actionModel.getId()/10000)*10000+jobDetail.getId());//update action id actionPer.setToJobId(jobDetail.getId()); actionPer.setAuto(jobDetail.getAuto()); actionPer.setConfigs(jobDetail.getConfigs()); actionPer.setCronExpression(jobDetail.getCronExpression());//update action cron expression actionPer.setCycle(jobDetail.getCycle()); actionPer.setDependencies(actionDependencies); actionPer.setJobDependencies(jobDependencies); actionPer.setDescr(jobDetail.getDescr()); actionPer.setGmtCreate(jobDetail.getGmtCreate()); actionPer.setGmtModified(new Date()); actionPer.setGroupId(jobDetail.getGroupId()); actionPer.setHistoryId(jobDetail.getHistoryId()); actionPer.setHost(jobDetail.getHost()); actionPer.setLastEndTime(jobDetail.getLastEndTime()); actionPer.setLastResult(jobDetail.getLastResult()); actionPer.setName(jobDetail.getName()); actionPer.setOffset(jobDetail.getOffset()); actionPer.setOwner(jobDetail.getOwner()); actionPer.setPostProcessers(jobDetail.getPostProcessers()); actionPer.setPreProcessers(jobDetail.getPreProcessers()); actionPer.setReadyDependency(jobDetail.getReadyDependency()); actionPer.setResources(jobDetail.getResources()); actionPer.setRunType(jobDetail.getRunType()); actionPer.setScheduleType(jobDetail.getScheduleType()); actionPer.setScript(jobDetail.getScript()); actionPer.setStartTime(jobDetail.getStartTime()); actionPer.setStartTimestamp(jobDetail.getStartTimestamp()); actionPer.setStatisStartTime(jobDetail.getStatisStartTime()); actionPer.setStatisEndTime(jobDetail.getStatisEndTime()); actionPer.setStatus(jobDetail.getStatus()); actionPer.setTimezone(jobDetail.getTimezone()); try { if(!actionDetails.containsKey(actionPer.getId())){ System.out.println("JobId: " + jobDetail.getId()+"; ActionId: " +actionPer.getId()); //if(actionPer.getId()>Long.parseLong(currentDateStr)){ context.getGroupManager().saveJob(actionPer); System.out.println("success"); actionDetails.put(actionPer.getId(),actionPer); } } catch (ZeusException e) { log.error("JobId:" + jobDetail.getId() + " Action" +actionPer.getId() + "", e); } } } } } }catch(Exception ex){ log.error("Action", ex); } } } if(noCompleteCount > 0 && loopCount < 60){ runDependencesJobToAction(jobDetails, actionDetails, currentDateStr, loopCount); } } }
package net.af0.sesame; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.FilterQueryProvider; import android.widget.SearchView; import android.widget.SimpleCursorAdapter; import com.github.amlcurran.showcaseview.ShowcaseView; import com.github.amlcurran.showcaseview.targets.ActionItemTarget; import com.github.amlcurran.showcaseview.targets.ActionViewTarget; import com.github.amlcurran.showcaseview.targets.Target; import net.sqlcipher.CursorWrapper; /** * An activity representing a list of Items. This activity has different presentations for handset * and tablet-size devices. On handsets, the activity presents a list of items, which when touched, * lead to a {@link ItemDetailActivity} representing item details. On tablets, the activity presents * the list of items and item details side-by-side using two vertical panes. * <p/> * The activity makes heavy use of fragments. The list of items is a {@link ItemListFragment} and * the item details (if present) is a {@link ItemDetailFragment}. * <p/> * This activity also implements the required {@link ItemListFragment.Callbacks} interface to listen * for item selections. */ public final class ItemListActivity extends FragmentActivity implements ItemListFragment.Callbacks, SearchView.OnQueryTextListener, LoaderManager.LoaderCallbacks<Cursor> { private static final int ADD_RECORD_REQUEST = 0; private static final int EDIT_RECORD_REQUEST = 1; private static final int LOADER_ID = 1; // ShowcaseView for first run. ShowcaseView showcase_; /** * Whether or not the activity is in two-pane mode, i.e. running on a tablet device. */ private boolean twoPane_; private long selectedId_; private ItemListFragment itemListFragment_; private SimpleCursorAdapter itemListAdapter_; @Override protected void onResume() { // If we're locked, go to the unlock view. if (SQLCipherDatabase.isLocked()) { startActivity(new Intent(getBaseContext(), UnlockActivity.class).setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP)); } else { refreshListFromDatabase(); } super.onResume(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu items for use in the action bar MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.list_activity_actions, menu); // Set up search widget SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView(); searchView.setOnQueryTextListener(this); // Show help showcase. Target t; int text; if (menu.findItem(R.id.add) != null) { // Not in overflow t = new ActionItemTarget(this, R.id.add); text = R.string.showcase_add_content_no_overflow; } else { t = new ActionViewTarget(this, ActionViewTarget.Type.OVERFLOW); text = R.string.showcase_add_content_in_overflow; } showcase_ = new ShowcaseView.Builder(this, true) .setTarget(t) .setContentTitle(R.string.showcase_add_title) .setContentText(text) .setStyle(R.style.AppTheme) .singleShot(Constants.SINGLE_SHOT_ITEM_LIST) .build(); return super.onCreateOptionsMenu(menu); } /** * Handle search queries. */ public boolean onQueryTextSubmit(String query) { itemListAdapter_.getFilter().filter(query); return true; } /** * Handle search queries. */ public boolean onQueryTextChange(String query) { itemListAdapter_.getFilter().filter(query); return true; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_item_list); if (findViewById(R.id.item_detail_container) != null) { // The detail container view will be present only in the large-screen layouts // (res/values-large and res/values-sw600dp). If this view is present, then the activity // should be in two-pane mode.x twoPane_ = true; // In two-pane mode, list items should be given the 'activated' state when touched. ((ItemListFragment) getSupportFragmentManager() .findFragmentById(R.id.item_list)) .setActivateOnItemClick(); } itemListFragment_ = (ItemListFragment) getSupportFragmentManager() .findFragmentById(R.id.item_list); itemListAdapter_ = new SimpleCursorAdapter( this, R.layout.two_line_list_item, null, new String[]{SQLCipherDatabase.COLUMN_DOMAIN, SQLCipherDatabase.COLUMN_USERNAME}, new int[]{R.id.text1, R.id.text2}, 0 ); itemListAdapter_.setFilterQueryProvider(new FilterQueryProvider() { @Override public Cursor runQuery(CharSequence constraint) { return SQLCipherDatabase.getContaining(constraint.toString()); } }); getSupportLoaderManager().initLoader(LOADER_ID, null, this); itemListFragment_.setListAdapter(itemListAdapter_); } /** * Callback method for option item selection. */ @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_lock: startActivity(new Intent(this, UnlockActivity.class).setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK )); return true; case R.id.action_export: return Common.ExportKeys(this); case R.id.action_import: Common.StartImportKeys(this); return true; case R.id.action_settings: startActivity(new Intent(this, SettingsActivity.class)); return true; case R.id.add: if (twoPane_) { // In two-pane mode, show the add key view in this activity by adding or // replacing the detail fragment using a fragment transaction. Bundle arguments = new Bundle(); arguments.putBoolean(Constants.ARG_TWO_PANE, Boolean.TRUE); EditItemFragment fragment = new EditItemFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .replace(R.id.item_detail_container, fragment) .commit(); } else { // In single-pane mode, simply start the add key activity for the selected item Intent addIntent = new Intent(this, EditItemActivity.class); addIntent.putExtra(Constants.ARG_TWO_PANE, Boolean.FALSE); startActivityForResult(addIntent, ADD_RECORD_REQUEST); } return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // There's probably a more efficient way to do this on item add than rereading the database, // but at least this ensures consistency, I guess. switch (requestCode) { case ADD_RECORD_REQUEST: if (resultCode == RESULT_OK) { refreshListFromDatabase(); // TODO: set selection to added item } break; case EDIT_RECORD_REQUEST: if (resultCode == RESULT_OK) { refreshListFromDatabase(); } onItemSelected(String.valueOf(selectedId_)); break; case Constants.IMPORT_DATABASE_RESULT: if (resultCode == RESULT_OK) { Common.onImportKeysResult(this, data, new Runnable() { @Override public void run() { refreshListFromDatabase(); } } ); } break; } } * /* Called from the child ItemListFragment on the Edit context menu. */ public void onEditItem(int position) { long id = getRecordFromPosition(position); if (twoPane_) { Bundle arguments = new Bundle(); arguments.putBoolean(Constants.ARG_TWO_PANE, true); arguments.putLong(Constants.ARG_ITEM_ID, id); EditItemFragment fragment = new EditItemFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .replace(R.id.item_detail_container, fragment) .commit(); } else { // In single-pane mode, simply start the detail activity for the selected item ID. Intent editIntent = new Intent(this, EditItemActivity.class); editIntent.putExtra(Constants.ARG_ITEM_ID, id); startActivityForResult(editIntent, EDIT_RECORD_REQUEST); } } /** * Called from the child ItemListFragment on the Edit context menu. */ public void onDeleteItem(int position) { long id = getRecordFromPosition(position); Bundle arguments = new Bundle(); arguments.putLong(Constants.ARG_ITEM_ID, id); DeleteItemFragment fragment = new DeleteItemFragment(); fragment.setArguments(arguments); fragment.show(getSupportFragmentManager(), "delete"); } /** * Callback method from {@link ItemListFragment.Callbacks} * indicating that the item with the given ID was selected. */ @Override public void onItemSelected(String id) { if (id == null) { // Clear the fragment. if (twoPane_) { getSupportFragmentManager().beginTransaction().remove( getSupportFragmentManager().findFragmentById(R.id.item_detail_container)); } return; } selectedId_ = Long.valueOf(id); if (SQLCipherDatabase.getRecord(selectedId_) == null) { // Item was deleted. We should find a more elegant way to do this. return; } if (twoPane_) { // In two-pane mode, show the detail view in this activity by // adding or replacing the detail fragment using a fragment transaction. Bundle arguments = new Bundle(); arguments.putLong(Constants.ARG_ITEM_ID, selectedId_); ItemDetailFragment fragment = new ItemDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .replace(R.id.item_detail_container, fragment) .commit(); } else { // In single-pane mode, simply start the detail activity // for the selected item ID. Intent detailIntent = new Intent(this, ItemDetailActivity.class); detailIntent.putExtra(Constants.ARG_ITEM_ID, selectedId_); startActivity(detailIntent); } } // Implement Loader callbacks. @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { return new RecordCursorLoader(this); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { itemListAdapter_.swapCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) { itemListAdapter_.swapCursor(null); } /** * Refresh the displayed list adapter from the open database. */ void refreshListFromDatabase() { getSupportLoaderManager().restartLoader(LOADER_ID, null, this); } /** * Get the record object for the specified offset in the list. */ private long getRecordFromPosition(int position) { return ((CursorWrapper)itemListAdapter_.getItem(position)).getLong(0); } private static class RecordCursorLoader extends CursorLoader { public RecordCursorLoader(Context ctx) { super(ctx); } @Override public Cursor loadInBackground() { if (SQLCipherDatabase.isLocked()) { return null; } return SQLCipherDatabase.getAllCursor(); } } }
package io.spine.server.entity; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.protobuf.Any; import io.spine.annotation.Internal; import io.spine.base.Error; import io.spine.base.EventMessage; import io.spine.base.Identifier; import io.spine.client.EntityId; import io.spine.core.Command; import io.spine.core.CommandId; import io.spine.core.CommandValidationError; import io.spine.core.Event; import io.spine.core.EventId; import io.spine.core.EventValidationError; import io.spine.core.MessageId; import io.spine.core.Origin; import io.spine.core.Version; import io.spine.option.EntityOption; import io.spine.server.entity.model.EntityClass; import io.spine.server.event.RejectionEnvelope; import io.spine.server.type.CommandEnvelope; import io.spine.server.type.EventEnvelope; import io.spine.system.server.CannotDispatchDuplicateCommand; import io.spine.system.server.CannotDispatchDuplicateEvent; import io.spine.system.server.CommandTarget; import io.spine.system.server.ConstraintViolated; import io.spine.system.server.EntityTypeName; import io.spine.system.server.HandlerFailedUnexpectedly; import io.spine.system.server.SystemWriteSide; import io.spine.system.server.event.CommandDispatchedToHandler; import io.spine.system.server.event.CommandHandled; import io.spine.system.server.event.CommandRejected; import io.spine.system.server.event.EntityArchived; import io.spine.system.server.event.EntityCreated; import io.spine.system.server.event.EntityDeleted; import io.spine.system.server.event.EntityRestored; import io.spine.system.server.event.EntityStateChanged; import io.spine.system.server.event.EntityUnarchived; import io.spine.system.server.event.EventDispatchedToReactor; import io.spine.system.server.event.EventDispatchedToSubscriber; import io.spine.system.server.event.EventImported; import io.spine.system.server.event.TargetAssignedToCommand; import io.spine.type.TypeUrl; import io.spine.validate.ValidationError; import java.util.Collection; import java.util.Optional; import java.util.Set; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static io.spine.base.Time.currentTime; import static io.spine.core.CommandValidationError.DUPLICATE_COMMAND_VALUE; import static io.spine.core.EventValidationError.DUPLICATE_EVENT_VALUE; import static io.spine.server.entity.EventFilter.allowAll; /** * The lifecycle callbacks of an {@link Entity}. * * <p>On each call, posts from zero to several system commands. See the individual method * descriptions for more info about the posted commands. * * <p>An instance of {@code EntityLifecycle} is associated with a single instance of entity. * * @see Repository#lifecycleOf(Object) Repository.lifecycleOf(I) */ @Internal @SuppressWarnings({"OverlyCoupledClass", "ClassWithTooManyMethods"}) // Posts system messages in multiple cases. public class EntityLifecycle { /** * The {@link SystemWriteSide} which the system messages are posted into. */ private final SystemWriteSide systemWriteSide; /** * The {@link EventFilter} applied to system events before posting. */ private final EventFilter eventFilter; /** * The message ID of of the associated {@link Entity} state. * * <p>Most commands posted by the {@code EntityLifecycle} are handled by * the {@code io.spine.system.server.EntityHistoryAggregate}. * Thus, storing an ID as a field is convenient. */ private final MessageId entityId; private final EntityTypeName typeName; /** * Creates a new instance. * * <p>Use this constructor for test purposes <b>only</b>. * * @see EntityLifecycle.Builder */ @VisibleForTesting protected EntityLifecycle(Object entityId, TypeUrl entityType, SystemWriteSide writeSide, EventFilter eventFilter, EntityTypeName typeName) { this.systemWriteSide = checkNotNull(writeSide); this.eventFilter = checkNotNull(eventFilter); this.typeName = checkNotNull(typeName); this.entityId = MessageId .newBuilder() .setId(Identifier.pack(entityId)) .setTypeUrl(entityType.value()) .vBuild(); } private EntityLifecycle(Builder builder) { this(builder.entityId, builder.entityType.stateType(), builder.writeSide, builder.eventFilter, builder.entityType.typeName()); } /** * Posts the {@link EntityCreated} system event. * * @param entityKind * the kind of the created entity */ public final void onEntityCreated(EntityOption.Kind entityKind) { EntityCreated event = EntityCreated .newBuilder() .setEntity(entityId) .setKind(entityKind) .vBuild(); postEvent(event); } /** * Posts the {@link TargetAssignedToCommand} * system command. * * @param commandId * the ID of the command which should be handled by the entity */ public final void onTargetAssignedToCommand(CommandId commandId) { EntityId entityId = EntityId .newBuilder() .setId(this.entityId.getId()) .buildPartial(); CommandTarget target = CommandTarget .newBuilder() .setEntityId(entityId) .setTypeUrl(this.entityId.getTypeUrl()) .vBuild(); TargetAssignedToCommand event = TargetAssignedToCommand .newBuilder() .setId(commandId) .setTarget(target) .vBuild(); postEvent(event); } /** * Posts the {@link io.spine.system.server.event.CommandDispatchedToHandler} system command. * * @param command * the dispatched command */ public final void onDispatchCommand(Command command) { CommandDispatchedToHandler systemCommand = CommandDispatchedToHandler .newBuilder() .setReceiver(entityId) .setPayload(command) .setWhenDispatched(currentTime()) .setEntityType(typeName) .vBuild(); Origin systemEventOrigin = CommandEnvelope.of(command) .asMessageOrigin(); postEvent(systemCommand, systemEventOrigin); } /** * Posts the {@link CommandHandled} system event. * * @param command * the handled command */ public final void onCommandHandled(Command command) { CommandHandled systemEvent = CommandHandled .newBuilder() .setId(command.getId()) .vBuild(); Origin systemEventOrigin = CommandEnvelope.of(command) .asMessageOrigin(); postEvent(systemEvent, systemEventOrigin); } /** * Posts the {@link CommandRejected} system event. * * @param commandId * the ID of the rejected command * @param rejection * the rejection event */ public final void onCommandRejected(CommandId commandId, Event rejection) { CommandRejected systemEvent = CommandRejected .newBuilder() .setId(commandId) .setRejectionEvent(rejection) .vBuild(); Origin systemEventOrigin = RejectionEnvelope.from(EventEnvelope.of(rejection)) .asMessageOrigin(); postEvent(systemEvent, systemEventOrigin); } /** * Posts the {@link EventDispatchedToSubscriber} system event. * * @param event * the dispatched event */ public final void onDispatchEventToSubscriber(Event event) { EventDispatchedToSubscriber systemCommand = EventDispatchedToSubscriber .newBuilder() .setReceiver(entityId) .setPayload(event) .setWhenDispatched(currentTime()) .setEntityType(typeName) .vBuild(); Origin systemEventOrigin = EventEnvelope.of(event) .asMessageOrigin(); postEvent(systemCommand, systemEventOrigin); } public final void onEventImported(Event event) { EventImported systemEvent = EventImported .newBuilder() .setReceiver(entityId) .setPayload(event) .setWhenImported(currentTime()) .setEntityType(typeName) .vBuild(); Origin systemEventOrigin = EventEnvelope.of(event) .asMessageOrigin(); postEvent(systemEvent, systemEventOrigin); } /** * Posts the {@link EventDispatchedToReactor} system event. * * @param event * the dispatched event */ public final void onDispatchEventToReactor(Event event) { EventDispatchedToReactor systemCommand = EventDispatchedToReactor .newBuilder() .setReceiver(entityId) .setPayload(event) .setWhenDispatched(currentTime()) .setEntityType(typeName) .vBuild(); Origin systemEventOrigin = EventEnvelope.of(event) .asMessageOrigin(); postEvent(systemCommand, systemEventOrigin); } /** * Posts the {@link EntityStateChanged} system event and the events related to * the lifecycle flags. * * <p>Only the actual changes in the entity attributes result into system events. * If the previous and new values are equal, then no events are posted. * * @param change * the change in the entity state and attributes * @param messageIds * the IDs of the messages which caused the {@code change}; typically, * {@link EventId EventId}s or {@link CommandId}s */ public final void onStateChanged(EntityRecordChange change, Set<? extends MessageId> messageIds, Origin origin) { postIfChanged(change, messageIds, origin); postIfArchived(change, messageIds); postIfDeleted(change, messageIds); postIfExtracted(change, messageIds); postIfRestored(change, messageIds); } /** * Posts the {@link ConstraintViolated} system event. * * @param lastMessage * the last message handled by the entity * @param root * the root message of the message chain which led to the violation * @param error * the description of violation * @param version * the version of the invalid entity */ public final void onInvalidEntity(MessageId lastMessage, MessageId root, ValidationError error, Version version) { MessageId entityId = MessageId .newBuilder() .setId(this.entityId.getId()) .setTypeUrl(this.entityId.getTypeUrl()) .setVersion(version) .buildPartial(); ConstraintViolated event = ConstraintViolated .newBuilder() .setEntity(entityId) .setLastMessage(lastMessage) .setRootMessage(root) .addAllViolation(error.getConstraintViolationList()) .vBuild(); postEvent(event); } /** * Posts a diagnostic event on a dispatching error. * * <p>Depending on the error type and code, may emit {@link HandlerFailedUnexpectedly}, * {@link CannotDispatchDuplicateEvent}, or {@link CannotDispatchDuplicateCommand}. * * @param dispatchedSignal * the ID of the dispatched signal * @param error * the dispatching error */ public final void onDispatchingFailed(MessageId dispatchedSignal, Error error) { checkNotNull(dispatchedSignal); checkNotNull(error); boolean duplicate = postIfDuplicate(dispatchedSignal, error); if (!duplicate) { postHandlerFailed(dispatchedSignal, error); } } public void onDuplicateEvent(EventId eventId) { checkNotNull(eventId); CannotDispatchDuplicateEvent event = CannotDispatchDuplicateEvent .newBuilder() .setEntity(entityId) .setEvent(eventId) .vBuild(); postEvent(event); } public void onDuplicateCommand(CommandId commandId) { checkNotNull(commandId); CannotDispatchDuplicateCommand event = CannotDispatchDuplicateCommand .newBuilder() .setEntity(entityId) .setCommand(commandId) .vBuild(); postEvent(event); } private void postIfChanged(EntityRecordChange change, Collection<? extends MessageId> messageIds, Origin origin) { Any oldState = change.getPreviousValue() .getState(); Any newState = change.getNewValue() .getState(); if (!oldState.equals(newState)) { Version newVersion = change.getNewValue() .getVersion(); EntityStateChanged event = EntityStateChanged .newBuilder() .setEntity(entityId) .setNewState(newState) .addAllSignalId(messageIds) .setNewVersion(newVersion) .vBuild(); postEvent(event, origin); } } private void postIfArchived(EntityRecordChange change, Collection<? extends MessageId> messageIds) { boolean oldValue = change.getPreviousValue() .getLifecycleFlags() .getArchived(); boolean newValue = change.getNewValue() .getLifecycleFlags() .getArchived(); if (newValue && !oldValue) { Version version = change.getNewValue() .getVersion(); EntityArchived event = EntityArchived .newBuilder() .setEntity(entityId) .addAllSignalId(ImmutableList.copyOf(messageIds)) .setVersion(version) .vBuild(); postEvent(event); } } private void postIfDeleted(EntityRecordChange change, Collection<? extends MessageId> messageIds) { boolean oldValue = change.getPreviousValue() .getLifecycleFlags() .getDeleted(); boolean newValue = change.getNewValue() .getLifecycleFlags() .getDeleted(); if (newValue && !oldValue) { Version version = change.getNewValue() .getVersion(); EntityDeleted event = EntityDeleted .newBuilder() .setEntity(entityId) .addAllSignalId(ImmutableList.copyOf(messageIds)) .setVersion(version) .vBuild(); postEvent(event); } } private void postIfExtracted(EntityRecordChange change, Collection<? extends MessageId> messageIds) { boolean oldValue = change.getPreviousValue() .getLifecycleFlags() .getArchived(); boolean newValue = change.getNewValue() .getLifecycleFlags() .getArchived(); if (!newValue && oldValue) { Version version = change.getNewValue() .getVersion(); EntityUnarchived event = EntityUnarchived .newBuilder() .setEntity(entityId) .addAllSignalId(ImmutableList.copyOf(messageIds)) .setVersion(version) .vBuild(); postEvent(event); } } private void postIfRestored(EntityRecordChange change, Collection<? extends MessageId> messageIds) { boolean oldValue = change.getPreviousValue() .getLifecycleFlags() .getDeleted(); boolean newValue = change.getNewValue() .getLifecycleFlags() .getDeleted(); if (!newValue && oldValue) { Version version = change.getNewValue() .getVersion(); EntityRestored event = EntityRestored .newBuilder() .setEntity(entityId) .addAllSignalId(ImmutableList.copyOf(messageIds)) .setVersion(version) .vBuild(); postEvent(event); } } private boolean postIfDuplicate(MessageId handledSignal, Error error) { return postIfDuplicateCommand(handledSignal, error) || postIfDuplicateEvent(handledSignal, error); } private boolean postIfDuplicateCommand(MessageId handledSignal, Error error) { String errorType = error.getType(); int errorCode = error.getCode(); boolean duplicateCommand = errorType.equals(CommandValidationError.class.getSimpleName()) && errorCode == DUPLICATE_COMMAND_VALUE; if (duplicateCommand) { onDuplicateCommand(handledSignal.asCommandId()); } return duplicateCommand; } private boolean postIfDuplicateEvent(MessageId handledSignal, Error error) { String errorType = error.getType(); int errorCode = error.getCode(); boolean duplicateEvent = errorType.equals(EventValidationError.class.getSimpleName()) && errorCode == DUPLICATE_EVENT_VALUE; if (duplicateEvent) { onDuplicateEvent(handledSignal.asEventId()); } return duplicateEvent; } private void postHandlerFailed(MessageId handledSignal, Error error) { HandlerFailedUnexpectedly systemEvent = HandlerFailedUnexpectedly .newBuilder() .setEntity(entityId) .setHandledSignal(handledSignal) .setError(error) .vBuild(); postEvent(systemEvent); } protected void postEvent(EventMessage event, Origin explicitOrigin) { Optional<? extends EventMessage> filtered = eventFilter.filter(event); filtered.ifPresent(systemEvent -> systemWriteSide.postEvent(systemEvent, explicitOrigin)); } protected void postEvent(EventMessage event) { Optional<? extends EventMessage> filtered = eventFilter.filter(event); filtered.ifPresent(systemWriteSide::postEvent); } /** * Creates a new instance of {@code Builder} for {@code EntityLifecycle} instances. * * @return new instance of {@code Builder} */ static Builder newBuilder() { return new Builder(); } /** * A builder for the {@code EntityLifecycle} instances. */ static final class Builder { private Object entityId; private EntityClass<?> entityType; private SystemWriteSide writeSide; private EventFilter eventFilter; /** * Prevents direct instantiation. */ private Builder() { } Builder setEntityId(Object entityId) { this.entityId = checkNotNull(entityId); return this; } Builder setEntityType(EntityClass<?> entityType) { this.entityType = checkNotNull(entityType); return this; } Builder setSystemWriteSide(SystemWriteSide writeSide) { this.writeSide = checkNotNull(writeSide); return this; } Builder setEventFilter(EventFilter eventFilter) { this.eventFilter = checkNotNull(eventFilter); return this; } /** * Creates a new instance of {@code EntityLifecycle}. * * @return new instance of {@code EntityLifecycle} */ EntityLifecycle build() { checkState(entityId != null); checkState(entityType != null); checkState(writeSide != null); if (eventFilter == null) { eventFilter = allowAll(); } return new EntityLifecycle(this); } } }
package uk.ac.cam.gpe21.droidssl.mitm; import org.bouncycastle.asn1.x500.AttributeTypeAndValue; import org.bouncycastle.asn1.x500.RDN; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.style.BCStyle; import org.bouncycastle.cert.jcajce.JcaX500NameUtil; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import uk.ac.cam.gpe21.droidssl.mitm.cert.CertificateGenerator; import uk.ac.cam.gpe21.droidssl.mitm.cert.KeyPairGenerator; import javax.net.ssl.*; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.file.Paths; import java.security.*; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.security.spec.InvalidKeySpecException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.Executors; public final class MitmServer { public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, IOException, KeyStoreException, CertificateException, NoSuchProviderException, UnrecoverableKeyException, InvalidKeySpecException { MitmServer server = new MitmServer(); server.start(); } private final Executor executor = Executors.newCachedThreadPool(); private final DestinationFinder destinationFinder = new NatDestinationFinder(); private final CertificateGenerator certificateGenerator; private final Map<CertificateKey, X509Certificate> certificateCache = new HashMap<>(); private final MitmKeyManager keyManager; private final SSLServerSocket serverSocket; private final SSLSocketFactory childFactory; public MitmServer() throws NoSuchAlgorithmException, KeyManagementException, IOException, KeyStoreException, CertificateException, NoSuchProviderException, UnrecoverableKeyException, InvalidKeySpecException { KeyPairGenerator keyGenerator = new KeyPairGenerator(); AsymmetricCipherKeyPair keyPair = keyGenerator.generate(); this.certificateGenerator = new CertificateGenerator(Paths.get("ca.crt"), Paths.get("ca.key"), keyPair); this.keyManager = new MitmKeyManager(certificateGenerator.getCaCertificate(), KeyPairGenerator.toJca(keyPair).getPrivate()); SSLContext context = SSLContext.getInstance("TLS"); context.init(new KeyManager[] { keyManager }, null, null); this.serverSocket = (SSLServerSocket) context.getServerSocketFactory().createServerSocket(8443); SSLContext childContext = SSLContext.getDefault(); this.childFactory = childContext.getSocketFactory(); } public void start() throws IOException, CertificateException { while (true) { SSLSocket socket = (SSLSocket) serverSocket.accept(); /* * Find the address of the target server and connect to it. */ InetSocketAddress addr = destinationFinder.getDestination(socket); SSLSocket other = (SSLSocket) childFactory.createSocket(addr.getAddress(), addr.getPort()); /* * Normally the handshake is only started when reading or writing * the first byte of data. However, we start it immediately so we * can get the server's real certificate before we start relaying * data between the server and client. */ other.startHandshake(); /* * Extract distinguished name and subjectAltNames from the certificate. */ Certificate[] chain = other.getSession().getPeerCertificates(); X509Certificate leaf = (X509Certificate) chain[0]; X500Name dn = JcaX500NameUtil.getSubject(leaf); String cn = null; // TODO extract into a method for (RDN rdn : dn.getRDNs()) { AttributeTypeAndValue first = rdn.getFirst(); if (first.getType().equals(BCStyle.CN)) { cn = first.getValue().toString(); } } if (cn == null) throw new IOException("DN has no CN!"); String[] sans = new String[0]; // TODO extract /* * Try to check if we have generated a certificate with the same DN * & SANs already - if so, re-use it. (If we don't re-use it, e.g. * a web browser thinks the certificate is different once we ignore * the untrusted issuer error message, and we'll get another * message to warn about the new certificate being untrusted ad * infinitum). */ CertificateKey key = new CertificateKey(cn, sans); X509Certificate fakeLeaf = certificateCache.get(key); if (fakeLeaf == null) { fakeLeaf = certificateGenerator.generateJca(cn, sans); certificateCache.put(key, fakeLeaf); } /* * Start the handshake with the client using the faked certificate. */ keyManager.setCertificate(socket, fakeLeaf); socket.startHandshake(); /* * Start two threads which relay data between the client and server * in both directions, while dumping the decrypted data to the * console. */ IoCopyRunnable clientToServerCopier = new IoCopyRunnable(socket.getInputStream(), other.getOutputStream()); IoCopyRunnable serverToClientCopier = new IoCopyRunnable(other.getInputStream(), socket.getOutputStream()); executor.execute(clientToServerCopier); executor.execute(serverToClientCopier); } } }
package org.bimserver.shared; import java.nio.ByteBuffer; import java.nio.ByteOrder; import org.bimserver.BimserverDatabaseException; import org.bimserver.emf.PackageMetaData; import org.bimserver.plugins.deserializers.DatabaseInterface; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EDataType; import org.eclipse.emf.ecore.EEnum; import org.eclipse.emf.ecore.EEnumLiteral; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ByteBufferVirtualObject extends AbstractByteBufferVirtualObject implements VirtualObject { private static final Logger LOGGER = LoggerFactory.getLogger(VirtualObject.class); private EClass eClass; private long oid; private QueryContext reusable; private int currentListStart = -1; private int currentListSize; private int featureCounter = 0; public ByteBufferVirtualObject(QueryContext reusable, EClass eClass, int capacity) { super(capacity); this.reusable = reusable; this.eClass = eClass; this.oid = reusable.getDatabaseInterface().newOid(eClass); int unsettedLength = reusable.getPackageMetaData().getUnsettedLength(eClass); buffer.put(new byte[unsettedLength]); } private boolean useUnsetBit(EStructuralFeature feature) { // TODO non-unsettable boolean values can also be stored in these bits if (feature.isUnsettable()) { return true; } else { if (feature.isMany()) { return true; } if (feature.getDefaultValue() == null || (feature.getDefaultValue() != null && feature.getDefaultValue() == null)) { return true; } } return false; } public void eUnset(EStructuralFeature feature) throws BimserverDatabaseException { if (useUnsetBit(feature)) { int pos = featureCounter / 8; byte b = buffer.get(pos); b |= (1 << (featureCounter % 8)); buffer.put(pos, b); } else { if (feature instanceof EReference) { if (feature.isMany()) { ensureCapacity(buffer.position(), 4); buffer.putInt(0); } else { ensureCapacity(buffer.position(), 2); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putShort((short)-1); buffer.order(ByteOrder.BIG_ENDIAN); } } else if (feature.getEType() instanceof EEnum) { writeEnum(feature, null); } else { writePrimitiveValue(feature, null); } } incrementFeatureCounter(feature); } public void setAttribute(EStructuralFeature feature, Object value) throws BimserverDatabaseException { if (feature.isMany()) { throw new UnsupportedOperationException("Feature isMany not supported by setAttribute"); } else { if (feature.getEType() instanceof EEnum) { writeEnum(feature, value); } else if (feature.getEType() instanceof EClass) { if (value == null) { ensureCapacity(buffer.position(), 2); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putShort((short) -1); buffer.order(ByteOrder.BIG_ENDIAN); } else if (value instanceof WrappedVirtualObject) { ByteBuffer otherBuffer = ((WrappedVirtualObject) value).write(); ensureCapacity(buffer.position(), otherBuffer.position()); buffer.put(otherBuffer.array(), 0, otherBuffer.position()); // writeWrappedValue(getPid(), getRid(), (WrappedVirtualObject) value, getPackageMetaData()); } else { throw new UnsupportedOperationException("??"); } } else if (feature.getEType() instanceof EDataType) { writePrimitiveValue(feature, value); } } incrementFeatureCounter(feature); } private void incrementFeatureCounter(EStructuralFeature feature) { featureCounter++; } private void writeEnum(EStructuralFeature feature, Object value) { if (value == null) { ensureCapacity(buffer.position(), 4); buffer.putInt(-1); } else { EEnum eEnum = (EEnum) feature.getEType(); EEnumLiteral eEnumLiteral = eEnum.getEEnumLiteralByLiteral(((Enum<?>) value).toString()); ensureCapacity(buffer.position(), 4); if (eEnumLiteral != null) { buffer.putInt(eEnumLiteral.getValue()); } else { LOGGER.error(((Enum<?>) value).toString() + " not found"); buffer.putInt(-1); } } } public Object eGet(EStructuralFeature feature) { throw new UnsupportedOperationException(); } public EClass eClass() { return eClass; } public long getOid() { return oid; } public ByteBuffer write() throws BimserverDatabaseException { EClass eClass = getDatabaseInterface().getEClassForOid(getOid()); if (!eClass.isSuperTypeOf(eClass())) { throw new BimserverDatabaseException("Object with oid " + getOid() + " is a " + eClass().getName() + " but it's cid-part says it's a " + eClass.getName()); } int nrFeatures = getPackageMetaData().getNrDatabaseFeatures(eClass); if (featureCounter > nrFeatures) { throw new BimserverDatabaseException("Too many features seem to have been set on " + this.eClass.getName() + " " + featureCounter + " / " + nrFeatures); } else if (featureCounter < nrFeatures) { throw new BimserverDatabaseException("Not all features seem to have been set on " + this.eClass.getName() + " " + featureCounter + " / " + nrFeatures); } return buffer; // if (buffer.position() != bufferSize) { // throw new BimserverDatabaseException("Value buffer sizes do not match for " + eClass().getName() + " " + buffer.position() + "/" + bufferSize); // return buffer; } private PackageMetaData getPackageMetaData() { return reusable.getPackageMetaData(); } private DatabaseInterface getDatabaseInterface() { return reusable.getDatabaseInterface(); } public int getPid() { return reusable.getPid(); } public int getRid() { return reusable.getRid(); } // private void writeWrappedValue(int pid, int rid, WrappedVirtualObject wrappedValue, PackageMetaData packageMetaData) throws BimserverDatabaseException { // EStructuralFeature eStructuralFeature = wrappedValue.eClass().getEStructuralFeature("wrappedValue"); // Short cid = getDatabaseInterface().getCidOfEClass(wrappedValue.eClass()); // ensureCapacity(buffer.position(), 2); // buffer.putShort((short) -cid); // writePrimitiveValue(eStructuralFeature, wrappedValue.getValue(eStructuralFeature)); // if (wrappedValue.eClass().getName().equals("IfcGloballyUniqueId")) { // EClass eClass = packageMetaData.getEClass("IfcGloballyUniqueId"); // if (wrappedValue.getOid() == -1) { // ((VirtualObject) wrappedValue).setOid(getDatabaseInterface().newOid(eClass)); // getDatabaseInterface().save(wrappedValue); public void setOid(long oid) { this.oid = oid; } public void setListItem(EStructuralFeature feature, int index, Object value) throws BimserverDatabaseException { if (currentListStart == -1) { throw new BimserverDatabaseException("Not currently writing a list"); } if (index + 1 > currentListSize) { currentListSize = index + 1; } if (value instanceof ByteBufferWrappedVirtualObject) { ByteBuffer otherBuffer = ((ByteBufferWrappedVirtualObject)value).write(); ensureCapacity(buffer.position(), otherBuffer.position()); buffer.put(otherBuffer.array(), 0, otherBuffer.position()); } else { writePrimitiveValue(feature, value); } } public void setListItemReference(EStructuralFeature structuralFeature, int index, EClass referenceEClass, Long referencedOid, int bufferPosition) throws BimserverDatabaseException { int pos; if (bufferPosition == -1) { if (currentListStart == -1) { throw new BimserverDatabaseException("Not currently writing a list"); } if (index + 1 > currentListSize) { currentListSize = index + 1; } pos = buffer.position(); } else { pos = bufferPosition; } ensureCapacity(pos, 8); if (referencedOid < 0) { throw new BimserverDatabaseException("Writing a reference with oid " + referencedOid + ", this is not supposed to happen, referenced: " + referencedOid + " " + referencedOid + " from " + getOid() + " " + this); } buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putLong(pos, referencedOid); buffer.order(ByteOrder.BIG_ENDIAN); if (bufferPosition == -1) { buffer.position(buffer.position() + 8); } } public void save() throws BimserverDatabaseException { getDatabaseInterface().save(this); } @Override public int reserveSpaceForReference(EStructuralFeature feature) { int pos = buffer.position(); ensureCapacity(pos, 8); buffer.putLong(-1); incrementFeatureCounter(feature); return pos; } @Override public int reserveSpaceForListReference() throws BimserverDatabaseException { if (currentListStart == -1) { throw new BimserverDatabaseException("Not currently writing a list"); } currentListSize++; int position = buffer.position(); ensureCapacity(position, 8); buffer.putLong(-1); return position; } @Override public void startList(EStructuralFeature feature) { ensureCapacity(buffer.position(), 4); buffer.putInt(0); currentListStart = buffer.position(); currentListSize = 0; incrementFeatureCounter(feature); } public void endList() { buffer.putInt(currentListStart - 4, currentListSize); currentListStart = -1; } @Override public void setReference(EStructuralFeature feature, long referenceOid, int bufferPosition) throws BimserverDatabaseException { if (bufferPosition == -1) { incrementFeatureCounter(feature); } int pos = bufferPosition == -1 ? buffer.position() : bufferPosition; ensureCapacity(pos, 8); if (referenceOid < 0) { throw new BimserverDatabaseException("Writing a reference with oid " + referenceOid + ", this is not supposed to happen, referenced: " + referenceOid + " " + referenceOid + " from " + getOid() + " " + this); } buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putLong(pos, referenceOid); buffer.order(ByteOrder.BIG_ENDIAN); if (bufferPosition == -1) { buffer.position(buffer.position() + 8); } } @Override public boolean useFeatureForSerialization(EStructuralFeature feature) { throw new UnsupportedOperationException(); } @Override public Object get(String name) { throw new UnsupportedOperationException(); } @Override public void set(String name, Object value) throws BimserverDatabaseException { setAttribute(eClass.getEStructuralFeature(name), value); } @Override public boolean has(String string) { throw new UnsupportedOperationException(); } @Override public boolean useFeatureForSerialization(EStructuralFeature feature, int index) { throw new UnsupportedOperationException(); } @Override public String toString() { return "ByteBufferVirtualObject/" + eClass.getName(); } }
package com.vedoware.shopify.test; import java.text.SimpleDateFormat; import org.junit.After; import org.junit.Before; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.vedoware.shopify.api.devshop.DevShopAccessService; public abstract class BaseTestClass { private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SZ"); private static String API_KEY = "2856dd64bc6adfd4ba80942dc76e9de3"; private static String PASSWORD = "988bf7c149733eb98685fd95028078cd"; private static String baseShopUrl = "https://" + "vedo-software-shop.myshopify.com/admin"; protected DevShopAccessService devShopRef = null; protected ObjectMapper deSerializationMapper = null; protected ObjectMapper serializationMapper = null; @Before public void setUp() throws Exception { devShopRef = new DevShopAccessService(API_KEY, PASSWORD, baseShopUrl); // Handle the date format serialization specifically serializationMapper = new ObjectMapper(); serializationMapper.enable(SerializationFeature.INDENT_OUTPUT); serializationMapper.setDateFormat(dateFormat); // Nothing special for the de-serialization deSerializationMapper = new ObjectMapper(); } @After public void tearDown() throws Exception { } }
package org.spine3.server.reflect; import com.google.common.base.Optional; import com.google.protobuf.Any; import com.google.protobuf.Message; import org.spine3.base.FieldFilter; import org.spine3.protobuf.AnyPacker; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Throwables.getRootCause; import static org.spine3.util.Exceptions.newIllegalArgumentException; /** * Provides information and dynamic access to a field of a {@code Message}. * * @author Alexander Yevsyukov */ public final class Field { /** * The name of the field as declared in the proto type. */ private final String name; /** * The method of obtaining the field value. */ private final Method getter; private Field(String name, Method getter) { this.name = name; this.getter = getter; } /** * Creates a new instance for a field of a message class. * * @param messageClass the class with the field * @param name the field name * @return new field instance */ private static Optional<Field> newField(Class<? extends Message> messageClass, String name) { checkNotNull(messageClass); checkNotNull(name); final Method getter; try { getter = Classes.getGetterForField(messageClass, name); } catch (NoSuchMethodException ignored) { return Optional.absent(); } final Field field = new Field(name, getter); return Optional.of(field); } /** * Creates instance for a field specified by the passed filter. * * @param messageClass the class of messages containing the field * @param filter the field filter * @return an {@code Field} wrapped into {@code Optional} or * {@code Optional.absent()} if there is no such field in the passed message class */ public static Optional<Field> forFilter(Class<? extends Message> messageClass, FieldFilter filter) { final String fieldName = getFieldName(filter); return newField(messageClass, fieldName); } private static String getFieldName(FieldFilter filter) { final String fieldPath = filter.getFieldPath(); final String fieldName = fieldPath.substring(fieldPath.lastIndexOf('.') + 1); if (fieldName.isEmpty()) { throw newIllegalArgumentException( "Unable to get a field name from the field filter: %s", filter); } return fieldName; } /** * Obtains the name of the field. */ public String getName() { return name; } public Message getValue(Message object) { final Message fieldValue; final Message result; try { fieldValue = (Message) getter.invoke(object); result = fieldValue instanceof Any ? AnyPacker.unpack((Any) fieldValue) : fieldValue; } catch (IllegalAccessException | InvocationTargetException e) { final Throwable rootCause = getRootCause(e); throw new IllegalStateException(rootCause); } return result; } }
package sg.ncl.service.team.web; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import sg.ncl.service.team.domain.Team; import sg.ncl.service.team.domain.TeamMember; import sg.ncl.service.team.domain.TeamPrivacy; import sg.ncl.service.team.domain.TeamStatus; import sg.ncl.service.team.domain.TeamVisibility; import java.time.ZonedDateTime; import java.util.List; import java.util.stream.Collectors; @Getter public class TeamInfo implements Team { private final String id; private final String name; private final String description; private final String website; private final String organisationType; private final TeamVisibility visibility; private final TeamPrivacy privacy; private final Boolean isClass; private final TeamStatus status; private final ZonedDateTime applicationDate; private final ZonedDateTime processedDate; private final List<TeamMemberInfo> members; @JsonCreator public TeamInfo( @JsonProperty("id") final String id, @JsonProperty("name") final String name, @JsonProperty("description") final String description, @JsonProperty("website") final String website, @JsonProperty("organisationType") final String organisationType, @JsonProperty("visibility") final TeamVisibility visibility, @JsonProperty("isClass") final Boolean isClass, @JsonProperty("privacy") final TeamPrivacy privacy, @JsonProperty("status") final TeamStatus status, @JsonProperty("applicationDate") final ZonedDateTime applicationDate, @JsonProperty("processedDate") final ZonedDateTime processedDate, @JsonProperty("members") final List<? extends TeamMember> members) { this.id = id; this.name = name; this.description = description; this.website = website; this.organisationType = organisationType; this.visibility = visibility; this.isClass = isClass; this.privacy = privacy; this.status = status; this.applicationDate = applicationDate; this.processedDate = processedDate; this.members = members.stream().map(TeamMemberInfo::new).collect(Collectors.toList()); } public TeamInfo(final Team team) { this( team.getId(), team.getName(), team.getDescription(), team.getWebsite(), team.getOrganisationType(), team.getVisibility(), team.getIsClass(), team.getPrivacy(), team.getStatus(), team.getApplicationDate(), team.getProcessedDate(), team.getMembers() ); } }
package org.xwiki.rendering.macro.descriptor; import org.xwiki.properties.BeanDescriptor; import org.xwiki.rendering.macro.MacroId; /** * Describe a macro with no parameters. * * @version $Id$ * @since 1.6M1 */ public class DefaultMacroDescriptor extends AbstractMacroDescriptor { /** * @param id the id of the macro * @param name the name of the macro (eg "Table Of Contents" for the TOC macro) * @since 2.3M1 */ public DefaultMacroDescriptor(MacroId id, String name) { this(id, name, null); } /** * @param id the id of the macro * @param name the name of the macro (eg "Table Of Contents" for the TOC macro) * @param description the description of the macro. * @since 2.3M1 */ public DefaultMacroDescriptor(MacroId id, String name, String description) { super(id, name, description, new DefaultContentDescriptor(), null); } /** * @param id the id of the macro * @param name the name of the macro (eg "Table Of Contents" for the TOC macro) * @param description the description of the macro. * @param contentDescriptor description of the macro content. * @since 2.3M1 */ public DefaultMacroDescriptor(MacroId id, String name, String description, ContentDescriptor contentDescriptor) { super(id, name, description, contentDescriptor, null); } /** * @param id the id of the macro * @param name the name of the macro (eg "Table Of Contents" for the TOC macro) * @param description the description of the macro. * @param contentDescriptor the description of the macro content. null indicate macro does not support content. * @param parametersBeanDescriptor the description of the parameters bean. * @since 2.3M1 */ public DefaultMacroDescriptor(MacroId id, String name, String description, ContentDescriptor contentDescriptor, BeanDescriptor parametersBeanDescriptor) { super(id, name, description, contentDescriptor, parametersBeanDescriptor); extractParameterDescriptorMap(); } }
package fi.nls.oskari.cache; import fi.nls.oskari.log.LogFactory; import fi.nls.oskari.log.Logger; import fi.nls.oskari.util.PropertyUtil; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentNavigableMap; import java.util.concurrent.ConcurrentSkipListMap; /** * Simple generic in memory cache */ public class Cache<T> { private static final Logger log = LogFactory.getLogger(Cache.class); private final ConcurrentNavigableMap<String,T> items = new ConcurrentSkipListMap<String, T>(); private volatile int limit = 1000; private volatile long expiration = 30 * 60 * 1000; private volatile long lastFlush = currentTime(); private String name; public final static String PROPERTY_LIMIT_PREFIX = "oskari.cache.limit."; private boolean cacheSizeConfigured = false; private boolean cacheMissDebugEnabled = false; public void setCacheMissDebugEnabled(boolean enabled) { cacheMissDebugEnabled = enabled; } public String getName() { return name; } public void setName(String name) { this.name = name; // setName is called after constructor by CacheManager so get the limit from properties in here int configuredLimit = PropertyUtil.getOptional(getLimitPropertyName(), -1); if(configuredLimit != -1) { cacheSizeConfigured = true; limit = configuredLimit; } } private String getLimitPropertyName() { return PROPERTY_LIMIT_PREFIX + getName(); } public int getLimit() { return limit; } /** * Amount of items to hold in cache. Defaults to 1000. * @param limit */ public void setLimit(int limit) { if(cacheSizeConfigured) { log.info("Trying to set cache limit, but it's configured by user so ignoring automatic limit change.", "Limit is", this.limit, "- Change limit with property: ", getLimitPropertyName()); return; } this.limit = limit; } /** * Time between flushes to keep cached values * @return */ public long getExpiration() { return expiration; } /** * Returns number of cached items * @return */ public long getSize() { return items.size(); } /** * Returns keys for cached items * @return */ public Set<String> getKeys() { return items.keySet(); } /** * Time to hold items in cache. Defaults to 30 minutes. * @param expiration in milliseconds */ public void setExpiration(long expiration) { this.expiration = expiration; } public long getLastFlush() { return lastFlush; } public T get(final String name) { flush(false); T value = items.get(name); if(cacheMissDebugEnabled && value == null) { log.debug("Cache", getName(), "miss for name", name); } return value; } public T remove(final String name) { flush(false); T value = items.remove(name); return value; } public boolean put(final String name, final T item) { flush(false); if(item == null) { // can't save null value return false; } final boolean overflowing = (items.size() >= limit); if(overflowing) { // limit reached - remove oldest object log.warn("Cache", getName(), "overflowing! Limit is", limit); log.info("Configure larger limit for cache by setting the property:", getLimitPropertyName()); final int retrycount = 5; int count = 0; // loop is meant to deal with concurrency issue where another thread modifies items. while (count < retrycount) { final Map.Entry<String, T> firstEntry = items.firstEntry(); if (null == firstEntry) { break; // was empty when checking for the first element } else { if (items.remove(firstEntry.getKey(), firstEntry.getValue())) { break; // we made some space for ourselves } else if (items.isEmpty()) { break; // wasn't empty before, but is now } } // let's give it an another shot, maybe next time the entry // will stick around long enough for us to remove it, looping... count++; } if(count == retrycount) { log.error("Error clearing overflowing cache", getName()); } } items.put(name, item); return overflowing; } public boolean flush(final boolean force) { final long now = currentTime(); if(force || (lastFlush + expiration < now)) { // flushCache log.debug("Flushing cache! Cache:", getName(), "Forced: ", force); items.clear(); lastFlush = now; return true; } return false; } private static long currentTime() { return System.nanoTime() / 1000L; } }
package com.jediterm.terminal.display; import com.jediterm.terminal.*; import com.jediterm.terminal.emulator.charset.CharacterSet; import com.jediterm.terminal.emulator.charset.GraphicSet; import com.jediterm.terminal.emulator.charset.GraphicSetState; import com.jediterm.terminal.emulator.mouse.*; import org.apache.log4j.Logger; import org.jetbrains.annotations.NotNull; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.*; /** * Terminal that reflects obtained commands and text at {@link TerminalDisplay}(handles change of cursor position, screen size etc) * and {@link BackBuffer}(stores printed text) * * @author traff */ public class JediTerminal implements Terminal, TerminalMouseListener { private static final Logger LOG = Logger.getLogger(JediTerminal.class.getName()); private static final int MIN_WIDTH = 5; private int myScrollRegionTop; private int myScrollRegionBottom; volatile private int myCursorX = 0; volatile private int myCursorY = 1; private int myTerminalWidth = 80; private int myTerminalHeight = 24; private final TerminalDisplay myDisplay; private final BackBuffer myBackBuffer; private final StyleState myStyleState; private StoredCursor myStoredCursor = null; private final EnumSet<TerminalMode> myModes = EnumSet.noneOf(TerminalMode.class); private final TerminalKeyEncoder myTerminalKeyEncoder = new TerminalKeyEncoder(); private final Tabulator myTabulator; private final GraphicSetState myGraphicSetState; private MouseFormat myMouseFormat = MouseFormat.MOUSE_FORMAT_XTERM; private TerminalOutputStream myTerminalOutput = null; private MouseMode myMouseMode = MouseMode.MOUSE_REPORTING_NONE; public JediTerminal(final TerminalDisplay display, final BackBuffer buf, final StyleState initialStyleState) { myDisplay = display; myBackBuffer = buf; myStyleState = initialStyleState; myTerminalWidth = display.getColumnCount(); myTerminalHeight = display.getRowCount(); myScrollRegionTop = 1; myScrollRegionBottom = myTerminalHeight; myTabulator = new DefaultTabulator(myTerminalWidth); myGraphicSetState = new GraphicSetState(); reset(); } @Override public void setModeEnabled(TerminalMode mode, boolean enabled) { if (enabled) { myModes.add(mode); } else { myModes.remove(mode); } mode.setEnabled(this, enabled); } @Override public void disconnected() { myDisplay.setCursorVisible(false); } private void wrapLines() { if (myCursorX >= myTerminalWidth) { myCursorX = 0; // clear the end of the line in the text buffer myBackBuffer.getLine(myCursorY - 1).deleteCharacters(myTerminalWidth); if (isAutoWrap()) { myBackBuffer.getLine(myCursorY - 1).setWrapped(true); myCursorY += 1; } } } private void finishText() { myDisplay.setCursor(myCursorX, myCursorY); scrollY(); } @Override public void writeCharacters(String string) { writeCharacters(decode(string).toCharArray(), 0, string.length()); } private void writeCharacters(final char[] chosenBuffer, final int start, final int length) { myBackBuffer.lock(); try { wrapLines(); scrollY(); if (length != 0) { myBackBuffer.writeBytes(myCursorX, myCursorY, chosenBuffer, start, length); } myCursorX += length; finishText(); } finally { myBackBuffer.unlock(); } } @Override public void writeDoubleByte(final char[] bytesOfChar) throws UnsupportedEncodingException { writeString(new String(bytesOfChar, 0, 2)); } public void writeString(String string) { doWriteString(decode(string)); } private String decode(String string) { StringBuilder result = new StringBuilder(); for (char c : string.toCharArray()) { result.append(myGraphicSetState.map(c)); } return result.toString(); } private void doWriteString(String string) { myBackBuffer.lock(); try { wrapLines(); scrollY(); myBackBuffer.writeString(myCursorX, myCursorY, string); myCursorX += string.length(); finishText(); } finally { myBackBuffer.unlock(); } } public void writeUnwrappedString(String string) { int length = string.length(); int off = 0; while (off < length) { int amountInLine = Math.min(distanceToLineEnd(), length - off); writeString(string.substring(off, off + amountInLine)); wrapLines(); scrollY(); off += amountInLine; } } public void scrollY() { myBackBuffer.lock(); try { if (myCursorY > myScrollRegionBottom) { final int dy = myScrollRegionBottom - myCursorY; myCursorY = myScrollRegionBottom; scrollArea(myScrollRegionTop, scrollingRegionSize(), dy); myDisplay.setCursor(myCursorX, myCursorY); } if (myCursorY < myScrollRegionTop) { myCursorY = myScrollRegionTop; } } finally { myBackBuffer.unlock(); } } @Override public void newLine() { myCursorY += 1; scrollY(); if (isAutoNewLine()) { carriageReturn(); } myDisplay.setCursor(myCursorX, myCursorY); } @Override public void mapCharsetToGL(int num) { myGraphicSetState.setGL(num); } @Override public void mapCharsetToGR(int num) { myGraphicSetState.setGR(num); } @Override public void designateCharacterSet(int tableNumber, char charset) { GraphicSet gs = myGraphicSetState.getGraphicSet(tableNumber); myGraphicSetState.designateGraphicSet(gs, charset); } @Override public void singleShiftSelect(int num) { myGraphicSetState.overrideGL(num); } @Override public void setAnsiConformanceLevel(int level) { if (level == 1 || level == 2) { myGraphicSetState.designateGraphicSet(0, CharacterSet.ASCII); //ASCII designated as G0 myGraphicSetState .designateGraphicSet(1, CharacterSet.DEC_SUPPLEMENTAL); //TODO: not DEC supplemental, but ISO Latin-1 supplemental designated as G1 mapCharsetToGL(0); mapCharsetToGR(1); } else if (level == 3) { designateCharacterSet(0, 'B'); //ASCII designated as G0 mapCharsetToGL(0); } else { throw new IllegalArgumentException(); } } @Override public void setWindowTitle(String name) { myDisplay.setWindowTitle(name); } @Override public void backspace() { myCursorX -= 1; if (myCursorX < 0) { myCursorY -= 1; myCursorX = myTerminalWidth - 1; } myDisplay.setCursor(myCursorX, myCursorY); } @Override public void carriageReturn() { myCursorX = 0; myDisplay.setCursor(myCursorX, myCursorY); } @Override public void horizontalTab() { myCursorX = myTabulator.nextTab(myCursorX); if (myCursorX >= myTerminalWidth) { myCursorX = 0; myCursorY += 1; } myDisplay.setCursor(myCursorX, myCursorY); } @Override public void eraseInDisplay(final int arg) { myBackBuffer.lock(); try { int beginY; int endY; switch (arg) { case 0: // Initial line if (myCursorX < myTerminalWidth) { myBackBuffer.eraseCharacters(myCursorX, myTerminalWidth, myCursorY - 1); } // Rest beginY = myCursorY; endY = myTerminalHeight; break; case 1: // initial line myBackBuffer.eraseCharacters(0, myCursorX + 1, myCursorY - 1); beginY = 0; endY = myCursorY - 1; break; case 2: beginY = 0; endY = myTerminalHeight; break; default: LOG.error("Unsupported erase in display mode:" + arg); beginY = 1; endY = 1; break; } // Rest of lines if (beginY != endY) { clearLines(beginY, endY); } } finally { myBackBuffer.unlock(); } } public void clearLines(final int beginY, final int endY) { myBackBuffer.lock(); try { myBackBuffer.clearLines(beginY, endY); } finally { myBackBuffer.unlock(); } } @Override public void clearScreen() { clearLines(0, myTerminalHeight); } @Override public void setCursorVisible(boolean visible) { myDisplay.setCursorVisible(visible); } @Override public void useAlternateBuffer(boolean enabled) { myBackBuffer.useAlternateBuffer(enabled); myDisplay.setScrollingEnabled(!enabled); } @Override public byte[] getCodeForKey(int key) { return myTerminalKeyEncoder.getCode(key); } @Override public void setApplicationArrowKeys(boolean enabled) { if (enabled) { myTerminalKeyEncoder.arrowKeysApplicationSequences(); } else { myTerminalKeyEncoder.arrowKeysAnsiCursorSequences(); } } @Override public void setApplicationKeypad(boolean enabled) { if (enabled) { myTerminalKeyEncoder.keypadApplicationSequences(); } else { myTerminalKeyEncoder.normalKeypad(); } } public void eraseInLine(int arg) { myBackBuffer.lock(); try { switch (arg) { case 0: if (myCursorX < myTerminalWidth) { myBackBuffer.eraseCharacters(myCursorX, myTerminalWidth, myCursorY - 1); } // delete to the end of line : line is no more wrapped myBackBuffer.getLine(myCursorY - 1).setWrapped(false); break; case 1: final int extent = Math.min(myCursorX + 1, myTerminalWidth); myBackBuffer.eraseCharacters(0, extent, myCursorY - 1); break; case 2: myBackBuffer.eraseCharacters(0, myTerminalWidth, myCursorY - 1); break; default: LOG.error("Unsupported erase in line mode:" + arg); break; } } finally { myBackBuffer.unlock(); } } @Override public void deleteCharacters(int count) { myBackBuffer.lock(); try { final int extent = Math.min(count, myTerminalWidth - myCursorX); myBackBuffer.deleteCharacters(myCursorX, myCursorY - 1, extent); } finally { myBackBuffer.unlock(); } } @Override public void insertBlankCharacters(int count) { myBackBuffer.lock(); try { final int extent = Math.min(count, myTerminalWidth - myCursorX); myBackBuffer.insertBlankCharacters(myCursorX, myCursorY - 1, extent); } finally { myBackBuffer.unlock(); } } @Override public void eraseCharacters(int count) { //Clear the next n characters on the cursor's line, including the cursor's //position. myBackBuffer.lock(); try { final int extent = Math.min(count, myTerminalWidth - myCursorX); myBackBuffer.eraseCharacters(myCursorX, myCursorX + extent, myCursorY - 1); } finally { myBackBuffer.unlock(); } } @Override public void clearTabStopAtCursor() { myTabulator.clearTabStop(myCursorX); } @Override public void clearAllTabStops() { myTabulator.clearAllTabStops(); } @Override public void setTabStopAtCursor() { myTabulator.setTabStop(myCursorX); } @Override public void insertLines(int count) { myBackBuffer.lock(); try { myBackBuffer.insertLines(myCursorY - 1, count, myScrollRegionBottom); } finally { myBackBuffer.unlock(); } } @Override public void deleteLines(int count) { myBackBuffer.lock(); try { myBackBuffer.deleteLines(myCursorY - 1, count, myScrollRegionBottom); } finally { myBackBuffer.unlock(); } } @Override public void setBlinkingCursor(boolean enabled) { myDisplay.setBlinkingCursor(enabled); } @Override public void cursorUp(final int countY) { myBackBuffer.lock(); try { myCursorY -= countY; myCursorY = Math.max(myCursorY, scrollingRegionTop()); myDisplay.setCursor(myCursorX, myCursorY); } finally { myBackBuffer.unlock(); } } @Override public void cursorDown(final int dY) { myBackBuffer.lock(); try { myCursorY += dY; myCursorY = Math.min(myCursorY, scrollingRegionBottom()); myDisplay.setCursor(myCursorX, myCursorY); } finally { myBackBuffer.unlock(); } } @Override public void index() { //Moves the cursor down one line in the //same column. If the cursor is at the //bottom margin, the page scrolls up myBackBuffer.lock(); try { if (myCursorY == myScrollRegionBottom) { scrollArea(myScrollRegionTop, scrollingRegionSize(), -1); } else { myCursorY += 1; myDisplay.setCursor(myCursorX, myCursorY); } } finally { myBackBuffer.unlock(); } } private void scrollArea(int scrollRegionTop, int scrollRegionSize, int dy) { myDisplay.scrollArea(scrollRegionTop, scrollRegionSize, dy); myBackBuffer.scrollArea(scrollRegionTop, dy, scrollRegionTop + scrollRegionSize - 1); } @Override public void nextLine() { myBackBuffer.lock(); try { myCursorX = 0; if (myCursorY == myScrollRegionBottom) { scrollArea(myScrollRegionTop, scrollingRegionSize(), -1); } else { myCursorY += 1; } myDisplay.setCursor(myCursorX, myCursorY); } finally { myBackBuffer.unlock(); } } private int scrollingRegionSize() { return myScrollRegionBottom - myScrollRegionTop + 1; } @Override public void reverseIndex() { //Moves the cursor up one line in the same //column. If the cursor is at the top margin, //the page scrolls down. myBackBuffer.lock(); try { if (myCursorY == myScrollRegionTop) { scrollArea(myScrollRegionTop, scrollingRegionSize(), 1); } else { myCursorY -= 1; myDisplay.setCursor(myCursorX, myCursorY); } } finally { myBackBuffer.unlock(); } } private int scrollingRegionTop() { return isOriginMode() ? myScrollRegionTop : 1; } private int scrollingRegionBottom() { return isOriginMode() ? myScrollRegionBottom : myTerminalHeight; } @Override public void cursorForward(final int dX) { myCursorX += dX; myCursorX = Math.min(myCursorX, myTerminalWidth - 1); myDisplay.setCursor(myCursorX, myCursorY); } @Override public void cursorBackward(final int dX) { myCursorX -= dX; myCursorX = Math.max(myCursorX, 0); myDisplay.setCursor(myCursorX, myCursorY); } @Override public void cursorHorizontalAbsolute(int x) { cursorPosition(x, myCursorY); } @Override public void linePositionAbsolute(int y) { myCursorY = y; myDisplay.setCursor(myCursorX, myCursorY); } @Override public void cursorPosition(int x, int y) { myCursorX = x - 1; if (isOriginMode()) { myCursorY = y + scrollingRegionTop() - 1; } else { myCursorY = y; } if (myCursorY > scrollingRegionBottom()) { myCursorY = scrollingRegionBottom(); } if (myCursorX > myTerminalWidth) { myCursorX = myTerminalWidth; } myDisplay.setCursor(myCursorX, myCursorY); } @Override public void setScrollingRegion(int top, int bottom) { if (top > bottom) { LOG.error("Top margin of scroll region can't be greater then bottom: " + top + ">" + bottom); } myScrollRegionTop = Math.max(1, top); myScrollRegionBottom = Math.min(myTerminalHeight, bottom); //DECSTBM moves the cursor to column 1, line 1 of the page cursorPosition(1, 1); } @Override public void scrollUp(int count) { myBackBuffer.lock(); try { scrollArea(myScrollRegionTop, scrollingRegionSize(), - count); } finally { myBackBuffer.unlock(); } } @Override public void scrollDown(int count) { myBackBuffer.lock(); try { scrollArea(myScrollRegionTop, scrollingRegionSize(), count); } finally { myBackBuffer.unlock(); } } @Override public void resetScrollRegions() { setScrollingRegion(1, myTerminalHeight); } @Override public void characterAttributes(final TextStyle textStyle) { myStyleState.setCurrent(textStyle); } @Override public void beep() { myDisplay.beep(); } @Override public int distanceToLineEnd() { return myTerminalWidth - myCursorX; } @Override public void saveCursor() { myStoredCursor = createCursorState(); } private StoredCursor createCursorState() { return new StoredCursor(myCursorX, myCursorY, myStyleState.getCurrent().clone(), isAutoWrap(), isOriginMode(), myGraphicSetState); } @Override public void restoreCursor() { if (myStoredCursor != null) { restoreCursor(myStoredCursor); } else { //If nothing was saved by DECSC setModeEnabled(TerminalMode.OriginMode, false); //Resets origin mode (DECOM) cursorPosition(1, 1); //Moves the cursor to the home position (upper left of screen). myStyleState.reset(); //Turns all character attributes off (normal setting). myGraphicSetState.resetState(); //myGraphicSetState.designateGraphicSet(0, CharacterSet.ASCII);//Maps the ASCII character set into GL //mapCharsetToGL(0); //myGraphicSetState.designateGraphicSet(1, CharacterSet.DEC_SUPPLEMENTAL); //mapCharsetToGR(1); //and the DEC Supplemental Graphic set into GR } myDisplay.setCursor(myCursorX, myCursorY); } public void restoreCursor(@NotNull StoredCursor storedCursor) { myCursorX = storedCursor.getCursorX(); myCursorY = storedCursor.getCursorY(); myStyleState.setCurrent(storedCursor.getTextStyle().clone()); setModeEnabled(TerminalMode.AutoWrap, storedCursor.isAutoWrap()); setModeEnabled(TerminalMode.OriginMode, storedCursor.isOriginMode()); CharacterSet[] designations = storedCursor.getDesignations(); for (int i = 0; i < designations.length; i++) { myGraphicSetState.designateGraphicSet(i, designations[i]); } myGraphicSetState.setGL(storedCursor.getGLMapping()); myGraphicSetState.setGR(storedCursor.getGRMapping()); if (storedCursor.getGLOverride() >= 0) { myGraphicSetState.overrideGL(storedCursor.getGLOverride()); } } @Override public void reset() { myGraphicSetState.resetState(); myStyleState.reset(); myBackBuffer.clearAll(); initModes(); initMouseModes(); cursorPosition(1, 1); } private void initMouseModes() { myMouseMode = MouseMode.MOUSE_REPORTING_NONE; myMouseFormat = MouseFormat.MOUSE_FORMAT_XTERM; } private void initModes() { myModes.clear(); setModeEnabled(TerminalMode.AutoNewLine, true); setModeEnabled(TerminalMode.AutoWrap, true); } public boolean isAutoNewLine() { return myModes.contains(TerminalMode.AutoNewLine); } public boolean isOriginMode() { return myModes.contains(TerminalMode.OriginMode); } public boolean isAutoWrap() { return myModes.contains(TerminalMode.AutoWrap); } private static int createButtonCode(MouseEvent event) { if ((event.getButton()) == MouseEvent.BUTTON1) { return MouseButtonCodes.LEFT; } else if (event.getButton() == MouseEvent.BUTTON3) { return MouseButtonCodes.NONE; //we dont handle right mouse button as it used for the context menu invocation } else { return MouseButtonCodes.RIGHT; } } private byte[] mouseReport(int button, int x, int y) { StringBuilder sb = new StringBuilder(); switch (myMouseFormat) { case MOUSE_FORMAT_XTERM_EXT: sb.append(String.format("\033[M%c%c%c", (char)(32 + button), (char)(32 + x), (char)(32 + y))); break; case MOUSE_FORMAT_URXVT: sb.append(String.format("\033[%d;%d;%dM", 32 + button, x, y)); break; case MOUSE_FORMAT_SGR: if ((button & MouseButtonModifierFlags.MOUSE_BUTTON_SGR_RELEASE_FLAG) != 0) { // for mouse release event sb.append(String.format("\033[<%d;%d;%dm", button ^ MouseButtonModifierFlags.MOUSE_BUTTON_SGR_RELEASE_FLAG, x, y)); } else { // for mouse press/motion event sb.append(String.format("\033[<%d;%d;%dM", button, x, y)); } break; case MOUSE_FORMAT_XTERM: default: sb.append(String.format("\033[M%c%c%c", (char)(32 + button), (char)(32 + x), (char)(32 + y))); break; } return sb.toString().getBytes(Charset.forName("UTF-8")); } private boolean shouldSendMouseData() { return myTerminalOutput != null && (myMouseMode == MouseMode.MOUSE_REPORTING_NORMAL || myMouseMode == MouseMode.MOUSE_REPORTING_ALL_MOTION || myMouseMode == MouseMode.MOUSE_REPORTING_BUTTON_MOTION); } @Override public void mousePressed(int x, int y, MouseEvent event) { if (shouldSendMouseData()) { int cb = createButtonCode(event); if (cb != MouseButtonCodes.NONE) { if (createButtonCode(event) == MouseButtonCodes.SCROLLDOWN || createButtonCode(event) == MouseButtonCodes.SCROLLUP) { // convert x11 scroll button number to terminal button code int offset = MouseButtonCodes.SCROLLDOWN; cb -= offset; cb |= MouseButtonModifierFlags.MOUSE_BUTTON_SCROLL_FLAG; } cb = applyModifierKeys(event, cb); myTerminalOutput.sendBytes(mouseReport(cb, x + 1, y + 1)); } } } @Override public void mouseReleased(int x, int y, MouseEvent event) { if (shouldSendMouseData()) { int cb = createButtonCode(event); if (cb != MouseButtonCodes.NONE) { if (myMouseFormat == MouseFormat.MOUSE_FORMAT_SGR) { // for SGR 1006 mode cb |= MouseButtonModifierFlags.MOUSE_BUTTON_SGR_RELEASE_FLAG; } else { // for 1000/1005/1015 mode cb = MouseButtonCodes.RELEASE; } cb = applyModifierKeys(event, cb); myTerminalOutput.sendBytes(mouseReport(cb, x + 1, y + 1)); } } } private static int applyModifierKeys(MouseEvent event, int cb) { if (event.isControlDown()) { cb |= MouseButtonModifierFlags.MOUSE_BUTTON_CTRL_FLAG; } if (event.isShiftDown()) { cb |= MouseButtonModifierFlags.MOUSE_BUTTON_SHIFT_FLAG; } if ((event.getModifiersEx() & InputEvent.META_MASK) != 0) { cb |= MouseButtonModifierFlags.MOUSE_BUTTON_META_FLAG; } return cb; } public void setTerminalOutput(TerminalOutputStream terminalOutput) { myTerminalOutput = terminalOutput; } @Override public void setMouseMode(@NotNull MouseMode mode) { myMouseMode = mode; } @Override public void setMouseFormat(MouseFormat mouseFormat) { myMouseFormat = mouseFormat; } public interface ResizeHandler { void sizeUpdated(int termWidth, int termHeight, int cursorY); } public Dimension resize(final Dimension pendingResize, final RequestOrigin origin) { final int oldHeight = myTerminalHeight; if (pendingResize.width <= MIN_WIDTH) { pendingResize.setSize(MIN_WIDTH, pendingResize.height); } final Dimension pixelSize = myDisplay.requestResize(pendingResize, origin, myCursorY, new ResizeHandler() { @Override public void sizeUpdated(int termWidth, int termHeight, int cursorY) { myTerminalWidth = termWidth; myTerminalHeight = termHeight; myCursorY = cursorY; myTabulator.resize(myTerminalWidth); } }); myScrollRegionBottom += myTerminalHeight - oldHeight; return pixelSize; } @Override public void fillScreen(final char c) { myBackBuffer.lock(); try { final char[] chars = new char[myTerminalWidth]; Arrays.fill(chars, c); final String str = new String(chars); for (int row = 1; row <= myTerminalHeight; row++) { myBackBuffer.writeString(0, row, str); } } finally { myBackBuffer.unlock(); } } @Override public int getTerminalHeight() { return myTerminalHeight; } @Override public int getCursorX() { return myCursorX; } @Override public int getCursorY() { return myCursorY; } @Override public StyleState getStyleState() { return myStyleState; } private static class DefaultTabulator implements Tabulator { private static final int TAB_LENGTH = 8; private final SortedSet<Integer> myTabStops; private int myWidth; private int myTabLength; public DefaultTabulator(int width) { this(width, TAB_LENGTH); } public DefaultTabulator(int width, int tabLength) { myTabStops = new TreeSet<Integer>(); myWidth = width; myTabLength = tabLength; initTabStops(width, tabLength); } private void initTabStops(int columns, int tabLength) { for (int i = tabLength; i < columns; i += tabLength) { myTabStops.add(i); } } public void resize(int columns) { if (columns > myWidth) { for (int i = myTabLength * (myWidth / myTabLength); i < columns; i += myTabLength) { if (i >= myWidth) { myTabStops.add(i); } } } else { Iterator<Integer> it = myTabStops.iterator(); while (it.hasNext()) { int i = it.next(); if (i > columns) { it.remove(); } } } myWidth = columns; } @Override public void clearTabStop(int position) { myTabStops.remove(Integer.valueOf(position)); } @Override public void clearAllTabStops() { myTabStops.clear(); } @Override public int getNextTabWidth(int position) { return nextTab(position) - position; } @Override public int getPreviousTabWidth(int position) { return position - previousTab(position); } @Override public int nextTab(int position) { int tabStop = Integer.MAX_VALUE; // Search for the first tab stop after the given position... SortedSet<Integer> tailSet = myTabStops.tailSet(position + 1); if (!tailSet.isEmpty()) { tabStop = tailSet.first(); } // Don't go beyond the end of the line... return Math.min(tabStop, (myWidth - 1)); } @Override public int previousTab(int position) { int tabStop = 0; // Search for the first tab stop before the given position... SortedSet<Integer> headSet = myTabStops.headSet(Integer.valueOf(position)); if (!headSet.isEmpty()) { tabStop = headSet.last(); } // Don't go beyond the start of the line... return Math.max(0, tabStop); } @Override public void setTabStop(int position) { myTabStops.add(Integer.valueOf(position)); } } }
package edu.cuny.citytech.defaultrefactoring.core.refactorings; import static org.eclipse.jdt.ui.JavaElementLabels.ALL_FULLY_QUALIFIED; import static org.eclipse.jdt.ui.JavaElementLabels.getElementLabel; import static org.eclipse.jdt.ui.JavaElementLabels.getTextLabel; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.BiFunction; import java.util.stream.Collectors; import java.util.stream.Stream; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IAnnotatable; import org.eclipse.jdt.core.IAnnotation; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IInitializer; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.ILocalVariable; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMemberValuePair; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.ITypeParameter; import org.eclipse.jdt.core.ITypeRoot; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.ASTMatcher; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.Assignment; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.ClassInstanceCreation; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.ConstructorInvocation; import org.eclipse.jdt.core.dom.CreationReference; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.FieldAccess; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.SuperConstructorInvocation; import org.eclipse.jdt.core.dom.SuperFieldAccess; import org.eclipse.jdt.core.dom.SuperMethodInvocation; import org.eclipse.jdt.core.dom.SuperMethodReference; import org.eclipse.jdt.core.dom.ThisExpression; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition; import org.eclipse.jdt.core.dom.rewrite.ListRewrite; import org.eclipse.jdt.core.refactoring.CompilationUnitChange; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.core.search.SearchMatch; import org.eclipse.jdt.core.search.SearchParticipant; import org.eclipse.jdt.core.search.SearchPattern; import org.eclipse.jdt.core.search.SearchRequestor; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.refactoring.RefactoringCoreMessages; import org.eclipse.jdt.internal.corext.refactoring.base.JavaStatusContext; import org.eclipse.jdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange; import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; import org.eclipse.jdt.internal.corext.refactoring.structure.ImportRewriteUtil; import org.eclipse.jdt.internal.corext.refactoring.structure.ReferenceFinderUtil; import org.eclipse.jdt.internal.corext.refactoring.structure.TypeVariableMaplet; import org.eclipse.jdt.internal.corext.refactoring.structure.HierarchyProcessor.TypeVariableMapper; import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser; import org.eclipse.jdt.internal.corext.refactoring.util.TextEditBasedChangeManager; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.JdtFlags; import org.eclipse.jdt.internal.corext.util.Strings; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; import org.eclipse.jdt.ui.JavaElementLabels; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.ltk.core.refactoring.Change; import org.eclipse.ltk.core.refactoring.GroupCategory; import org.eclipse.ltk.core.refactoring.GroupCategorySet; import org.eclipse.ltk.core.refactoring.NullChange; import org.eclipse.ltk.core.refactoring.RefactoringDescriptor; import org.eclipse.ltk.core.refactoring.RefactoringStatus; import org.eclipse.ltk.core.refactoring.RefactoringStatusContext; import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry; import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext; import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant; import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor; import org.eclipse.ltk.core.refactoring.participants.SharableParticipants; import org.eclipse.text.edits.MalformedTreeException; import org.eclipse.text.edits.TextEdit; import org.osgi.framework.FrameworkUtil; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import edu.cuny.citytech.defaultrefactoring.core.descriptors.MigrateSkeletalImplementationToInterfaceRefactoringDescriptor; import edu.cuny.citytech.defaultrefactoring.core.messages.Messages; import edu.cuny.citytech.defaultrefactoring.core.messages.PreconditionFailure; import edu.cuny.citytech.defaultrefactoring.core.utils.RefactoringAvailabilityTester; import edu.cuny.citytech.defaultrefactoring.core.utils.TimeCollector; import edu.cuny.citytech.defaultrefactoring.core.utils.TypeVariableUtil; import edu.cuny.citytech.defaultrefactoring.core.utils.Util; /** * The activator class controls the plug-in life cycle * * @author <a href="mailto:rkhatchadourian@citytech.cuny.edu">Raffi * Khatchadourian</a> */ @SuppressWarnings({ "restriction" }) public class MigrateSkeletalImplementationToInterfaceRefactoringProcessor extends RefactoringProcessor { private final class SourceMethodBodyAnalysisVisitor extends ASTVisitor { private boolean methodContainsSuperReference; private boolean methodContainsCallToProtectedObjectMethod; private boolean methodContainsTypeIncompatibleThisReference; private boolean methodContainsQualifiedThisExpression; private Set<IMethod> calledProtectedObjectMethodSet = new HashSet<>(); private IMethod sourceMethod; private Optional<IProgressMonitor> monitor; public SourceMethodBodyAnalysisVisitor(IMethod sourceMethod, Optional<IProgressMonitor> monitor) { super(false); this.sourceMethod = sourceMethod; this.monitor = monitor; } protected Set<IMethod> getCalledProtectedObjectMethodSet() { return calledProtectedObjectMethodSet; } @Override public boolean visit(SuperConstructorInvocation node) { this.methodContainsSuperReference = true; return super.visit(node); } protected boolean doesMethodContainsSuperReference() { return methodContainsSuperReference; } protected boolean doesMethodContainsCallToProtectedObjectMethod() { return methodContainsCallToProtectedObjectMethod; } protected boolean doesMethodContainsTypeIncompatibleThisReference() { return methodContainsTypeIncompatibleThisReference; } protected boolean doesMethodContainQualifiedThisExpression() { return methodContainsQualifiedThisExpression; } @Override public boolean visit(SuperFieldAccess node) { this.methodContainsSuperReference = true; return super.visit(node); } @Override public boolean visit(SuperMethodInvocation node) { this.methodContainsSuperReference = true; return super.visit(node); } @Override public boolean visit(SuperMethodReference node) { this.methodContainsSuperReference = true; return super.visit(node); } @Override public boolean visit(MethodInvocation node) { // check for calls to particular java.lang.Object // methods #144. IMethodBinding methodBinding = node.resolveMethodBinding(); if (methodBinding.getDeclaringClass().getQualifiedName().equals("java.lang.Object")) { IMethod calledObjectMethod = (IMethod) methodBinding.getJavaElement(); try { if (Flags.isProtected(calledObjectMethod.getFlags())) { this.methodContainsCallToProtectedObjectMethod = true; this.calledProtectedObjectMethodSet.add(calledObjectMethod); } } catch (JavaModelException e) { throw new RuntimeException(e); } } return super.visit(node); } @Override public boolean visit(ThisExpression node) { // #153: Precondition missing for compile-time type of this // TODO: #153 There is actually a lot more checks we should add // here. /* * TODO: Actually need to examine every kind of expression where * `this` may appear. #149. Really, type constraints can (or should) * be used for this. Actually, similar to enum problem, especially * with finding the parameter from where the `this` expression came. * Assignment is only one kind of expression, we need to also look * at comparison and switches. */ if (node.getQualifier() != null) this.methodContainsQualifiedThisExpression = true; ASTNode parent = node.getParent(); process(parent, node); return super.visit(node); } private void process(ASTNode node, ThisExpression thisExpression) { switch (node.getNodeType()) { case ASTNode.METHOD_INVOCATION: case ASTNode.CLASS_INSTANCE_CREATION: case ASTNode.CONSTRUCTOR_INVOCATION: // NOTE: super isn't allowed inside the source method body. case ASTNode.ASSIGNMENT: case ASTNode.RETURN_STATEMENT: case ASTNode.VARIABLE_DECLARATION_FRAGMENT: { // get the target method. IMethod targetMethod = null; try { targetMethod = getTargetMethod(this.sourceMethod, this.monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN))); } catch (JavaModelException e) { throw new RuntimeException(e); } IType destinationInterface = targetMethod.getDeclaringType(); // get the destination interface. ITypeBinding destinationInterfaceTypeBinding = null; try { destinationInterfaceTypeBinding = ASTNodeSearchUtil.getTypeDeclarationNode(destinationInterface, getCompilationUnit(destinationInterface.getTypeRoot(), new SubProgressMonitor( this.monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN))) .resolveBinding(); } catch (JavaModelException e) { throw new RuntimeException(e); } if (node.getNodeType() == ASTNode.CONSTRUCTOR_INVOCATION) { ConstructorInvocation constructorInvocation = (ConstructorInvocation) node; List<?> arguments = constructorInvocation.arguments(); IMethodBinding methodBinding = constructorInvocation.resolveConstructorBinding(); processArguments(arguments, methodBinding, thisExpression, destinationInterfaceTypeBinding); } else if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) { ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) node; List<?> arguments = classInstanceCreation.arguments(); IMethodBinding methodBinding = classInstanceCreation.resolveConstructorBinding(); processArguments(arguments, methodBinding, thisExpression, destinationInterfaceTypeBinding); } else if (node.getNodeType() == ASTNode.METHOD_INVOCATION) { MethodInvocation methodInvocation = (MethodInvocation) node; List<?> arguments = methodInvocation.arguments(); IMethodBinding methodBinding = methodInvocation.resolveMethodBinding(); processArguments(arguments, methodBinding, thisExpression, destinationInterfaceTypeBinding); } else if (node.getNodeType() == ASTNode.ASSIGNMENT) { Assignment assignment = (Assignment) node; Expression leftHandSide = assignment.getLeftHandSide(); Expression rightHandSide = assignment.getRightHandSide(); processAssignment(assignment, thisExpression, destinationInterfaceTypeBinding, leftHandSide, rightHandSide); } else if (node.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) { VariableDeclarationFragment vdf = (VariableDeclarationFragment) node; Expression initializer = vdf.getInitializer(); SimpleName name = vdf.getName(); processAssignment(vdf, thisExpression, destinationInterfaceTypeBinding, name, initializer); } else if (node.getNodeType() == ASTNode.RETURN_STATEMENT) { ReturnStatement returnStatement = (ReturnStatement) node; // sanity check. Expression expression = returnStatement.getExpression(); expression = (Expression) Util.stripParenthesizedExpressions(expression); Assert.isTrue(expression == thisExpression, "The return expression should be this."); MethodDeclaration targetMethodDeclaration = null; try { targetMethodDeclaration = ASTNodeSearchUtil .getMethodDeclarationNode(targetMethod, getCompilationUnit(targetMethod.getTypeRoot(), new SubProgressMonitor(this.monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN))); } catch (JavaModelException e) { throw new RuntimeException(e); } ITypeBinding returnType = targetMethodDeclaration.resolveBinding().getReturnType(); // ensure that the destination type is assignment compatible // with the return type. if (!isAssignmentCompatible(destinationInterfaceTypeBinding, returnType)) this.methodContainsTypeIncompatibleThisReference = true; } else throw new IllegalStateException("Unexpected node type: " + node.getNodeType()); break; } case ASTNode.PARENTHESIZED_EXPRESSION: { process(node.getParent(), thisExpression); } } } /** * Process a list of arguments stemming from a method-like call. * * @param arguments * The list of arguments to process. * @param methodBinding * The binding of the corresponding method call. * @param thisExpression * The this expression we are looking for. * @param destinationInterfaceTypeBinding * The binding of the destination interface. */ private void processArguments(List<?> arguments, IMethodBinding methodBinding, ThisExpression thisExpression, ITypeBinding destinationInterfaceTypeBinding) { // find where (or if) the this expression occurs in the // method // invocation arguments. for (int i = 0; i < arguments.size(); i++) { Object object = arguments.get(i); // if we are at the argument where this appears. if (object == thisExpression) { // get the type binding from the corresponding // parameter. ITypeBinding parameterTypeBinding = methodBinding.getParameterTypes()[i]; // the type of this will change to the destination // interface. Let's check whether an expression of // the destination type can be assigned to a // variable of // the parameter type. // TODO: Does `isAssignmentCompatible()` also work // with // comparison? if (!isAssignmentCompatible(destinationInterfaceTypeBinding, parameterTypeBinding)) { this.methodContainsTypeIncompatibleThisReference = true; break; } } } } private void processAssignment(ASTNode node, ThisExpression thisExpression, ITypeBinding destinationInterfaceTypeBinding, Expression leftHandSide, Expression rightHandSide) { // if `this` appears on the LHS. if (leftHandSide == thisExpression) { // in this case, we need to check that the RHS can be // assigned to a variable of the destination type. if (!isAssignmentCompatible(rightHandSide.resolveTypeBinding(), destinationInterfaceTypeBinding)) this.methodContainsTypeIncompatibleThisReference = true; } else if (rightHandSide == thisExpression) { // otherwise, if `this` appears on the RHS. Then, we // need to check that the LHS can receive a variable of // the destination type. if (!isAssignmentCompatible(destinationInterfaceTypeBinding, leftHandSide.resolveTypeBinding())) this.methodContainsTypeIncompatibleThisReference = true; } else { throw new IllegalStateException( "this: " + thisExpression + " must appear either on the LHS or RHS of the assignment: " + node); } } } private final class FieldAccessAnalysisSearchRequestor extends SearchRequestor { private final Optional<IProgressMonitor> monitor; private boolean accessesFieldsFromImplicitParameter; private FieldAccessAnalysisSearchRequestor(Optional<IProgressMonitor> monitor) { this.monitor = monitor; } @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { if (match.isInsideDocComment()) return; // get the AST node corresponding to the field // access. It should be some kind of name // (simple of qualified). ASTNode node = ASTNodeSearchUtil.getAstNode(match, getCompilationUnit( ((IMember) match.getElement()).getTypeRoot(), new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN))); // examine the node's parent. ASTNode parent = node.getParent(); switch (parent.getNodeType()) { case ASTNode.FIELD_ACCESS: { FieldAccess fieldAccess = (FieldAccess) parent; // the expression is the LHS of the // selection operator. Expression expression = fieldAccess.getExpression(); if (expression == null || expression.getNodeType() == ASTNode.THIS_EXPRESSION) // either there is nothing on the LHS // or it's this, in which case we fail. this.accessesFieldsFromImplicitParameter = true; break; } case ASTNode.SUPER_FIELD_ACCESS: { // super will also tell us that it's an // instance field access of this. this.accessesFieldsFromImplicitParameter = true; break; } default: { // it must be an unqualified field access, // meaning that it's an instance field access of this. this.accessesFieldsFromImplicitParameter = true; } } } public boolean hasAccessesToFieldsFromImplicitParameter() { return accessesFieldsFromImplicitParameter; } } private final class MethodReceiverAnalysisVisitor extends ASTVisitor { private IMethod accessedMethod; private boolean encounteredThisReceiver; public boolean hasEncounteredThisReceiver() { return encounteredThisReceiver; } private MethodReceiverAnalysisVisitor(IMethod accessedMethod) { this.accessedMethod = accessedMethod; } @Override public boolean visit(MethodInvocation methodInvocation) { IMethodBinding methodBinding = methodInvocation.resolveMethodBinding(); IJavaElement javaElement = methodBinding.getJavaElement(); if (javaElement == null) logWarning("Could not get Java element from binding: " + methodBinding + " while processing: " + methodInvocation); else if (javaElement.equals(accessedMethod)) { Expression expression = methodInvocation.getExpression(); expression = (Expression) Util.stripParenthesizedExpressions(expression); // FIXME: It's not really that the expression is a `this` // expression but that the type of the expression comes from a // `this` expression. In other words, we may need to climb the // AST. if (expression == null || expression.getNodeType() == ASTNode.THIS_EXPRESSION) { this.encounteredThisReceiver = true; } } return super.visit(methodInvocation); } @Override public boolean visit(SuperMethodInvocation node) { if (node.resolveMethodBinding().getJavaElement().equals(accessedMethod)) this.encounteredThisReceiver = true; return super.visit(node); } } private Set<IMethod> sourceMethods = new LinkedHashSet<>(); private Set<IMethod> unmigratableMethods = new UnmigratableMethodSet(sourceMethods); private static final String FUNCTIONAL_INTERFACE_ANNOTATION_NAME = "FunctionalInterface"; private Map<ICompilationUnit, CompilationUnitRewrite> compilationUnitToCompilationUnitRewriteMap = new HashMap<>(); private Map<ITypeRoot, CompilationUnit> typeRootToCompilationUnitMap = new HashMap<>(); @SuppressWarnings("unused") private static final GroupCategorySet SET_MIGRATE_METHOD_IMPLEMENTATION_TO_INTERFACE = new GroupCategorySet( new GroupCategory("edu.cuny.citytech.defaultrefactoring", //$NON-NLS-1$ Messages.CategoryName, Messages.CategoryDescription)); private static Map<IMethod, IMethod> methodToTargetMethodMap = new HashMap<>(); /** The code generation settings, or <code>null</code> */ private CodeGenerationSettings settings; /** Does the refactoring use a working copy layer? */ private final boolean layer; private static Table<IMethod, IType, IMethod> methodTargetInterfaceTargetMethodTable = HashBasedTable.create(); private SearchEngine searchEngine = new SearchEngine(); /** * For excluding AST parse time. */ private TimeCollector excludedTimeCollector = new TimeCollector(); /** * The minimum logging level, one of the constants in * org.eclipse.core.runtime.IStatus. */ private static int loggingLevel = IStatus.WARNING; /** * Creates a new refactoring with the given methods to refactor. * * @param methods * The methods to refactor. * @throws JavaModelException */ public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(final IMethod[] methods, final CodeGenerationSettings settings, boolean layer, Optional<IProgressMonitor> monitor) throws JavaModelException { try { this.settings = settings; this.layer = layer; Collections.addAll(this.getSourceMethods(), methods); monitor.ifPresent(m -> m.beginTask("Finding target methods ...", methods.length)); for (IMethod method : methods) { // this will populate the map if needed. getTargetMethod(method, monitor); monitor.ifPresent(m -> m.worked(1)); } } finally { monitor.ifPresent(IProgressMonitor::done); } } public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(final IMethod[] methods, final CodeGenerationSettings settings, Optional<IProgressMonitor> monitor) throws JavaModelException { this(methods, settings, false, monitor); } public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(Optional<IProgressMonitor> monitor) throws JavaModelException { this(null, null, false, monitor); } public MigrateSkeletalImplementationToInterfaceRefactoringProcessor() throws JavaModelException { this(null, null, false, Optional.empty()); } /** * {@inheritDoc} */ @Override public Object[] getElements() { return getMigratableMethods().toArray(); } public Set<IMethod> getMigratableMethods() { Set<IMethod> difference = new LinkedHashSet<>(this.getSourceMethods()); difference.removeAll(this.getUnmigratableMethods()); return difference; } @Override public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException, OperationCanceledException { try { this.clearCaches(); this.getExcludedTimeCollector().clear(); if (this.getSourceMethods().isEmpty()) return RefactoringStatus.createFatalErrorStatus(Messages.MethodsNotSpecified); else { RefactoringStatus status = new RefactoringStatus(); pm.beginTask(Messages.CheckingPreconditions, this.getSourceMethods().size()); for (IMethod sourceMethod : this.getSourceMethods()) { status.merge(checkDeclaringType(sourceMethod, Optional.of(new SubProgressMonitor(pm, 0)))); status.merge(checkCandidateDestinationInterfaces(sourceMethod, Optional.of(new SubProgressMonitor(pm, 0)))); pm.worked(1); } return status; } } catch (Exception e) { JavaPlugin.log(e); throw e; } finally { pm.done(); } } private RefactoringStatus checkDestinationInterfaceTargetMethods(IMethod sourceMethod) throws JavaModelException { RefactoringStatus status = new RefactoringStatus(); logInfo("Checking destination interface target methods..."); // Ensure that target methods are not already default methods. // For each method to move, add a warning if the associated target // method is already default. IMethod targetMethod = getTargetMethod(sourceMethod, Optional.empty()); if (targetMethod != null) { int targetMethodFlags = targetMethod.getFlags(); if (Flags.isDefaultMethod(targetMethodFlags)) { RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.TargetMethodIsAlreadyDefault, targetMethod); addUnmigratableMethod(sourceMethod, entry); } } return status; } private RefactoringStatus checkDestinationInterfaces(Optional<IProgressMonitor> monitor) throws JavaModelException { try { RefactoringStatus status = new RefactoringStatus(); monitor.ifPresent(m -> m.beginTask("Checking destination interfaces ...", this.getSourceMethods().size())); for (IMethod sourceMethod : this.getSourceMethods()) { final Optional<IType> targetInterface = this.getDestinationInterface(sourceMethod); // Can't be empty. if (!targetInterface.isPresent()) { addErrorAndMark(status, PreconditionFailure.NoDestinationInterface, sourceMethod); return status; } // Must be a pure interface. if (!isPureInterface(targetInterface.get())) { RefactoringStatusEntry error = addError(status, sourceMethod, PreconditionFailure.DestinationTypeMustBePureInterface, targetInterface.get()); addUnmigratableMethod(sourceMethod, error); } // Make sure it exists. RefactoringStatus existence = checkExistence(targetInterface.get(), PreconditionFailure.DestinationInterfaceDoesNotExist); status.merge(existence); if (!existence.isOK()) addUnmigratableMethod(sourceMethod, existence.getEntryWithHighestSeverity()); // Make sure we can write to it. RefactoringStatus writabilitiy = checkWritabilitiy(targetInterface.get(), PreconditionFailure.DestinationInterfaceNotWritable); status.merge(writabilitiy); if (!writabilitiy.isOK()) addUnmigratableMethod(sourceMethod, writabilitiy.getEntryWithHighestSeverity()); // Make sure it doesn't have compilation errors. RefactoringStatus structure = checkStructure(targetInterface.get()); status.merge(structure); if (!structure.isOK()) addUnmigratableMethod(sourceMethod, structure.getEntryWithHighestSeverity()); // #35: The target interface should not be a // @FunctionalInterface. if (isInterfaceFunctional(targetInterface.get())) { RefactoringStatusEntry error = addError(status, sourceMethod, PreconditionFailure.DestinationInterfaceIsFunctional, targetInterface.get()); addUnmigratableMethod(sourceMethod, error); } // Can't be strictfp if all the methods to be migrated aren't // also strictfp if (Flags.isStrictfp(targetInterface.get().getFlags()) && !allMethodsToMoveInTypeAreStrictFP(sourceMethod.getDeclaringType())) { RefactoringStatusEntry error = addError(status, sourceMethod, PreconditionFailure.DestinationInterfaceIsStrictFP, targetInterface.get()); addUnmigratableMethod(sourceMethod, error); } status.merge(checkDestinationInterfaceTargetMethods(sourceMethod)); monitor.ifPresent(m -> m.worked(1)); } return status; } finally { monitor.ifPresent(IProgressMonitor::done); } } private IType[] getTypesReferencedInMovedMembers(IMethod sourceMethod, final Optional<IProgressMonitor> monitor) throws JavaModelException { // TODO: Cache this result. final IType[] types = ReferenceFinderUtil.getTypesReferencedIn(new IJavaElement[] { sourceMethod }, monitor.orElseGet(NullProgressMonitor::new)); final List<IType> result = new ArrayList<IType>(types.length); final List<IMember> members = Arrays.asList(new IMember[] { sourceMethod }); for (int index = 0; index < types.length; index++) { if (!members.contains(types[index]) && !types[index].equals(sourceMethod.getDeclaringType())) result.add(types[index]); } return result.toArray(new IType[result.size()]); } private boolean canBeAccessedFrom(IMethod sourceMethod, final IMember member, final IType target, final ITypeHierarchy hierarchy) throws JavaModelException { Assert.isTrue(!(member instanceof IInitializer)); if (member.exists()) { if (target.equals(member.getDeclaringType())) return true; if (target.equals(member)) return true; // NOTE: We are not creating stubs (for now). /* * if (member instanceof IMethod) { final IMethod method = (IMethod) * member; final IMethod stub = * target.getMethod(method.getElementName(), * method.getParameterTypes()); if (stub.exists()) return true; } */ if (member.getDeclaringType() == null) { if (!(member instanceof IType)) return false; if (JdtFlags.isPublic(member)) return true; if (!JdtFlags.isPackageVisible(member)) return false; if (JavaModelUtil.isSamePackage(((IType) member).getPackageFragment(), target.getPackageFragment())) return true; final IType type = member.getDeclaringType(); if (type != null) return hierarchy.contains(type); return false; } final IType declaringType = member.getDeclaringType(); // if the member's declaring type isn't accessible from the target // type. if (!canBeAccessedFrom(sourceMethod, declaringType, target, hierarchy)) return false; // then, the member isn't accessible from the // target type. // otherwise, the member's declaring type is accessible from the // target type. // We are going to be moving the source method from it's // declaring type. // We know that the member's declaring type is accessible from // the target. // We also know that the member's declaring type and the target // type are different. // The question now is if the target type can access the // particular member given that // the target type can access the member's declaring type. // if it's public, the answer is yes. if (JdtFlags.isPublic(member)) return true; // if the member is private, the answer is no. else if (JdtFlags.isPrivate(member)) return false; // if it's package-private or protected. else if (JdtFlags.isPackageVisible(member) || JdtFlags.isProtected(member)) { // then, if the member's declaring type in the same package // as the target's declaring type, the answer is yes. if (JavaModelUtil.isVisible(member, target.getPackageFragment())) return true; // otherwise, if it's protected. else if (JdtFlags.isProtected(member)) // then, the answer is yes if the target type is a // sub-type of the member's declaring type. Otherwise, // the answer is no. return hierarchy.contains(declaringType); else return false; // not accessible. } else throw new IllegalStateException("Member: " + member + " has no known visibility."); } return false; } private RefactoringStatus checkAccessedTypes(IMethod sourceMethod, final Optional<IProgressMonitor> monitor, final ITypeHierarchy hierarchy) throws JavaModelException { final RefactoringStatus result = new RefactoringStatus(); final IType[] accessedTypes = getTypesReferencedInMovedMembers(sourceMethod, monitor); final IType destination = getDestinationInterface(sourceMethod).get(); final List<IMember> pulledUpList = Arrays.asList(sourceMethod); for (int index = 0; index < accessedTypes.length; index++) { final IType type = accessedTypes[index]; if (!type.exists()) continue; if (!canBeAccessedFrom(sourceMethod, type, destination, hierarchy) && !pulledUpList.contains(type)) { final String message = org.eclipse.jdt.internal.corext.util.Messages.format( PreconditionFailure.TypeNotAccessible.getMessage(), new String[] { JavaElementLabels.getTextLabel(type, JavaElementLabels.ALL_FULLY_QUALIFIED), JavaElementLabels.getTextLabel(destination, JavaElementLabels.ALL_FULLY_QUALIFIED) }); result.addEntry(RefactoringStatus.ERROR, message, JavaStatusContext.create(type), MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, PreconditionFailure.TypeNotAccessible.ordinal(), sourceMethod); this.getUnmigratableMethods().add(sourceMethod); } } monitor.ifPresent(IProgressMonitor::done); return result; } private RefactoringStatus checkAccessedFields(IMethod sourceMethod, final Optional<IProgressMonitor> monitor, final ITypeHierarchy destinationInterfaceSuperTypeHierarchy) throws CoreException { monitor.ifPresent(m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking_referenced_elements, 2)); final RefactoringStatus result = new RefactoringStatus(); final List<IMember> pulledUpList = Arrays.asList(sourceMethod); final IField[] accessedFields = ReferenceFinderUtil.getFieldsReferencedIn(new IJavaElement[] { sourceMethod }, new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), 1)); final IType destination = getDestinationInterface(sourceMethod).orElseThrow(() -> new IllegalArgumentException( "Source method: " + sourceMethod + " has no destiantion interface.")); for (int index = 0; index < accessedFields.length; index++) { final IField accessedField = accessedFields[index]; if (!accessedField.exists()) continue; boolean isAccessible = pulledUpList.contains(accessedField) || canBeAccessedFrom(sourceMethod, accessedField, destination, destinationInterfaceSuperTypeHierarchy) || Flags.isEnum(accessedField.getFlags()); if (!isAccessible) { final String message = org.eclipse.jdt.internal.corext.util.Messages.format( PreconditionFailure.FieldNotAccessible.getMessage(), new String[] { JavaElementLabels.getTextLabel(accessedField, JavaElementLabels.ALL_FULLY_QUALIFIED), JavaElementLabels.getTextLabel(destination, JavaElementLabels.ALL_FULLY_QUALIFIED) }); result.addEntry(RefactoringStatus.ERROR, message, JavaStatusContext.create(accessedField), MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, PreconditionFailure.FieldNotAccessible.ordinal(), sourceMethod); this.getUnmigratableMethods().add(sourceMethod); } else if (!JdtFlags.isStatic(accessedField) && !accessedField.getDeclaringType().isInterface()) { // it's accessible and it's an instance field. // Let's decide if the source method is accessing it from this // object or another. If it's from this object, we fail. // First, find all references of the accessed field in the // source method. FieldAccessAnalysisSearchRequestor requestor = new FieldAccessAnalysisSearchRequestor(monitor); this.getSearchEngine().search( SearchPattern.createPattern(accessedField, IJavaSearchConstants.REFERENCES, SearchPattern.R_EXACT_MATCH), new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, SearchEngine.createJavaSearchScope(new IJavaElement[] { sourceMethod }), requestor, new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN)); if (requestor.hasAccessesToFieldsFromImplicitParameter()) addErrorAndMark(result, PreconditionFailure.SourceMethodAccessesInstanceField, sourceMethod, accessedField); } } monitor.ifPresent(IProgressMonitor::done); return result; } private RefactoringStatus checkAccessedMethods(IMethod sourceMethod, final Optional<IProgressMonitor> monitor, final ITypeHierarchy destinationInterfaceSuperTypeHierarchy) throws CoreException { monitor.ifPresent(m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking_referenced_elements, 3)); final RefactoringStatus result = new RefactoringStatus(); final List<IMember> pulledUpList = Arrays.asList(sourceMethod); final Set<IMethod> accessedMethods = new LinkedHashSet<>( Arrays.asList(ReferenceFinderUtil.getMethodsReferencedIn(new IJavaElement[] { sourceMethod }, new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), 1)))); // also add constructors. accessedMethods.addAll(getConstructorsReferencedIn(new IJavaElement[] { sourceMethod }, monitor.map(m -> new SubProgressMonitor(m, 1)))); final IType destination = getDestinationInterface(sourceMethod).orElseThrow(() -> new IllegalArgumentException( "Source method: " + sourceMethod + " has no destiantion interface.")); for (IMethod accessedMethod : accessedMethods) { if (!accessedMethod.exists()) continue; boolean isAccessible = pulledUpList.contains(accessedMethod) || canBeAccessedFrom(sourceMethod, accessedMethod, destination, destinationInterfaceSuperTypeHierarchy); if (!isAccessible) { final String message = org.eclipse.jdt.internal.corext.util.Messages.format( PreconditionFailure.MethodNotAccessible.getMessage(), new String[] { getTextLabel(accessedMethod, ALL_FULLY_QUALIFIED), getTextLabel(destination, ALL_FULLY_QUALIFIED) }); result.addEntry(RefactoringStatus.ERROR, message, JavaStatusContext.create(accessedMethod), MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, PreconditionFailure.MethodNotAccessible.ordinal(), sourceMethod); this.getUnmigratableMethods().add(sourceMethod); } else if (!JdtFlags.isStatic(accessedMethod)) { // it's accessible and it's not static. // we'll need to check the implicit parameters. MethodDeclaration sourceMethodDeclaration = ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod, getCompilationUnit(sourceMethod.getTypeRoot(), new SubProgressMonitor( monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN))); MethodReceiverAnalysisVisitor visitor = new MethodReceiverAnalysisVisitor(accessedMethod); sourceMethodDeclaration.getBody().accept(visitor); // if this is the implicit parameter. if (visitor.hasEncounteredThisReceiver()) { // let's check to see if the method is somewhere in the // hierarchy. IType methodDeclaringType = accessedMethod.getDeclaringType(); // is this method declared in a type that is in the // declaring type's super type hierarchy? ITypeHierarchy declaringTypeSuperTypeHierarchy = getSuperTypeHierarchy( sourceMethod.getDeclaringType(), monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN))); if (declaringTypeSuperTypeHierarchy.contains(methodDeclaringType)) { // if so, then we need to check that it is in the // destination interface's super type hierarchy. boolean methodInHiearchy = isMethodInHierarchy(accessedMethod, destinationInterfaceSuperTypeHierarchy); if (!methodInHiearchy) { final String message = org.eclipse.jdt.internal.corext.util.Messages.format( PreconditionFailure.MethodNotAccessible.getMessage(), new String[] { getTextLabel(accessedMethod, ALL_FULLY_QUALIFIED), getTextLabel(destination, ALL_FULLY_QUALIFIED) }); result.addEntry(RefactoringStatus.ERROR, message, JavaStatusContext.create(accessedMethod), MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, PreconditionFailure.MethodNotAccessible.ordinal(), sourceMethod); this.getUnmigratableMethods().add(sourceMethod); } } } } } monitor.ifPresent(IProgressMonitor::done); return result; } private Collection<? extends IMethod> getConstructorsReferencedIn(IJavaElement[] elements, final Optional<IProgressMonitor> monitor) throws CoreException { Collection<IMethod> ret = new LinkedHashSet<>(); SearchPattern pattern = SearchPattern.createPattern("*", IJavaSearchConstants.CONSTRUCTOR, IJavaSearchConstants.REFERENCES, SearchPattern.R_PATTERN_MATCH); IJavaSearchScope scope = SearchEngine.createJavaSearchScope(elements, true); SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }; this.getSearchEngine().search(pattern, participants, scope, new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { if (match.isInsideDocComment()) return; ASTNode node = ASTNodeSearchUtil.getAstNode(match, getCompilationUnit( ((IMember) match.getElement()).getTypeRoot(), new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN))); node = Util.stripParenthesizedExpressions(node); IMethod constructor = extractConstructor(node); if (constructor != null) ret.add(constructor); } private IMethod extractConstructor(ASTNode node) { if (node == null) throw new IllegalArgumentException("Node is null"); else { switch (node.getNodeType()) { case ASTNode.CLASS_INSTANCE_CREATION: { ClassInstanceCreation creation = (ClassInstanceCreation) node; IMethodBinding binding = creation.resolveConstructorBinding(); return (IMethod) binding.getJavaElement(); } case ASTNode.CONSTRUCTOR_INVOCATION: { ConstructorInvocation invocation = (ConstructorInvocation) node; IMethodBinding binding = invocation.resolveConstructorBinding(); return (IMethod) binding.getJavaElement(); } case ASTNode.SUPER_CONSTRUCTOR_INVOCATION: { SuperConstructorInvocation invocation = (SuperConstructorInvocation) node; IMethodBinding binding = invocation.resolveConstructorBinding(); return (IMethod) binding.getJavaElement(); } case ASTNode.CREATION_REFERENCE: { CreationReference reference = (CreationReference) node; IMethodBinding binding = reference.resolveMethodBinding(); if (binding == null) { logWarning("Could not resolve method binding from creation reference: " + reference); return null; } IMethod javaElement = (IMethod) binding.getJavaElement(); return javaElement; } default: { // try the parent node. return extractConstructor(node.getParent()); } } } } }, monitor.orElseGet(NullProgressMonitor::new)); return ret; } private static boolean isMethodInHierarchy(IMethod method, ITypeHierarchy hierarchy) { // TODO: Cache this? return Stream.of(hierarchy.getAllTypes()).parallel().anyMatch(t -> { IMethod[] methods = t.findMethods(method); return methods != null && methods.length > 0; }); } private RefactoringStatus checkAccesses(IMethod sourceMethod, final Optional<IProgressMonitor> monitor) throws CoreException { final RefactoringStatus result = new RefactoringStatus(); try { monitor.ifPresent( m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking_referenced_elements, 4)); IType destinationInterface = getDestinationInterface(sourceMethod) .orElseThrow(() -> new IllegalArgumentException( "Source method: " + sourceMethod + " has no destination interface.")); final ITypeHierarchy destinationInterfaceSuperTypeHierarchy = getSuperTypeHierarchy(destinationInterface, monitor.map(m -> new SubProgressMonitor(m, 1))); result.merge(checkAccessedTypes(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1)), destinationInterfaceSuperTypeHierarchy)); result.merge(checkAccessedFields(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1)), destinationInterfaceSuperTypeHierarchy)); result.merge(checkAccessedMethods(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1)), destinationInterfaceSuperTypeHierarchy)); } finally { monitor.ifPresent(IProgressMonitor::done); } return result; } private boolean allMethodsToMoveInTypeAreStrictFP(IType type) throws JavaModelException { for (Iterator<IMethod> iterator = this.getSourceMethods().iterator(); iterator.hasNext();) { IMethod method = iterator.next(); if (method.getDeclaringType().equals(type) && !Flags.isStrictfp(method.getFlags())) return false; } return true; } private static boolean isInterfaceFunctional(final IType anInterface) throws JavaModelException { // TODO: #37: Compute effectively functional interfaces. return Stream.of(anInterface.getAnnotations()).parallel().map(IAnnotation::getElementName) .anyMatch(s -> s.contains(FUNCTIONAL_INTERFACE_ANNOTATION_NAME)); } private RefactoringStatus checkValidInterfacesInDeclaringTypeHierarchy(IMethod sourceMethod, Optional<IProgressMonitor> monitor) throws JavaModelException { RefactoringStatus status = new RefactoringStatus(); monitor.ifPresent(m -> m.beginTask("Checking valid interfaces in declaring type hierarchy ...", IProgressMonitor.UNKNOWN)); try { ITypeHierarchy hierarchy = this.getDeclaringTypeHierarchy(sourceMethod, monitor); IType[] declaringTypeSuperInterfaces = hierarchy.getAllSuperInterfaces(sourceMethod.getDeclaringType()); // the number of methods sourceMethod is implementing. long numberOfImplementedMethods = Arrays.stream(declaringTypeSuperInterfaces).parallel().distinct().flatMap( i -> Arrays.stream(Optional.ofNullable(i.findMethods(sourceMethod)).orElse(new IMethod[] {}))) .count(); if (numberOfImplementedMethods > 1) addErrorAndMark(status, PreconditionFailure.SourceMethodImplementsMultipleMethods, sourceMethod); // for each subclass of the declaring type. for (IType subclass : hierarchy.getSubclasses(sourceMethod.getDeclaringType())) { status.merge(checkClassForMissingSourceMethodImplementation(sourceMethod, subclass, hierarchy, monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN)))); } } finally { monitor.ifPresent(IProgressMonitor::done); } return status; } /** * Checks the given class and its subclasses for any required * implementations of the source method. The required implementations are * deemed by the interfaces the given class implements. * * @param sourceMethod * The source method being migrated to an interface. * @param clazz * The class to check for any missing needed implementations of * the source method. * @param declaringTypeHierarchy * Hierarchy of the source method's declaring type. * @return {@link RefactoringStatus} indicating the result of the * precondition check. * @throws JavaModelException * When asserting that the given {@link IType} is indeed a * class. */ private RefactoringStatus checkClassForMissingSourceMethodImplementation(IMethod sourceMethod, IType clazz, ITypeHierarchy declaringTypeHierarchy, Optional<IProgressMonitor> monitor) throws JavaModelException { RefactoringStatus status = new RefactoringStatus(); // does the class have an implementation or declaration of the source // method? IMethod[] classMethodMatchingSourceMethod = clazz.findMethods(sourceMethod); if (classMethodMatchingSourceMethod != null && classMethodMatchingSourceMethod.length > 0) // in this case, the class has an implementation. No need to check // any interfaces or subclasses. // because any interfaces would be satisfied and any unsatisfied // interfaces will inherit the method from this class. return status; // otherwise, no matching methods were found in the given class. else { // retrieve super interfaces of the class. IType[] superInterfaces = getSuperInterfaces(clazz, declaringTypeHierarchy, monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN))); try { monitor.ifPresent(m -> m.beginTask("Checking class for missing source method implementation ...", superInterfaces.length)); // retrieve the destination interface. IType destinationInterface = getTargetMethod(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN))).getDeclaringType(); // for each super interface of the given class. for (IType superInterface : superInterfaces) { // if it is not equal to the destination interface. if (!superInterface.equals(destinationInterface)) { IMethod[] interfaceMethodMatchingSourceMethod = superInterface.findMethods(sourceMethod); if (interfaceMethodMatchingSourceMethod != null && interfaceMethodMatchingSourceMethod.length > 0) // there are multiple method definitions stemming // from // interfaces. // this class doesn't have an implementation of the // source // method nor does it inherit it. addErrorAndMark(status, PreconditionFailure.SourceMethodProvidesImplementationsForMultipleMethods, sourceMethod, superInterface); } monitor.ifPresent(m -> m.worked(1)); } // check subclasses of the given class. for (IType subclass : declaringTypeHierarchy.getSubclasses(clazz)) status.merge(checkClassForMissingSourceMethodImplementation(sourceMethod, subclass, declaringTypeHierarchy, monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN)))); return status; } finally { monitor.ifPresent(IProgressMonitor::done); } } } private static IType[] getSuperInterfaces(IType type, ITypeHierarchy typeHierarchy, Optional<IProgressMonitor> monitor) throws JavaModelException { Set<IType> ret = new LinkedHashSet<>(); IType[] superInterfaces = typeHierarchy.getSuperInterfaces(type); ret.addAll(Arrays.asList(superInterfaces)); monitor.ifPresent(m -> m.beginTask("Retreiving super interfaces ...", superInterfaces.length)); try { for (IType superInterface : superInterfaces) { ret.addAll(Arrays .asList(getSuperInterfaces(superInterface, monitor.map(m -> new SubProgressMonitor(m, 1))))); } } finally { monitor.ifPresent(IProgressMonitor::done); } return ret.toArray(new IType[ret.size()]); } private Optional<IType> getDestinationInterface(IMethod sourceMethod) throws JavaModelException { return Optional.ofNullable(getTargetMethod(sourceMethod, Optional.empty())).map(IMethod::getDeclaringType); } private RefactoringStatus checkValidClassesInDeclaringTypeHierarchy(IMethod sourceMethod, final ITypeHierarchy declaringTypeHierarchy) throws JavaModelException { RefactoringStatus status = new RefactoringStatus(); IType[] allDeclaringTypeSuperclasses = declaringTypeHierarchy .getAllSuperclasses(sourceMethod.getDeclaringType()); // is the source method overriding anything in the declaring type // hierarchy? If so, don't allow the refactoring to proceed #107. if (Stream.of(allDeclaringTypeSuperclasses).parallel().anyMatch(c -> { IMethod[] methods = c.findMethods(sourceMethod); return methods != null && methods.length > 0; })) addErrorAndMark(status, PreconditionFailure.SourceMethodOverridesMethod, sourceMethod); return status; } private void addWarning(RefactoringStatus status, IMethod sourceMethod, PreconditionFailure failure) { addWarning(status, sourceMethod, failure, new IJavaElement[] {}); } private RefactoringStatus checkDeclaringType(IMethod sourceMethod, Optional<IProgressMonitor> monitor) throws JavaModelException { RefactoringStatus status = new RefactoringStatus(); IType type = sourceMethod.getDeclaringType(); if (type.isAnnotation()) addErrorAndMark(status, PreconditionFailure.NoMethodsInAnnotationTypes, sourceMethod, type); if (type.isInterface()) addErrorAndMark(status, PreconditionFailure.NoMethodsInInterfaces, sourceMethod, type); if (type.isBinary()) addErrorAndMark(status, PreconditionFailure.NoMethodsInBinaryTypes, sourceMethod, type); if (type.isReadOnly()) addErrorAndMark(status, PreconditionFailure.NoMethodsInReadOnlyTypes, sourceMethod, type); if (type.isAnonymous()) addErrorAndMark(status, PreconditionFailure.NoMethodsInAnonymousTypes, sourceMethod, type); if (type.isLambda()) // TODO for now. addErrorAndMark(status, PreconditionFailure.NoMethodsInLambdas, sourceMethod, type); if (type.isLocal()) // TODO for now. addErrorAndMark(status, PreconditionFailure.NoMethodsInLocals, sourceMethod, type); // TODO enclosing type must implement an interface, at least for // now, // which one of which will become the target interface. // it is probably possible to still perform the refactoring // without this condition but I believe that this is // the particular pattern we are targeting. status.merge(checkDeclaringTypeHierarchy(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1)))); return status; } private void addErrorAndMark(RefactoringStatus status, PreconditionFailure failure, IMethod sourceMethod, IMember... related) { RefactoringStatusEntry error = addError(status, sourceMethod, failure, sourceMethod, related); addUnmigratableMethod(sourceMethod, error); } private RefactoringStatus checkDeclaringTypeHierarchy(IMethod sourceMethod, Optional<IProgressMonitor> monitor) throws JavaModelException { try { RefactoringStatus status = new RefactoringStatus(); monitor.ifPresent(m -> m.subTask("Checking declaring type hierarchy...")); final ITypeHierarchy declaringTypeHierarchy = this.getDeclaringTypeHierarchy(sourceMethod, monitor); status.merge(checkValidClassesInDeclaringTypeHierarchy(sourceMethod, declaringTypeHierarchy)); status.merge(checkValidInterfacesInDeclaringTypeHierarchy(sourceMethod, monitor)); return status; } finally { monitor.ifPresent(IProgressMonitor::done); } } private RefactoringStatus checkCandidateDestinationInterfaces(IMethod sourceMethod, final Optional<IProgressMonitor> monitor) throws JavaModelException { RefactoringStatus status = new RefactoringStatus(); IType[] interfaces = getCandidateDestinationInterfaces(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1))); if (interfaces.length == 0) addErrorAndMark(status, PreconditionFailure.NoMethodsInTypesWithNoCandidateTargetTypes, sourceMethod, sourceMethod.getDeclaringType()); else if (interfaces.length > 1) // TODO: For now, let's make sure there's only one candidate type // #129. addErrorAndMark(status, PreconditionFailure.NoMethodsInTypesWithMultipleCandidateTargetTypes, sourceMethod, sourceMethod.getDeclaringType()); return status; } /** * Returns the possible target interfaces for the migration. NOTE: One * difference here between this refactoring and pull up is that we can have * a much more complex type hierarchy due to multiple interface inheritance * in Java. * <p> * TODO: It should be possible to pull up a method into an interface (i.e., * "Pull Up Method To Interface") that is not implemented explicitly. For * example, there may be a skeletal implementation class that implements all * the target interface's methods without explicitly declaring so. * Effectively skeletal? * * @param monitor * A progress monitor. * @return The possible target interfaces for the migration. * @throws JavaModelException * upon Java model problems. */ public static IType[] getCandidateDestinationInterfaces(IMethod sourcMethod, final Optional<IProgressMonitor> monitor) throws JavaModelException { try { monitor.ifPresent(m -> m.beginTask("Retrieving candidate types...", IProgressMonitor.UNKNOWN)); IType[] superInterfaces = getSuperInterfaces(sourcMethod.getDeclaringType(), monitor.map(m -> new SubProgressMonitor(m, 1))); Stream<IType> candidateStream = Stream.of(superInterfaces).parallel().filter(Objects::nonNull) .filter(IJavaElement::exists).filter(t -> !t.isReadOnly()).filter(t -> !t.isBinary()); Set<IType> ret = new HashSet<>(); for (Iterator<IType> iterator = candidateStream.iterator(); iterator.hasNext();) { IType superInterface = iterator.next(); IMethod[] interfaceMethods = superInterface.findMethods(sourcMethod); if (interfaceMethods != null) // the matching methods cannot already be default. for (IMethod method : interfaceMethods) if (!JdtFlags.isDefaultMethod(method)) ret.add(superInterface); } return ret.toArray(new IType[ret.size()]); } finally { monitor.ifPresent(IProgressMonitor::done); } } private static IType[] getSuperInterfaces(IType type, final Optional<IProgressMonitor> monitor) throws JavaModelException { try { monitor.ifPresent(m -> m.beginTask("Retrieving type super interfaces...", IProgressMonitor.UNKNOWN)); return getSuperTypeHierarchy(type, monitor.map(m -> new SubProgressMonitor(m, 1))) .getAllSuperInterfaces(type); } finally { monitor.ifPresent(IProgressMonitor::done); } } private ITypeHierarchy getDeclaringTypeHierarchy(IMethod sourceMethod, final Optional<IProgressMonitor> monitor) throws JavaModelException { try { monitor.ifPresent(m -> m.subTask("Retrieving declaring type hierarchy...")); IType declaringType = sourceMethod.getDeclaringType(); return this.getTypeHierarchy(declaringType, monitor); } finally { monitor.ifPresent(IProgressMonitor::done); } } @SuppressWarnings("unused") private ITypeHierarchy getDestinationInterfaceHierarchy(IMethod sourceMethod, final Optional<IProgressMonitor> monitor) throws JavaModelException { try { monitor.ifPresent(m -> m.subTask("Retrieving destination type hierarchy...")); IType destinationInterface = getDestinationInterface(sourceMethod).get(); return this.getTypeHierarchy(destinationInterface, monitor); } finally { monitor.ifPresent(IProgressMonitor::done); } } private static Map<IType, ITypeHierarchy> typeToSuperTypeHierarchyMap = new HashMap<>(); private static Map<IType, ITypeHierarchy> getTypeToSuperTypeHierarchyMap() { return typeToSuperTypeHierarchyMap; } private static ITypeHierarchy getSuperTypeHierarchy(IType type, final Optional<IProgressMonitor> monitor) throws JavaModelException { try { monitor.ifPresent(m -> m.subTask("Retrieving declaring super type hierarchy...")); if (getTypeToSuperTypeHierarchyMap().containsKey(type)) return getTypeToSuperTypeHierarchyMap().get(type); else { ITypeHierarchy newSupertypeHierarchy = type .newSupertypeHierarchy(monitor.orElseGet(NullProgressMonitor::new)); getTypeToSuperTypeHierarchyMap().put(type, newSupertypeHierarchy); return newSupertypeHierarchy; } } finally { monitor.ifPresent(IProgressMonitor::done); } } private RefactoringStatus checkSourceMethods(Optional<IProgressMonitor> pm) throws CoreException { try { RefactoringStatus status = new RefactoringStatus(); pm.ifPresent(m -> m.beginTask(Messages.CheckingPreconditions, this.getSourceMethods().size())); for (IMethod sourceMethod : this.getSourceMethods()) { RefactoringStatus existenceStatus = checkExistence(sourceMethod, PreconditionFailure.MethodDoesNotExist); if (!existenceStatus.isOK()) { status.merge(existenceStatus); addUnmigratableMethod(sourceMethod, existenceStatus.getEntryWithHighestSeverity()); } RefactoringStatus writabilityStatus = checkWritabilitiy(sourceMethod, PreconditionFailure.CantChangeMethod); if (!writabilityStatus.isOK()) { status.merge(writabilityStatus); addUnmigratableMethod(sourceMethod, writabilityStatus.getEntryWithHighestSeverity()); } RefactoringStatus structureStatus = checkStructure(sourceMethod); if (!structureStatus.isOK()) { status.merge(structureStatus); addUnmigratableMethod(sourceMethod, structureStatus.getEntryWithHighestSeverity()); } if (sourceMethod.isConstructor()) { RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoConstructors, sourceMethod); addUnmigratableMethod(sourceMethod, entry); } status.merge(checkAnnotations(sourceMethod)); // synchronized methods aren't allowed in interfaces (even // if they're default). if (Flags.isSynchronized(sourceMethod.getFlags())) { RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoSynchronizedMethods, sourceMethod); addUnmigratableMethod(sourceMethod, entry); } if (Flags.isStatic(sourceMethod.getFlags())) { RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoStaticMethods, sourceMethod); addUnmigratableMethod(sourceMethod, entry); } if (Flags.isAbstract(sourceMethod.getFlags())) { RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoAbstractMethods, sourceMethod); addUnmigratableMethod(sourceMethod, entry); } // final methods aren't allowed in interfaces. if (Flags.isFinal(sourceMethod.getFlags())) { RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoFinalMethods, sourceMethod); addUnmigratableMethod(sourceMethod, entry); } // native methods don't have bodies. As such, they can't // be skeletal implementors. if (JdtFlags.isNative(sourceMethod)) { RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoNativeMethods, sourceMethod); addUnmigratableMethod(sourceMethod, entry); } if (sourceMethod.isLambdaMethod()) { RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.NoLambdaMethods, sourceMethod); addUnmigratableMethod(sourceMethod, entry); } status.merge(checkExceptions(sourceMethod)); // ensure that the method has a target. if (getTargetMethod(sourceMethod, pm.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN))) == null) addErrorAndMark(status, PreconditionFailure.SourceMethodHasNoTargetMethod, sourceMethod); else { status.merge(checkParameters(sourceMethod, pm.map(m -> new SubProgressMonitor(m, 1)))); status.merge(checkReturnType(sourceMethod, pm.map(m -> new SubProgressMonitor(m, 1)))); status.merge(checkAccesses(sourceMethod, pm.map(m -> new SubProgressMonitor(m, 1)))); status.merge(checkGenericDeclaringType(sourceMethod, pm.map(m -> new SubProgressMonitor(m, 1)))); status.merge(checkProjectCompliance(sourceMethod)); } pm.ifPresent(m -> m.worked(1)); } return status; } finally { pm.ifPresent(IProgressMonitor::done); } } private RefactoringStatus checkGenericDeclaringType(IMethod sourceMethod, Optional<IProgressMonitor> monitor) throws JavaModelException { final RefactoringStatus status = new RefactoringStatus(); try { final IMember[] pullables = new IMember[] { sourceMethod }; monitor.ifPresent(m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, pullables.length)); final IType declaring = sourceMethod.getDeclaringType(); final ITypeParameter[] parameters = declaring.getTypeParameters(); if (parameters.length > 0) { monitor.ifPresent(m -> m.beginTask("Retrieving target method.", IProgressMonitor.UNKNOWN)); IMethod targetMethod = getTargetMethod(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN))); final TypeVariableMaplet[] mapping = TypeVariableUtil.subTypeToInheritedType(declaring, targetMethod.getDeclaringType()); IMember member = null; int length = 0; for (int index = 0; index < pullables.length; index++) { member = pullables[index]; final String[] unmapped = TypeVariableUtil.getUnmappedVariables(mapping, declaring, member); length = unmapped.length; String superClassLabel = BasicElementLabels .getJavaElementName(targetMethod.getDeclaringType().getElementName()); switch (length) { case 0: break; case 1: status.addEntry(RefactoringStatus.ERROR, String.format(PreconditionFailure.TypeVariableNotAvailable.getMessage(), unmapped[0], superClassLabel), JavaStatusContext.create(member), MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, PreconditionFailure.TypeVariableNotAvailable.ordinal(), sourceMethod); addUnmigratableMethod(sourceMethod, status.getEntryWithHighestSeverity()); break; case 2: status.addEntry(RefactoringStatus.ERROR, MessageFormat.format(PreconditionFailure.TypeVariable2NotAvailable.getMessage(), unmapped[0], unmapped[1], superClassLabel), JavaStatusContext.create(member), MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, PreconditionFailure.TypeVariable2NotAvailable.ordinal(), sourceMethod); addUnmigratableMethod(sourceMethod, status.getEntryWithHighestSeverity()); break; case 3: status.addEntry(RefactoringStatus.ERROR, MessageFormat.format(PreconditionFailure.TypeVariable3NotAvailable.getMessage(), unmapped[0], unmapped[1], unmapped[2], superClassLabel), JavaStatusContext.create(member), MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, PreconditionFailure.TypeVariable3NotAvailable.ordinal(), sourceMethod); addUnmigratableMethod(sourceMethod, status.getEntryWithHighestSeverity()); break; default: status.addEntry(RefactoringStatus.ERROR, MessageFormat.format(PreconditionFailure.TypeVariablesNotAvailable.getMessage(), superClassLabel), JavaStatusContext.create(member), MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, PreconditionFailure.TypeVariablesNotAvailable.ordinal(), sourceMethod); addUnmigratableMethod(sourceMethod, status.getEntryWithHighestSeverity()); } monitor.ifPresent(m -> m.worked(1)); monitor.ifPresent(m -> { if (m.isCanceled()) throw new OperationCanceledException(); }); } } } finally { monitor.ifPresent(IProgressMonitor::done); } return status; } /** * Annotations between source and target methods must be consistent. Related * to #45. * * @param sourceMethod * The method to check annotations. * @return The resulting {@link RefactoringStatus}. * @throws JavaModelException * If the {@link IAnnotation}s cannot be retrieved. */ private RefactoringStatus checkAnnotations(IMethod sourceMethod) throws JavaModelException { RefactoringStatus status = new RefactoringStatus(); IMethod targetMethod = getTargetMethod(sourceMethod, Optional.empty()); if (targetMethod != null && (!checkAnnotations(sourceMethod, targetMethod).isOK() || !checkAnnotations(sourceMethod.getDeclaringType(), targetMethod.getDeclaringType()).isOK())) addErrorAndMark(status, PreconditionFailure.AnnotationMismatch, sourceMethod, targetMethod); return status; } private void addUnmigratableMethod(IMethod method, Object reason) { this.getUnmigratableMethods().add(method); this.logInfo( "Method " + getElementLabel(method, ALL_FULLY_QUALIFIED) + " is not migratable because: " + reason); } private RefactoringStatus checkAnnotations(IAnnotatable source, IAnnotatable target) throws JavaModelException { // a set of annotations from the source method. Set<IAnnotation> sourceAnnotationSet = new HashSet<>(Arrays.asList(source.getAnnotations())); // remove any annotations to not consider. removeSpecialAnnotations(sourceAnnotationSet); // a set of source method annotation names. Set<String> sourceMethodAnnotationElementNames = sourceAnnotationSet.parallelStream() .map(IAnnotation::getElementName).collect(Collectors.toSet()); // a set of target method annotation names. Set<String> targetAnnotationElementNames = getAnnotationElementNames(target); // if the source method annotation names don't match the target method // annotation names. if (!sourceMethodAnnotationElementNames.equals(targetAnnotationElementNames)) return RefactoringStatus.createErrorStatus(PreconditionFailure.AnnotationNameMismatch.getMessage(), new RefactoringStatusContext() { @Override public Object getCorrespondingElement() { return source; } }); else { // otherwise, we have the same annotations names. Check the // values. for (IAnnotation sourceAnnotation : sourceAnnotationSet) { IMemberValuePair[] sourcePairs = sourceAnnotation.getMemberValuePairs(); IAnnotation targetAnnotation = target.getAnnotation(sourceAnnotation.getElementName()); IMemberValuePair[] targetPairs = targetAnnotation.getMemberValuePairs(); // sanity check. Assert.isTrue(sourcePairs.length == targetPairs.length, "Source and target pairs differ."); Arrays.parallelSort(sourcePairs, Comparator.comparing(IMemberValuePair::getMemberName)); Arrays.parallelSort(targetPairs, Comparator.comparing(IMemberValuePair::getMemberName)); for (int i = 0; i < sourcePairs.length; i++) if (!sourcePairs[i].getMemberName().equals(targetPairs[i].getMemberName()) || sourcePairs[i].getValueKind() != targetPairs[i].getValueKind() || !(sourcePairs[i].getValue().equals(targetPairs[i].getValue()))) return RefactoringStatus.createErrorStatus( formatMessage(PreconditionFailure.AnnotationValueMismatch.getMessage(), sourceAnnotation, targetAnnotation), JavaStatusContext.create(findEnclosingMember(sourceAnnotation))); } } return new RefactoringStatus(); } /** * Remove any annotations that we don't want considered. * * @param annotationSet * The set of annotations to work with. */ private void removeSpecialAnnotations(Set<IAnnotation> annotationSet) { // Special case: don't consider the @Override annotation in the source // (the target will never have this) annotationSet.removeIf(a -> a.getElementName().equals(Override.class.getName())); annotationSet.removeIf(a -> a.getElementName().equals(Override.class.getSimpleName())); } private static IMember findEnclosingMember(IJavaElement element) { if (element == null) return null; else if (element instanceof IMember) return (IMember) element; else return findEnclosingMember(element.getParent()); } private Set<String> getAnnotationElementNames(IAnnotatable annotatable) throws JavaModelException { return Arrays.stream(annotatable.getAnnotations()).parallel().map(IAnnotation::getElementName) .collect(Collectors.toSet()); } /** * #44: Ensure that exception types between the source and target methods * match. * * @param sourceMethod * The source method. * @return The corresponding {@link RefactoringStatus}. * @throws JavaModelException * If there is trouble retrieving exception types from * sourceMethod. */ private RefactoringStatus checkExceptions(IMethod sourceMethod) throws JavaModelException { RefactoringStatus status = new RefactoringStatus(); IMethod targetMethod = getTargetMethod(sourceMethod, Optional.empty()); if (targetMethod != null) { Set<String> sourceMethodExceptionTypeSet = getExceptionTypeSet(sourceMethod); Set<String> targetMethodExceptionTypeSet = getExceptionTypeSet(targetMethod); if (!sourceMethodExceptionTypeSet.equals(targetMethodExceptionTypeSet)) { RefactoringStatusEntry entry = addError(status, sourceMethod, PreconditionFailure.ExceptionTypeMismatch, sourceMethod, targetMethod); addUnmigratableMethod(sourceMethod, entry); } } return status; } private static Set<String> getExceptionTypeSet(IMethod method) throws JavaModelException { return Stream.of(method.getExceptionTypes()).parallel().collect(Collectors.toSet()); } /** * Check that the annotations in the parameters are consistent between the * source and target, as well as type arguments. * * FIXME: What if the annotation type is not available in the target? * * @param sourceMethod * The method to check. * @param monitor * An optional {@link IProgressMonitor}. * @return {@link RefactoringStatus} indicating the result of the check. * @throws JavaModelException */ private RefactoringStatus checkParameters(IMethod sourceMethod, Optional<IProgressMonitor> monitor) throws JavaModelException { RefactoringStatus status = new RefactoringStatus(); ILocalVariable[] sourceMethodParameters = sourceMethod.getParameters(); monitor.ifPresent(m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, sourceMethodParameters.length * 2 + 1)); try { IMethod targetMethod = getTargetMethod(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1))); // for each parameter. for (int i = 0; i < sourceMethodParameters.length; i++) { ILocalVariable sourceParameter = sourceMethodParameters[i]; // get the corresponding target parameter. ILocalVariable targetParameter = targetMethod.getParameters()[i]; if (!checkAnnotations(sourceParameter, targetParameter).isOK()) addErrorAndMark(status, PreconditionFailure.MethodContainsInconsistentParameterAnnotations, sourceMethod, targetMethod); monitor.ifPresent(m -> m.worked(1)); } // check generics #160. IMethodBinding sourceMethodBinding = resolveMethodBinding(sourceMethod, monitor); IMethodBinding targetMethodBinding = resolveMethodBinding(targetMethod, monitor); if (targetMethodBinding != null) { ITypeBinding[] sourceMethodParameterTypes = sourceMethodBinding.getParameterTypes(); ITypeBinding[] targetMethodParameterTypes = targetMethodBinding.getParameterTypes(); for (int i = 0; i < sourceMethodParameterTypes.length; i++) { monitor.ifPresent(m -> m.worked(1)); ITypeBinding[] sourceMethodParameterTypeParameters = sourceMethodParameterTypes[i] .getTypeArguments(); ITypeBinding[] targetMethodParamaterTypeParameters = targetMethodParameterTypes[i] .getTypeArguments(); boolean hasAssignmentIncompatibleTypeParameter = false; if (sourceMethodParameterTypeParameters.length != targetMethodParamaterTypeParameters.length) { addErrorAndMark(status, PreconditionFailure.MethodContainsIncompatibleParameterTypeParameters, sourceMethod, targetMethod); break; // no more parameter types. } else for (int j = 0; j < sourceMethodParameterTypeParameters.length; j++) { // if both aren't type variables. if (!typeArgumentsAreTypeVariables(sourceMethodParameterTypeParameters[j], targetMethodParamaterTypeParameters[j])) { // then check if they are assignment compatible. if (!isAssignmentCompatible(sourceMethodParameterTypeParameters[j], targetMethodParamaterTypeParameters[j])) { addErrorAndMark(status, PreconditionFailure.MethodContainsIncompatibleParameterTypeParameters, sourceMethod, targetMethod); hasAssignmentIncompatibleTypeParameter = true; break; // no more type parameters. } } } if (hasAssignmentIncompatibleTypeParameter) break; // no more parameter types. } } } finally { monitor.ifPresent(IProgressMonitor::done); } return status; } private IMethodBinding resolveMethodBinding(IMethod method, Optional<IProgressMonitor> monitor) throws JavaModelException { MethodDeclaration methodDeclarationNode = ASTNodeSearchUtil.getMethodDeclarationNode(method, getCompilationUnit(method.getTypeRoot(), new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN))); if (methodDeclarationNode != null) return methodDeclarationNode.resolveBinding(); else return null; } /** * Check that return types are compatible between the source and target * methods. * * @param sourceMethod * The method to check. * @param monitor * Optional progress monitor. * @return {@link RefactoringStatus} indicating the result of the check. * @throws JavaModelException */ private RefactoringStatus checkReturnType(IMethod sourceMethod, Optional<IProgressMonitor> monitor) throws JavaModelException { RefactoringStatus status = new RefactoringStatus(); monitor.ifPresent(m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, 4)); try { IMethod targetMethod = getTargetMethod(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1))); String sourceMethodReturnType = Util.getQualifiedNameFromTypeSignature(sourceMethod.getReturnType(), sourceMethod.getDeclaringType()); String targetMethodReturnType = Util.getQualifiedNameFromTypeSignature(targetMethod.getReturnType(), targetMethod.getDeclaringType()); if (!sourceMethodReturnType.equals(targetMethodReturnType)) { addErrorAndMark(status, PreconditionFailure.IncompatibleMethodReturnTypes, sourceMethod, targetMethod); monitor.ifPresent(m -> m.worked(3)); } else { monitor.ifPresent(m -> m.worked(1)); // check generics #160. ITypeBinding sourceMethodReturnTypeBinding = resolveReturnTypeBinding(sourceMethod, Optional.empty()); ITypeBinding[] sourceMethodReturnTypeTypeArguments = sourceMethodReturnTypeBinding.getTypeArguments(); if (sourceMethodReturnTypeTypeArguments.length > 0) { // type arguments exist in the return type of the source // method. ITypeBinding targetMethodReturnTypeBinding = resolveReturnTypeBinding(targetMethod, Optional.empty()); ITypeBinding[] targetMethodReturnTypeTypeArguments = targetMethodReturnTypeBinding .getTypeArguments(); // are the type arguments the same length? if (sourceMethodReturnTypeTypeArguments.length != targetMethodReturnTypeTypeArguments.length) { addErrorAndMark(status, PreconditionFailure.IncompatibleMethodReturnTypes, sourceMethod, targetMethod); monitor.ifPresent(m -> m.worked(2)); } else { monitor.ifPresent(m -> m.worked(1)); // are the type arguments compatible? for (int i = 0; i < sourceMethodReturnTypeTypeArguments.length; i++) { if (!typeArgumentsAreTypeVariables(sourceMethodReturnTypeTypeArguments[i], targetMethodReturnTypeTypeArguments[i])) { // then, we should check their assignment // compatibility. if (!isAssignmentCompatible(sourceMethodReturnTypeTypeArguments[i], targetMethodReturnTypeTypeArguments[i])) { addErrorAndMark(status, PreconditionFailure.IncompatibleMethodReturnTypes, sourceMethod, targetMethod); break; } } monitor.ifPresent(m -> m.worked(1)); } } } } } finally { monitor.ifPresent(IProgressMonitor::done); } return status; } private boolean typeArgumentsAreTypeVariables(ITypeBinding typeArgument, ITypeBinding otherTypeArgument) { return typeArgument.isTypeVariable() && otherTypeArgument.isTypeVariable(); } private static boolean isAssignmentCompatible(ITypeBinding typeBinding, ITypeBinding otherTypeBinding) { // Workaround if (typeBinding == null && otherTypeBinding == null) return true; else if (typeBinding == null || otherTypeBinding == null) return false; else return typeBinding.isAssignmentCompatible(otherTypeBinding) || typeBinding.isInterface() && otherTypeBinding.isInterface() && (typeBinding.isEqualTo(otherTypeBinding) || Arrays .stream(typeBinding.getInterfaces()).anyMatch(itb -> itb.isEqualTo(otherTypeBinding))); } private ITypeBinding resolveReturnTypeBinding(IMethod method, Optional<IProgressMonitor> monitor) throws JavaModelException { MethodDeclaration methodDeclarationNode = ASTNodeSearchUtil.getMethodDeclarationNode(method, getCompilationUnit(method.getTypeRoot(), new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN))); if (methodDeclarationNode != null) { Type returnType = methodDeclarationNode.getReturnType2(); return returnType.resolveBinding(); } else return null; } private RefactoringStatus checkStructure(IMember member) throws JavaModelException { if (!member.isStructureKnown()) { return RefactoringStatus.createErrorStatus( MessageFormat.format(Messages.CUContainsCompileErrors, getElementLabel(member, ALL_FULLY_QUALIFIED), getElementLabel(member.getCompilationUnit(), ALL_FULLY_QUALIFIED)), JavaStatusContext.create(member.getCompilationUnit())); } return new RefactoringStatus(); } private static RefactoringStatusEntry getLastRefactoringStatusEntry(RefactoringStatus status) { return status.getEntryAt(status.getEntries().length - 1); } private RefactoringStatus checkWritabilitiy(IMember member, PreconditionFailure failure) { if (member.isBinary() || member.isReadOnly()) { return createError(failure, member); } return new RefactoringStatus(); } private RefactoringStatus checkExistence(IMember member, PreconditionFailure failure) { if (member == null || !member.exists()) { return createError(failure, member); } return new RefactoringStatus(); } public Set<IMethod> getSourceMethods() { return this.sourceMethods; } public Set<IMethod> getUnmigratableMethods() { return this.unmigratableMethods; } private RefactoringStatus checkSourceMethodBodies(Optional<IProgressMonitor> pm) throws JavaModelException { try { RefactoringStatus status = new RefactoringStatus(); pm.ifPresent(m -> m.beginTask("Checking source method bodies ...", this.getSourceMethods().size())); Iterator<IMethod> it = this.getSourceMethods().iterator(); while (it.hasNext()) { IMethod sourceMethod = it.next(); MethodDeclaration declaration = getMethodDeclaration(sourceMethod, pm); if (declaration != null) { Block body = declaration.getBody(); if (body != null) { SourceMethodBodyAnalysisVisitor visitor = new SourceMethodBodyAnalysisVisitor(sourceMethod, pm); body.accept(visitor); if (visitor.doesMethodContainsSuperReference()) addErrorAndMark(status, PreconditionFailure.MethodContainsSuperReference, sourceMethod); if (visitor.doesMethodContainsCallToProtectedObjectMethod()) addErrorAndMark(status, PreconditionFailure.MethodContainsCallToProtectedObjectMethod, sourceMethod, visitor.getCalledProtectedObjectMethodSet().stream().findAny().orElseThrow( () -> new IllegalStateException("No associated object method"))); if (visitor.doesMethodContainsTypeIncompatibleThisReference()) { // FIXME: The error context should be the this // reference that caused the error. addErrorAndMark(status, PreconditionFailure.MethodContainsTypeIncompatibleThisReference, sourceMethod); } if (sourceMethod.getDeclaringType().isMember() && visitor.doesMethodContainQualifiedThisExpression()) { // FIXME: The error context should be the this // reference that caused the error. addErrorAndMark(status, PreconditionFailure.MethodContainsQualifiedThisExpression, sourceMethod); } } } pm.ifPresent(m -> m.worked(1)); } return status; } finally { pm.ifPresent(IProgressMonitor::done); } } private MethodDeclaration getMethodDeclaration(IMethod method, Optional<IProgressMonitor> pm) throws JavaModelException { ITypeRoot root = method.getCompilationUnit(); CompilationUnit unit = this.getCompilationUnit(root, new SubProgressMonitor(pm.orElseGet(NullProgressMonitor::new), IProgressMonitor.UNKNOWN)); MethodDeclaration declaration = ASTNodeSearchUtil.getMethodDeclarationNode(method, unit); return declaration; } private static void addWarning(RefactoringStatus status, IMethod sourceMethod, PreconditionFailure failure, IJavaElement... relatedElementCollection) { addEntry(status, sourceMethod, RefactoringStatus.WARNING, failure, relatedElementCollection); } private static RefactoringStatusEntry addError(RefactoringStatus status, IMethod sourceMethod, PreconditionFailure failure, IJavaElement... relatedElementCollection) { addEntry(status, sourceMethod, RefactoringStatus.ERROR, failure, relatedElementCollection); return getLastRefactoringStatusEntry(status); } private static void addEntry(RefactoringStatus status, IMethod sourceMethod, int severity, PreconditionFailure failure, IJavaElement... relatedElementCollection) { String message = formatMessage(failure.getMessage(), relatedElementCollection); // add the first element as the context if appropriate. if (relatedElementCollection.length > 0 && relatedElementCollection[0] instanceof IMember) { IMember member = (IMember) relatedElementCollection[0]; RefactoringStatusContext context = JavaStatusContext.create(member); status.addEntry(new RefactoringStatusEntry(severity, message, context, MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, failure.ordinal(), sourceMethod)); } else // otherwise, just add the message. status.addEntry(new RefactoringStatusEntry(severity, message, null, MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, failure.ordinal(), sourceMethod)); } private static String formatMessage(String message, IJavaElement... relatedElementCollection) { Object[] elementNames = Arrays.stream(relatedElementCollection).parallel().filter(Objects::nonNull) .map(re -> getElementLabel(re, ALL_FULLY_QUALIFIED)).toArray(); message = MessageFormat.format(message, elementNames); return message; } private static RefactoringStatusEntry addError(RefactoringStatus status, IMethod sourceMethod, PreconditionFailure failure, IMember member, IMember... more) { List<String> elementNames = new ArrayList<>(); elementNames.add(getElementLabel(member, ALL_FULLY_QUALIFIED)); Stream<String> stream = Arrays.asList(more).parallelStream().map(m -> getElementLabel(m, ALL_FULLY_QUALIFIED)); Stream<String> concat = Stream.concat(elementNames.stream(), stream); List<String> collect = concat.collect(Collectors.toList()); status.addEntry(RefactoringStatus.ERROR, MessageFormat.format(failure.getMessage(), collect.toArray()), JavaStatusContext.create(member), MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID, failure.ordinal(), sourceMethod); return getLastRefactoringStatusEntry(status); } private static RefactoringStatus createWarning(String message, IMember member) { return createRefactoringStatus(message, member, RefactoringStatus::createWarningStatus); } private RefactoringStatus createError(PreconditionFailure failure, IMember member) { return createRefactoringStatus(failure.getMessage(), member, RefactoringStatus::createErrorStatus); } private static RefactoringStatus createFatalError(String message, IMember member) { return createRefactoringStatus(message, member, RefactoringStatus::createFatalErrorStatus); } private static RefactoringStatus createRefactoringStatus(String message, IMember member, BiFunction<String, RefactoringStatusContext, RefactoringStatus> function) { String elementName = getElementLabel(member, ALL_FULLY_QUALIFIED); return function.apply(MessageFormat.format(message, elementName), JavaStatusContext.create(member)); } /** * Creates a working copy layer if necessary. * * @param monitor * the progress monitor to use * @return a status describing the outcome of the operation */ private RefactoringStatus createWorkingCopyLayer(IProgressMonitor monitor) { try { monitor.beginTask(Messages.CheckingPreconditions, 1); // TODO ICompilationUnit unit = // getDeclaringType().getCompilationUnit(); // if (fLayer) // unit = unit.findWorkingCopy(fOwner); // resetWorkingCopies(unit); return new RefactoringStatus(); } finally { monitor.done(); } } @Override public RefactoringStatus checkFinalConditions(final IProgressMonitor monitor, final CheckConditionsContext context) throws CoreException, OperationCanceledException { try { monitor.beginTask(Messages.CheckingPreconditions, 12); final RefactoringStatus status = new RefactoringStatus(); if (!this.getSourceMethods().isEmpty()) status.merge(createWorkingCopyLayer(new SubProgressMonitor(monitor, 4))); if (status.hasFatalError()) return status; if (monitor.isCanceled()) throw new OperationCanceledException(); status.merge(checkSourceMethods(Optional.of(new SubProgressMonitor(monitor, 1)))); if (status.hasFatalError()) return status; if (monitor.isCanceled()) throw new OperationCanceledException(); status.merge(checkSourceMethodBodies(Optional.of(new SubProgressMonitor(monitor, 1)))); if (status.hasFatalError()) return status; if (monitor.isCanceled()) throw new OperationCanceledException(); // TODO: Should this be a separate method? status.merge(checkDestinationInterfaces(Optional.of(new SubProgressMonitor(monitor, 1)))); if (status.hasFatalError()) return status; if (monitor.isCanceled()) throw new OperationCanceledException(); status.merge(checkTargetMethods(Optional.of(new SubProgressMonitor(monitor, 1)))); // check if there are any methods left to migrate. if (this.getUnmigratableMethods().containsAll(this.getSourceMethods())) // if not, we have a fatal error. status.addFatalError(Messages.NoMethodsHavePassedThePreconditions); // TODO: // Checks.addModifiedFilesToChecker(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()), // context); return status; } catch (Exception e) { JavaPlugin.log(e); throw e; } finally { monitor.done(); } } private RefactoringStatus checkTargetMethods(Optional<IProgressMonitor> monitor) throws JavaModelException { RefactoringStatus status = new RefactoringStatus(); // first, create a map of target methods to their set of migratable // source methods. Map<IMethod, Set<IMethod>> targetMethodToMigratableSourceMethodsMap = createTargetMethodToMigratableSourceMethodsMap( monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN))); monitor.ifPresent(m -> m.beginTask("Checking target methods ...", targetMethodToMigratableSourceMethodsMap.keySet().size())); // for each target method. for (IMethod targetMethod : targetMethodToMigratableSourceMethodsMap.keySet()) { Set<IMethod> migratableSourceMethods = targetMethodToMigratableSourceMethodsMap.get(targetMethod); // if the target method is associated with multiple source methods. if (migratableSourceMethods.size() > 1) { // we need to decide which of the source methods will be // migrated and which will not. We'll build equivalence sets to // see which of the source method bodies are the same. Then, // we'll pick the largest equivalence set to migrate. That will // reduce the greatest number of methods in the system. The // other sets will become unmigratable. Those methods will just // override the new default method. // (MakeSet). Set<Set<IMethod>> equivalenceSets = createEquivalenceSets(migratableSourceMethods); // merge the sets. mergeEquivalenceSets(equivalenceSets, monitor); // find the largest set size. equivalenceSets.stream().map(s -> s.size()).max(Integer::compareTo) // find the first set with this size. .flatMap(size -> equivalenceSets.stream().filter(s -> s.size() == size).findFirst()).ifPresent( // for all of the methods in the other sets ... fls -> equivalenceSets.stream().filter(s -> s != fls).flatMap(s -> s.stream()) // mark them as unmigratable. .forEach(m -> addErrorAndMark(status, PreconditionFailure.TargetMethodHasMultipleSourceMethods, m, targetMethod))); } monitor.ifPresent(m -> m.worked(1)); } monitor.ifPresent(IProgressMonitor::done); return status; } private void mergeEquivalenceSets(Set<Set<IMethod>> equivalenceSets, Optional<IProgressMonitor> monitor) throws JavaModelException { // A map of methods to their equivalence set. Map<IMethod, Set<IMethod>> methodToEquivalenceSetMap = new LinkedHashMap<>(); for (Set<IMethod> set : equivalenceSets) { for (IMethod method : set) { methodToEquivalenceSetMap.put(method, set); } } monitor.ifPresent( m -> m.beginTask("Merging method equivalence sets ...", methodToEquivalenceSetMap.keySet().size())); for (IMethod method : methodToEquivalenceSetMap.keySet()) { for (IMethod otherMethod : methodToEquivalenceSetMap.keySet()) { if (method != otherMethod) { Set<IMethod> methodSet = methodToEquivalenceSetMap.get(method); // Find(method) Set<IMethod> otherMethodSet = methodToEquivalenceSetMap.get(otherMethod); // Find(otherMethod) // if they are different sets and the elements are // equivalent. if (methodSet != otherMethodSet && isEquivalent(method, otherMethod, monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN)))) { // Union(Find(method), Find(otherMethod)) methodSet.addAll(otherMethodSet); equivalenceSets.remove(otherMethodSet); // update the map. for (IMethod methodInOtherMethodSet : otherMethodSet) { methodToEquivalenceSetMap.put(methodInOtherMethodSet, methodSet); } } } } monitor.ifPresent(m -> m.worked(1)); } monitor.ifPresent(IProgressMonitor::done); } private boolean isEquivalent(IMethod method, IMethod otherMethod, Optional<IProgressMonitor> monitor) throws JavaModelException { monitor.ifPresent(m -> m.beginTask("Checking method equivalence ...", 2)); MethodDeclaration methodDeclaration = this.getMethodDeclaration(method, monitor.map(m -> new SubProgressMonitor(m, 1))); MethodDeclaration otherMethodDeclaration = this.getMethodDeclaration(otherMethod, monitor.map(m -> new SubProgressMonitor(m, 1))); monitor.ifPresent(IProgressMonitor::done); Block methodDeclarationBody = methodDeclaration.getBody(); Block otherMethodDeclarationBody = otherMethodDeclaration.getBody(); boolean match = methodDeclarationBody.subtreeMatch(new ASTMatcher(), otherMethodDeclarationBody); return match; } private static Set<Set<IMethod>> createEquivalenceSets(Set<IMethod> migratableSourceMethods) { Set<Set<IMethod>> ret = new LinkedHashSet<>(); migratableSourceMethods.stream().forEach(m -> { Set<IMethod> set = new LinkedHashSet<>(); set.add(m); ret.add(set); }); return ret; } private Map<IMethod, Set<IMethod>> createTargetMethodToMigratableSourceMethodsMap( Optional<IProgressMonitor> monitor) throws JavaModelException { Map<IMethod, Set<IMethod>> ret = new LinkedHashMap<>(); Set<IMethod> migratableMethods = this.getMigratableMethods(); monitor.ifPresent(m -> m.beginTask("Finding migratable source methods for each target method ...", migratableMethods.size())); for (IMethod sourceMethod : migratableMethods) { IMethod targetMethod = getTargetMethod(sourceMethod, Optional.empty()); ret.compute(targetMethod, (k, v) -> { if (v == null) { Set<IMethod> sourceMethodSet = new LinkedHashSet<>(); sourceMethodSet.add(sourceMethod); return sourceMethodSet; } else { v.add(sourceMethod); return v; } }); monitor.ifPresent(m -> m.worked(1)); } monitor.ifPresent(IProgressMonitor::done); return ret; } private void clearCaches() { getTypeToSuperTypeHierarchyMap().clear(); getMethodToTargetMethodMap().clear(); getTypeToTypeHierarchyMap().clear(); getCompilationUnitToCompilationUnitRewriteMap().clear(); } public TimeCollector getExcludedTimeCollector() { return excludedTimeCollector; } private RefactoringStatus checkProjectCompliance(IMethod sourceMethod) throws JavaModelException { RefactoringStatus status = new RefactoringStatus(); IMethod targetMethod = getTargetMethod(sourceMethod, Optional.empty()); IJavaProject destinationProject = targetMethod.getJavaProject(); if (!JavaModelUtil.is18OrHigher(destinationProject)) addErrorAndMark(status, PreconditionFailure.DestinationProjectIncompatible, sourceMethod, targetMethod); return status; } @Override public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException { try { pm.beginTask(Messages.CreatingChange, 1); final TextEditBasedChangeManager manager = new TextEditBasedChangeManager(); Set<IMethod> migratableMethods = this.getMigratableMethods(); if (migratableMethods.isEmpty()) return new NullChange(Messages.NoMethodsToMigrate); // the set of target methods that we transformed to default methods. Set<IMethod> transformedTargetMethods = new HashSet<>(migratableMethods.size()); for (IMethod sourceMethod : migratableMethods) { // get the source method declaration. CompilationUnit sourceCompilationUnit = getCompilationUnit(sourceMethod.getTypeRoot(), pm); MethodDeclaration sourceMethodDeclaration = ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod, sourceCompilationUnit); logInfo("Source method declaration: " + sourceMethodDeclaration); CompilationUnitRewrite sourceRewrite = getCompilationUnitRewrite(sourceMethod.getCompilationUnit(), sourceCompilationUnit); // Find the target method. IMethod targetMethod = getTargetMethod(sourceMethod, Optional.of(new SubProgressMonitor(pm, IProgressMonitor.UNKNOWN))); // if we have not already transformed this method if (!transformedTargetMethods.contains(targetMethod)) { IType destinationInterface = targetMethod.getDeclaringType(); logInfo("Migrating method: " + getElementLabel(sourceMethod, ALL_FULLY_QUALIFIED) + " to interface: " + destinationInterface.getFullyQualifiedName()); CompilationUnit destinationCompilationUnit = this .getCompilationUnit(destinationInterface.getTypeRoot(), pm); CompilationUnitRewrite destinationCompilationUnitRewrite = getCompilationUnitRewrite( targetMethod.getCompilationUnit(), destinationCompilationUnit); ImportRewriteContext context = new ContextSensitiveImportRewriteContext(destinationCompilationUnit, destinationCompilationUnitRewrite.getImportRewrite()); MethodDeclaration targetMethodDeclaration = ASTNodeSearchUtil.getMethodDeclarationNode(targetMethod, destinationCompilationUnit); final TypeVariableMaplet[] mapping = TypeVariableUtil.subTypeToSuperType( sourceMethod.getDeclaringType(), targetMethod.getDeclaringType(), targetMethod.getDeclaringType()); // tack on the source method body to the target method. pm.beginTask("Copying source method body ...", IProgressMonitor.UNKNOWN); copyMethodBody(sourceRewrite, destinationCompilationUnitRewrite, sourceMethod, sourceMethodDeclaration, targetMethodDeclaration, mapping, new SubProgressMonitor(pm, IProgressMonitor.UNKNOWN)); // add any static imports needed to the target method's // compilation unit for static fields referenced in the // source method. addStaticImports(sourceMethodDeclaration, targetMethodDeclaration, destinationCompilationUnitRewrite, context); // alter the target parameter names to match that of the // source method if necessary #148. changeTargetMethodParametersToMatchSource(sourceMethodDeclaration, targetMethodDeclaration, destinationCompilationUnitRewrite.getASTRewrite()); // Change the target method to default. convertToDefault(targetMethodDeclaration, destinationCompilationUnitRewrite.getASTRewrite()); // Remove any abstract modifiers from the target method as // both abstract and default are not allowed. removeAbstractness(targetMethodDeclaration, destinationCompilationUnitRewrite.getASTRewrite()); // TODO: Do we need to worry about preserving ordering of // the // modifiers? // if the source method is strictfp. // FIXME: Actually, I think we need to check that, in the // case the target method isn't already strictfp, that the // other // methods in the hierarchy are. if ((Flags.isStrictfp(sourceMethod.getFlags()) || Flags.isStrictfp(sourceMethod.getDeclaringType().getFlags())) && !Flags.isStrictfp(targetMethod.getFlags())) // change the target method to strictfp. convertToStrictFP(targetMethodDeclaration, destinationCompilationUnitRewrite.getASTRewrite()); // deal with imports ImportRewriteUtil.addImports(destinationCompilationUnitRewrite, context, sourceMethodDeclaration, new HashMap<Name, String>(), new HashMap<Name, String>(), false); transformedTargetMethods.add(targetMethod); } // Remove the source method. removeMethod(sourceMethodDeclaration, sourceRewrite.getASTRewrite()); sourceRewrite.getImportRemover().registerRemovedNode(sourceMethodDeclaration); } // save the source changes. ICompilationUnit[] units = this.getCompilationUnitToCompilationUnitRewriteMap().keySet().stream() .filter(cu -> !manager.containsChangesIn(cu)).toArray(ICompilationUnit[]::new); for (ICompilationUnit cu : units) { CompilationUnit compilationUnit = getCompilationUnit(cu, pm); manageCompilationUnit(manager, getCompilationUnitRewrite(cu, compilationUnit), Optional.of(new SubProgressMonitor(pm, IProgressMonitor.UNKNOWN))); } final Map<String, String> arguments = new HashMap<>(); int flags = RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE; // TODO: Fill in description. MigrateSkeletalImplementationToInterfaceRefactoringDescriptor descriptor = new MigrateSkeletalImplementationToInterfaceRefactoringDescriptor( null, "TODO", null, arguments, flags); return new DynamicValidationRefactoringChange(descriptor, getProcessorName(), manager.getAllChanges()); } finally { pm.done(); this.clearCaches(); } } /** * Add any static imports needed to the target method's compilation unit for * static fields referenced in the source method. * * @param sourceMethodDeclaration * The method being migrated. * @param targetMethodDeclaration * The target for the migration. * @param destinationCompilationUnitRewrite * The rewrite associated with the target's compilation unit. * @param context * The context in which to add static imports if necessary. */ private void addStaticImports(MethodDeclaration sourceMethodDeclaration, MethodDeclaration targetMethodDeclaration, CompilationUnitRewrite destinationCompilationUnitRewrite, ImportRewriteContext context) { sourceMethodDeclaration.accept(new ASTVisitor() { @Override public boolean visit(SimpleName node) { // add any necessary static imports. if (node.getParent().getNodeType() != ASTNode.QUALIFIED_NAME) { IBinding binding = node.resolveBinding(); if (binding.getKind() == IBinding.VARIABLE) { IVariableBinding variableBinding = ((IVariableBinding) binding); if (variableBinding.isField()) { ITypeBinding declaringClass = variableBinding.getDeclaringClass(); processStaticImport(variableBinding, declaringClass, targetMethodDeclaration, destinationCompilationUnitRewrite, context); } } } return super.visit(node); } private void processStaticImport(IBinding binding, ITypeBinding declaringClass, MethodDeclaration targetMethodDeclaration, CompilationUnitRewrite destinationCompilationUnitRewrite, ImportRewriteContext context) { if (Modifier.isStatic(binding.getModifiers()) && !declaringClass.isEqualTo(targetMethodDeclaration.resolveBinding().getDeclaringClass())) destinationCompilationUnitRewrite.getImportRewrite().addStaticImport(binding, context); } @Override public boolean visit(MethodInvocation node) { if (node.getExpression() == null) { // it's an // unqualified // method call. IMethodBinding methodBinding = node.resolveMethodBinding(); ITypeBinding declaringClass = methodBinding.getDeclaringClass(); processStaticImport(methodBinding, declaringClass, targetMethodDeclaration, destinationCompilationUnitRewrite, context); } return super.visit(node); } }); } private CompilationUnit getCompilationUnit(ITypeRoot root, IProgressMonitor pm) { CompilationUnit compilationUnit = this.typeRootToCompilationUnitMap.get(root); if (compilationUnit == null) { this.getExcludedTimeCollector().start(); compilationUnit = RefactoringASTParser.parseWithASTProvider(root, true, pm); this.getExcludedTimeCollector().stop(); this.typeRootToCompilationUnitMap.put(root, compilationUnit); } return compilationUnit; } private CompilationUnitRewrite getCompilationUnitRewrite(ICompilationUnit unit, CompilationUnit root) { CompilationUnitRewrite rewrite = this.getCompilationUnitToCompilationUnitRewriteMap().get(unit); if (rewrite == null) { rewrite = new CompilationUnitRewrite(unit, root); this.getCompilationUnitToCompilationUnitRewriteMap().put(unit, rewrite); } return rewrite; } private void manageCompilationUnit(final TextEditBasedChangeManager manager, CompilationUnitRewrite rewrite, Optional<IProgressMonitor> monitor) throws CoreException { monitor.ifPresent(m -> m.beginTask("Creating change ...", IProgressMonitor.UNKNOWN)); CompilationUnitChange change = rewrite.createChange(false, monitor.orElseGet(NullProgressMonitor::new)); change.setTextType("java"); manager.manage(rewrite.getCu(), change); } private void changeTargetMethodParametersToMatchSource(MethodDeclaration sourceMethodDeclaration, MethodDeclaration targetMethodDeclaration, ASTRewrite destinationRewrite) { Assert.isLegal(sourceMethodDeclaration.parameters().size() == targetMethodDeclaration.parameters().size()); // iterate over the source method parameters. for (int i = 0; i < sourceMethodDeclaration.parameters().size(); i++) { // get the parameter for the source method. SingleVariableDeclaration sourceParameter = (SingleVariableDeclaration) sourceMethodDeclaration.parameters() .get(i); // get the corresponding target method parameter. SingleVariableDeclaration targetParameter = (SingleVariableDeclaration) targetMethodDeclaration.parameters() .get(i); // if the names don't match. if (!sourceParameter.getName().equals(targetParameter.getName())) { // change the target method parameter to match it since that is // what the body will use. ASTNode sourceParameterNameCopy = ASTNode.copySubtree(destinationRewrite.getAST(), sourceParameter.getName()); destinationRewrite.replace(targetParameter.getName(), sourceParameterNameCopy, null); } } } private void copyMethodBody(final CompilationUnitRewrite sourceRewrite, final CompilationUnitRewrite targetRewrite, final IMethod method, final MethodDeclaration oldMethod, final MethodDeclaration newMethod, final TypeVariableMaplet[] mapping, final IProgressMonitor monitor) throws JavaModelException { final Block body = oldMethod.getBody(); if (body == null) { newMethod.setBody(null); return; } try { final IDocument document = new Document(method.getCompilationUnit().getBuffer().getContents()); final ASTRewrite rewrite = ASTRewrite.create(body.getAST()); final ITrackedNodePosition position = rewrite.track(body); body.accept(new TypeVariableMapper(rewrite, mapping)); rewrite.rewriteAST(document, method.getJavaProject().getOptions(true)).apply(document, TextEdit.NONE); String content = document.get(position.getStartPosition(), position.getLength()); final String[] lines = Strings.convertIntoLines(content); Strings.trimIndentation(lines, method.getJavaProject(), false); content = Strings.concatenate(lines, StubUtility.getLineDelimiterUsed(method)); ASTNode stringPlaceholder = targetRewrite.getASTRewrite().createStringPlaceholder(content, ASTNode.BLOCK); targetRewrite.getASTRewrite().set(newMethod, MethodDeclaration.BODY_PROPERTY, stringPlaceholder, null); } catch (MalformedTreeException exception) { JavaPlugin.log(exception); } catch (BadLocationException exception) { JavaPlugin.log(exception); } } private void removeMethod(MethodDeclaration methodDeclaration, ASTRewrite rewrite) { // TODO: Do we need an edit group?? rewrite.remove(methodDeclaration, null); } private void convertToDefault(MethodDeclaration methodDeclaration, ASTRewrite rewrite) { addModifierKeyword(methodDeclaration, ModifierKeyword.DEFAULT_KEYWORD, rewrite); } private void removeAbstractness(MethodDeclaration methodDeclaration, ASTRewrite rewrite) { removeModifierKeyword(methodDeclaration, ModifierKeyword.ABSTRACT_KEYWORD, rewrite); } private void convertToStrictFP(MethodDeclaration methodDeclaration, ASTRewrite rewrite) { addModifierKeyword(methodDeclaration, ModifierKeyword.STRICTFP_KEYWORD, rewrite); } private void addModifierKeyword(MethodDeclaration methodDeclaration, ModifierKeyword modifierKeyword, ASTRewrite rewrite) { Modifier modifier = rewrite.getAST().newModifier(modifierKeyword); ListRewrite listRewrite = rewrite.getListRewrite(methodDeclaration, methodDeclaration.getModifiersProperty()); listRewrite.insertLast(modifier, null); } @SuppressWarnings("unchecked") private void removeModifierKeyword(MethodDeclaration methodDeclaration, ModifierKeyword modifierKeyword, ASTRewrite rewrite) { ListRewrite listRewrite = rewrite.getListRewrite(methodDeclaration, methodDeclaration.getModifiersProperty()); listRewrite.getOriginalList().stream().filter(o -> o instanceof Modifier).map(Modifier.class::cast) .filter(m -> ((Modifier) m).getKeyword().equals(modifierKeyword)).findAny() .ifPresent(m -> listRewrite.remove((ASTNode) m, null)); } private static Map<IMethod, IMethod> getMethodToTargetMethodMap() { return methodToTargetMethodMap; } /** * Finds the target (interface) method declaration in the destination * interface for the given source method. * * TODO: Something is very wrong here. There can be multiple targets for a * given source method because it can be declared in multiple interfaces up * and down the hierarchy. What this method right now is really doing is * finding the target method for the given source method in the destination * interface. As such, we should be sure what the destination is prior to * this call. * * @param sourceMethod * The method that will be migrated to the target interface. * @return The target method that will be manipulated or null if not found. * @throws JavaModelException */ public static IMethod getTargetMethod(IMethod sourceMethod, Optional<IProgressMonitor> monitor) throws JavaModelException { IMethod targetMethod = getMethodToTargetMethodMap().get(sourceMethod); if (targetMethod == null) { IType destinationInterface = getDestinationInterface(sourceMethod, monitor); if (getMethodTargetInterfaceTargetMethodTable().contains(sourceMethod, destinationInterface)) targetMethod = getMethodTargetInterfaceTargetMethodTable().get(sourceMethod, destinationInterface); else if (destinationInterface != null) { targetMethod = findTargetMethod(sourceMethod, destinationInterface); if (targetMethod == null) logWarning("Could not retrieve target method for source method: " + sourceMethod + " and destination interface: " + destinationInterface); else getMethodTargetInterfaceTargetMethodTable().put(sourceMethod, destinationInterface, targetMethod); } getMethodToTargetMethodMap().put(sourceMethod, targetMethod); } return targetMethod; } private static IType getDestinationInterface(IMethod sourceMethod, Optional<IProgressMonitor> monitor) throws JavaModelException { try { IType[] candidateDestinationInterfaces = getCandidateDestinationInterfaces(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1))); // FIXME: Really just returning the first match here return Arrays.stream(candidateDestinationInterfaces).findFirst().orElse(null); } finally { monitor.ifPresent(IProgressMonitor::done); } } /** * Finds the target (interface) method declaration in the given type for the * given source method. * * @param sourceMethod * The method that will be migrated to the target interface. * @param targetInterface * The interface for which sourceMethod will be migrated. * @return The target method that will be manipulated or null if not found. * @throws JavaModelException */ private static IMethod findTargetMethod(IMethod sourceMethod, IType targetInterface) throws JavaModelException { if (targetInterface == null) return null; // not found. Assert.isNotNull(sourceMethod); Assert.isLegal(sourceMethod.exists(), "Source method does not exist."); Assert.isLegal(targetInterface.exists(), "Target interface does not exist."); Assert.isLegal(targetInterface.isInterface(), "Target interface must be an interface."); IMethod ret = null; for (IMethod method : targetInterface.getMethods()) { if (method.exists() && method.getElementName().equals(sourceMethod.getElementName())) { ILocalVariable[] parameters = method.getParameters(); ILocalVariable[] sourceParameters = sourceMethod.getParameters(); if (parameterListMatches(parameters, method, sourceParameters, sourceMethod)) { if (ret != null) throw new IllegalStateException("Found multiple matches of method: " + sourceMethod.getElementName() + " in interface: " + targetInterface.getElementName()); else ret = method; } } } return ret; } private static boolean parameterListMatches(ILocalVariable[] parameters, IMethod method, ILocalVariable[] sourceParameters, IMethod sourceMethod) throws JavaModelException { if (parameters.length == sourceParameters.length) { for (int i = 0; i < parameters.length; i++) { String paramString = Util.getQualifiedNameFromTypeSignature(parameters[i].getTypeSignature(), method.getDeclaringType()); String sourceParamString = Util.getQualifiedNameFromTypeSignature( sourceParameters[i].getTypeSignature(), sourceMethod.getDeclaringType()); if (!paramString.equals(sourceParamString)) return false; } return true; } else return false; } private static void log(int severity, String message) { if (severity >= getLoggingLevel()) { String name = FrameworkUtil.getBundle(MigrateSkeletalImplementationToInterfaceRefactoringProcessor.class) .getSymbolicName(); IStatus status = new Status(severity, name, message); JavaPlugin.log(status); } } private void logInfo(String message) { log(IStatus.INFO, message); } private static void logWarning(String message) { log(IStatus.WARNING, message); } @Override public String getIdentifier() { return MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID; } @Override public String getProcessorName() { return Messages.Name; } @Override public boolean isApplicable() throws CoreException { return RefactoringAvailabilityTester.isInterfaceMigrationAvailable(getSourceMethods().parallelStream() .filter(m -> !this.getUnmigratableMethods().contains(m)).toArray(IMethod[]::new), Optional.empty()); } /** * Returns true if the given type is a pure interface, i.e., it is an * interface but not an annotation. * * @param type * The type to check. * @return True if the given type is a pure interface and false otherwise. * @throws JavaModelException */ private static boolean isPureInterface(IType type) throws JavaModelException { return type != null && type.isInterface() && !type.isAnnotation(); } private Map<IType, ITypeHierarchy> typeToTypeHierarchyMap = new HashMap<>(); private Map<IType, ITypeHierarchy> getTypeToTypeHierarchyMap() { return typeToTypeHierarchyMap; } private ITypeHierarchy getTypeHierarchy(IType type, Optional<IProgressMonitor> monitor) throws JavaModelException { try { ITypeHierarchy ret = this.getTypeToTypeHierarchyMap().get(type); if (ret == null) { ret = type.newTypeHierarchy(monitor.orElseGet(NullProgressMonitor::new)); this.getTypeToTypeHierarchyMap().put(type, ret); } return ret; } finally { monitor.ifPresent(IProgressMonitor::done); } } @Override public RefactoringParticipant[] loadParticipants(RefactoringStatus status, SharableParticipants sharedParticipants) throws CoreException { return new RefactoringParticipant[0]; } private static Table<IMethod, IType, IMethod> getMethodTargetInterfaceTargetMethodTable() { return methodTargetInterfaceTargetMethodTable; } private SearchEngine getSearchEngine() { return searchEngine; } /** * Minimum logging level. One of the constants in * org.eclipse.core.runtime.IStatus. * * @param level * The minimum logging level to set. * @see org.eclipse.core.runtime.IStatus. */ public static void setLoggingLevel(int level) { loggingLevel = level; } protected static int getLoggingLevel() { return loggingLevel; } protected Map<ICompilationUnit, CompilationUnitRewrite> getCompilationUnitToCompilationUnitRewriteMap() { return this.compilationUnitToCompilationUnitRewriteMap; } }
package BluebellAdventures.CreateScenes; import java.io.IOException; import java.awt.Color; import java.awt.event.MouseEvent; import java.awt.Font; import java.awt.Graphics2D; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import BluebellAdventures.Characters.Character; import BluebellAdventures.Actions.ChangeScene; import Megumin.Actions.Action; import Megumin.Actions.Interact; import Megumin.Actions.MouseCrash; import Megumin.Database.Database; import Megumin.Nodes.Layer; import Megumin.Nodes.Scene; import Megumin.Nodes.Sprite; import Megumin.Point; public class CreateGameOverScene { public static Scene createGameOverScene(String backgroundImage, Sprite sprite, boolean victory) throws IOException { Interact interact = Interact.getInstance(); Character player = (Character)sprite; //init sprite Sprite background = new Sprite(backgroundImage); Sprite printStats = new Sprite() { @Override public void render(Graphics2D g) { g.setFont(new Font("TimesRoman", Font.BOLD, 35)); g.setColor(Color.white); g.drawString("Score: " + player.getSnackScore(), 560, 430); } }; // [1] Submit - Highscore Sprite submitHighScore = null; if (victory) { submitHighScore = new Sprite("resource/image/tag_highscore.png", new Point(600, 480)); Action saveHighScore = new MouseCrash(new Action() { @Override public void update(Sprite sprite) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String currentTime = sdf.format(new java.util.Date()); try { Database.getInstance().update("INSERT INTO Records (Score, Date_Time) VALUE('" + player.getSnackScore() + "', '" + currentTime + "')"); new ChangeScene(CreateMenuScene.createMenuScene(), "menu").update(null); } catch (SQLException e) { System.out.println(e); System.exit(1); } catch (IOException e){ System.exit(1); } } }); interact.addEvent(MouseEvent.BUTTON1, Interact.ON_MOUSE_CLICK, submitHighScore, saveHighScore, "game over"); } // [2] Back to Main Menu Sprite mainMenu = new Sprite("resource/image/tag_winback.png", new Point(650, 610)); Scene menu = CreateMenuScene.createMenuScene(); Action backToMenu = new MouseCrash(new ChangeScene(menu, "menu")); interact.addEvent(MouseEvent.BUTTON1, Interact.ON_MOUSE_CLICK, mainMenu, backToMenu, "game over"); //init layer Layer backgroundLayer = new Layer(); backgroundLayer.addSprite(background); Layer tabLayer = new Layer(); tabLayer.addSprite(printStats); if (victory) { tabLayer.addSprite(submitHighScore); } tabLayer.addSprite(mainMenu); //init scene Scene gameover = new Scene(); gameover.setName("game over"); gameover.addLayer(backgroundLayer); gameover.addLayer(tabLayer); return gameover; } }
package org.skeleton.generator.bc.command.file.impl.sql.definition.oracle; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.skeleton.generator.bc.command.file.impl.sql.SqlFileWriteCommand; import org.skeleton.generator.model.metadata.DataType; import org.skeleton.generator.model.om.Column; import org.skeleton.generator.model.om.QualifiedColumn; import org.skeleton.generator.model.om.Table; public class OracleTableDefinitionFileWriteCommand extends SqlFileWriteCommand { private Table table; private String sequenceName; private Map<String, String> fieldMap; /* * constructor */ public OracleTableDefinitionFileWriteCommand(Table table) { super(table.myPackage.model.project.sourceFolder + "\\SQL\\" + table.myPackage.name.toUpperCase(), table.originalName); this.table = table; this.sequenceName = table.name + "_id_seq"; fieldMap = new HashMap<>(); for (int i = 0; i < table.getInsertColumnList().size(); i++) { fieldMap.put(table.getInsertColumnList().get(i).name, "ARG" + i); } for (int i = 0; i < table.columns.size(); i++) { if (table.columns.get(i).referenceTable != null) { fieldMap.put(table.columns.get(i).name, "ID_ARG" + i); } } } @Override public void writeContent() throws IOException { createGet(); createTable(); if (table.myPackage.model.project.audited) { createAuditTable(); } createFind(); createInsert(); createUpdate(); writeNotOverridableContent(); skipLine(); } private void createTable() { writeLine("-- suppression de la table --"); writeLine("BEGIN"); writeLine("EXECUTE IMMEDIATE 'DROP TABLE " + table.name + "';"); writeLine("EXCEPTION"); writeLine("WHEN OTHERS THEN NULL;"); writeLine("END;"); writeLine("/"); skipLine(); writeLine("-- suppression de la sequence --"); writeLine("BEGIN"); writeLine("EXECUTE IMMEDIATE 'DROP SEQUENCE " + sequenceName + "';"); writeLine("EXCEPTION"); writeLine("WHEN OTHERS THEN NULL;"); writeLine("END;"); writeLine("/"); skipLine(); writeLine("-- table --"); writeLine("CREATE TABLE " + table.name); writeLine("("); write(table.columns.get(0).name + " " + DataType.getOracleType(table.columns.get(0).dataType)); for (int i = 1; i < this.table.columns.size(); i++) { writeLine(","); write(this.table.columns.get(i).name + " " + DataType.getOracleType(table.columns.get(i).dataType)); if (this.table.columns.get(i).nullable) { write(" NULL"); } else { write(" NOT NULL"); } if (this.table.columns.get(i).unique) { if (!(i == 1 && table.cardinality == 1)) { write(" UNIQUE"); } } } writeLine(","); write("CONSTRAINT UC_" + table.name + " UNIQUE (" + this.table.columns.get(1).name); for (int i = 2; i <= this.table.cardinality; i++) { write("," + this.table.columns.get(i).name); } writeLine(")"); write("USING INDEX (CREATE INDEX UC_" + table.name + " ON " + table.name + "(" + this.table.columns.get(1).name); for (int i = 2; i <= this.table.cardinality; i++) { write("," + this.table.columns.get(i).name); } writeLine(") TABLESPACE " + table.myPackage.model.project.databaseName + "_IND)"); writeLine(", CONSTRAINT PK_" + table.name + " PRIMARY KEY (" + this.table.columns.get(0).name + ")"); writeLine("USING INDEX (CREATE INDEX PK_" + table.name + " ON " + table.name + "(" + this.table.columns.get(0).name + ") TABLESPACE " + table.myPackage.model.project.databaseName + "_IND)"); for (int i = 1; i < this.table.columns.size(); i++) { if (this.table.columns.get(i).referenceTable != null) { write(", CONSTRAINT FK_" + table.name + "_" + i + " FOREIGN KEY (" + this.table.columns.get(i).name + ") REFERENCES " + table.columns.get(i).referenceTable.name); if (this.table.columns.get(i).deleteCascade) { write(" ON DELETE CASCADE"); } skipLine(); } } writeLine(") TABLESPACE " + table.myPackage.model.project.databaseName + "_TBL"); writeLine("/"); for (int i = 1; i < this.table.columns.size(); i++) { if (this.table.columns.get(i).referenceTable != null) { writeLine("CREATE INDEX FK_" + table.name + "_" + i + " ON " + this.table.name + "(" + this.table.columns.get(i).name + ") TABLESPACE " + table.myPackage.model.project.databaseName + "_IND;/"); } } skipLine(); writeLine("-- sequence --"); writeLine("CREATE SEQUENCE " + sequenceName + " MINVALUE 0 NOMAXVALUE START WITH 0 INCREMENT BY 1 NOCYCLE;"); writeLine("/"); skipLine(); } /* * create audit table */ private void createAuditTable() { writeLine("-- suppression de la table d'audit --"); writeLine("BEGIN"); writeLine("EXECUTE IMMEDIATE 'DROP TABLE " + table.name + "_AUD';"); writeLine("EXCEPTION"); writeLine("WHEN OTHERS THEN NULL;"); writeLine("END;"); writeLine("/"); skipLine(); writeLine("-- table d'audit des elements --"); writeLine("CREATE TABLE " + table.name + "_AUD"); writeLine("("); writeLine(table.columns.get(0).name + " int NOT NULL,"); writeLine("REV int NOT NULL,"); writeLine("REVTYPE smallint NOT NULL,"); for (int i = 1;i<this.table.columns.size();i++) { writeLine(this.table.columns.get(i).name + " " + DataType.getOracleType(table.columns.get(i).dataType) + " NULL,"); } writeLine("CONSTRAINT PK_" + table.name + "_AUD PRIMARY KEY (ID, REV),"); writeLine("CONSTRAINT FK_" + table.name + "_AUD FOREIGN KEY (REV)"); writeLine("REFERENCES AUDITENTITY (ID)"); writeLine(") TABLESPACE " + table.myPackage.model.project.databaseName + "_AUD"); writeLine("/"); skipLine(); writeLine("CREATE INDEX FK_" + table.name + "_AUD ON " + this.table.name + "_AUD(REV);/"); } /* * create get stored procedure */ private void createGet() { writeLine("-- requete permettant de recupperer les elements par business key --"); writeLine("/*SELECT"); List<String> fields = getSelectedFields(table.getQualifiedColumns()); List<String> jointures = getJointures(table.getQualifiedColumns()); boolean start = true; for (String field:fields) { if (start) { start = false; } else { writeLine(","); } write(field); } skipLine(); writeLine("FROM " + table.name); for (String jointure:jointures) { writeLine(jointure); } writeLine("*/"); } private List<String> getSelectedFields(List<QualifiedColumn> qualifiedColumns) { List<String> selectedFields = new ArrayList<String>(); for (QualifiedColumn qualifiedColumn:qualifiedColumns) { if (qualifiedColumn.children != null) { selectedFields.addAll(getSelectedFields(qualifiedColumn.children)); } else { selectedFields.add(qualifiedColumn.tableAlias + "." + qualifiedColumn.columnName); } } return selectedFields; } private List<String> getJointures(List<QualifiedColumn> qualifiedColumns) { List<String> jointures = new ArrayList<String>(); for (QualifiedColumn qualifiedColumn:qualifiedColumns) { if (qualifiedColumn.children != null) { jointures.add("LEFT OUTER JOIN " + qualifiedColumn.children.get(0).tableName + " " + qualifiedColumn.children.get(0).tableAlias + " ON " + qualifiedColumn.tableAlias + "." + qualifiedColumn.columnName + " = " + qualifiedColumn.children.get(0).tableAlias + ".ID"); jointures.addAll(getJointures(qualifiedColumn.children)); } } return jointures; } /* * create find stored procedure */ private void createFind() { List<Column> findColumnList = this.table.getFindColumnList(); List<Column> tempColumnList; writeLine("-- procedure permettant de trouver un element a partir de codes --"); writeLine("CREATE OR REPLACE PROCEDURE find_" + table.name.toLowerCase()); writeLine("("); for (int i = 0; i < findColumnList.size(); i++) { writeLine("v" + fieldMap.get(findColumnList.get(i).name) + " IN " + DataType.getPlOracleType(findColumnList.get(i).dataType) + ","); } writeLine("vID OUT NUMBER"); writeLine(") AS"); for (int i = 1; i <= this.table.cardinality; i++) { if (this.table.columns.get(i).referenceTable != null) { writeLine("v" + fieldMap.get(this.table.columns.get(i).name) + " NUMBER;"); } } writeLine("BEGIN"); writeLine("IF v" + fieldMap.get(findColumnList.get(0).name) + " IS NULL"); for (int i = 1; i < findColumnList.size(); i++) { writeLine("AND v" + fieldMap.get(findColumnList.get(i).name) + " IS NULL"); } writeLine("THEN"); writeLine("vID := NULL;"); writeLine("ELSE"); for (int i = 1; i <= this.table.cardinality; i++) { if (this.table.columns.get(i).referenceTable != null) { write("find_" + this.table.columns.get(i).referenceTable.name.toLowerCase() + " ("); tempColumnList = this.table.columns.get(i).referenceTable.getFindColumnList(); for (int j = 0; j < tempColumnList.size(); j++) { write("v" + fieldMap.get(this.table.columns.get(i).name.replace("_ID", "_") + tempColumnList.get(j).name) + ","); } writeLine("v" + fieldMap.get(this.table.columns.get(i).name) + ");"); } } writeLine("SELECT " + table.name + ".ID"); writeLine("INTO vID"); writeLine("FROM " + table.name); writeLine("WHERE " + table.name + "." + this.table.columns.get(1).name + " = v" + fieldMap.get(this.table.columns.get(1).name)); for (int i = 2; i <= this.table.cardinality; i++) { writeLine("AND " + table.name + "." + this.table.columns.get(i).name + " = v" + fieldMap.get(this.table.columns.get(i).name)); } writeLine(";"); writeLine("IF vID IS NULL"); writeLine("THEN"); writeLine("vID := -1;"); writeLine("END IF;"); writeLine("END IF;"); writeLine("END;"); writeLine("/"); skipLine(); } /* create insert stored procedures */ private void createInsert() { List<Column> insertColumnList = this.table.getInsertColumnList(); List<Column> tempColumnList; writeLine("-- procedure permettant d'inserer un nouvel element --"); writeLine("CREATE OR REPLACE PROCEDURE ins_" + table.name.toLowerCase()); writeLine("("); write("v" + table.columns.get(1).name + " IN " + DataType.getPlOracleType(table.columns.get(1).dataType)); for (int i = 2; i < table.columns.size(); i++) { writeLine(","); write("v" + table.columns.get(i).name + " IN " + DataType.getPlOracleType(table.columns.get(i).dataType)); } skipLine(); writeLine(") AS"); writeLine("vREV NUMBER;"); writeLine("vID NUMBER;"); writeLine("BEGIN"); writeLine("vID := " + sequenceName + ".NEXTVAL;"); write("INSERT INTO " + table.name + " (ID, " + this.table.columns.get(1).name); for (int i = 2; i < this.table.columns.size(); i++) { write(", " + this.table.columns.get(i).name); } write(") VALUES (vID, v" + this.table.columns.get(1).name); for (int i = 2; i < this.table.columns.size(); i++) { write(", v" + this.table.columns.get(i).name); } writeLine(");"); if (table.myPackage.model.project.audited) { writeLine("vREV := hibernate_sequence.NEXTVAL;"); writeLine("INSERT INTO AUDITENTITY (ID, TIMESTAMP, LOGIN) VALUES (vREV, current_millis(), 'sys');"); write("INSERT INTO " + table.name + "_AUD (ID, REV, REVTYPE, " + this.table.columns.get(1).name); for (int i = 2; i < this.table.columns.size(); i++) { write(", " + this.table.columns.get(i).name); } write(") VALUES (vID, vREV, 0, v" + this.table.columns.get(1).name); for (int i = 2; i < this.table.columns.size(); i++) { write(", v" + this.table.columns.get(i).name); } writeLine(");"); } writeLine("END;"); writeLine("/"); skipLine(); writeLine("-- procedure permettant d'inserer un nouvel element a l'aide des codes --"); writeLine("CREATE OR REPLACE PROCEDURE ins_" + table.name.toLowerCase() + "_bc"); writeLine("("); write("v" + fieldMap.get(insertColumnList.get(0).name) + " " + DataType.getPlOracleType(insertColumnList.get(0).dataType)); for (int i = 1; i < insertColumnList.size(); i++) { writeLine(","); write("v" + fieldMap.get(insertColumnList.get(i).name) + " " + DataType.getPlOracleType(insertColumnList.get(i).dataType)); } skipLine(); writeLine(") AS"); for (int i = 1; i < this.table.columns.size(); i++) { if (this.table.columns.get(i).referenceTable != null) { writeLine("v" + fieldMap.get(this.table.columns.get(i).name) + " NUMBER;"); } } writeLine("BEGIN"); for (int i = 1; i < this.table.columns.size(); i++) { if (this.table.columns.get(i).referenceTable != null) { write("find_" + this.table.columns.get(i).referenceTable.name.toLowerCase() + " ("); tempColumnList = this.table.columns.get(i).referenceTable.getFindColumnList(); for (int j = 0; j < tempColumnList.size(); j++) { write("v" + fieldMap.get(this.table.columns.get(i).name.replace("_ID", "_") + tempColumnList.get(j).name) + ","); } writeLine("v" + fieldMap.get(this.table.columns.get(i).name) + ");"); } } write("ins_" + table.name.toLowerCase() + " (v" + fieldMap.get(this.table.columns.get(1).name)); for (int i = 2; i < this.table.columns.size(); i++) { write(", v" + fieldMap.get(this.table.columns.get(i).name)); } writeLine(");"); writeLine("END;"); writeLine("/"); skipLine(); } /* create update stored procedures */ private void createUpdate() { List<Column> insertColumnList = this.table.getInsertColumnList(); List<Column> tempColumnList; writeLine("-- procedure permettant de mettre a jour un element --"); writeLine("CREATE OR REPLACE PROCEDURE upd_" + table.name.toLowerCase()); writeLine("("); write("v" + table.columns.get(0).name + " IN " + DataType.getPlOracleType(table.columns.get(0).dataType)); for (int i = 1; i < table.columns.size(); i++) { writeLine(","); write("v" + table.columns.get(i).name + " IN " + DataType.getPlOracleType(table.columns.get(i).dataType)); } skipLine(); writeLine(") AS"); writeLine("vREV NUMBER;"); writeLine("BEGIN"); writeLine("UPDATE " + table.name + " set " + this.table.columns.get(1).name + " = v" + this.table.columns.get(1).name); for (int i = 2; i < this.table.columns.size(); i++) { writeLine(", " + this.table.columns.get(i).name + " = v" + this.table.columns.get(i).name); } writeLine("where ID = vID;"); if (table.myPackage.model.project.audited) { writeLine("vREV := hibernate_sequence.NEXTVAL;"); writeLine("INSERT INTO AUDITENTITY (ID, TIMESTAMP, LOGIN) VALUES (vREV, current_millis(), 'sys');"); write("INSERT INTO " + table.name + "_AUD (ID, REV, REVTYPE, " + this.table.columns.get(1).name); for (int i = 2; i < this.table.columns.size(); i++) { write(", " + this.table.columns.get(i).name); } write(") VALUES (vID, vREV, 1, v" + this.table.columns.get(1).name); for (int i = 2; i < this.table.columns.size(); i++) { write(", v" + this.table.columns.get(i).name); } writeLine(");"); } writeLine("END;"); writeLine("/"); skipLine(); writeLine("-- procedure permettant de mettre a jour element a l'aide des codes --"); writeLine("CREATE OR REPLACE PROCEDURE upd_" + table.name.toLowerCase() + "_bc"); writeLine("("); write("v" + fieldMap.get(insertColumnList.get(0).name) + " " + DataType.getPlOracleType(insertColumnList.get(0).dataType)); for (int i = 1; i < insertColumnList.size(); i++) { writeLine(","); write("v" + fieldMap.get(insertColumnList.get(i).name) + " " + DataType.getPlOracleType(insertColumnList.get(i).dataType)); } skipLine(); writeLine(") AS"); writeLine("vID NUMBER;"); for (int i = 1; i < this.table.columns.size(); i++) { if (this.table.columns.get(i).referenceTable != null) { writeLine("v" + fieldMap.get(this.table.columns.get(i).name) + " NUMBER;"); } } writeLine("BEGIN"); write("find_" + this.table.name.toLowerCase() + " ("); tempColumnList = this.table.getFindColumnList(); for (int j = 0; j < tempColumnList.size(); j++) { write("v" + fieldMap.get(tempColumnList.get(j).name) + ","); } writeLine("vID);"); for (int i = 1; i < this.table.columns.size(); i++) { if (this.table.columns.get(i).referenceTable != null) { write("find_" + this.table.columns.get(i).referenceTable.name.toLowerCase() + " ("); tempColumnList = this.table.columns.get(i).referenceTable.getFindColumnList(); for (int j = 0; j < tempColumnList.size(); j++) { write("v" + fieldMap.get(this.table.columns.get(i).name.replace("_ID", "_") + tempColumnList.get(j).name) + ","); } writeLine("v" + fieldMap.get(this.table.columns.get(i).name) + ");"); } } write("upd_" + table.name.toLowerCase() + " (vID"); for (int i = 1; i < this.table.columns.size(); i++) { write(", v" + fieldMap.get(this.table.columns.get(i).name)); } writeLine(");"); writeLine("END;"); writeLine("/"); skipLine(); } }
package com.intuit.karate.core; import com.intuit.karate.StringUtils; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.tree.ParseTreeWalker; import org.antlr.v4.runtime.tree.TerminalNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * * @author pthomas3 */ public class FeatureParser extends KarateParserBaseListener { private static final Logger logger = LoggerFactory.getLogger(FeatureParser.class); private final ParserErrorListener errorListener = new ParserErrorListener(); private final Feature feature; private final CommonTokenStream tokenStream; private FeatureParser(Feature feature, InputStream is) { this.feature = feature; CharStream stream; try { stream = CharStreams.fromStream(is, StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } KarateLexer lexer = new KarateLexer(stream); tokenStream = new CommonTokenStream(lexer); KarateParser parser = new KarateParser(tokenStream); parser.addErrorListener(errorListener); RuleContext tree = parser.feature(); ParseTreeWalker walker = new ParseTreeWalker(); walker.walk(this, tree); } protected static void parse(Feature feature) { FeatureParser fp = new FeatureParser(feature, feature.getResource().getStream()); if (fp.errorListener.isFail()) { String errorMessage = fp.errorListener.getMessage(); logger.error("not a valid feature file: {} - {}", feature.getResource().getRelativePath(), errorMessage); throw new RuntimeException(errorMessage); } } private static int getActualLine(TerminalNode node) { int count = 0; for (char c : node.getText().toCharArray()) { if (c == '\n') { count++; } else if (!Character.isWhitespace(c)) { break; } } return node.getSymbol().getLine() + count; } private static List<Tag> toTags(int line, List<TerminalNode> nodes) { List<Tag> tags = new ArrayList(); for (TerminalNode node : nodes) { String text = node.getText(); if (line == -1) { line = getActualLine(node); } String[] tokens = text.trim().split("\\s+"); // handles spaces and tabs also for (String t : tokens) { tags.add(new Tag(line, t)); } } return tags; } private static Table toTable(KarateParser.TableContext ctx) { List<TerminalNode> nodes = ctx.TABLE_ROW(); int rowCount = nodes.size(); if (rowCount < 1) { // if scenario outline found without examples return null; } List<List<String>> rows = new ArrayList(rowCount); List<Integer> lineNumbers = new ArrayList(rowCount); for (TerminalNode node : nodes) { List<String> tokens = StringUtils.split(node.getText().trim(), '|', true); int count = tokens.size(); for (int i = 0; i < count; i++) { tokens.set(i, tokens.get(i).trim()); } rows.add(tokens); lineNumbers.add(getActualLine(node)); } return new Table(rows, lineNumbers); } public static final String TRIPLE_QUOTES = "\"\"\""; private static int indexOfFirstText(String s) { int pos = 0; for (char c : s.toCharArray()) { if (!Character.isWhitespace(c)) { return pos; } pos++; } return 0; // defensive coding } private static String fixDocString(String temp) { int quotePos = temp.indexOf(TRIPLE_QUOTES); int endPos = temp.lastIndexOf(TRIPLE_QUOTES); String raw = temp.substring(quotePos + 3, endPos).replaceAll("\r", ""); List<String> lines = StringUtils.split(raw, '\n', false); StringBuilder sb = new StringBuilder(); int marginPos = -1; Iterator<String> iterator = lines.iterator(); while (iterator.hasNext()) { String line = iterator.next(); int firstTextPos = indexOfFirstText(line); if (marginPos == -1) { marginPos = firstTextPos; } if (marginPos < line.length() && marginPos <= firstTextPos) { line = line.substring(marginPos); } if (iterator.hasNext()) { sb.append(line).append('\n'); } else { sb.append(line); } } return sb.toString().trim(); } private List<String> collectComments(ParserRuleContext prc) { List<Token> tokens = tokenStream.getHiddenTokensToLeft(prc.start.getTokenIndex()); if (tokens == null) { return null; } List<String> comments = new ArrayList(tokens.size()); for (Token t : tokens) { comments.add(StringUtils.trimToNull(t.getText())); } return comments; } private List<Step> toSteps(Scenario scenario, List<KarateParser.StepContext> list) { List<Step> steps = new ArrayList(list.size()); int index = 0; for (KarateParser.StepContext sc : list) { Step step = scenario == null ? new Step(feature, index++) : new Step(scenario, index++); step.setComments(collectComments(sc)); steps.add(step); int stepLine = sc.line().getStart().getLine(); step.setLine(stepLine); step.setPrefix(sc.prefix().getText().trim()); step.setText(sc.line().getText().trim()); if (sc.docString() != null) { String raw = sc.docString().getText(); step.setDocString(fixDocString(raw)); step.setEndLine(stepLine + StringUtils.countLineFeeds(raw)); } else if (sc.table() != null) { Table table = toTable(sc.table()); step.setTable(table); step.setEndLine(stepLine + StringUtils.countLineFeeds(sc.table().getText())); } else { step.setEndLine(stepLine); } } return steps; } @Override public void enterFeatureHeader(KarateParser.FeatureHeaderContext ctx) { if (ctx.featureTags() != null) { feature.setTags(toTags(ctx.featureTags().getStart().getLine(), ctx.featureTags().FEATURE_TAGS())); } if (ctx.FEATURE() != null) { feature.setLine(ctx.FEATURE().getSymbol().getLine()); if (ctx.featureDescription() != null) { StringUtils.Pair pair = StringUtils.splitByFirstLineFeed(ctx.featureDescription().getText()); feature.setName(pair.left); feature.setDescription(pair.right); } } } @Override public void enterBackground(KarateParser.BackgroundContext ctx) { Background background = new Background(); feature.setBackground(background); background.setLine(getActualLine(ctx.BACKGROUND())); List<Step> steps = toSteps(null, ctx.step()); if (!steps.isEmpty()) { background.setSteps(steps); } if (logger.isTraceEnabled()) { logger.trace("background steps: {}", steps); } } @Override public void enterScenario(KarateParser.ScenarioContext ctx) { FeatureSection section = new FeatureSection(); Scenario scenario = new Scenario(feature, section, -1); scenario.setLine(getActualLine(ctx.SCENARIO())); section.setScenario(scenario); feature.addSection(section); if (ctx.tags() != null) { scenario.setTags(toTags(-1, ctx.tags().TAGS())); } if (ctx.scenarioDescription() != null) { StringUtils.Pair pair = StringUtils.splitByFirstLineFeed(ctx.scenarioDescription().getText()); scenario.setName(pair.left); scenario.setDescription(pair.right); } List<Step> steps = toSteps(scenario, ctx.step()); scenario.setSteps(steps); } @Override public void enterScenarioOutline(KarateParser.ScenarioOutlineContext ctx) { FeatureSection section = new FeatureSection(); ScenarioOutline outline = new ScenarioOutline(feature, section); outline.setLine(getActualLine(ctx.SCENARIO_OUTLINE())); section.setScenarioOutline(outline); feature.addSection(section); if (ctx.tags() != null) { outline.setTags(toTags(-1, ctx.tags().TAGS())); } if (ctx.scenarioDescription() != null) { outline.setDescription(ctx.scenarioDescription().getText()); StringUtils.Pair pair = StringUtils.splitByFirstLineFeed(ctx.scenarioDescription().getText()); outline.setName(pair.left); outline.setDescription(pair.right); } List<Step> steps = toSteps(null, ctx.step()); outline.setSteps(steps); if (logger.isTraceEnabled()) { logger.trace("outline steps: {}", steps); } List<ExamplesTable> examples = new ArrayList(ctx.examples().size()); outline.setExamplesTables(examples); for (KarateParser.ExamplesContext ec : ctx.examples()) { Table table = toTable(ec.table()); ExamplesTable example = new ExamplesTable(outline, table); examples.add(example); if (ec.tags() != null) { example.setTags(toTags(-1, ec.tags().TAGS())); } if (logger.isTraceEnabled()) { logger.trace("example rows: {}", table.getRows()); } } } }
package org.kuali.rice.krms.api; import java.util.Map; /** * Loads a {@link Context} for the given set of criteria. Applications who * want to provide their own means for creating a context and supplying it to * the KRMS engine can do so by implementing a custom ContextProvider. * * @see Context * * @author Kuali Rice Team (rice.collab@kuali.org) * */ public interface ContextProvider { /** * Loads the context for the given selection criteria, facts, and execution * options. If no context can be located based on the given criteria, then * this method should return null. * * <p>In the case where multiple Contexts could potentially be identified * from the same set of selection criteria, it is up to the implementer * of the ContextProvider to ensure that the most appropriate Context is * returned. Or alternatively, an exception could be thrown indicating * context ambiguity. * * <p>The sectionCriteria, facts, and executionOptions which are passed to * this method should never be null. However, they might be empty. * * @param selectionCriteria the criteria to use during the selection phase of engine operation * @param facts * @param executionOptions * @return */ public Context loadContext(SelectionCriteria selectionCriteria, Map<Asset, Object> facts, Map<String, String> executionOptions); }
package edu.umd.cs.findbugs.ba; import java.util.*; import org.apache.bcel.Constants; import org.apache.bcel.classfile.*; import org.apache.bcel.generic.*; /** * A CFGBuilder that really tries to construct accurate control flow graphs. * The CFGs it creates have accurate exception edges, and have accurately * inlined JSR subroutines. * * @see CFG * @author David Hovemeyer */ public class BetterCFGBuilder2 implements CFGBuilder, EdgeTypes, Debug { private static final boolean DEBUG = Boolean.getBoolean("cfgbuilder.debug"); private static final boolean NO_STATIC_FIELD_EXCEPTIONS = !Boolean.getBoolean("cfgbuilder.staticFieldExceptions"); private static final boolean NO_LOAD_CONSTANT_EXCEPTIONS = !Boolean.getBoolean("cfgbuilder.ldcExceptions"); // TODO: don't forget to change BasicBlock so ATHROW is considered to have a null check /** * A work list item for creating the CFG for a subroutine. */ private static class WorkListItem { private final InstructionHandle start; private final BasicBlock basicBlock; /** * Constructor. * @param start first instruction in the basic block * @param basicBlock the basic block to build */ public WorkListItem(InstructionHandle start, BasicBlock basicBlock) { this.start = start; this.basicBlock = basicBlock; } /** Get the start instruction. */ public InstructionHandle getStartInstruction() { return start; } /** Get the basic block. */ public BasicBlock getBasicBlock() { return basicBlock; } } /** * A placeholder for a control edge that escapes its subroutine to return * control back to an outer (calling) subroutine. It will turn into a * real edge during inlining. */ private static class EscapeTarget { private final InstructionHandle target; private final int edgeType; /** * Constructor. * @param target the target instruction in a calling subroutine * @param edgeType the type of edge that should be created when the * subroutine is inlined into its calling context */ public EscapeTarget(InstructionHandle target, int edgeType) { this.target = target; this.edgeType = edgeType; } /** Get the target instruction. */ public InstructionHandle getTarget() { return target; } /** Get the edge type. */ public int getEdgeType() { return edgeType; } } private static final LinkedList<EscapeTarget> emptyEscapeTargetList = new LinkedList<EscapeTarget>(); /** * JSR subroutine. The top level subroutine is where execution starts. * Each subroutine has its own CFG. Eventually, * all JSR subroutines will be inlined into the top level subroutine, * resulting in an accurate CFG for the overall method. */ private class Subroutine { private final InstructionHandle start; private final BitSet instructionSet; private final CFG cfg; private IdentityHashMap<InstructionHandle, BasicBlock> blockMap; private IdentityHashMap<BasicBlock, List<EscapeTarget>> escapeTargetListMap; private BitSet returnBlockSet; private BitSet exitBlockSet; private BitSet unhandledExceptionBlockSet; private LinkedList<WorkListItem> workList; /** * Constructor. * @param start the start instruction for the subroutine */ public Subroutine(InstructionHandle start) { this.start = start; this.instructionSet = new BitSet(); this.cfg = new CFG(); this.blockMap = new IdentityHashMap<InstructionHandle, BasicBlock>(); this.escapeTargetListMap = new IdentityHashMap<BasicBlock, List<EscapeTarget>>(); this.returnBlockSet = new BitSet(); this.exitBlockSet = new BitSet(); this.unhandledExceptionBlockSet = new BitSet(); this.workList = new LinkedList<WorkListItem>(); } /** Get the start instruction. */ public InstructionHandle getStartInstruction() { return start; } /** Allocate a new basic block in the subroutine. */ public BasicBlock allocateBasicBlock() { return cfg.allocate(); } /** Add a work list item for a basic block to be constructed. */ public void addItem(WorkListItem item) { workList.add(item); } /** Are there more work list items? */ public boolean hasMoreWork() { return !workList.isEmpty(); } /** Get the next work list item. */ public WorkListItem nextItem() { return workList.removeFirst(); } /** Get the entry block for the subroutine's CFG. */ public BasicBlock getEntry() { return cfg.getEntry(); } /** Get the exit block for the subroutine's CFG. */ public BasicBlock getExit() { return cfg.getExit(); } /** Get the start block for the subroutine's CFG. (I.e., the block containing the start instruction.) */ public BasicBlock getStartBlock() { return getBlock(start); } /** Get the subroutine's CFG. */ public CFG getCFG() { return cfg; } /** * Add an instruction to the subroutine. * We keep track of which instructions are part of which subroutines. * No instruction may be part of more than one subroutine. * @param handle the instruction to be added to the subroutine */ public void addInstruction(InstructionHandle handle) throws CFGBuilderException { int position = handle.getPosition(); if (usedInstructionSet.get(position)) throw new CFGBuilderException("Instruction " + handle + " visited in multiple subroutines"); instructionSet.set(position); usedInstructionSet.set(position); } /** * Is the given instruction part of this subroutine? */ public boolean containsInstruction(InstructionHandle handle) { return instructionSet.get(handle.getPosition()); } /** * Get the basic block in the subroutine for the given instruction. * If the block doesn't exist yet, it is created, and a work list * item is added which will populate it. Note that if start is * an exception thrower, the block returned will be its ETB. * * @param start the start instruction for the block * @return the basic block for the instruction */ public BasicBlock getBlock(InstructionHandle start) { BasicBlock block = blockMap.get(start); if (block == null) { block = allocateBasicBlock(); blockMap.put(start, block); // Block is an exception handler? CodeExceptionGen exceptionGen = exceptionHandlerMap.getHandlerForStartInstruction(start); if (exceptionGen != null) block.setExceptionGen(exceptionGen); addItem(new WorkListItem(start, block)); } return block; } /** * Indicate that the method returns at the end of the given block. * @param block the returning block */ public void setReturnBlock(BasicBlock block) { returnBlockSet.set(block.getId()); } /** * Does the method return at the end of this block? */ public boolean isReturnBlock(BasicBlock block) { return returnBlockSet.get(block.getId()); } /** * Indicate that System.exit() is called at the end of the given block. * @param block the exiting block */ public void setExitBlock(BasicBlock block) { exitBlockSet.set(block.getId()); } /** * Is System.exit() called at the end of this block? */ public boolean isExitBlock(BasicBlock block) { return exitBlockSet.get(block.getId()); } /** * Indicate that an unhandled exception may be thrown by * the given block. * @param block the block throwing an unhandled exception */ public void setUnhandledExceptionBlock(BasicBlock block) { unhandledExceptionBlockSet.set(block.getId()); } /** * Does this block throw an unhandled exception? */ public boolean isUnhandledExceptionBlock(BasicBlock block) { return unhandledExceptionBlockSet.get(block.getId()); } /** * Add a control flow edge to the subroutine. * If the control target has not yet been added to the subroutine, * a new work list item is added. If the control target is in * another subroutine, an EscapeTarget is added. * @param sourceBlock the source basic block * @param target the control target * @param edgeType the type of control edge */ public void addEdgeAndExplore(BasicBlock sourceBlock, InstructionHandle target, int edgeType) { if (usedInstructionSet.get(target.getPosition()) && !containsInstruction(target)) { // Control escapes this subroutine List<EscapeTarget> escapeTargetList = escapeTargetListMap.get(sourceBlock); if (escapeTargetList == null) { escapeTargetList = new LinkedList<EscapeTarget>(); escapeTargetListMap.put(sourceBlock, escapeTargetList); } escapeTargetList.add(new EscapeTarget(target, edgeType)); } else { // Edge within the current subroutine BasicBlock targetBlock = getBlock(target); addEdge(sourceBlock, targetBlock, edgeType); } } /** * Add an edge to the subroutine's CFG. * @param sourceBlock the source basic block * @param destBlock the destination basic block * @param edgeType the type of edge */ public void addEdge(BasicBlock sourceBlock, BasicBlock destBlock, int edgeType) { if (VERIFY_INTEGRITY) { if (destBlock.isExceptionHandler() && edgeType != HANDLED_EXCEPTION_EDGE) throw new IllegalStateException("In method " + SignatureConverter.convertMethodSignature(methodGen) + ": exception handler " + destBlock.getFirstInstruction() + " reachable by non exception edge type " + edgeType); } cfg.addEdge(sourceBlock, destBlock, edgeType); } /** * Get an Iterator over the EscapeTargets of given basic block. * @param sourceBlock the basic block * @return an Iterator over the EscapeTargets */ public Iterator<EscapeTarget> escapeTargetIterator(BasicBlock sourceBlock) { List<EscapeTarget> escapeTargetList = escapeTargetListMap.get(sourceBlock); if (escapeTargetList == null) escapeTargetList = emptyEscapeTargetList; return escapeTargetList.iterator(); } } /** * Inlining context. * This essentially consists of a inlining site and * a subroutine to be inlined. A stack of calling contexts * is maintained in order to resolve EscapeTargets. */ private static class Context { private final Context caller; private final Subroutine subroutine; private final CFG result; private final IdentityHashMap<BasicBlock, BasicBlock> blockMap; private final LinkedList<BasicBlock> workList; /** * Constructor. * @param caller the calling context * @param subroutine the subroutine being inlined * @param result the result CFG */ public Context(Context caller, Subroutine subroutine, CFG result) { this.caller = caller; this.subroutine = subroutine; this.result = result; this.blockMap = new IdentityHashMap<BasicBlock, BasicBlock>(); this.workList = new LinkedList<BasicBlock>(); } /** Get the calling context. */ public Context getCaller() { return caller; } /** Get the subroutine being inlined. */ public Subroutine getSubroutine() { return subroutine; } /** Get the result CFG. */ public CFG getResult() { return result; } /** Add a basic block to the inlining work list. */ public void addItem(BasicBlock item) { workList.add(item); } /** Are there more work list items? */ public boolean hasMoreWork() { return !workList.isEmpty(); } /** Get the next work list item (basic block to be inlined). */ public BasicBlock nextItem() { return workList.removeFirst(); } /** * Map a basic block in a subroutine to the corresponding block * in the resulting CFG. * @param subBlock the subroutine block * @param resultBlock the result CFG block */ public void mapBlock(BasicBlock subBlock, BasicBlock resultBlock) { blockMap.put(subBlock, resultBlock); } /** * Get the block in the result CFG corresponding to the given * subroutine block. * @param subBlock the subroutine block * @return the result CFG block */ public BasicBlock getBlock(BasicBlock subBlock) { BasicBlock resultBlock = blockMap.get(subBlock); if (resultBlock == null) { resultBlock = result.allocate(); blockMap.put(subBlock, resultBlock); workList.add(subBlock); } return resultBlock; } /** Check to ensure that this context is not the result of recursion. */ public void checkForRecursion() throws CFGBuilderException { Context callerContext = caller; while (callerContext != null) { if (callerContext.subroutine == this.subroutine) throw new CFGBuilderException("JSR recursion detected!"); callerContext = callerContext.caller; } } } private MethodGen methodGen; private ConstantPoolGen cpg; private ExceptionHandlerMap exceptionHandlerMap; private BitSet usedInstructionSet; private LinkedList<Subroutine> subroutineWorkList; private IdentityHashMap<InstructionHandle, Subroutine> jsrSubroutineMap; private Subroutine topLevelSubroutine; private CFG cfg; /** * Constructor. * @param methodGen the method to build a CFG for */ public BetterCFGBuilder2(MethodGen methodGen) { this.methodGen = methodGen; this.cpg = methodGen.getConstantPool(); this.exceptionHandlerMap = new ExceptionHandlerMap(methodGen); this.usedInstructionSet = new BitSet(); this.jsrSubroutineMap = new IdentityHashMap<InstructionHandle, Subroutine>(); this.subroutineWorkList = new LinkedList<Subroutine>(); } public void build() throws CFGBuilderException { topLevelSubroutine = new Subroutine(methodGen.getInstructionList().getStart()); subroutineWorkList.add(topLevelSubroutine); // Build top level subroutine and all JSR subroutines while (!subroutineWorkList.isEmpty()) { Subroutine subroutine = subroutineWorkList.removeFirst(); if (DEBUG) System.out.println("Starting subroutine " + subroutine.getStartInstruction()); build(subroutine); } // Inline everything into the top level subroutine cfg = inlineAll(); if (VERIFY_INTEGRITY) cfg.checkIntegrity(); } public CFG getCFG() { return cfg; } /** * Build a subroutine. * We iteratively add basic blocks to the subroutine * until there are no more blocks reachable from the calling context. * As JSR instructions are encountered, new Subroutines are added * to the subroutine work list. * * @param subroutine the subroutine */ private void build(Subroutine subroutine) throws CFGBuilderException { // Prime the work list subroutine.addEdgeAndExplore(subroutine.getEntry(), subroutine.getStartInstruction(), START_EDGE); // Keep going until all basic blocks in the subroutine have been added while (subroutine.hasMoreWork()) { WorkListItem item = subroutine.nextItem(); InstructionHandle handle = item.getStartInstruction(); BasicBlock basicBlock = item.getBasicBlock(); // Add exception handler block (ETB) for exception-throwing instructions if (isPEI(handle)) { if (DEBUG) System.out.println("ETB block " + basicBlock.getId() + " for " + handle); handleExceptions(subroutine, handle, basicBlock); BasicBlock body = subroutine.allocateBasicBlock(); subroutine.addEdge(basicBlock, body, FALL_THROUGH_EDGE); basicBlock = body; } if (DEBUG) System.out.println("BODY block " + basicBlock.getId() + " for " + handle); if (!basicBlock.isEmpty()) throw new IllegalStateException("Block isn't empty!"); // Add instructions until we get to the end of the block boolean endOfBasicBlock = false; do { Instruction ins = handle.getInstruction(); // Add the instruction to the block if (DEBUG) System.out.println("BB " + basicBlock.getId() + ": adding" + handle); basicBlock.addInstruction(handle); subroutine.addInstruction(handle); short opcode = ins.getOpcode(); // TODO: should check instruction to ensure that in a JSR subroutine // no assignments are made to the local containing the return address. // if (ins instanceof ASTORE) ... if (opcode == Constants.JSR || opcode == Constants.JSR_W) { // Find JSR subroutine, add it to subroutine work list if // we haven't built a CFG for it yet JsrInstruction jsr = (JsrInstruction) ins; InstructionHandle jsrTarget = jsr.getTarget(); Subroutine jsrSubroutine = jsrSubroutineMap.get(jsrTarget); if (jsrSubroutine == null) { jsrSubroutine = new Subroutine(jsrTarget); jsrSubroutineMap.put(jsrTarget, jsrSubroutine); subroutineWorkList.add(jsrSubroutine); } // This ends the basic block. // Add a JSR_EDGE to the successor. // It will be replaced later by the inlined JSR subroutine. subroutine.addEdgeAndExplore(basicBlock, handle.getNext(), JSR_EDGE); endOfBasicBlock = true; } else if (opcode == Constants.RET) { // End of JSR subroutine subroutine.addEdge(basicBlock, subroutine.getExit(), RET_EDGE); endOfBasicBlock = true; } else { TargetEnumeratingVisitor visitor = new TargetEnumeratingVisitor(handle, cpg); if (visitor.isEndOfBasicBlock()) { endOfBasicBlock = true; // Add control edges as appropriate if (visitor.instructionIsThrow()) { handleExceptions(subroutine, handle, basicBlock); } else if (visitor.instructionIsExit()) { subroutine.setExitBlock(basicBlock); } else if (visitor.instructionIsReturn()) { subroutine.setReturnBlock(basicBlock); } else { Iterator<Target> i = visitor.targetIterator(); while (i.hasNext()) { Target target = i.next(); subroutine.addEdgeAndExplore(basicBlock, target.getTargetInstruction(), target.getEdgeType()); } } } } if (!endOfBasicBlock) { InstructionHandle next = handle.getNext(); if (next == null) throw new CFGBuilderException("Control falls off end of method: " + handle); // Is the next instruction a control merge or a PEI? if (isMerge(next) || isPEI(next)) { subroutine.addEdgeAndExplore(basicBlock, next, FALL_THROUGH_EDGE); endOfBasicBlock = true; } else { // Basic block continues handle = next; } } } while (!endOfBasicBlock); } } /** * Add exception edges for given instruction. * @param subroutine the subroutine containing the instruction * @param pei the instruction which throws an exception * @param etb the exception thrower block (ETB) for the instruction */ private void handleExceptions(Subroutine subroutine, InstructionHandle pei, BasicBlock etb) { etb.setExceptionThrower(pei); // Remember whether or not an ANY exception type handler // is reachable. If so, then we know that exceptions raised // at this instruction cannot propagate out of the method. boolean sawAnyExceptionHandler = false; List<CodeExceptionGen> exceptionHandlerList = exceptionHandlerMap.getHandlerList(pei); if (exceptionHandlerList != null) { // TODO: should try to prune some obviously infeasible exception edges Iterator<CodeExceptionGen> i = exceptionHandlerList.iterator(); while (i.hasNext()) { CodeExceptionGen exceptionHandler = i.next(); InstructionHandle handlerStart = exceptionHandler.getHandlerPC(); subroutine.addEdgeAndExplore(etb, handlerStart, HANDLED_EXCEPTION_EDGE); if (exceptionHandler.getCatchType() == null || exceptionHandler.getCatchType().equals(ObjectType.THROWABLE)) sawAnyExceptionHandler = true; } } // If required, mark this block as throwing an unhandled exception. // For now, we assume that if there is no reachable handler that handles // ANY exception type, then the exception can be thrown out of the method. // FIXME: this is more conservative than necessary. if (!sawAnyExceptionHandler) { if (DEBUG) System.out.println("Adding unhandled exception edge from " + pei); subroutine.setUnhandledExceptionBlock(etb); } } /** * Return whether or not the given instruction can throw exceptions. * @param handle the instruction * @return true if the instruction can throw an exception, false otherwise */ private boolean isPEI(InstructionHandle handle) { Instruction ins = handle.getInstruction(); short opcode = ins.getOpcode(); if (!(ins instanceof ExceptionThrower)) return false; // Return instructions can throw exceptions only if the method is synchronized if (ins instanceof ReturnInstruction && !methodGen.isSynchronized()) return false; // We're really not interested in exceptions that could hypothetically be // thrown by static field accesses. if (NO_STATIC_FIELD_EXCEPTIONS && (opcode == Constants.GETSTATIC || opcode == Constants.PUTSTATIC)) return false; // Exceptions from LDC instructions seem a bit far fetched as well. if (NO_LOAD_CONSTANT_EXCEPTIONS && (opcode == Constants.LDC || opcode == Constants.LDC_W || opcode == Constants.LDC2_W)) return false; return true; } /** * Determine whether or not the given instruction is a control flow merge. * @param handle the instruction * @return true if the instruction is a control merge, false otherwise */ private static boolean isMerge(InstructionHandle handle) { if (handle.hasTargeters()) { // Check all targeters of this handle to see if any // of them are branches. If so, the instruction is a merge. InstructionTargeter[] targeterList = handle.getTargeters(); for (int i = 0; i < targeterList.length; ++i) { InstructionTargeter targeter = targeterList[i]; if (targeter instanceof BranchInstruction) return true; } } return false; } /** * Inline all JSR subroutines into the top-level subroutine. * This produces a complete CFG for the entire method, in which * all JSR subroutines are inlined. * @return the CFG for the method */ private CFG inlineAll() throws CFGBuilderException { CFG result = new CFG(); Context rootContext = new Context(null, topLevelSubroutine, result); rootContext.mapBlock(topLevelSubroutine.getEntry(), result.getEntry()); rootContext.mapBlock(topLevelSubroutine.getExit(), result.getExit()); BasicBlock resultStartBlock = rootContext.getBlock(topLevelSubroutine.getStartBlock()); result.addEdge(result.getEntry(), resultStartBlock, START_EDGE); inline(rootContext); return result; } /** * Inline a subroutine into a calling context. * @param context the Context */ public void inline(Context context) throws CFGBuilderException { CFG result = context.getResult(); // Check to ensure we're not trying to inline something that is recursive context.checkForRecursion(); Subroutine subroutine = context.getSubroutine(); CFG subCFG = subroutine.getCFG(); while (context.hasMoreWork()) { BasicBlock subBlock = context.nextItem(); BasicBlock resultBlock = context.getBlock(subBlock); // Copy instructions into the result block BasicBlock.InstructionIterator insIter = subBlock.instructionIterator(); while (insIter.hasNext()) { InstructionHandle handle = insIter.next(); resultBlock.addInstruction(handle); } // Set exception thrower status if (subBlock.isExceptionThrower()) resultBlock.setExceptionThrower(subBlock.getExceptionThrower()); // Set exception handler status if (subBlock.isExceptionHandler()) resultBlock.setExceptionGen(subBlock.getExceptionGen()); // Add control edges (including inlining JSR subroutines) Iterator<Edge> edgeIter = subCFG.outgoingEdgeIterator(subBlock); while (edgeIter.hasNext()) { Edge edge = edgeIter.next(); int edgeType = edge.getType(); if (edgeType == JSR_EDGE) { // Inline a JSR subroutine... // Create a new Context InstructionHandle jsrHandle = subBlock.getLastInstruction(); JsrInstruction jsr = (JsrInstruction) jsrHandle.getInstruction(); Subroutine jsrSub = jsrSubroutineMap.get(jsr.getTarget()); Context jsrContext = new Context(context, jsrSub, context.getResult()); // The start block in the JSR subroutine maps to the first // inlined block in the result CFG. BasicBlock resultJSRStartBlock = jsrContext.getBlock(jsrSub.getStartBlock()); result.addEdge(resultBlock, resultJSRStartBlock, GOTO_EDGE); // The exit block in the JSR subroutine maps to the result block // corresponding to the instruction following the JSR. // (I.e., that is where control returns after the execution of // the JSR subroutine.) BasicBlock subJSRSuccessorBlock = subroutine.getBlock(jsrHandle.getNext()); BasicBlock resultJSRSuccessorBlock = context.getBlock(subJSRSuccessorBlock); jsrContext.mapBlock(jsrSub.getExit(), resultJSRSuccessorBlock); // Inline the JSR subroutine inline(jsrContext); } else { // Ordinary control edge BasicBlock resultTarget = context.getBlock(edge.getTarget()); result.addEdge(resultBlock, resultTarget, edge.getType()); } } // Add control edges for escape targets Iterator<EscapeTarget> escapeTargetIter = subroutine.escapeTargetIterator(subBlock); while (escapeTargetIter.hasNext()) { EscapeTarget escapeTarget = escapeTargetIter.next(); InstructionHandle targetInstruction = escapeTarget.getTarget(); // Look for the calling context which has the target instruction Context caller = context.getCaller(); while (caller != null) { if (caller.getSubroutine().containsInstruction(targetInstruction)) break; caller = caller.getCaller(); } if (caller == null) throw new CFGBuilderException("Unknown caller for escape target " + targetInstruction + " referenced by " + context.getSubroutine().getStartInstruction()); // Find result block in caller BasicBlock subCallerTargetBlock = caller.getSubroutine().getBlock(targetInstruction); BasicBlock resultCallerTargetBlock = caller.getBlock(subCallerTargetBlock); // Add an edge to caller context result.addEdge(resultBlock, resultCallerTargetBlock, escapeTarget.getEdgeType()); } // If the block returns from the method, add a return edge if (subroutine.isReturnBlock(subBlock)) { result.addEdge(resultBlock, result.getExit(), RETURN_EDGE); } // If the block calls System.exit(), add an exit edge if (subroutine.isExitBlock(subBlock)) { result.addEdge(resultBlock, result.getExit(), EXIT_EDGE); } // If the block throws an unhandled exception, add an unhandled // exception edge if (subroutine.isUnhandledExceptionBlock(subBlock)) { result.addEdge(resultBlock, result.getExit(), UNHANDLED_EXCEPTION_EDGE); } } /* while (blocks are left) { get block from subroutine get corresponding block from result copy instructions into result block if (block terminated by JSR) { get JSR subroutine create new context create GOTO edge from current result block to start block of new inlined context map subroutine exit block to result JSR successor block inline (new context, result) } else { for each outgoing edge { map each target to result blocks (add block to to work list if needed) add edges to result } for each outgoing escape target { add edges into blocks in outer contexts (adding those blocks to outer work list if needed) } if (block returns) { add return edge from result block to result CFG exit block } if (block calls System.exit()) { add exit edge from result block to result CFG exit block } if (block throws unhandled exception) { add unhandled exception edge from result block to result CFG exit block } } } */ } /** * Test driver. */ public static void main(String[] argv) throws Exception { if (argv.length != 1) { System.err.println("Usage: " + BetterCFGBuilder2.class.getName() + " <class file>"); System.exit(1); } String methodName = System.getProperty("cfgbuilder.method"); JavaClass jclass = new ClassParser(argv[0]).parse(); ClassGen classGen = new ClassGen(jclass); Method[] methodList = jclass.getMethods(); for (int i = 0; i < methodList.length; ++i) { Method method = methodList[i]; if (method.isAbstract() || method.isNative()) continue; if (methodName != null && !method.getName().equals(methodName)) continue; MethodGen methodGen = new MethodGen(method, jclass.getClassName(), classGen.getConstantPool()); CFGBuilder cfgBuilder = new BetterCFGBuilder2(methodGen); cfgBuilder.build(); CFG cfg = cfgBuilder.getCFG(); CFGPrinter cfgPrinter = new CFGPrinter(cfg); System.out.println(" System.out.println("Method: " + SignatureConverter.convertMethodSignature(methodGen)); System.out.println(" cfgPrinter.print(System.out); } } } // vim:ts=4
package edu.umd.cs.findbugs.ba.ch; import java.io.IOException; import org.apache.bcel.generic.ArrayType; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.Type; import edu.umd.cs.findbugs.FindBugsTestCase; import edu.umd.cs.findbugs.RunnableWithExceptions; import edu.umd.cs.findbugs.ba.ObjectTypeFactory; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.detect.FindRefComparison; import junit.framework.AssertionFailedError; import junit.framework.TestCase; /** * Tests for Subtypes2. * * @author Bill Pugh * @author David Hovemeyer */ public class Subtypes2Test extends FindBugsTestCase { ObjectType typeSerializable; ObjectType typeClonable; ObjectType typeObject; ObjectType typeInteger; ObjectType typeString; ArrayType typeArraySerializable; ArrayType typeArrayClonable; ArrayType typeArrayObject; ArrayType typeArrayInteger; ArrayType typeArrayString; ArrayType typeArrayArrayObject; ArrayType typeArrayArraySerializable; ArrayType typeArrayArrayString; ArrayType typeArrayInt; ArrayType typeArrayArrayInt; ObjectType typeDynamicString; ObjectType typeStaticString; ObjectType typeParameterString; /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ @Override protected void setUp() throws Exception { typeSerializable = ObjectTypeFactory.getInstance("java.io.Serializable"); typeClonable = ObjectTypeFactory.getInstance("java.lang.Cloneable"); typeObject = ObjectTypeFactory.getInstance("java.lang.Object"); typeInteger = ObjectTypeFactory.getInstance("java.lang.Integer"); typeString = ObjectTypeFactory.getInstance("java.lang.String"); typeArraySerializable = new ArrayType(typeSerializable,1); typeArrayClonable = new ArrayType(typeClonable,1); typeArrayObject = new ArrayType(typeObject,1); typeArrayInteger = new ArrayType(typeInteger,1); typeArrayString = new ArrayType(typeString, 1); typeArrayArrayObject = new ArrayType(typeObject, 2); typeArrayArraySerializable = new ArrayType(typeSerializable, 2); typeArrayArrayString = new ArrayType(typeString, 2); typeArrayInt = new ArrayType(Type.INT, 1); typeArrayArrayInt = new ArrayType(Type.INT, 2); typeDynamicString = new FindRefComparison.DynamicStringType(); typeStaticString = new FindRefComparison.StaticStringType(); typeParameterString = new FindRefComparison.ParameterStringType(); } private static Subtypes2 getSubtypes2() { try { return Global.getAnalysisCache().getDatabase(Subtypes2.class); } catch (CheckedAnalysisException e) { throw new IllegalStateException(); } } public void testStringSubtypeOfObject() throws Throwable { executeFindBugsTest(new RunnableWithExceptions(){ /* (non-Javadoc) * @see edu.umd.cs.findbugs.RunnableWithExceptions#run() */ public void run() throws Throwable { Subtypes2 test = getSubtypes2(); assertTrue(test.isSubtype(typeString, typeObject)); } }); } public void testStringSubtypeOfSerializable() throws Throwable { executeFindBugsTest(new RunnableWithExceptions(){ /* (non-Javadoc) * @see edu.umd.cs.findbugs.RunnableWithExceptions#run() */ public void run() throws Throwable { Subtypes2 test = getSubtypes2(); assertTrue(test.isSubtype(typeString, typeSerializable)); } }); } public void testIdentitySubtype() throws Throwable { executeFindBugsTest(new RunnableWithExceptions() { /* (non-Javadoc) * @see edu.umd.cs.findbugs.RunnableWithExceptions#run() */ public void run() throws Throwable { Subtypes2 test = getSubtypes2(); assertTrue(test.isSubtype(typeObject, typeObject)); assertTrue(test.isSubtype(typeSerializable, typeSerializable)); assertTrue(test.isSubtype(typeArrayClonable, typeArrayClonable)); } }); } public void testInterfaceIsSubtypeOfObject() throws Throwable { executeFindBugsTest(new RunnableWithExceptions() { public void run() throws ClassNotFoundException { Subtypes2 test = getSubtypes2(); assertTrue(test.isSubtype(typeClonable, typeObject)); } }); } public void testArrays() throws Throwable { executeFindBugsTest(new RunnableWithExceptions() { /* (non-Javadoc) * @see edu.umd.cs.findbugs.RunnableWithExceptions#run() */ public void run() throws Throwable { Subtypes2 test = getSubtypes2(); assertTrue(test.isSubtype(typeArrayClonable, typeObject)); assertTrue(test.isSubtype(typeArrayClonable, typeArrayObject)); } }); } public void testUnrelatedTypes() throws Throwable { executeFindBugsTest(new RunnableWithExceptions(){ /* (non-Javadoc) * @see edu.umd.cs.findbugs.RunnableWithExceptions#run() */ public void run() throws Throwable { Subtypes2 test = getSubtypes2(); assertFalse(test.isSubtype(typeInteger, typeString)); } }); } public void testArraysWrongDimension() throws Throwable { executeFindBugsTest(new RunnableWithExceptions(){ /* (non-Javadoc) * @see edu.umd.cs.findbugs.RunnableWithExceptions#run() */ public void run() throws Throwable { Subtypes2 test = getSubtypes2(); assertFalse(test.isSubtype(typeArrayArrayString, typeArrayString)); } }); } public void testMultidimensionalArrayIsSubtypeOfObjectArray() throws Throwable { executeFindBugsTest(new RunnableWithExceptions() { /* (non-Javadoc) * @see edu.umd.cs.findbugs.RunnableWithExceptions#run() */ public void run() throws Throwable { Subtypes2 test = getSubtypes2(); assertTrue(test.isSubtype(typeArrayArrayString, typeArrayObject)); assertTrue(test.isSubtype(typeArrayArraySerializable, typeArrayObject)); assertTrue(test.isSubtype(typeArrayArrayInt, typeArrayObject)); } }); } public void testArrayOfPrimitiveIsSubtypeOfObject() throws Throwable { executeFindBugsTest(new RunnableWithExceptions(){ /* (non-Javadoc) * @see edu.umd.cs.findbugs.RunnableWithExceptions#run() */ public void run() throws Throwable { Subtypes2 test = getSubtypes2(); assertTrue(test.isSubtype(typeArrayInt, typeObject)); } }); } public void testSpecialStringSubclasses() throws Throwable { executeFindBugsTest(new RunnableWithExceptions() { /* (non-Javadoc) * @see edu.umd.cs.findbugs.RunnableWithExceptions#run() */ public void run() throws Throwable { Subtypes2 test = getSubtypes2(); assertTrue(test.isSubtype(typeDynamicString, typeString)); assertTrue(test.isSubtype(typeStaticString, typeString)); assertTrue(test.isSubtype(typeParameterString, typeString)); } }); } }
package gov.nih.nci.cananolab.dto.common; import gov.nih.nci.cananolab.domain.common.Organization; import gov.nih.nci.cananolab.domain.common.PointOfContact; /** * PointOfContact view bean * * @author tanq, cais * */ //TODO: need to revise PointOfContactBean, copy from OrganizationBean public class PointOfContactBean{ private PointOfContact domain; private String POCName; private Organization organization; private String[] orgVisibilityGroups = new String[0]; private String[] pocVisibilityGroups = new String[0]; private String[] emailVisibilityGroups = new String[0]; private String[] phoneVisibilityGroups = new String[0]; private boolean hidden = false; private String address; //TODO: need info for nanoparticleSample?? public PointOfContactBean() { super(); domain = new PointOfContact(); organization = new Organization(); domain.setOrganization(organization); POCName = ""; } public PointOfContactBean(PointOfContact pointOfContact) { domain = pointOfContact; organization = pointOfContact.getOrganization(); //TODO:: the following not needed?? String firstName = domain.getFirstName(); POCName = ""; if (firstName!=null) { POCName = firstName +" "; } String lastName = domain.getLastName(); if (lastName!=null) { POCName+=lastName; } if (domain.getOrganization()!=null) { String orgName = domain.getOrganization().getName(); if (orgName!=null) { POCName+="("+orgName+")"; } } } /** * @return the domain */ public PointOfContact getDomain() { return domain; } /** * @param domain the domain to set */ public void setDomain(PointOfContact domain) { this.domain = domain; } /** * @return the pocs */ public Organization getOrganization() { return organization; } /** * @param pocs the pocs to set */ public void setOrganization(Organization organization) { this.organization = organization; } /** * @return the orgVisibilityGroups */ public String[] getOrgVisibilityGroups() { return orgVisibilityGroups; } /** * @param orgVisibilityGroups the orgVisibilityGroups to set */ public void setOrgVisibilityGroups(String[] orgVisibilityGroups) { this.orgVisibilityGroups = orgVisibilityGroups; } /** * @return the pocVisibilityGroups */ public String[] getPocVisibilityGroups() { return pocVisibilityGroups; } /** * @param pocVisibilityGroups the pocVisibilityGroups to set */ public void setPocVisibilityGroups(String[] pocVisibilityGroups) { this.pocVisibilityGroups = pocVisibilityGroups; } /** * @return the emailVisibilityGroups */ public String[] getEmailVisibilityGroups() { return emailVisibilityGroups; } /** * @param emailVisibilityGroups the emailVisibilityGroups to set */ public void setEmailVisibilityGroups(String[] emailVisibilityGroups) { this.emailVisibilityGroups = emailVisibilityGroups; } /** * @return the phoneVisibilityGroups */ public String[] getPhoneVisibilityGroups() { return phoneVisibilityGroups; } /** * @param phoneVisibilityGroups the phoneVisibilityGroups to set */ public void setPhoneVisibilityGroups(String[] phoneVisibilityGroups) { this.phoneVisibilityGroups = phoneVisibilityGroups; } /** * @return the hidden */ public boolean isHidden() { return hidden; } /** * @param hidden the hidden to set */ public void setHidden(boolean hidden) { this.hidden = hidden; } /** * @return the pOCName */ public String getPOCName() { String firstName = domain.getFirstName(); POCName = ""; if (firstName!=null) { POCName = firstName +" "; } String lastName = domain.getLastName(); if (lastName!=null) { POCName+=lastName; } if (domain.getOrganization()!=null) { String orgName = domain.getOrganization().getName(); if (orgName!=null) { POCName+="("+orgName+")"; } } return POCName; } /** * @param name the pOCName to set */ public void setPOCName(String name) { POCName = name; } }
package org.xwiki.panels.test.ui; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.xwiki.administration.test.po.AdministrationMenu; import org.xwiki.model.reference.DocumentReference; import org.xwiki.panels.test.po.PageLayoutTabContent; import org.xwiki.panels.test.po.PageWithPanels; import org.xwiki.panels.test.po.PanelsAdministrationPage; import org.xwiki.test.docker.junit5.TestReference; import org.xwiki.test.docker.junit5.UITest; import org.xwiki.test.docker.junit5.browser.Browser; import org.xwiki.test.ui.TestUtils; import org.xwiki.test.ui.po.ViewPage; import org.xwiki.test.ui.po.editor.WikiEditPage; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Verify the Panels Administration features. * * @version $Id$ * @since 11.2 */ @UITest(browser = Browser.CHROME) public class PanelsAdministrationIT { @BeforeAll public void setup(TestUtils setup) { setup.loginAsSuperAdmin(); } @Test public void verifyPanelWizard(TestUtils setup, TestReference testReference) { PanelsAdministrationPage panelsAdminPage = PanelsAdministrationPage.gotoPage(); PageLayoutTabContent pageLayoutTabContent = panelsAdminPage.selectPageLayout(); // create a right column layout pageLayoutTabContent.selectRightColumnLayout().openPanelListSection(); PageWithPanels pageWithPanels = new PageWithPanels(); assertTrue(pageWithPanels.hasRightPanels()); // put quicklinks to right column pageLayoutTabContent.dragPanelToColumn("QuickLinks", PageLayoutTabContent.Column.RIGHT); assertTrue(new PageWithPanels().hasPanelInRightColumn("QuickLinks")); panelsAdminPage.clickSave(); setup.gotoPage("Main", "WebHome"); pageWithPanels = new PageWithPanels(); assertFalse(pageWithPanels.hasLeftPanels()); assertTrue(pageWithPanels.hasRightPanels()); assertTrue(pageWithPanels.hasPanelInRightColumn("QuickLinks")); // create a both columns layout panelsAdminPage = PanelsAdministrationPage.gotoPage(); pageLayoutTabContent = panelsAdminPage.selectPageLayout(); pageLayoutTabContent.selectBothColumnsLayout().openPanelListSection(); pageWithPanels = new PageWithPanels(); assertTrue(pageWithPanels.hasRightPanels()); assertTrue(pageWithPanels.hasLeftPanels()); // remove quicklinks from right panel pageLayoutTabContent.removePanelFromColumn("QuickLinks", PageLayoutTabContent.Column.RIGHT); pageWithPanels = new PageWithPanels(); assertFalse(pageWithPanels.hasPanelInRightColumn("QuickLinks")); panelsAdminPage.clickSave(); // columns are not visible anymore since there's nothing in them setup.gotoPage("Main", "WebHome"); pageWithPanels = new PageWithPanels(); assertFalse(pageWithPanels.hasLeftPanels()); assertFalse(pageWithPanels.hasRightPanels()); assertFalse(pageWithPanels.hasPanelInRightColumn("QuickLinks")); // put panels in both left and right columns panelsAdminPage = PanelsAdministrationPage.gotoPage(); pageLayoutTabContent = panelsAdminPage.selectPageLayout(); assertTrue(pageLayoutTabContent.isLayoutSelected(PageLayoutTabContent.Layout.NOCOLUMN)); pageLayoutTabContent.selectBothColumnsLayout().openPanelListSection(); pageWithPanels = new PageWithPanels(); assertTrue(pageWithPanels.hasRightPanels()); assertTrue(pageWithPanels.hasLeftPanels()); pageLayoutTabContent.dragPanelToColumn("Welcome", PageLayoutTabContent.Column.RIGHT); pageLayoutTabContent.dragPanelToColumn("Applications", PageLayoutTabContent.Column.LEFT); panelsAdminPage.clickSave(); setup.gotoPage("Main", "WebHome"); pageWithPanels = new PageWithPanels(); assertTrue(pageWithPanels.hasLeftPanels()); assertTrue(pageWithPanels.hasRightPanels()); assertTrue(pageWithPanels.hasPanelInRightColumn("Welcome")); assertTrue(pageWithPanels.hasPanelInLeftColumn("Applications")); // test panel wizard at space level ViewPage viewPage = setup.gotoPage(testReference); WikiEditPage wikiEditPage = viewPage.editWiki(); wikiEditPage.setContent("aaa"); wikiEditPage.clickSaveAndView(); setup.gotoPage(new DocumentReference("WebPreferences", testReference.getLastSpaceReference()), "admin"); new AdministrationMenu().expandCategoryWithName("Look & Feel") .getSectionByName("Look & Feel", "Panels") .click(); panelsAdminPage = new PanelsAdministrationPage(); pageLayoutTabContent = panelsAdminPage.selectPageLayout().selectLeftColumnLayout().openPanelListSection(); pageLayoutTabContent.dragPanelToColumn("QuickLinks", PageLayoutTabContent.Column.LEFT); panelsAdminPage.clickSave(); setup.gotoPage(testReference); pageWithPanels = new PageWithPanels(); assertTrue(pageWithPanels.hasLeftPanels()); assertFalse(pageWithPanels.hasRightPanels()); assertTrue(pageWithPanels.hasPanelInLeftColumn("QuickLinks")); assertTrue(pageWithPanels.hasPanelInLeftColumn("Applications")); setup.gotoPage("Main", "WebHome"); pageWithPanels = new PageWithPanels(); assertTrue(pageWithPanels.hasLeftPanels()); assertTrue(pageWithPanels.hasRightPanels()); assertTrue(pageWithPanels.hasPanelInRightColumn("Welcome")); assertTrue(pageWithPanels.hasPanelInLeftColumn("Applications")); assertFalse(pageWithPanels.hasPanelInRightColumn("QuickLinks")); } }
package gov.nih.nci.codegen.core.util; import gov.nih.nci.common.util.Constant; import java.io.StringReader; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import org.apache.log4j.Logger; import org.jaxen.JaxenException; import org.jaxen.jdom.JDOMXPath; import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.omg.uml.foundation.core.*; import org.omg.uml.foundation.core.Classifier; import org.omg.uml.foundation.core.Operation; import org.omg.uml.foundation.core.Parameter; import org.omg.uml.foundation.extensionmechanisms.TaggedValue; /** * @author caBIO Team * @version 1.0 */ public class UML13JavaSourceHelper { private static Logger log = Logger.getLogger(UML13JavaSourceHelper.class); /** * Creates an UML13JavaSourceHelper instance */ public UML13JavaSourceHelper() { super(); } private static String getDocumentation(Classifier klass) { TaggedValue doc = UML13Utils.getTaggedValue(klass, "documentation"); String docStr; if (doc != null) { docStr = doc.getValue(); for(int i=2;i<=8;i++) { TaggedValue docNext = UML13Utils.getTaggedValue(klass, "documentation"+i); if(docNext==null) break; docStr += docNext.getValue(); } } else { doc = UML13Utils.getTaggedValue(klass, "description"); if (doc == null) return " "; docStr = doc.getValue(); for(int i=2;i<=8;i++) { TaggedValue docNext = UML13Utils.getTaggedValue(klass, "description"+i); if(docNext==null) break; docStr += docNext.getValue(); } } return docStr; } private static String getDocumentation(Operation op) { TaggedValue doc = UML13Utils.getTaggedValue(op, "documentation"); if (doc == null) return " "; String docStr = doc.getValue(); for(int i=2;i<=8;i++) { TaggedValue docNext = UML13Utils.getTaggedValue(op, "documentation"+i); if(docNext==null) break; docStr += docNext.getValue(); } return docStr; } private static String getDocumentation(Parameter p) { TaggedValue doc = UML13Utils.getTaggedValue(p, "documentation"); if (doc == null) return " "; String docStr = doc.getValue(); for(int i=2;i<=8;i++) { TaggedValue docNext = UML13Utils.getTaggedValue(p, "documentation"+i); if(docNext==null) break; docStr += docNext.getValue(); } return docStr; } private static String getDocumentation(Attribute att) { TaggedValue doc = UML13Utils.getTaggedValue(att, "description"); String docStr; if (doc != null) { docStr = doc.getValue(); for(int i=2;i<=8;i++) { TaggedValue docNext = UML13Utils.getTaggedValue(att, "description"+i); if(docNext==null) break; docStr += docNext.getValue(); } } else { doc = UML13Utils.getTaggedValue(att, "documentation"); if (doc == null ) return " "; docStr = doc.getValue(); for(int i=2;i<=8;i++) { TaggedValue docNext = UML13Utils.getTaggedValue(att, "documentation"+i); if(docNext==null) break; docStr += docNext.getValue(); } } return docStr; } public static String getClassJavadoc(Classifier klass) { StringBuffer javadocOut = new StringBuffer(); TaggedValue specialdep = UML13Utils.getTaggedValue(klass, "deprecation1"); String docStr = getDocumentation(klass); docStr = getLineFormattedJavadoc(docStr); javadocOut.append(" /**\n"); javadocOut.append(docStr); javadocOut.append("\n"); if (specialdep != null) { javadocOut.append("* @deprecated "); javadocOut.append(specialdep.getValue()); javadocOut.append("\n"); } javadocOut.append(" */\n"); return javadocOut.toString(); } /** * Gets the java doc string for the specified class * * @param klass * class to get java doscs * @return String containing the java docs specs */ public static String getAllClassJavadoc(Classifier klass) { try { StringBuffer javadocOut = new StringBuffer(); TaggedValue doc = UML13Utils.getTaggedValue(klass, "documentation"); TaggedValue dep = UML13Utils.getTaggedValue(klass, "deprecation"); TaggedValue see = UML13Utils.getTaggedValue(klass, "see"); String docStr = getDocumentation(klass); docStr = getLineFormattedJavadoc(docStr); javadocOut.append(" /**\n"); javadocOut.append(docStr); javadocOut.append("\n"); if (dep != null) { javadocOut.append("* @deprecated "); javadocOut.append(dep.getValue()); javadocOut.append("\n"); } if (see != null) { javadocOut.append("* @see "); javadocOut.append(see.getValue()); javadocOut.append("\n"); } javadocOut.append(" */\n"); return javadocOut.toString(); } catch (Exception ex) { log.error("Exception: ", ex); } return ""; } public static String getMethodJavadoc(Operation op) { StringBuffer javadocOut = new StringBuffer(); TaggedValue dep = UML13Utils.getTaggedValue(op, "deprecated"); Classifier ret = UML13Utils.getReturnType(op); String docStr = getDocumentation(op); docStr = getLineFormattedJavadoc(docStr); javadocOut.append(" /**\n"); javadocOut.append(docStr); javadocOut.append("\n"); if (dep != null) { javadocOut.append("* @deprecated "); javadocOut.append(dep.getValue()); javadocOut.append("\n"); } for (Iterator i = UML13Utils.getParameters(op).iterator(); i.hasNext();) { Parameter p = (Parameter) i.next(); String pDocStr = getDocumentation(p); javadocOut.append(" * @param "); javadocOut.append(p.getName()); javadocOut.append(Constant.SPACE); javadocOut.append(pDocStr); javadocOut.append("\n"); } if (ret != null && !"void".equalsIgnoreCase(ret.getName())) { javadocOut.append(" * @return "); javadocOut.append(ret.getName()); javadocOut.append("\n"); } for (Iterator i = UML13Utils.getExceptions(op).iterator(); i.hasNext();) { Classifier ex = (Classifier) i.next(); javadocOut.append(" * @throws "); javadocOut.append(UML13Utils.getQualifiedName(ex)); javadocOut.append("\n"); } javadocOut.append(" */\n"); return javadocOut.toString(); } public static String getAssociationAttributeJavadoc(String associationType, boolean isCollection) { StringBuffer javadocOut = new StringBuffer(); javadocOut.append("/**\n"); javadocOut.append("An associated "); if(isCollection) javadocOut.append(" collection of "); javadocOut.append(associationType); javadocOut.append(" object"); javadocOut.append("\n"); javadocOut.append(" */\n"); return javadocOut.toString(); } public static String getAssociationAttributeJavadocGetter(String associationName) { StringBuffer javadocOut = new StringBuffer(); javadocOut.append("/**\n"); javadocOut.append("Retreives the value of "+associationName+" attribue\n"); javadocOut.append(" * @return "); javadocOut.append(associationName); javadocOut.append("\n"); javadocOut.append(" */\n"); return javadocOut.toString(); } public static String getAssociationAttributeJavadocSetter(String associationName) { StringBuffer javadocOut = new StringBuffer(); javadocOut.append("/**\n"); javadocOut.append("Sets the value of "+associationName+" attribue\n"); javadocOut.append("@param ").append(associationName); javadocOut.append("\n"); javadocOut.append(" */\n"); return javadocOut.toString(); } public static String getAttributeJavadoc(Attribute att) { StringBuffer javadocOut = new StringBuffer(); TaggedValue dep = UML13Utils.getTaggedValue(att, "deprecated"); String docStr = getDocumentation(att); docStr = getLineFormattedJavadoc(docStr); javadocOut.append("/**\n"); javadocOut.append(docStr); javadocOut.append("\n"); if (dep != null) { javadocOut.append("* @deprecated "); javadocOut.append(dep.getValue()); javadocOut.append("\n"); } javadocOut.append(" */\n"); return javadocOut.toString(); } public static String getAttributeJavadocSetter(Attribute att) { StringBuffer javadocOut = new StringBuffer(); String docStr = getDocumentation(att); javadocOut.append("/**\n"); javadocOut.append("Sets the value of "+att.getName()+" attribue\n"); javadocOut.append("@param ").append(att.getName()); javadocOut.append(" ").append(docStr); javadocOut.append("\n"); javadocOut.append(" */\n"); return javadocOut.toString(); } public static String getAttributeJavadocGetter(Attribute att) { StringBuffer javadocOut = new StringBuffer(); String docStr = getDocumentation(att); javadocOut.append("/**\n"); javadocOut.append("Retreives the value of "+att.getName()+" attribue\n"); javadocOut.append(" * @return "); javadocOut.append(att.getName()); javadocOut.append("\n"); javadocOut.append("\n"); javadocOut.append(" */\n"); return javadocOut.toString(); } /** * Formats the javadoc text * * @param val * @return */ public static String getLineFormattedJavadoc(String val) { StringBuffer javadocOut = new StringBuffer(); if (val == null) { //javadocOut.append(" * DOCUMENT ME!"); } else { // replace newlines val.replace('\n', ' '); val.replaceAll("<", "&lt;"); val.replaceAll(">", "&gt;"); if (val.length() > 80) { javadocOut.append(" * "); StringBuffer line = new StringBuffer(); int lineLength = 0; StringTokenizer st = new StringTokenizer(val); while (st.hasMoreTokens()) { String t = st.nextToken(); lineLength += t.length(); line.append(t); line.append(Constant.SPACE); if (lineLength > 80) { javadocOut.append(line.toString()); javadocOut.append("\n * "); line = new StringBuffer(); lineLength = 0; } } if (line.length() > 0) { javadocOut.append(line.toString()); javadocOut.append("\n * "); } } else { javadocOut.append(" * "); javadocOut.append(val); } } return javadocOut.toString().replaceAll("@", "\n* @"); } public Element selectElement(String exp, Element context) { Element result = null; try { JDOMXPath xpath = new JDOMXPath(exp); result = (Element) xpath.selectSingleNode(context); } catch (JaxenException e) { log.error(e.getMessage()); throw new RuntimeException(e); } if (result == null) { log.debug("Couldn't find element for path " + exp); /* * throw new RuntimeException("Couldn't find element for path " + * exp); */ } return result; } public List selectElements(String exp, Element context) { List result = null; try { JDOMXPath xpath = new JDOMXPath(exp); result = xpath.selectNodes(context); } catch (JaxenException e) { log.error(e.getMessage()); throw new RuntimeException(e); } return result; } public Element buildJDOMElement(String xml) { Element root = null; try { root = (new SAXBuilder(false)).build(new StringReader(xml)) .getRootElement(); } catch (Exception ex) { log.error("Couldn't build XML doc: ", ex); throw new RuntimeException("Couldn't build XML doc", ex); } return root; } public String outputString(Element e) { try { XMLOutputter p = new XMLOutputter(); p.setFormat(Format.getPrettyFormat()); return p.outputString(e); } catch (Exception ex) { log.error("Error outputting string: " + ex.getMessage()); throw new RuntimeException("Error outputting string: " + ex.getMessage(), ex); } } }
package org.xins.server; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Enumeration; import java.util.Iterator; import java.util.Properties; import javax.servlet.ServletConfig; import org.apache.log4j.LogManager; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.helpers.NullEnumeration; import org.xins.common.MandatoryArgumentChecker; import org.xins.common.collections.InvalidPropertyValueException; import org.xins.common.collections.PropertiesPropertyReader; import org.xins.common.collections.PropertyReader; import org.xins.common.collections.PropertyReaderUtils; import org.xins.common.collections.StatsPropertyReader; import org.xins.common.io.FileWatcher; import org.xins.common.text.TextUtils; import org.xins.logdoc.LogCentral; import org.xins.logdoc.UnsupportedLocaleException; /** * Manager for the runtime configuration file. Owns the watcher for the config * file and is responsible for triggering actions when the file has actually * changed. * * @version $Revision$ $Date$ * @author Mees Witteman (<a href="mailto:mees.witteman@nl.wanadoo.com">mees.witteman@nl.wanadoo.com</a>) * @author Anthony Goubard (<a href="mailto:anthony.goubard@nl.wanadoo.com">anthony.goubard@nl.wanadoo.com</a>) * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) */ final class ConfigManager extends Object { // Class fields /** * The object to synchronize on when reading and initializing from the * runtime configuration file. */ private static final Object RUNTIME_PROPERTIES_LOCK = new Object(); // Class functions /** * Initializes the logging subsystem with fallback default settings. */ static void configureLoggerFallback() { Properties settings = new Properties(); // Send all log messages to the logger named 'console' settings.setProperty( "log4j.rootLogger", "ALL, console"); // Define an appender for the console settings.setProperty( "log4j.appender.console", "org.apache.log4j.ConsoleAppender"); // Use a pattern-layout for the appender settings.setProperty( "log4j.appender.console.layout", "org.apache.log4j.PatternLayout"); // Define the pattern for the appender settings.setProperty( "log4j.appender.console.layout.ConversionPattern", "%16x %6c{1} %-6p %m%n"); // Do not show the debug logs produced by XINS. settings.setProperty("log4j.logger.org.xins.", "INFO"); // Perform Log4J configuration PropertyConfigurator.configure(settings); } // Constructors ConfigManager(Engine engine, ServletConfig config) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("engine", engine, "config", config); // Initialize fields _engine = engine; _config = config; _configFileListener = new ConfigurationFileListener(); } // Fields /** * The <code>Engine</code> that owns this <code>ConfigManager</code>. Never * <code>null</code>. */ private final Engine _engine; /** * Servlet configuration. Never <code>null</code>. */ private final ServletConfig _config; /** * The listener that is notified when the configuration file changes. Only * one instance is created ever. */ private final ConfigurationFileListener _configFileListener; /** * The name of the runtime configuration file. Initially <code>null</code>. */ private String _configFile; /** * Watcher for the runtime configuration file. Initially <code>null</code>. */ private FileWatcher _configFileWatcher; /** * The set of properties read from the runtime configuration file. Never * <code>null</code>. */ private StatsPropertyReader _runtimeProperties; // Methods /** * Determines the name of the runtime configuration file. The system * properties will be queried first. If they do not provide it, then the * servlet initialization properties are tried. Once determined, the name * will be stored internally. */ void determineConfigFile() { // TODO: Check state // TODO: What if the name cannot be determined? String prop = APIServlet.CONFIG_FILE_SYSTEM_PROPERTY; String configFile = null; try { configFile = System.getProperty(prop); } catch (SecurityException exception) { Log.log_3230(exception, prop); } // If the name of the configuration file is not set in a system property // (typically passed on the command-line) try to get it from the servlet // initialization properties (typically set in a web.xml file) if (configFile == null || configFile.trim().length() < 1) { Log.log_3231(prop); configFile = _config.getInitParameter(prop); // If it is still not set, then assume null if (configFile != null && configFile.trim().length() < 1) { configFile = null; } } _configFile = configFile; } /** * Unifies the file separator character on the _configFile property and then * reads the runtime properties file, initializes the logging subsystem * with the read properties and then stores those properties on the engine. * If the _configFile is empty, then an empty set of properties is set on * the engine. */ void readRuntimeProperties() { // TODO: Check state // If the value is not set only localhost can access the API. // NOTE: Don't trim the configuration file name, since it may start // with a space or other whitespace character. if (_configFile == null || _configFile.length() < 1) { Log.log_3205(APIServlet.CONFIG_FILE_SYSTEM_PROPERTY); _runtimeProperties = null; } else { // Unify the file separator character _configFile = _configFile.replace('/', File.separatorChar); _configFile = _configFile.replace('\\', File.separatorChar); // TODO: Allow a slash in the file name? // Initialize the logging subsystem Log.log_3300(_configFile); synchronized (ConfigManager.RUNTIME_PROPERTIES_LOCK) { Properties properties = new Properties(); try { // Open file, load properties, close file FileInputStream in = new FileInputStream(_configFile); properties.load(in); in.close(); // No such file } catch (FileNotFoundException exception) { Log.log_3301(exception, _configFile); // Security issue } catch (SecurityException exception) { Log.log_3302(exception, _configFile); // Other I/O error } catch (IOException exception) { Log.log_3303(exception, _configFile); } // Attempt to configure Log4J configureLogger(properties); // Convert to a PropertyReader PropertyReader pr = new PropertiesPropertyReader(properties); _runtimeProperties = new StatsPropertyReader(pr); } } } /** * Gets the runtime properties. * * @return * the runtime properties, never <code>null</code>. */ PropertyReader getRuntimeProperties() { if (_runtimeProperties == null) { return PropertyReaderUtils.EMPTY_PROPERTY_READER; } else { return _runtimeProperties; } } /** * Determines the reload interval for the config file, initializes the API * if the interval has changed and starts the config file watcher. */ void init() { // TODO: Check the state // Determine the reload interval int interval = APIServlet.DEFAULT_CONFIG_RELOAD_INTERVAL; if (_configFile != null) { try { interval = determineConfigReloadInterval(); // If the interval could not be parsed, then use the default } catch (InvalidPropertyValueException exception) { // ignore } } // Initialize the API boolean reinitialized = _engine.initAPI(); // Start the configuration file watch interval, if the location of the // file is set and the interval is greater than 0 if (_configFile != null && interval > 0) { startConfigFileWatcher(interval); } // Log each unused runtime property logUnusedRuntimeProperties(); // Re-initialized the framework if (reinitialized) { Log.log_3415(); } } /** * Logs the unused runtime properties. Properties for Log4J (those starting * with <code>"log4j."</code> are ignored. */ private void logUnusedRuntimeProperties() { if (_runtimeProperties != null) { Iterator unused = _runtimeProperties.getUnused().getNames(); while (unused.hasNext()) { String name = (String) unused.next(); if (name != null) { if (! name.startsWith("log4j.")) { Log.log_3434(name); } } } } } void startConfigFileWatcher(int interval) throws IllegalArgumentException { // TODO: Describe preconditions // Check preconditions if (_configFile == null || _configFile.length() < 1) { throw new IllegalStateException("Name of runtime configuration file not set."); } else if (_configFileWatcher != null) { throw new IllegalStateException("Runtime configuration file watcher exists."); } else if (interval < 1) { throw new IllegalArgumentException("interval (" + interval + ") < 1"); } // Create and start a file watch thread _configFileWatcher = new FileWatcher(_configFile, interval, _configFileListener); _configFileWatcher.start(); } /** * If the config file watcher == <code>null</code>, then the config file * listener will be re-initialized. If not the file watcher will be * interrupted. */ void reloadPropertiesIfChanged() { // TODO: Improve method description if (_configFileWatcher == null) { _configFileListener.reinit(); } else { _configFileWatcher.interrupt(); } } void configureLogger(Properties properties) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("properties", properties); // Reset Log4J configuration LogManager.getLoggerRepository().resetConfiguration(); // Reconfigure Log4J PropertyConfigurator.configure(properties); // Determine if Log4J is properly initialized Enumeration appenders = LogManager.getLoggerRepository().getRootLogger().getAllAppenders(); // If the properties did not include Log4J configuration settings, then // fallback to default settings if (appenders instanceof NullEnumeration) { Log.log_3304(_configFile); configureLoggerFallback(); // Otherwise log that custom Log4J configuration settings were applied } else { Log.log_3305(); } } /** * Determines the interval for checking the runtime properties file for * modifications. * * @return * the interval to use, always &gt;= 1. * * @throws InvalidPropertyValueException * if the interval cannot be determined because it does not qualify as a * positive 32-bit unsigned integer number. */ int determineConfigReloadInterval() throws InvalidPropertyValueException { // Check state if (_configFile == null || _configFile.length() < 1) { throw new IllegalStateException("Name of runtime configuration file not set."); } // Get the runtime property String prop = APIServlet.CONFIG_RELOAD_INTERVAL_PROPERTY; String s = _runtimeProperties.get(prop); int interval = -1; // If the property is set, parse it if (s != null && s.length() >= 1) { try { interval = Integer.parseInt(s); // Negative value if (interval < 0) { Log.log_3409(_configFile, prop, s); throw new InvalidPropertyValueException(prop, s, "Negative value."); // Non-negative value } else { Log.log_3410(_configFile, prop, s); } // Not a valid number string } catch (NumberFormatException nfe) { Log.log_3409(_configFile, prop, s); throw new InvalidPropertyValueException(prop, s, "Not a 32-bit integer number."); } // Property not set, use the default } else { Log.log_3408(_configFile, prop); interval = APIServlet.DEFAULT_CONFIG_RELOAD_INTERVAL; } return interval; } /** * Determines the log locale. * * @return * <code>false</code> if the specified locale is not supported, * <code>true</code> otherwise. */ boolean determineLogLocale() { // TODO: Determine what happens/should happen when there was a log // locale specified and then it was removed. String newLocale = null; // If we have runtime properties, then get the log locale if (_runtimeProperties != null) { newLocale = _runtimeProperties.get(LogCentral.LOG_LOCALE_PROPERTY); if (TextUtils.isEmpty(newLocale)) { newLocale = _runtimeProperties.get(APIServlet.LOG_LOCALE_PROPERTY); } } // If the log locale is set, apply it if (newLocale != null) { String currentLocale = LogCentral.getLocale(); if (!currentLocale.equals(newLocale)) { Log.log_3306(currentLocale, newLocale); try { LogCentral.setLocale(newLocale); Log.log_3307(currentLocale, newLocale); } catch (UnsupportedLocaleException exception) { Log.log_3308(currentLocale, newLocale); return false; } } } return true; } /** * Stops the config file watcher thread. */ void destroy() { // TODO: Change state of this object? // stop the FileWatcher if (_configFileWatcher != null) { _configFileWatcher.end(); } _configFileWatcher = null; } // Inner classes /** * Listener that reloads the configuration file if it changes. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) * * @since XINS 1.0.0 */ private final class ConfigurationFileListener extends Object implements FileWatcher.Listener { // Constructors /** * Constructs a new <code>ConfigurationFileListener</code> object. */ private ConfigurationFileListener() { // empty } // Fields // Methods /** * Re-initializes the framework. The run-time properties are re-read, * the configuration file reload interval is determined, the API is * re-initialized and then the new interval is applied to the watch * thread for the configuration file. */ private void reinit() { Log.log_3407(_configFile); boolean reinitialized; synchronized (RUNTIME_PROPERTIES_LOCK) { // Apply the new runtime settings to the logging subsystem readRuntimeProperties(); // Determine the interval int newInterval; try { newInterval = determineConfigReloadInterval(); } catch (InvalidPropertyValueException exception) { // Logging is already done in determineConfigReloadInterval() return; } // Re-initialize the API reinitialized = _engine.initAPI(); updateFileWatcher(newInterval); } // Log each unused runtime property logUnusedRuntimeProperties(); // Re-initialized the framework if (reinitialized) { Log.log_3415(); } } private void updateFileWatcher(int newInterval) throws IllegalStateException { // Check state if (_configFileWatcher == null) { throw new IllegalStateException("There is no configuration file watcher."); } // Update the file watch interval int oldInterval = _configFileWatcher.getInterval(); if (oldInterval != newInterval) { if (newInterval == 0 && _configFileWatcher != null) { _configFileWatcher.end(); _configFileWatcher = null; } else if (newInterval > 0 && _configFileWatcher == null) { _configFileWatcher = new FileWatcher(_configFile, newInterval, _configFileListener); _configFileWatcher.start(); } else { _configFileWatcher.setInterval(newInterval); Log.log_3403(_configFile, oldInterval, newInterval); } } } /** * Callback method called when the configuration file is found while it * was previously not found. * * <p>This will trigger re-initialization. */ public void fileFound() { reinit(); } /** * Callback method called when the configuration file is (still) not * found. * * <p>The implementation of this method does not perform any actions. */ public void fileNotFound() { Log.log_3400(_configFile); } /** * Callback method called when the configuration file is (still) not * modified. * * <p>The implementation of this method does not perform any actions. */ public void fileNotModified() { Log.log_3402(_configFile); } /** * Callback method called when the configuration file could not be * examined due to a <code>SecurityException</code>. * * <p>The implementation of this method does not perform any actions. * * @param exception * the caught security exception, should not be <code>null</code> * (although this is not checked). */ public void securityException(SecurityException exception) { Log.log_3401(exception, _configFile); } /** * Callback method called when the configuration file is modified since * the last time it was checked. * * <p>This will trigger re-initialization. */ public void fileModified() { reinit(); } } }
package org.jcoderz.phoenix.chart2d; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Dimension; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.Map.Entry; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import net.sourceforge.chart2d.Chart2D; import net.sourceforge.chart2d.Chart2DProperties; import net.sourceforge.chart2d.Dataset; import net.sourceforge.chart2d.GraphChart2D; import net.sourceforge.chart2d.GraphChart2DProperties; import net.sourceforge.chart2d.GraphProperties; import net.sourceforge.chart2d.LBChart2D; import net.sourceforge.chart2d.LLChart2D; import net.sourceforge.chart2d.LegendProperties; import net.sourceforge.chart2d.MultiColorsProperties; import net.sourceforge.chart2d.Object2DProperties; import net.sourceforge.chart2d.PieChart2D; import net.sourceforge.chart2d.PieChart2DProperties; import net.sourceforge.chart2d.WarningRegionProperties; import org.apache.xpath.XPathAPI; import org.apache.xpath.objects.XObject; import org.jcoderz.commons.types.Date; import org.jcoderz.commons.util.Constants; import org.jcoderz.commons.util.IoUtil; import org.jcoderz.commons.util.LoggingProxy; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.traversal.NodeIterator; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class Chart2DHandlerImpl implements Chart2DHandler { private static final int DEFAULT_WIDTH = 768; private static final int DEFAULT_HEIGHT = 1024; private static final int DEBUG_ARG_NUM = 3; private static final String TIME_PATTERN = "(([0-9]+) minutes? )?([0-9]+) seconds?"; private static final int TIME_PATTERN_MINUTES_GROUP = 2; private static final int TIME_PATTERN_SECONDS_GROUP = 3; private static boolean sDebug = false; private static boolean sMultible = false; private Object2DProperties mObject2DProperties; private Chart2DProperties mChart2DProperties; private GraphChart2DProperties mGraphChart2DProperties; private List mCurrentLabelText; private PieChart2DProperties mPieChart2DProperties; private LegendProperties mLegendProperties; private final List mDataSets = new ArrayList(); private final List mMultiColorsProperties = new ArrayList(); private final List mGraphProperties = new ArrayList(); private final List mWarningRegionProperties = new ArrayList(); private int mWidth = DEFAULT_WIDTH; private int mHeight = DEFAULT_HEIGHT; private String mFilename; private String mType; private List mCurrentDataSet; private List mCurrentSet; private List mCurrentCategory; private MultiColorsProperties mCurrentMultiColorsProperties; private List mCurrentMultiColors; private String mChartType; private List mCurrentLegendLabelsTexts; private boolean mDoConvertToStacked; private final File mDataRepository; private final Set mFilePatterns = new TreeSet(); private final List mXaxis = new ArrayList(); private int mXaxisModulus = 1; private final Map mXpathCache = new HashMap(); private DocumentBuilder mDocumentBuilder; /** * A new handler for cart2d files. * The repository directory is used to read input xml files and to * read and store a cache file. * * @param dataRepository the directory to the logfiles, * can be null. */ public Chart2DHandlerImpl (File dataRepository) { mDataRepository = dataRepository; if (mDataRepository != null) { collectPatterns(mDataRepository, null); if (mFilePatterns.isEmpty()) { throw new RuntimeException("No files found in repository path " + mDataRepository + "."); } readCache(); } } /** * Commandline interface to this handler. * Parameters should be * &lt;input file or dir> [context path] [debug] * * @param args args the commandline aruments. * @throws IOException if a io problem occures. */ public static void main (String[] args) throws IOException { File[] in; File para; if ((args.length < 1) || (args.length > DEBUG_ARG_NUM)) { String msg; msg = "Usage: java " + Chart2DHandlerImpl.class.getName() + " <input file or directory> [context path] [debug]"; log(msg); throw new IllegalArgumentException(msg); } if (args.length == DEBUG_ARG_NUM) { sDebug = true; } File dataRepository = null; if (args.length > 1) { if (args[1].equals("debug")) { sDebug = true; } else { dataRepository = new File(args[1]); } } if (sDebug) { final Handler[] handlers = Logger.getLogger("").getHandlers(); for (int index = 0; index < handlers.length; index++) { handlers[index].setLevel(Level.ALL); } Logger.getLogger("org.jcoderz.phoenix.chart2d").setLevel(Level.ALL); Logger.getLogger("").setLevel(Level.ALL); } para = new File(args[0]); if (para.isFile()) { in = new File[] {para}; } else { final FilenameFilter filter = new FilenameFilter() { public boolean accept (File dir, String name) { return name.endsWith(".xml"); } }; in = para.listFiles(filter); } sMultible = in.length > 1; final Iterator i = Arrays.asList(in).iterator(); while (i.hasNext()) { final File current = (File) i.next(); log("in: " + current.getAbsolutePath()); try { final Chart2DHandlerImpl handler = new Chart2DHandlerImpl(dataRepository); Chart2DHandler theHandler = handler; if (sDebug) { theHandler = (Chart2DHandler) LoggingProxy.getProxy(handler); } Chart2DParser.parse(new InputSource(new FileInputStream(current)), theHandler); handler.writeCache(); } catch (Exception ex) { log("Got exception", ex); } } log("Done."); } /** {@inheritDoc} */ public void handleGraphLabelsLinesStyle (final Attributes meta) throws SAXException { } /** * Handles opening of Category a new ArrayList is created to * collect inner Data elements. * @param meta the attributes that come with the element. * @throws SAXException never. */ public void startCategory (final Attributes meta) throws SAXException { if (mCurrentSet.size() < mCurrentLabelText.size()) { logDebug("startCategory x = " + mCurrentSet.size() + "/" + mCurrentLabelText.get(mCurrentSet.size())); } mCurrentCategory = new ArrayList(); } /** * Handles the closing of Category. * The Category data, containing the collected Data elements * is added to the corrent Set. * @throws SAXException never. */ public void endCategory () throws SAXException { if (mCurrentSet.size() < mCurrentLabelText.size()) { logDebug("endCategory x = " + mCurrentSet.size() + "/" + mCurrentLabelText.get(mCurrentSet.size())); } mCurrentSet.add(mCurrentCategory); mCurrentCategory = null; } /** * Handles opening of MultiColorsProperties. * @param meta the attributes that come with the element. * @throws SAXException never. */ public void startMultiColorsProperties (final Attributes meta) throws SAXException { final MultiColorsProperties props = new MultiColorsProperties(); props.setMultiColorsPropertiesToDefaults(); setProperties(props, meta); mCurrentMultiColorsProperties = props; mCurrentMultiColors = new ArrayList(); } /** * Handles the end of the MultiColorsProperties element. * Adds the collected MultiColors to the properties. * @throws SAXException never. */ public void endMultiColorsProperties () throws SAXException { if (!mCurrentMultiColors.isEmpty()) { mCurrentMultiColorsProperties .setColorsCustom((Color[]) mCurrentMultiColors .toArray(new Color[] {})); } mMultiColorsProperties.add(mCurrentMultiColorsProperties); mCurrentMultiColors = null; } /** * Handles opening of LBChart2D and registeres the chart type * accordingly. * @param meta the attributes that come with the element. * @throws SAXException never. */ public void startLBChart2D (final Attributes meta) throws SAXException { mChartType = "LBChart2D"; } /** {@inheritDoc} */ public void endLBChart2D () throws SAXException { } /** * Handles the content of the LegentLablesTexts element. * Special handling for xpath expressions is done here. * See {@link Chart2DHandlerImpl} for details. * @param data the element content. * @param meta attributes set with the element. * @throws SAXException if an error occurs. */ public void handleLegendLabelsTexts (final String data, final Attributes meta) throws SAXException { if (data.startsWith("!")) { try { final DocumentBuilder builder = getDocumentBuilder(); final Document document = builder.parse( new File(mDataRepository, ((Pair) mXaxis.get(mXaxis.size() - 1)).getFileName())); final NodeIterator i = XPathAPI.selectNodeIterator( document, data.substring(1)); Node node = i.nextNode(); while (node != null) { logDebug("Legend Label: " + node.getNodeValue()); mCurrentLegendLabelsTexts.add(node.getNodeValue()); node = i.nextNode(); } } catch (Exception ex) { final SAXException e = new SAXException(ex); e.initCause(ex); throw e; } } else { mCurrentLegendLabelsTexts.add(data); } } /** {@inheritDoc} */ public void startDataset (final Attributes meta) throws SAXException { mDoConvertToStacked = meta.getIndex("DoConvertToStacked") != -1; mCurrentDataSet = new ArrayList(); } /** * Called at the end of a dataset. * The collected data is passed to chart2d. * @throws SAXException if an error occures. */ public void endDataset () throws SAXException { final int zSize = ((List) ((List) mCurrentDataSet.get(0)).get(0)).size(); final int ySize = ((List) mCurrentDataSet.get(0)).size(); final Dataset dataset = new Dataset(mCurrentDataSet.size(), ySize, zSize); if (!sMultible) { log("Dimension: [" + mCurrentDataSet.size() + "][" + ySize + "][" + zSize + "]"); } Iterator i; Iterator j; Iterator k; int x; int y; int z; x = 0; i = mCurrentDataSet.iterator(); while (i.hasNext()) { y = 0; j = ((List) i.next()).iterator(); while (j.hasNext()) { z = 0; k = ((List) j.next()).iterator(); while (k.hasNext()) { final float f = ((Float) k.next()).floatValue(); if (!sMultible) { log("point[" + x + "/" + mCurrentLegendLabelsTexts.get(x) + "][" + y + "/" + mCurrentLabelText.get(y) + "][" + z + "] = " + f); } dataset.set(x, y, z, f); z++; } y++; } x++; } if (mDoConvertToStacked) { dataset.doConvertToStacked(); } mDataSets.add(dataset); mCurrentDataSet = null; } /** {@inheritDoc} */ public void handlePieChart2DProperties (final Attributes meta) throws SAXException { mPieChart2DProperties = new PieChart2DProperties(); mPieChart2DProperties.setPieChart2DPropertiesToDefaults(); setProperties(mPieChart2DProperties, meta); } /** {@inheritDoc} */ public void startGraphChart2DProperties (final Attributes meta) throws SAXException { mGraphChart2DProperties = new GraphChart2DProperties(); mGraphChart2DProperties.setGraphChart2DPropertiesToDefaults(); setProperties(mGraphChart2DProperties, meta); mCurrentLabelText = new ArrayList(); } /** {@inheritDoc} */ public void endGraphChart2DProperties () throws SAXException { if (!mCurrentLabelText.isEmpty()) { mGraphChart2DProperties .setLabelsAxisLabelsTexts((String[]) mCurrentLabelText .toArray(new String[] {})); } } /** {@inheritDoc} */ public void handleAxisLabelText (final java.lang.String data, final Attributes meta) throws SAXException { if (data.startsWith("!")) { // Maximum number of builds aggregated in one label final int max = Integer.parseInt(meta.getValue("max")); // number of labels final int count = Integer.parseInt(meta.getValue("count")); Collection map = fileMatcher(data.substring(1)); int size = map.size(); if (size == 0) { throw new RuntimeException("No files found for pattern " + data + " in " + mDataRepository + "."); } if (size > max * count) { final List newList = new ArrayList(max * count); final Iterator it = map.iterator(); int remove = size - (max * count); while (remove > 0) { it.next(); remove } while (it.hasNext()) { newList.add(it.next()); } map = newList; size = map.size(); } mXaxisModulus = Math.max(1, size / count); logDebug("Will have " + mXaxisModulus + " enties per category."); mXaxis.addAll(map); final Iterator i = map.iterator(); int xPos = 0; while (i.hasNext()) { final String label = ((Pair) i.next()).getLabel(); if (xPos % mXaxisModulus == 0) { logDebug("X-Label: " + label); mCurrentLabelText.add(label); } xPos++; } } else { mCurrentLabelText.add(data); } } private List fileMatcher (String filePattern) { final List result = new ArrayList(); final Pattern pattern = Pattern.compile(filePattern); final Iterator i = mFilePatterns.iterator(); while (i.hasNext()) { final String fileName = (String) i.next(); final Matcher m = pattern.matcher(fileName); if (m.matches()) { result.add(new Pair(fileName, m.group(1))); } } return result; } /** {@inheritDoc} */ public void startChart2D (final Attributes meta) throws SAXException { String value; value = meta.getValue("Width"); if (value != null) { mWidth = Integer.decode(value).intValue(); } value = meta.getValue("Height"); if (value != null) { mHeight = Integer.decode(value).intValue(); } value = meta.getValue("Type"); if (value != null) { mType = value; } value = meta.getValue("Filename"); if (value != null) { mFilename = value; } } /** {@inheritDoc} */ public void endChart2D () throws SAXException { try { Chart2D chart2d = null; if ("PieChart2D".equals(mChartType)) { final PieChart2D chart = new PieChart2D(); chart.setObject2DProperties(mObject2DProperties); chart.setChart2DProperties(mChart2DProperties); chart.setPieChart2DProperties(mPieChart2DProperties); chart.setLegendProperties(mLegendProperties); chart.setDataset((Dataset) mDataSets.get(0)); chart.setMultiColorsProperties( (MultiColorsProperties) mMultiColorsProperties.get(0)); chart2d = chart; } else if ("LLChart2D".equals(mChartType)) { final LLChart2D chart = new LLChart2D(); fillChartData(chart); chart2d = chart; } else if ("LBChart2D".equals(mChartType)) { final LBChart2D chart = new LBChart2D(); fillChartData(chart); chart2d = chart; } else { throw new SAXException("Unknown chart type " + mChartType + "."); } final Dimension size = new Dimension(mWidth, mHeight); chart2d.setMaximumSize(size); chart2d.setPreferredSize(size); if (chart2d.validate(false)) { javax.imageio.ImageIO.write(chart2d.getImage(), mType, new File( mFilename)); log("out: " + new File(mFilename).getAbsolutePath()); } else { chart2d.validate(true); } } catch (Exception ex) { final SAXException e = new SAXException(ex); e.initCause(ex); throw e; } } /** {@inheritDoc} */ public void startLLChart2D (final Attributes meta) throws SAXException { mChartType = "LLChart2D"; } /** {@inheritDoc} */ public void endLLChart2D () throws SAXException { } /** {@inheritDoc} */ public void handleGraphNumbersLinesStyle (final Attributes meta) throws SAXException { } /** {@inheritDoc} */ public void handleData (final java.lang.String data, final Attributes meta) throws SAXException { if (data.startsWith("!")) { // LOOPIT final Iterator z = mCurrentLegendLabelsTexts.iterator(); while (z.hasNext()) { final String zValue = (String) z.next(); int xPos = 0; final Iterator x = mXaxis.iterator(); while (x.hasNext()) { final Pair pair = (Pair) x.next(); final String fileName = pair.getFileName(); String query = data.substring(1); query = query.replaceAll("\\$z", zValue); String value = resolveXpath(fileName, query); if (value.length() == 0) { value = "0"; } else if (value.indexOf("second") != -1) { value = parseAntTime(value); } mCurrentCategory.add(new Float(Float.parseFloat(value))); xPos++; while (xPos % mXaxisModulus != 0 && !x.hasNext()) { xPos++; // continue chart with last value. mCurrentCategory.add(new Float(Float.parseFloat(value))); } if ((xPos % mXaxisModulus == 0 && x.hasNext()) || (!x.hasNext() && z.hasNext())) { endCategory(); // it is save to call startCategory without a entry... startCategory(null); } } if (z.hasNext()) { endSet(); startSet(null); startCategory(null); } } } else { mCurrentCategory.add(new Float(Float.parseFloat(data))); } } private String parseAntTime (String value) { final Pattern pat = Pattern.compile(TIME_PATTERN); final Matcher mat = pat.matcher(value); logDebug("grops " + value); String result = value; if (mat.matches()) { int minutes = 0; int seconds = 0; if (mat.group(TIME_PATTERN_MINUTES_GROUP) != null) { minutes = Integer.parseInt( mat.group(TIME_PATTERN_MINUTES_GROUP)); } if (mat.group(TIME_PATTERN_SECONDS_GROUP) != null) { seconds = Integer.parseInt( mat.group(TIME_PATTERN_SECONDS_GROUP)); } result = String.valueOf( Date.SECONDS_PER_MINUTE * minutes + seconds); } return result; } private String resolveXpath (String fileName, String xpath) throws SAXException { logDebug(xpath + " in " + fileName); String result = null; final String cacheKey = xpath + "@" + fileName; result = (String) mXpathCache.get(cacheKey); if (result == null) { try { final DocumentBuilder builder = getDocumentBuilder(); final Document document = builder.parse(new File(mDataRepository, fileName)); final XObject object = XPathAPI.eval(document, xpath); result = object.str(); } catch (Exception ex) { final SAXException e = new SAXException(ex); e.initCause(ex); throw e; } logDebug(" = " + result); mXpathCache.put(cacheKey, result); } else { logDebug(" = " + result + " (cached)"); } return result; } /** {@inheritDoc} */ public void startPieChart2D (final Attributes meta) throws SAXException { mChartType = "PieChart2D"; } /** {@inheritDoc} */ public void endPieChart2D () throws SAXException { } /** {@inheritDoc} */ public void handleObject2DProperties (final Attributes meta) throws SAXException { mObject2DProperties = new Object2DProperties(); mObject2DProperties.setObject2DPropertiesToDefaults(); setProperties(mObject2DProperties, meta); } /** {@inheritDoc} */ public void handleWarningRegionProperties (final Attributes meta) throws SAXException { final WarningRegionProperties props = new WarningRegionProperties(); props.setToDefaults(); setProperties(props, meta); } /** {@inheritDoc} */ public void handleChart2DProperties (final Attributes meta) throws SAXException { mChart2DProperties = new Chart2DProperties(); mChart2DProperties.setChart2DPropertiesToDefaults(); setProperties(mChart2DProperties, meta); } /** {@inheritDoc} */ public void startSet (final Attributes meta) throws SAXException { if (mCurrentDataSet.size() < mCurrentLegendLabelsTexts.size()) { logDebug("startSet z = " + mCurrentDataSet.size() + "/" + mCurrentLegendLabelsTexts.get(mCurrentDataSet.size())); } mCurrentSet = new ArrayList(); } /** {@inheritDoc} */ public void endSet () throws SAXException { if (mCurrentDataSet.size() < mCurrentLegendLabelsTexts.size()) { logDebug("endSet z = " + mCurrentDataSet.size() + "/" + mCurrentLegendLabelsTexts.get(mCurrentDataSet.size())); } mCurrentDataSet.add(mCurrentSet); mCurrentSet = null; } /** {@inheritDoc} */ public void startGraphProperties (final Attributes meta) throws SAXException { final GraphProperties props = new GraphProperties(); props.setGraphPropertiesToDefaults(); setProperties(props, meta); mGraphProperties.add(props); } /** {@inheritDoc} */ public void endGraphProperties () throws SAXException { } /** {@inheritDoc} */ public void handleColorsCustom (final java.lang.String data, final Attributes meta) throws SAXException { mCurrentMultiColors.add(getColor(data)); } /** {@inheritDoc} */ public void startLegendProperties (final Attributes meta) throws SAXException { mLegendProperties = new LegendProperties(); mLegendProperties.setLegendPropertiesToDefaults(); mCurrentLegendLabelsTexts = new ArrayList(); } /** {@inheritDoc} */ public void endLegendProperties () throws SAXException { if (!mCurrentLegendLabelsTexts.isEmpty()) { mLegendProperties .setLegendLabelsTexts((String[]) mCurrentLegendLabelsTexts .toArray(new String[] {})); } } private void setProperties (Object props, final Attributes meta) { int i = meta.getLength() - 1; for (; i >= 0; i { final String key = meta.getQName(i); final String value = meta.getValue(i); Method m; final String setterName = "set" + key; try { m = props.getClass().getDeclaredMethod(setterName, new Class[] {String.class}); m.invoke(props, new Object[] {value}); } catch (Exception ex) { m = null; } if (m == null) { try { m = props.getClass().getDeclaredMethod(setterName, new Class[] {Boolean.TYPE}); m.invoke(props, new Object[] {Boolean.valueOf(value)}); } catch (Exception ex) { m = null; } } if (m == null) { try { m = props.getClass().getDeclaredMethod(setterName, new Class[] {Integer.TYPE}); m.invoke(props, new Object[] {getInteger(value, props)}); } catch (Exception ex) { m = null; } } if (m == null) { try { m = props.getClass().getDeclaredMethod(setterName, new Class[] {Color.class}); m.invoke(props, new Object[] {getColor(value)}); } catch (Exception ex) { m = null; } } if (m == null) { try { m = props.getClass().getDeclaredMethod(setterName, new Class[] {Float.TYPE}); m.invoke(props, new Object[] {Float.valueOf(value)}); } catch (Exception ex) { m = null; } } if (m == null) { try { m = props.getClass().getDeclaredMethod(setterName, new Class[] {Dimension.class}); m.invoke(props, new Object[] {getDimension(value)}); } catch (Exception ex) { m = null; } } if (m == null) { try { m = props.getClass().getDeclaredMethod(setterName, new Class[] {java.awt.AlphaComposite.class}); m.invoke(props, new Object[] {getAlphaComposite(value, props)}); } catch (Exception ex) { m = null; } } if (m == null) { log("Could not set " + props.getClass().getName() + "." + setterName + " = " + value); } } } private Color getColor (String col) { Color c = null; try { try { c = Color.decode(col); } catch (Exception ex) { final Field f = Color.class.getField(col); c = (Color) f.get(null); } } catch (Exception ex) { // no match } return c; } private Dimension getDimension (String val) { final double w = Double.parseDouble(val.substring(0, val.indexOf('x'))); final double h = Double.parseDouble(val.substring(1 + val.indexOf('x'))); final Dimension d = new Dimension(); d.setSize(w, h); return d; } private Integer getInteger (String value, Object properties) throws Exception { int i; try { i = Integer.decode(value).intValue(); } catch (Exception ex) { try { final Field f = properties.getClass().getField(value); i = f.getInt(null); } catch (Exception exx) { final Field f = java.awt.Font.class.getField(value); i = f.getInt(null); } } return new Integer(i); } private AlphaComposite getAlphaComposite (String value, Object properties) throws Exception { AlphaComposite alpha = null; try { final Field f = properties.getClass().getField( value.toUpperCase(Constants.SYSTEM_LOCALE)); alpha = (AlphaComposite) f.get(null); } catch (Exception exx) { try { final Field f = AlphaComposite.class.getField( value.toUpperCase(Constants.SYSTEM_LOCALE)); alpha = AlphaComposite.getInstance(f.getInt(null)); } catch (Exception ex) { try { final Field f = AlphaComposite.class.getField(value); alpha = (AlphaComposite) f.get(null); } catch (Exception exxx) { // no match } } } return alpha; } private void fillChartData (final GraphChart2D chart) { chart.setObject2DProperties(mObject2DProperties); chart.setChart2DProperties(mChart2DProperties); chart.setGraphChart2DProperties(mGraphChart2DProperties); chart.setLegendProperties(mLegendProperties); Iterator i = mDataSets.iterator(); while (i.hasNext()) { chart.addDataset((Dataset) i.next()); } i = mMultiColorsProperties.iterator(); while (i.hasNext()) { chart.addMultiColorsProperties((MultiColorsProperties) i.next()); } i = mGraphProperties.iterator(); while (i.hasNext()) { chart.addGraphProperties((GraphProperties) i.next()); } i = mWarningRegionProperties.iterator(); while (i.hasNext()) { chart.addWarningRegionProperties( (WarningRegionProperties) i.next()); } } /** * Reads the xpath query cache if possible. */ private void readCache () { BufferedReader reader = null; try { final File inFile = new File(mDataRepository, "stat-cache"); if (inFile.canRead()) { reader = new BufferedReader(new FileReader(inFile)); String line = reader.readLine(); while (line != null) { if (line.length() > 0) { final String[] data = line.split("\t"); if (data.length > 1) { mXpathCache.put(data[0], data[1]); } else { mXpathCache.put(data[0], ""); } line = reader.readLine(); } } } } catch (IOException ex) { throw new RuntimeException("Failed to read cache.", ex); } finally { IoUtil.close(reader); } } /** * Writes the xpath query cache if possible. */ public void writeCache () { if (mDataRepository != null) { BufferedWriter writer = null; try { final File file = new File(mDataRepository, "stat-cache"); writer = new BufferedWriter(new FileWriter(file, false)); final Iterator i = mXpathCache.entrySet().iterator(); while (i.hasNext()) { final Entry entry = (Entry) i.next(); writer.write((String) entry.getKey()); writer.write('\t'); writer.write((String) entry.getValue()); writer.write('\n'); } } catch (IOException ex) { throw new RuntimeException("Failed to write cache.", ex); } finally { IoUtil.close(writer); } } } /** * Collects files available in the given path. * @param dataRepository the path to look in * @param path the pattern representation of the path; */ private void collectPatterns (File dataRepository, String path) { final String thisPath; if (path == null) { thisPath = ""; } else { thisPath = path + "/" + dataRepository.getName(); } if (dataRepository.isFile()) { mFilePatterns.add(thisPath); } else if (dataRepository.isDirectory()) { final File[] sub = dataRepository.listFiles(); for (int i = 0; i < sub.length; i++) { collectPatterns(sub[i], thisPath); } } } /** Returns the lazy initialized document builder. */ private DocumentBuilder getDocumentBuilder () throws ParserConfigurationException { if (mDocumentBuilder == null) { mDocumentBuilder = DocumentBuilderFactory.newInstance(). newDocumentBuilder(); } return mDocumentBuilder; } private static void log (String data) { System.out.println(data); } private static void log (String data, Throwable thr) { System.out.println(data + thr.getMessage()); thr.printStackTrace(System.out); } private static void logDebug (String data) { if (sDebug) { log(data); } } private static class Pair { private final String mFileName; private final String mLabel; public Pair (final String fileName, final String label) { super(); mFileName = fileName; mLabel = label; } public String getFileName () { return mFileName; } public String getLabel () { return mLabel; } } }