answer
stringlengths 17
10.2M
|
|---|
package com.docusign.esign.client;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.joda.*;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.LoggingFilter;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.file.FileDataBodyPart;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import javax.ws.rs.core.Response.Status.Family;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;
import java.net.URLEncoder;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import com.docusign.esign.client.auth.Authentication;
import com.docusign.esign.client.auth.HttpBasicAuth;
import com.docusign.esign.client.auth.JWTUtils;
import com.docusign.esign.client.auth.ApiKeyAuth;
import com.docusign.esign.client.auth.OAuth;
import com.docusign.esign.client.auth.AccessTokenListener;
import com.docusign.esign.client.auth.OAuthFlow;
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2017-03-06T16:42:36.211-08:00")
public class ApiClient {
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private String basePath = "https:
private boolean debugging = false;
private int connectionTimeout = 0;
private int readTimeout = 0;
private Client httpClient;
private ObjectMapper mapper;
private Map<String, Authentication> authentications;
private int statusCode;
private Map<String, List<String>> responseHeaders;
private DateFormat dateFormat;
public ApiClient() {
mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
mapper.registerModule(new JodaModule());
httpClient = buildHttpClient(debugging);
// Use RFC3339 format for date and datetime.
// See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
// Use UTC as the default time zone.
this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
this.mapper.setDateFormat((DateFormat) dateFormat.clone());
// Set default User-Agent.
setUserAgent("Java-Swagger");
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();
}
public ApiClient(String basePath) {
this();
this.basePath = basePath;
}
public ApiClient(String oAuthBasePath, String[] authNames) {
this();
for(String authName : authNames) {
Authentication auth;
if (authName == "docusignAccessCode") {
auth = new OAuth(httpClient, OAuthFlow.accessCode, oAuthBasePath + "/oauth/auth", oAuthBasePath + "/oauth/token", "all");
} else if (authName == "docusignApiKey") {
auth = new ApiKeyAuth("header", "docusignApiKey");
} else {
throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");
}
addAuthorization(authName, auth);
}
}
/**
* Basic constructor for single auth name
* @param authName
*/
public ApiClient(String oAuthBasePath, String authName) {
this(oAuthBasePath, new String[]{authName});
}
/**
* Helper constructor for OAuth2
* @param oAuthBasePath The API base path
* @param authName the authentication method name ("oauth" or "api_key")
* @param clientId OAuth2 Client ID
* @param secret OAuth2 Client secret
*/
public ApiClient(String oAuthBasePath, String authName, String clientId, String secret) {
this(oAuthBasePath, authName);
this.getTokenEndPoint()
.setClientId(clientId)
.setClientSecret(secret);
}
public String getBasePath() {
return basePath;
}
public ApiClient setBasePath(String basePath) {
this.basePath = basePath;
return this;
}
/**
* Gets the status code of the previous request
*/
public int getStatusCode() {
return statusCode;
}
/**
* Gets the response headers of the previous request
*/
public Map<String, List<String>> getResponseHeaders() {
return responseHeaders;
}
/**
* Get authentications (key: authentication name, value: authentication).
*/
public Map<String, Authentication> getAuthentications() {
return authentications;
}
/**
* Get authentication for the given name.
*
* @param authName The authentication name
* @return The authentication, null if not found
*/
public Authentication getAuthentication(String authName) {
return authentications.get(authName);
}
public void addAuthorization(String authName, Authentication auth) {
authentications.put(authName, auth);
}
/**
* Helper method to set username for the first HTTP basic authentication.
*/
public void setUsername(String username) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setUsername(username);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set password for the first HTTP basic authentication.
*/
public void setPassword(String password) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPassword(password);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set API key value for the first API key authentication.
*/
public void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set API key prefix for the first API key authentication.
*/
public void setApiKeyPrefix(String apiKeyPrefix) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Set the User-Agent header's value (by adding to the default header map).
*/
public ApiClient setUserAgent(String userAgent) {
addDefaultHeader("User-Agent", userAgent);
return this;
}
public void updateAccessToken() {
for (Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
((OAuth) auth).updateAccessToken();
return;
}
}
throw new RuntimeException("No OAuth2 authentication configured!");
}
/**
* Helper method to preset the OAuth access token of the first OAuth found in the apiAuthorizations (there should be only one)
* @param accessToken OAuth access token
* @param expiresIn Validity period in seconds
*/
public void setAccessToken(final String accessToken, Long expiresIn) {
for (Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
((OAuth) auth).setAccessToken(accessToken, expiresIn);
return;
}
}
addAuthorization("docusignAccessCode", new Authentication() {
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams) {
headerParams.put("Authorization", "Bearer " + accessToken);
}
});
//throw new RuntimeException("No OAuth2 authentication configured!");
}
/**
* Add a default header.
*
* @param key The header's key
* @param value The header's value
*/
public ApiClient addDefaultHeader(String key, String value) {
defaultHeaderMap.put(key, value);
return this;
}
/**
* Check that whether debugging is enabled for this API client.
*/
public boolean isDebugging() {
return debugging;
}
/**
* Enable/disable debugging for this API client.
*
* @param debugging To enable (true) or disable (false) debugging
*/
public ApiClient setDebugging(boolean debugging) {
this.debugging = debugging;
// Rebuild HTTP Client according to the new "debugging" value.
this.httpClient = buildHttpClient(debugging);
return this;
}
/**
* Connect timeout (in milliseconds).
*/
public int getConnectTimeout() {
return connectionTimeout;
}
/**
* Set the connect timeout (in milliseconds).
* A value of 0 means no timeout, otherwise values must be between 1 and
* {@link Integer#MAX_VALUE}.
*/
public ApiClient setConnectTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
httpClient.setConnectTimeout(connectionTimeout);
return this;
}
/**
* Read timeout (in milliseconds).
*/
public int getReadTimeout() {
return readTimeout;
}
/**
* Set the read timeout (in milliseconds).
* A value of 0 means no timeout, otherwise values must be between 1 and
* {@link Integer#MAX_VALUE}.
*/
public ApiClient setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
httpClient.setReadTimeout(readTimeout);
return this;
}
/**
* Get the date format used to parse/format date parameters.
*/
public DateFormat getDateFormat() {
return dateFormat;
}
/**
* Set the date format used to parse/format date parameters.
*/
public ApiClient setDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
// also set the date format for model (de)serialization with Date properties
this.mapper.setDateFormat((DateFormat) dateFormat.clone());
return this;
}
/**
* Helper method to configure the token endpoint of the first oauth found in the authentications (there should be only one)
* @return
*/
public TokenRequestBuilder getTokenEndPoint() {
for(Authentication auth : getAuthentications().values()) {
if (auth instanceof OAuth) {
OAuth oauth = (OAuth) auth;
return oauth.getTokenRequestBuilder();
}
}
return null;
}
/**
* Helper method to configure authorization endpoint of the first oauth found in the authentications (there should be only one)
* @return
*/
public AuthenticationRequestBuilder getAuthorizationEndPoint() {
for(Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
OAuth oauth = (OAuth) auth;
return oauth.getAuthenticationRequestBuilder();
}
}
return null;
}
/**
* Helper method to configure the OAuth accessCode/implicit flow parameters
* @param clientId OAuth2 client ID
* @param clientSecret OAuth2 client secret
* @param redirectURI OAuth2 redirect uri
*/
public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) {
for(Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
OAuth oauth = (OAuth) auth;
oauth.getTokenRequestBuilder()
.setClientId(clientId)
.setClientSecret(clientSecret)
.setRedirectURI(redirectURI);
oauth.getAuthenticationRequestBuilder()
.setClientId(clientId)
.setRedirectURI(redirectURI);
return;
}
}
}
public String getAuthorizationUri() throws OAuthSystemException {
return getAuthorizationEndPoint().buildQueryMessage().getLocationUri();
}
/**
* Configures a listener which is notified when a new access token is received.
* @param accessTokenListener
*/
public void registerAccessTokenListener(AccessTokenListener accessTokenListener) {
for(Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
OAuth oauth = (OAuth) auth;
oauth.registerAccessTokenListener(accessTokenListener);
return;
}
}
}
/**
* Helper method to build the OAuth JWT grant uri (used once to get a user consent for impersonation)
* @param clientId OAuth2 client ID
* @param redirectURI OAuth2 redirect uri
* @return the OAuth JWT grant uri as a String
*/
public String getJWTUri(String clientId, String redirectURI, String oAuthBasePath) {
return UriBuilder.fromUri(oAuthBasePath)
.scheme("https")
.path("/oauth/auth")
.queryParam("response_type", "code")
.queryParam("scope", "signature%20impersonation")
.queryParam("client_id", clientId)
.queryParam("redirect_uri", redirectURI)
.build().toString();
}
/**
* Configures the current instance of ApiClient with a fresh OAuth JWT access token from DocuSign
* @param publicKeyFilename the filename of the RSA public key
* @param privateKeyFilename the filename of the RSA private key
* @param oAuthBasePath DocuSign OAuth base path (account-d.docusign.com for the developer sandbox
and account.docusign.com for the production platform)
* @param clientId DocuSign OAuth Client Id (AKA Integrator Key)
* @param userId DocuSign user Id to be impersonated (This is a UUID)
* @param expiresIn in seconds for the token time-to-live
* @throws IOException if there is an issue with either the public or private file
* @throws ApiException if there is an error while exchanging the JWT with an access token
*/
public void configureJWTAuthorizationFlow(String publicKeyFilename, String privateKeyFilename, String oAuthBasePath, String clientId, String userId, long expiresIn) throws IOException, ApiException {
try {
String assertion = JWTUtils.generateJWTAssertion(publicKeyFilename, privateKeyFilename, oAuthBasePath, clientId, userId, expiresIn);
MultivaluedMap<String, String> form = new MultivaluedMapImpl();
form.add("assertion", assertion);
form.add("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
Client client = Client.create();
WebResource webResource = client.resource("https://" + oAuthBasePath + "/oauth/token");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, form);
ObjectMapper mapper = new ObjectMapper();
JsonNode responseJson = mapper.readValue(response.getEntityInputStream(), JsonNode.class);
if (!responseJson.has("access_token") || !responseJson.has("expires_in")) {
throw new ApiException("Error while requesting an access token: " + responseJson);
}
String accessToken = responseJson.get("access_token").asText();
expiresIn = responseJson.get("expires_in").asLong();
setAccessToken(accessToken, expiresIn);
} catch (JsonParseException e) {
throw new ApiException("Error while parsing the response for the access token.");
} catch (JsonMappingException e) {
throw e;
} catch (IOException e) {
throw e;
}
}
/**
* Parse the given string into Date object.
*/
public Date parseDate(String str) {
try {
return dateFormat.parse(str);
} catch (java.text.ParseException e) {
throw new RuntimeException(e);
}
}
/**
* Format the given Date object into string.
*/
public String formatDate(Date date) {
return dateFormat.format(date);
}
/**
* Format the given parameter object into string.
*/
public String parameterToString(Object param) {
if (param == null) {
return "";
} else if (param instanceof Date) {
return formatDate((Date) param);
} else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for(Object o : (Collection<?>)param) {
if(b.length() > 0) {
b.append(",");
}
b.append(String.valueOf(o));
}
return b.toString();
} else {
return String.valueOf(param);
}
}
/*
Format to {@code Pair} objects.
*/
public List<Pair> parameterToPairs(String collectionFormat, String name, Object value){
List<Pair> params = new ArrayList<Pair>();
// preconditions
if (name == null || name.isEmpty() || value == null) return params;
Collection<?> valueCollection = null;
if (value instanceof Collection<?>) {
valueCollection = (Collection<?>) value;
} else {
params.add(new Pair(name, parameterToString(value)));
return params;
}
if (valueCollection.isEmpty()){
return params;
}
// get the collection format
collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv
// create the params based on the collection format
if (collectionFormat.equals("multi")) {
for (Object item : valueCollection) {
params.add(new Pair(name, parameterToString(item)));
}
return params;
}
String delimiter = ",";
if (collectionFormat.equals("csv")) {
delimiter = ",";
} else if (collectionFormat.equals("ssv")) {
delimiter = " ";
} else if (collectionFormat.equals("tsv")) {
delimiter = "\t";
} else if (collectionFormat.equals("pipes")) {
delimiter = "|";
}
StringBuilder sb = new StringBuilder() ;
for (Object item : valueCollection) {
sb.append(delimiter);
sb.append(parameterToString(item));
}
params.add(new Pair(name, sb.substring(1)));
return params;
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
*/
public boolean isJsonMime(String mime) {
return mime != null && mime.matches("(?i)application\\/json(;.*)?");
}
/**
* Select the Accept header's value from the given accepts array:
* if JSON exists in the given array, use it;
* otherwise use all of them (joining into a string)
*
* @param accepts The accepts array to select from
* @return The Accept header to use. If the given array is empty,
* null will be returned (not to set the Accept header explicitly).
*/
public String selectHeaderAccept(String[] accepts) {
if (accepts.length == 0) {
return null;
}
for (String accept : accepts) {
if (isJsonMime(accept)) {
return accept;
}
}
return StringUtil.join(accepts, ",");
}
/**
* Select the Content-Type header's value from the given array:
* if JSON exists in the given array, use it;
* otherwise use the first one of the array.
*
* @param contentTypes The Content-Type array to select from
* @return The Content-Type header to use. If the given array is empty,
* JSON will be used.
*/
public String selectHeaderContentType(String[] contentTypes) {
if (contentTypes.length == 0) {
return "application/json";
}
for (String contentType : contentTypes) {
if (isJsonMime(contentType)) {
return contentType;
}
}
return contentTypes[0];
}
/**
* Escape the given string to be used as URL query value.
*/
public String escapeString(String str) {
try {
return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
} catch (UnsupportedEncodingException e) {
return str;
}
}
/**
* Serialize the given Java object into string according the given
* Content-Type (only JSON is supported for now).
*/
public Object serialize(Object obj, String contentType, Map<String, Object> formParams) throws ApiException {
if (contentType.startsWith("multipart/form-data")) {
FormDataMultiPart mp = new FormDataMultiPart();
for (Entry<String, Object> param: formParams.entrySet()) {
if (param.getValue() instanceof File) {
File file = (File) param.getValue();
mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE));
} else {
mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE);
}
}
return mp;
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
return this.getXWWWFormUrlencodedParams(formParams);
} else {
// We let Jersey attempt to serialize the body
return obj;
}
}
/**
* Build full URL by concatenating base path, the given sub path and query parameters.
*
* @param path The sub path
* @param queryParams The query parameters
* @return The full URL
*/
private String buildUrl(String path, List<Pair> queryParams) {
final StringBuilder url = new StringBuilder();
url.append(basePath).append(path);
if (queryParams != null && !queryParams.isEmpty()) {
// support (constant) query string in `path`, e.g. "/posts?draft=1"
String prefix = path.contains("?") ? "&" : "?";
for (Pair param : queryParams) {
if (param.getValue() != null) {
if (prefix != null) {
url.append(prefix);
prefix = null;
} else {
url.append("&");
}
String value = parameterToString(param.getValue());
url.append(escapeString(param.getName())).append("=").append(escapeString(value));
}
}
}
return url.toString();
}
private ClientResponse getAPIResponse(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames) throws ApiException {
if (body != null && !formParams.isEmpty()) {
throw new ApiException(500, "Cannot have body and form params");
}
updateParamsForAuth(authNames, queryParams, headerParams);
final String url = buildUrl(path, queryParams);
Builder builder;
if (accept == null) {
builder = httpClient.resource(url).getRequestBuilder();
} else {
builder = httpClient.resource(url).accept(accept);
}
for (String key : headerParams.keySet()) {
builder = builder.header(key, headerParams.get(key));
}
for (String key : defaultHeaderMap.keySet()) {
if (!headerParams.containsKey(key)) {
builder = builder.header(key, defaultHeaderMap.get(key));
}
}
// Add DocuSign Tracking Header
builder = builder.header("X-DocuSign-SDK", "Java");
if (body == null) {
builder = builder.header("Content-Length", "0");
}
ClientResponse response = null;
if ("GET".equals(method)) {
response = (ClientResponse) builder.get(ClientResponse.class);
} else if ("POST".equals(method)) {
response = builder.type(contentType).post(ClientResponse.class, serialize(body, contentType, formParams));
} else if ("PUT".equals(method)) {
response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType, formParams));
} else if ("DELETE".equals(method)) {
response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType, formParams));
} else {
throw new ApiException(500, "unknown method type " + method);
}
return response;
}
/**
* Invoke API by sending HTTP request with the given options.
*
* @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
* @param queryParams The query parameters
* @param body The request body object - if it is not binary, otherwise null
* @param headerParams The header parameters
* @param formParams The form parameters
* @param accept The request's Accept header
* @param contentType The request's Content-Type header
* @param authNames The authentications to apply
* @return The response body in type of string
*/
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String accept, String contentType, String[] authNames, GenericType<T> returnType) throws ApiException {
ClientResponse response = getAPIResponse(path, method, queryParams, body, headerParams, formParams, accept, contentType, authNames);
if (response.getStatusInfo().getFamily() != Family.SUCCESSFUL) {
String respBody = null;
respBody = response.getEntity(String.class);
throw new ApiException(
response.getStatusInfo().getStatusCode(),
"Error while requesting server, received a non successful HTTP code " + response.getStatusInfo().getStatusCode() + " with response Body: '" + respBody + "'",
response.getHeaders(),
respBody);
}
statusCode = response.getStatusInfo().getStatusCode();
responseHeaders = response.getHeaders();
if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) {
return null;
} else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
if (returnType == null)
return null;
else
return response.getEntity(returnType);
} else {
String message = "error";
String respBody = null;
if (response.hasEntity()) {
try {
respBody = response.getEntity(String.class);
message = respBody;
} catch (RuntimeException e) {
// e.printStackTrace();
}
}
throw new ApiException(
response.getStatusInfo().getStatusCode(),
message,
response.getHeaders(),
respBody);
}
}
/**
* Update query and header parameters based on authentication settings.
*
* @param authNames The authentications to apply
*/
private void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) {
for (String authName : authNames) {
Authentication auth = authentications.get(authName);
if (auth == null) continue;
auth.applyToParams(queryParams, headerParams);
}
}
/**
* Encode the given form parameters as request body.
*/
private String getXWWWFormUrlencodedParams(Map<String, Object> formParams) {
StringBuilder formParamBuilder = new StringBuilder();
for (Entry<String, Object> param : formParams.entrySet()) {
String valueStr = parameterToString(param.getValue());
try {
formParamBuilder.append(URLEncoder.encode(param.getKey(), "utf8"))
.append("=")
.append(URLEncoder.encode(valueStr, "utf8"));
formParamBuilder.append("&");
} catch (UnsupportedEncodingException e) {
// move on to next
}
}
String encodedFormParams = formParamBuilder.toString();
if (encodedFormParams.endsWith("&")) {
encodedFormParams = encodedFormParams.substring(0, encodedFormParams.length() - 1);
}
return encodedFormParams;
}
/**
* Build the Client used to make HTTP requests.
*/
private Client buildHttpClient(boolean debugging) {
// Add the JSON serialization support to Jersey
JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper);
DefaultClientConfig conf = new DefaultClientConfig();
conf.getSingletons().add(jsonProvider);
Client client = Client.create(conf);
if (debugging) {
client.addFilter(new LoggingFilter());
}
return client;
}
}
|
package com.facebook.litho;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.pm.ApplicationInfo;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.support.v4.util.LongSparseArray;
import android.support.v4.view.accessibility.AccessibilityManagerCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.litho.displaylist.DisplayList;
import com.facebook.litho.displaylist.DisplayListException;
import com.facebook.litho.reference.BorderColorDrawableReference;
import com.facebook.litho.reference.Reference;
import com.facebook.infer.annotation.ThreadSafe;
import com.facebook.yoga.YogaConstants;
import com.facebook.yoga.YogaDirection;
import com.facebook.yoga.YogaEdge;
import static android.content.Context.ACCESSIBILITY_SERVICE;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
import static android.os.Build.VERSION_CODES.M;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
import static android.support.v4.view.ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO;
import static com.facebook.litho.Component.isHostSpec;
import static com.facebook.litho.Component.isLayoutSpecWithSizeSpec;
import static com.facebook.litho.Component.isMountSpec;
import static com.facebook.litho.Component.isMountViewSpec;
import static com.facebook.litho.ComponentContext.NULL_LAYOUT;
import static com.facebook.litho.ComponentLifecycle.MountType.NONE;
import static com.facebook.litho.ComponentsLogger.ACTION_SUCCESS;
import static com.facebook.litho.ComponentsLogger.EVENT_COLLECT_RESULTS;
import static com.facebook.litho.ComponentsLogger.EVENT_CREATE_LAYOUT;
import static com.facebook.litho.ComponentsLogger.EVENT_CSS_LAYOUT;
import static com.facebook.litho.ComponentsLogger.PARAM_LOG_TAG;
import static com.facebook.litho.ComponentsLogger.PARAM_TREE_DIFF_ENABLED;
import static com.facebook.litho.MountItem.FLAG_DUPLICATE_PARENT_STATE;
import static com.facebook.litho.MountState.ROOT_HOST_ID;
import static com.facebook.litho.NodeInfo.FOCUS_SET_TRUE;
import static com.facebook.litho.SizeSpec.EXACTLY;
/**
* The main role of {@link LayoutState} is to hold the output of layout calculation. This includes
* mountable outputs and visibility outputs. A centerpiece of the class is {@link
* #collectResults(InternalNode, LayoutState, DiffNode)} which prepares the before-mentioned outputs
* based on the provided {@link InternalNode} for later use in {@link MountState}.
*/
class LayoutState {
static final Comparator<LayoutOutput> sTopsComparator =
new Comparator<LayoutOutput>() {
@Override
public int compare(LayoutOutput lhs, LayoutOutput rhs) {
final int lhsTop = lhs.getBounds().top;
final int rhsTop = rhs.getBounds().top;
return lhsTop < rhsTop
? -1
: lhsTop > rhsTop
? 1
// Hosts should be higher for tops so that they are mounted first if possible.
: isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent())
? 0
: isHostSpec(lhs.getComponent()) ? -1 : 1;
}
};
static final Comparator<LayoutOutput> sBottomsComparator =
new Comparator<LayoutOutput>() {
@Override
public int compare(LayoutOutput lhs, LayoutOutput rhs) {
final int lhsBottom = lhs.getBounds().bottom;
final int rhsBottom = rhs.getBounds().bottom;
return lhsBottom < rhsBottom
? -1
: lhsBottom > rhsBottom
? 1
// Hosts should be lower for bottoms so that they are mounted first if possible.
: isHostSpec(lhs.getComponent()) == isHostSpec(rhs.getComponent())
? 0
: isHostSpec(lhs.getComponent()) ? 1 : -1;
}
};
private static final int[] DRAWABLE_STATE_ENABLED = new int[]{android.R.attr.state_enabled};
private static final int[] DRAWABLE_STATE_NOT_ENABLED = new int[]{};
private ComponentContext mContext;
private TransitionContext mTransitionContext;
private Component<?> mComponent;
private int mWidthSpec;
private int mHeightSpec;
private final List<LayoutOutput> mMountableOutputs = new ArrayList<>(8);
private final List<VisibilityOutput> mVisibilityOutputs = new ArrayList<>(8);
private final LongSparseArray<Integer> mOutputsIdToPositionMap = new LongSparseArray<>(8);
private final LayoutStateOutputIdCalculator mLayoutStateOutputIdCalculator;
private final ArrayList<LayoutOutput> mMountableOutputTops = new ArrayList<>();
private final ArrayList<LayoutOutput> mMountableOutputBottoms = new ArrayList<>();
private final List<TestOutput> mTestOutputs;
private InternalNode mLayoutRoot;
private DiffNode mDiffTreeRoot;
// Reference count will be initialized to 1 in init().
private final AtomicInteger mReferenceCount = new AtomicInteger(-1);
private int mWidth;
private int mHeight;
private int mCurrentX;
private int mCurrentY;
private int mCurrentLevel = 0;
// Holds the current host marker in the layout tree.
private long mCurrentHostMarker = -1;
private int mCurrentHostOutputPosition = -1;
private boolean mShouldDuplicateParentState = true;
private boolean mShouldGenerateDiffTree = false;
private int mComponentTreeId = -1;
private AccessibilityManager mAccessibilityManager;
private boolean mAccessibilityEnabled = false;
private StateHandler mStateHandler;
LayoutState() {
mLayoutStateOutputIdCalculator = new LayoutStateOutputIdCalculator();
mTestOutputs = ComponentsConfiguration.isEndToEndTestRun ? new ArrayList<TestOutput>(8) : null;
}
/**
* Acquires a new layout output for the internal node and its associated component. It returns
* null if there's no component associated with the node as the mount pass only cares about nodes
* that will potentially mount content into the component host.
*/
@Nullable
private static LayoutOutput createGenericLayoutOutput(
InternalNode node,
LayoutState layoutState) {
final Component<?> component = node.getComponent();
// Skip empty nodes and layout specs because they don't mount anything.
if (component == null || component.getLifecycle().getMountType() == NONE) {
return null;
}
return createLayoutOutput(
component,
layoutState,
node,
true /* useNodePadding */,
node.getImportantForAccessibility(),
layoutState.mShouldDuplicateParentState);
}
private static LayoutOutput createHostLayoutOutput(LayoutState layoutState, InternalNode node) {
final LayoutOutput hostOutput = createLayoutOutput(
HostComponent.create(),
layoutState,
node,
false /* useNodePadding */,
node.getImportantForAccessibility(),
node.isDuplicateParentStateEnabled());
hostOutput.getViewNodeInfo().setTransitionKey(node.getTransitionKey());
return hostOutput;
}
private static LayoutOutput createDrawableLayoutOutput(
Component<?> component,
LayoutState layoutState,
InternalNode node) {
return createLayoutOutput(
component,
layoutState,
node,
false /* useNodePadding */,
IMPORTANT_FOR_ACCESSIBILITY_NO,
layoutState.mShouldDuplicateParentState);
}
private static LayoutOutput createLayoutOutput(
Component<?> component,
LayoutState layoutState,
InternalNode node,
boolean useNodePadding,
int importantForAccessibility,
boolean duplicateParentState) {
final boolean isMountViewSpec = isMountViewSpec(component);
final LayoutOutput layoutOutput = ComponentsPools.acquireLayoutOutput();
layoutOutput.setComponent(component);
layoutOutput.setImportantForAccessibility(importantForAccessibility);
// The mount operation will need both the marker for the target host and its matching
// parent host to ensure the correct hierarchy when nesting the host views.
layoutOutput.setHostMarker(layoutState.mCurrentHostMarker);
if (layoutState.mCurrentHostOutputPosition >= 0) {
final LayoutOutput hostOutput =
layoutState.mMountableOutputs.get(layoutState.mCurrentHostOutputPosition);
final Rect hostBounds = hostOutput.getBounds();
layoutOutput.setHostTranslationX(hostBounds.left);
layoutOutput.setHostTranslationY(hostBounds.top);
}
int l = layoutState.mCurrentX + node.getX();
int t = layoutState.mCurrentY + node.getY();
int r = l + node.getWidth();
int b = t + node.getHeight();
final int paddingLeft = useNodePadding ? node.getPaddingLeft() : 0;
final int paddingTop = useNodePadding ? node.getPaddingTop() : 0;
final int paddingRight = useNodePadding ? node.getPaddingRight() : 0;
final int paddingBottom = useNodePadding ? node.getPaddingBottom() : 0;
// View mount specs are able to set their own attributes when they're mounted.
// Non-view specs (drawable and layout) always transfer their view attributes
// to their respective hosts.
// Moreover, if the component mounts a view, then we apply padding to the view itself later on.
// Otherwise, apply the padding to the bounds of the layout output.
if (isMountViewSpec) {
layoutOutput.setNodeInfo(node.getNodeInfo());
// Acquire a ViewNodeInfo, set it up and release it after passing it to the LayoutOutput.
final ViewNodeInfo viewNodeInfo = ViewNodeInfo.acquire();
viewNodeInfo.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
viewNodeInfo.setLayoutDirection(node.getResolvedLayoutDirection());
viewNodeInfo.setExpandedTouchBounds(node, l, t, r, b);
layoutOutput.setViewNodeInfo(viewNodeInfo);
viewNodeInfo.release();
} else {
l += paddingLeft;
t += paddingTop;
r -= paddingRight;
b -= paddingBottom;
}
layoutOutput.setBounds(l, t, r, b);
int flags = 0;
if (duplicateParentState) {
flags |= FLAG_DUPLICATE_PARENT_STATE;
}
layoutOutput.setFlags(flags);
return layoutOutput;
}
/**
* Acquires a {@link VisibilityOutput} object and computes the bounds for it using the information
* stored in the {@link InternalNode}.
*/
private static VisibilityOutput createVisibilityOutput(
InternalNode node,
LayoutState layoutState) {
final int l = layoutState.mCurrentX + node.getX();
final int t = layoutState.mCurrentY + node.getY();
final int r = l + node.getWidth();
final int b = t + node.getHeight();
final EventHandler visibleHandler = node.getVisibleHandler();
final EventHandler focusedHandler = node.getFocusedHandler();
final EventHandler fullImpressionHandler = node.getFullImpressionHandler();
final EventHandler invisibleHandler = node.getInvisibleHandler();
final VisibilityOutput visibilityOutput = ComponentsPools.acquireVisibilityOutput();
final Component<?> handlerComponent;
// Get the component from the handler that is not null. If more than one is not null, then
// getting the component from any of them works.
if (visibleHandler != null) {
handlerComponent = (Component<?>) visibleHandler.mHasEventDispatcher;
} else if (focusedHandler != null) {
handlerComponent = (Component<?>) focusedHandler.mHasEventDispatcher;
} else if (fullImpressionHandler != null) {
handlerComponent = (Component<?>) fullImpressionHandler.mHasEventDispatcher;
} else {
handlerComponent = (Component<?>) invisibleHandler.mHasEventDispatcher;
}
visibilityOutput.setComponent(handlerComponent);
visibilityOutput.setBounds(l, t, r, b);
visibilityOutput.setVisibleEventHandler(visibleHandler);
visibilityOutput.setFocusedEventHandler(focusedHandler);
visibilityOutput.setFullImpressionEventHandler(fullImpressionHandler);
visibilityOutput.setInvisibleEventHandler(invisibleHandler);
return visibilityOutput;
}
private static TestOutput createTestOutput(
InternalNode node,
LayoutState layoutState,
LayoutOutput layoutOutput) {
final int l = layoutState.mCurrentX + node.getX();
final int t = layoutState.mCurrentY + node.getY();
final int r = l + node.getWidth();
final int b = t + node.getHeight();
final TestOutput output = ComponentsPools.acquireTestOutput();
output.setTestKey(node.getTestKey());
output.setBounds(l, t, r, b);
output.setHostMarker(layoutState.mCurrentHostMarker);
if (layoutOutput != null) {
output.setLayoutOutputId(layoutOutput.getId());
}
return output;
}
private static boolean isLayoutDirectionRTL(Context context) {
ApplicationInfo applicationInfo = context.getApplicationInfo();
if ((SDK_INT >= JELLY_BEAN_MR1)
&& (applicationInfo.flags & ApplicationInfo.FLAG_SUPPORTS_RTL) != 0) {
int layoutDirection = getLayoutDirection(context);
return layoutDirection == View.LAYOUT_DIRECTION_RTL;
}
return false;
}
@TargetApi(JELLY_BEAN_MR1)
private static int getLayoutDirection(Context context) {
return context.getResources().getConfiguration().getLayoutDirection();
}
/**
* Determine if a given {@link InternalNode} within the context of a given {@link LayoutState}
* requires to be wrapped inside a view.
*
* @see #needsHostView(InternalNode, LayoutState)
*/
private static boolean hasViewContent(InternalNode node, LayoutState layoutState) {
final Component<?> component = node.getComponent();
final NodeInfo nodeInfo = node.getNodeInfo();
final boolean implementsAccessibility =
(nodeInfo != null && nodeInfo.hasAccessibilityHandlers())
|| (component != null && component.getLifecycle().implementsAccessibility());
final int importantForAccessibility = node.getImportantForAccessibility();
// A component has accessibility content if:
// 1. Accessibility is currently enabled.
// 2. Accessibility hasn't been explicitly disabled on it
// i.e. IMPORTANT_FOR_ACCESSIBILITY_NO.
// 3. Any of these conditions are true:
// - It implements accessibility support.
// - It has a content description.
// - It has importantForAccessibility set as either IMPORTANT_FOR_ACCESSIBILITY_YES
// or IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS.
// IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS should trigger an inner host
// so that such flag is applied in the resulting view hierarchy after the component
// tree is mounted. Click handling is also considered accessibility content but
// this is already covered separately i.e. click handler is not null.
final boolean hasAccessibilityContent = layoutState.mAccessibilityEnabled
&& importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_NO
&& (implementsAccessibility
|| (nodeInfo != null && !TextUtils.isEmpty(nodeInfo.getContentDescription()))
|| importantForAccessibility != IMPORTANT_FOR_ACCESSIBILITY_AUTO);
final boolean hasTouchEventHandlers = (nodeInfo != null && nodeInfo.hasTouchEventHandlers());
final boolean hasViewTag = (nodeInfo != null && nodeInfo.getViewTag() != null);
final boolean hasViewTags = (nodeInfo != null && nodeInfo.getViewTags() != null);
final boolean isFocusableSetTrue =
(nodeInfo != null && nodeInfo.getFocusState() == FOCUS_SET_TRUE);
return hasTouchEventHandlers
|| hasViewTag
|| hasViewTags
|| hasAccessibilityContent
|| isFocusableSetTrue;
}
/**
* Collects layout outputs and release the layout tree. The layout outputs hold necessary
* information to be used by {@link MountState} to mount components into a {@link ComponentHost}.
* <p/>
* Whenever a component has view content (view tags, click handler, etc), a new host 'marker'
* is added for it. The mount pass will use the markers to decide which host should be used
* for each layout output. The root node unconditionally generates a layout output corresponding
* to the root host.
* <p/>
* The order of layout outputs follows a depth-first traversal in the tree to ensure the hosts
* will be created at the right order when mounting. The host markers will be define which host
* each mounted artifacts will be attached to.
* <p/>
* At this stage all the {@link InternalNode} for which we have LayoutOutputs that can be recycled
* will have a DiffNode associated. If the CachedMeasures are valid we'll try to recycle both the
* host and the contents (including background/foreground). In all other cases instead we'll only
* try to re-use the hosts. In some cases the host's structure might change between two updates
* even if the component is of the same type. This can happen for example when a click listener is
* added. To avoid trying to re-use the wrong host type we explicitly check that after all the
* children for a subtree have been added (this is when the actual host type is resolved). If the
* host type changed compared to the one in the DiffNode we need to refresh the ids for the whole
* subtree in order to ensure that the MountState will unmount the subtree and mount it again on
* the correct host.
* <p/>
*
* @param node InternalNode to process.
* @param layoutState the LayoutState currently operating.
* @param parentDiffNode whether this method also populates the diff tree and assigns the root
* to mDiffTreeRoot.
*/
private static void collectResults(
InternalNode node,
LayoutState layoutState,
DiffNode parentDiffNode) {
if (node.hasNewLayout()) {
node.markLayoutSeen();
}
final Component<?> component = node.getComponent();
// Early return if collecting results of a node holding a nested tree.
if (node.isNestedTreeHolder()) {
// If the nested tree is defined, it has been resolved during a measure call during
// layout calculation.
InternalNode nestedTree = resolveNestedTree(
node,
SizeSpec.makeSizeSpec(node.getWidth(), EXACTLY),
SizeSpec.makeSizeSpec(node.getHeight(), EXACTLY));
if (nestedTree == NULL_LAYOUT) {
return;
}
// Account for position of the holder node.
layoutState.mCurrentX += node.getX();
layoutState.mCurrentY += node.getY();
collectResults(nestedTree, layoutState, parentDiffNode);
layoutState.mCurrentX -= node.getX();
layoutState.mCurrentY -= node.getY();
return;
}
final boolean shouldGenerateDiffTree = layoutState.mShouldGenerateDiffTree;
final DiffNode currentDiffNode = node.getDiffNode();
final boolean shouldUseCachedOutputs =
isMountSpec(component) && currentDiffNode != null;
final boolean isCachedOutputUpdated = shouldUseCachedOutputs && node.areCachedMeasuresValid();
final DiffNode diffNode;
if (shouldGenerateDiffTree) {
diffNode = createDiffNode(node, parentDiffNode);
if (parentDiffNode == null) {
layoutState.mDiffTreeRoot = diffNode;
}
} else {
diffNode = null;
}
final boolean needsHostView = needsHostView(node, layoutState);
final long currentHostMarker = layoutState.mCurrentHostMarker;
final int currentHostOutputPosition = layoutState.mCurrentHostOutputPosition;
int hostLayoutPosition = -1;
// 1. Insert a host LayoutOutput if we have some interactive content to be attached to.
if (needsHostView) {
hostLayoutPosition = addHostLayoutOutput(node, layoutState, diffNode);
layoutState.mCurrentLevel++;
layoutState.mCurrentHostMarker =
layoutState.mMountableOutputs.get(hostLayoutPosition).getId();
layoutState.mCurrentHostOutputPosition = hostLayoutPosition;
}
// We need to take into account flattening when setting duplicate parent state. The parent after
// flattening may no longer exist. Therefore the value of duplicate parent state should only be
// true if the path between us (inclusive) and our inner/root host (exclusive) all are
// duplicate parent state.
final boolean shouldDuplicateParentState = layoutState.mShouldDuplicateParentState;
layoutState.mShouldDuplicateParentState =
needsHostView || (shouldDuplicateParentState && node.isDuplicateParentStateEnabled());
// Generate the layoutOutput for the given node.
final LayoutOutput layoutOutput = createGenericLayoutOutput(node, layoutState);
if (layoutOutput != null) {
final long previousId = shouldUseCachedOutputs ? currentDiffNode.getContent().getId() : -1;
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
layoutOutput,
layoutState.mCurrentLevel,
LayoutOutput.TYPE_CONTENT,
previousId,
isCachedOutputUpdated);
}
// If we don't need to update this output we can safely re-use the display list from the
// previous output.
if (isCachedOutputUpdated) {
layoutOutput.setDisplayList(currentDiffNode.getContent().getDisplayList());
}
// 2. Add background if defined.
final Reference<? extends Drawable> background = node.getBackground();
if (background != null) {
if (layoutOutput != null && layoutOutput.hasViewNodeInfo()) {
layoutOutput.getViewNodeInfo().setBackground(background);
} else {
final LayoutOutput convertBackground = (currentDiffNode != null)
? currentDiffNode.getBackground()
: null;
final LayoutOutput backgroundOutput = addDrawableComponent(
node,
layoutState,
convertBackground,
background,
LayoutOutput.TYPE_BACKGROUND);
if (diffNode != null) {
diffNode.setBackground(backgroundOutput);
}
}
}
// 3. Now add the MountSpec (either View or Drawable) to the Outputs.
if (isMountSpec(component)) {
// Notify component about its final size.
component.getLifecycle().onBoundsDefined(layoutState.mContext, node, component);
addMountableOutput(layoutState, layoutOutput);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
layoutOutput,
layoutState.mMountableOutputs.size() - 1);
if (diffNode != null) {
diffNode.setContent(layoutOutput);
}
}
// 4. Add border color if defined.
if (node.shouldDrawBorders()) {
final LayoutOutput convertBorder = (currentDiffNode != null)
? currentDiffNode.getBorder()
: null;
final LayoutOutput borderOutput = addDrawableComponent(
node,
layoutState,
convertBorder,
getBorderColorDrawable(node),
LayoutOutput.TYPE_BORDER);
if (diffNode != null) {
diffNode.setBorder(borderOutput);
}
}
// 5. Extract the Transitions.
if (SDK_INT >= ICE_CREAM_SANDWICH) {
if (node.getTransitionKey() != null) {
layoutState
.getOrCreateTransitionContext()
.addTransitionKey(node.getTransitionKey());
}
if (component != null) {
Transition transition = component.getLifecycle().onLayoutTransition(
layoutState.mContext,
component);
if (transition != null) {
layoutState.getOrCreateTransitionContext().add(transition);
}
}
}
layoutState.mCurrentX += node.getX();
layoutState.mCurrentY += node.getY();
// We must process the nodes in order so that the layout state output order is correct.
for (int i = 0, size = node.getChildCount(); i < size; i++) {
collectResults(
node.getChildAt(i),
layoutState,
diffNode);
}
layoutState.mCurrentX -= node.getX();
layoutState.mCurrentY -= node.getY();
// 6. Add foreground if defined.
final Reference<? extends Drawable> foreground = node.getForeground();
if (foreground != null) {
if (layoutOutput != null && layoutOutput.hasViewNodeInfo() && SDK_INT >= M) {
layoutOutput.getViewNodeInfo().setForeground(foreground);
} else {
final LayoutOutput convertForeground = (currentDiffNode != null)
? currentDiffNode.getForeground()
: null;
final LayoutOutput foregroundOutput = addDrawableComponent(
node,
layoutState,
convertForeground,
foreground,
LayoutOutput.TYPE_FOREGROUND);
if (diffNode != null) {
diffNode.setForeground(foregroundOutput);
}
}
}
// 7. Add VisibilityOutputs if any visibility-related event handlers are present.
if (node.hasVisibilityHandlers()) {
final VisibilityOutput visibilityOutput = createVisibilityOutput(node, layoutState);
final long previousId =
shouldUseCachedOutputs ? currentDiffNode.getVisibilityOutput().getId() : -1;
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetVisibilityOutputId(
visibilityOutput,
layoutState.mCurrentLevel,
previousId);
layoutState.mVisibilityOutputs.add(visibilityOutput);
if (diffNode != null) {
diffNode.setVisibilityOutput(visibilityOutput);
}
}
// 8. If we're in a testing environment, maintain an additional data structure with
// information about nodes that we can query later.
if (layoutState.mTestOutputs != null && !TextUtils.isEmpty(node.getTestKey())) {
final TestOutput testOutput = createTestOutput(node, layoutState, layoutOutput);
layoutState.mTestOutputs.add(testOutput);
}
// All children for the given host have been added, restore the previous
// host, level, and duplicate parent state value in the recursive queue.
if (layoutState.mCurrentHostMarker != currentHostMarker) {
layoutState.mCurrentHostMarker = currentHostMarker;
layoutState.mCurrentHostOutputPosition = currentHostOutputPosition;
layoutState.mCurrentLevel
}
layoutState.mShouldDuplicateParentState = shouldDuplicateParentState;
Collections.sort(layoutState.mMountableOutputTops, sTopsComparator);
Collections.sort(layoutState.mMountableOutputBottoms, sBottomsComparator);
}
private static void calculateAndSetHostOutputIdAndUpdateState(
InternalNode node,
LayoutOutput hostOutput,
LayoutState layoutState,
boolean isCachedOutputUpdated) {
if (layoutState.isLayoutRoot(node)) {
// The root host (ComponentView) always has ID 0 and is unconditionally
// set as dirty i.e. no need to use shouldComponentUpdate().
hostOutput.setId(ROOT_HOST_ID);
// Special case where the host marker of the root host is pointing to itself.
hostOutput.setHostMarker(ROOT_HOST_ID);
hostOutput.setUpdateState(LayoutOutput.STATE_DIRTY);
} else {
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
hostOutput,
layoutState.mCurrentLevel,
LayoutOutput.TYPE_HOST,
-1,
isCachedOutputUpdated);
}
}
private static LayoutOutput addDrawableComponent(
InternalNode node,
LayoutState layoutState,
LayoutOutput recycle,
Reference<? extends Drawable> reference,
@LayoutOutput.LayoutOutputType int type) {
final Component<DrawableComponent> drawableComponent = DrawableComponent.create(reference);
drawableComponent.setScopedContext(
ComponentContext.withComponentScope(node.getContext(), drawableComponent));
final boolean isOutputUpdated;
if (recycle != null) {
isOutputUpdated = !drawableComponent.getLifecycle().shouldComponentUpdate(
recycle.getComponent(),
drawableComponent);
} else {
isOutputUpdated = false;
}
final long previousId = recycle != null ? recycle.getId() : -1;
final LayoutOutput output = addDrawableLayoutOutput(
drawableComponent,
layoutState,
node,
type,
previousId,
isOutputUpdated);
return output;
}
private static Reference<? extends Drawable> getBorderColorDrawable(InternalNode node) {
if (!node.shouldDrawBorders()) {
throw new RuntimeException("This node does not support drawing border color");
}
return BorderColorDrawableReference.create(node.getContext())
.color(node.getBorderColor())
.borderLeft(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.LEFT)))
.borderTop(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.TOP)))
.borderRight(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.RIGHT)))
.borderBottom(FastMath.round(node.mYogaNode.getLayoutBorder(YogaEdge.BOTTOM)))
.build();
}
private static void addLayoutOutputIdToPositionsMap(
LongSparseArray outputsIdToPositionMap,
LayoutOutput layoutOutput,
int position) {
if (outputsIdToPositionMap != null) {
outputsIdToPositionMap.put(layoutOutput.getId(), position);
}
}
private static LayoutOutput addDrawableLayoutOutput(
Component<DrawableComponent> drawableComponent,
LayoutState layoutState,
InternalNode node,
@LayoutOutput.LayoutOutputType int layoutOutputType,
long previousId,
boolean isCachedOutputUpdated) {
drawableComponent.getLifecycle().onBoundsDefined(
layoutState.mContext,
node,
drawableComponent);
final LayoutOutput drawableLayoutOutput = createDrawableLayoutOutput(
drawableComponent,
layoutState,
node);
layoutState.mLayoutStateOutputIdCalculator.calculateAndSetLayoutOutputIdAndUpdateState(
drawableLayoutOutput,
layoutState.mCurrentLevel,
layoutOutputType,
previousId,
isCachedOutputUpdated);
addMountableOutput(layoutState, drawableLayoutOutput);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
drawableLayoutOutput,
layoutState.mMountableOutputs.size() - 1);
return drawableLayoutOutput;
}
static void releaseNodeTree(InternalNode node, boolean isNestedTree) {
if (node == NULL_LAYOUT) {
throw new IllegalArgumentException("Cannot release a null node tree");
}
for (int i = node.getChildCount() - 1; i >= 0; i
final InternalNode child = node.getChildAt(i);
if (isNestedTree && node.hasNewLayout()) {
node.markLayoutSeen();
}
// A node must be detached from its parent *before* being released (otherwise the parent would
// retain a reference to a node that may get re-used by another thread)
node.removeChildAt(i);
releaseNodeTree(child, isNestedTree);
}
if (node.hasNestedTree() && node.getNestedTree() != NULL_LAYOUT) {
releaseNodeTree(node.getNestedTree(), true);
}
ComponentsPools.release(node);
}
/**
* If we have an interactive LayoutSpec or a MountSpec Drawable, we need to insert an
* HostComponent in the Outputs such as it will be used as a HostView at Mount time. View
* MountSpec are not allowed.
*
* @return The position the HostLayoutOutput was inserted.
*/
private static int addHostLayoutOutput(
InternalNode node,
LayoutState layoutState,
DiffNode diffNode) {
final Component<?> component = node.getComponent();
// Only the root host is allowed to wrap view mount specs as a layout output
// is unconditionally added for it.
if (isMountViewSpec(component) && !layoutState.isLayoutRoot(node)) {
throw new IllegalArgumentException("We shouldn't insert a host as a parent of a View");
}
final LayoutOutput hostLayoutOutput = createHostLayoutOutput(layoutState, node);
// The component of the hostLayoutOutput will be set later after all the
// children got processed.
addMountableOutput(layoutState, hostLayoutOutput);
final int hostOutputPosition = layoutState.mMountableOutputs.size() - 1;
if (diffNode != null) {
diffNode.setHost(hostLayoutOutput);
}
calculateAndSetHostOutputIdAndUpdateState(
node,
hostLayoutOutput,
layoutState,
false);
addLayoutOutputIdToPositionsMap(
layoutState.mOutputsIdToPositionMap,
hostLayoutOutput,
hostOutputPosition);
return hostOutputPosition;
}
static <T extends ComponentLifecycle> LayoutState calculate(
ComponentContext c,
Component<T> component,
int componentTreeId,
int widthSpec,
int heightSpec,
boolean shouldGenerateDiffTree,
DiffNode previousDiffTreeRoot) {
// Detect errors internal to components
component.markLayoutStarted();
LayoutState layoutState = ComponentsPools.acquireLayoutState(c);
layoutState.mShouldGenerateDiffTree = shouldGenerateDiffTree;
layoutState.mComponentTreeId = componentTreeId;
layoutState.mAccessibilityManager =
(AccessibilityManager) c.getSystemService(ACCESSIBILITY_SERVICE);
layoutState.mAccessibilityEnabled = isAccessibilityEnabled(layoutState.mAccessibilityManager);
layoutState.mComponent = component;
layoutState.mWidthSpec = widthSpec;
layoutState.mHeightSpec = heightSpec;
component.applyStateUpdates(c);
final InternalNode root = createAndMeasureTreeForComponent(
component.getScopedContext(),
component,
null, // nestedTreeHolder is null because this is measuring the root component tree.
widthSpec,
heightSpec,
previousDiffTreeRoot);
switch (SizeSpec.getMode(widthSpec)) {
case SizeSpec.EXACTLY:
layoutState.mWidth = SizeSpec.getSize(widthSpec);
break;
case SizeSpec.AT_MOST:
layoutState.mWidth = Math.min(root.getWidth(), SizeSpec.getSize(widthSpec));
break;
case SizeSpec.UNSPECIFIED:
layoutState.mWidth = root.getWidth();
break;
}
switch (SizeSpec.getMode(heightSpec)) {
case SizeSpec.EXACTLY:
layoutState.mHeight = SizeSpec.getSize(heightSpec);
break;
case SizeSpec.AT_MOST:
layoutState.mHeight = Math.min(root.getHeight(), SizeSpec.getSize(heightSpec));
break;
case SizeSpec.UNSPECIFIED:
layoutState.mHeight = root.getHeight();
break;
}
layoutState.mLayoutStateOutputIdCalculator.clear();
// Reset markers before collecting layout outputs.
layoutState.mCurrentHostMarker = -1;
final ComponentsLogger logger = c.getLogger();
if (root == NULL_LAYOUT) {
return layoutState;
}
layoutState.mLayoutRoot = root;
ComponentsSystrace.beginSection("collectResults:" + component.getSimpleName());
if (logger != null) {
logger.eventStart(EVENT_COLLECT_RESULTS, component, PARAM_LOG_TAG, c.getLogTag());
}
collectResults(root, layoutState, null);
if (logger != null) {
logger.eventEnd(EVENT_COLLECT_RESULTS, component, ACTION_SUCCESS);
}
ComponentsSystrace.endSection();
if (!ComponentsConfiguration.IS_INTERNAL_BUILD && layoutState.mLayoutRoot != null) {
releaseNodeTree(layoutState.mLayoutRoot, false /* isNestedTree */);
layoutState.mLayoutRoot = null;
}
if (ThreadUtils.isMainThread() && ComponentsConfiguration.shouldGenerateDisplayLists) {
collectDisplayLists(layoutState);
}
return layoutState;
}
void preAllocateMountContent() {
if (mMountableOutputs != null && !mMountableOutputs.isEmpty()) {
for (int i = 0, size = mMountableOutputs.size(); i < size; i++) {
final Component component = mMountableOutputs.get(i).getComponent();
if (Component.isMountViewSpec(component)) {
final ComponentLifecycle lifecycle = component.getLifecycle();
if (!lifecycle.hasBeenPreallocated()) {
final int poolSize = lifecycle.poolSize();
int insertedCount = 0;
while (insertedCount < poolSize &&
ComponentsPools.canAddMountContentToPool(mContext, lifecycle)) {
ComponentsPools.release(
mContext,
lifecycle,
lifecycle.createMountContent(mContext));
insertedCount++;
}
lifecycle.setWasPreallocated();
}
}
}
}
}
private static void collectDisplayLists(LayoutState layoutState) {
final Rect rect = new Rect();
final ComponentContext context = layoutState.mContext;
final Activity activity = findActivityInContext(context);
if (activity == null || activity.isFinishing() || isActivityDestroyed(activity)) {
return;
}
for (int i = 0, count = layoutState.getMountableOutputCount(); i < count; i++) {
final LayoutOutput output = layoutState.getMountableOutputAt(i);
final Component component = output.getComponent();
final ComponentLifecycle lifecycle = component.getLifecycle();
if (lifecycle.shouldUseDisplayList()) {
output.getMountBounds(rect);
if (output.getDisplayList() != null && output.getDisplayList().isValid()) {
// This output already has a valid DisplayList from diffing. No need to re-create it.
// Just update its bounds.
try {
output.getDisplayList().setBounds(rect.left, rect.top, rect.right, rect.bottom);
continue;
} catch (DisplayListException e) {
// Nothing to do here.
}
}
final DisplayList displayList = DisplayList.createDisplayList(
lifecycle.getClass().getSimpleName());
if (displayList != null) {
Drawable drawable =
(Drawable) ComponentsPools.acquireMountContent(context, lifecycle.getId());
if (drawable == null) {
drawable = (Drawable) lifecycle.createMountContent(context);
}
final LayoutOutput clickableOutput = findInteractiveRoot(layoutState, output);
boolean isStateEnabled = false;
if (clickableOutput != null && clickableOutput.getNodeInfo() != null) {
final NodeInfo nodeInfo = clickableOutput.getNodeInfo();
if (nodeInfo.hasTouchEventHandlers() || nodeInfo.getFocusState() == FOCUS_SET_TRUE) {
isStateEnabled = true;
}
}
if (isStateEnabled) {
drawable.setState(DRAWABLE_STATE_ENABLED);
} else {
drawable.setState(DRAWABLE_STATE_NOT_ENABLED);
}
lifecycle.mount(
context,
drawable,
component);
lifecycle.bind(context, drawable, component);
output.getMountBounds(rect);
drawable.setBounds(0, 0, rect.width(), rect.height());
try {
final Canvas canvas = displayList.start(rect.width(), rect.height());
drawable.draw(canvas);
displayList.end(canvas);
displayList.setBounds(rect.left, rect.top, rect.right, rect.bottom);
output.setDisplayList(displayList);
} catch (DisplayListException e) {
// Display list creation failed. Make sure the DisplayList for this output is set
// to null.
output.setDisplayList(null);
}
lifecycle.unbind(context, drawable, component);
lifecycle.unmount(context, drawable, component);
ComponentsPools.release(context, lifecycle, drawable);
}
}
}
}
private static LayoutOutput findInteractiveRoot(LayoutState layoutState, LayoutOutput output) {
if (output.getId() == ROOT_HOST_ID) {
return output;
}
if ((output.getFlags() & FLAG_DUPLICATE_PARENT_STATE) != 0) {
final int parentPosition = layoutState.getLayoutOutputPositionForId(output.getHostMarker());
if (parentPosition >= 0) {
final LayoutOutput parent = layoutState.mMountableOutputs.get(parentPosition);
if (parent == null) {
return null;
}
return findInteractiveRoot(layoutState, parent);
}
return null;
}
return output;
}
private static boolean isActivityDestroyed(Activity activity) {
if (SDK_INT >= JELLY_BEAN_MR1) {
return activity.isDestroyed();
}
return false;
}
private static Activity findActivityInContext(Context context) {
if (context instanceof Activity) {
return (Activity) context;
} else if (context instanceof ContextWrapper) {
return findActivityInContext(((ContextWrapper) context).getBaseContext());
}
return null;
}
@VisibleForTesting
static <T extends ComponentLifecycle> InternalNode createTree(
Component<T> component,
ComponentContext context) {
final ComponentsLogger logger = context.getLogger();
if (logger != null) {
logger.eventStart(EVENT_CREATE_LAYOUT, context, PARAM_LOG_TAG, context.getLogTag());
logger.eventAddTag(EVENT_CREATE_LAYOUT, context, component.getSimpleName());
}
final InternalNode root = (InternalNode) component.getLifecycle().createLayout(
context,
component,
true /* resolveNestedTree */);
if (logger != null) {
logger.eventEnd(EVENT_CREATE_LAYOUT, context, ACTION_SUCCESS);
}
return root;
}
@VisibleForTesting
static void measureTree(
InternalNode root,
int widthSpec,
int heightSpec,
DiffNode previousDiffTreeRoot) {
final ComponentContext context = root.getContext();
final Component component = root.getComponent();
ComponentsSystrace.beginSection("measureTree:" + component.getSimpleName());
if (YogaConstants.isUndefined(root.getStyleWidth())) {
root.setStyleWidthFromSpec(widthSpec);
}
if (YogaConstants.isUndefined(root.getStyleHeight())) {
root.setStyleHeightFromSpec(heightSpec);
}
if (previousDiffTreeRoot != null) {
ComponentsSystrace.beginSection("applyDiffNode");
applyDiffNodeToUnchangedNodes(root, previousDiffTreeRoot);
ComponentsSystrace.endSection(/* applyDiffNode */);
}
final ComponentsLogger logger = context.getLogger();
if (logger != null) {
logger.eventStart(EVENT_CSS_LAYOUT, component, PARAM_LOG_TAG, context.getLogTag());
logger.eventAddParam(
EVENT_CSS_LAYOUT,
component,
PARAM_TREE_DIFF_ENABLED,
String.valueOf(previousDiffTreeRoot != null));
}
root.calculateLayout(
SizeSpec.getMode(widthSpec) == SizeSpec.UNSPECIFIED
? YogaConstants.UNDEFINED
: SizeSpec.getSize(widthSpec),
SizeSpec.getMode(heightSpec) == SizeSpec.UNSPECIFIED
? YogaConstants.UNDEFINED
: SizeSpec.getSize(heightSpec));
if (logger != null) {
logger.eventEnd(EVENT_CSS_LAYOUT, component, ACTION_SUCCESS);
}
ComponentsSystrace.endSection(/* measureTree */);
}
/**
* Create and measure the nested tree or return the cached one for the same size specs.
*/
static InternalNode resolveNestedTree(
InternalNode nestedTreeHolder,
int widthSpec,
int heightSpec) {
final ComponentContext context = nestedTreeHolder.getContext();
final Component<?> component = nestedTreeHolder.getComponent();
InternalNode nestedTree = nestedTreeHolder.getNestedTree();
if (nestedTree == null
|| !hasCompatibleSizeSpec(
nestedTree.getLastWidthSpec(),
nestedTree.getLastHeightSpec(),
widthSpec,
heightSpec,
nestedTree.getLastMeasuredWidth(),
nestedTree.getLastMeasuredHeight())) {
if (nestedTree != null) {
if (nestedTree != NULL_LAYOUT) {
releaseNodeTree(nestedTree, true /* isNestedTree */);
}
nestedTree = null;
}
if (component.hasCachedLayout()) {
final InternalNode cachedLayout = component.getCachedLayout();
final boolean hasCompatibleLayoutDirection =
InternalNode.hasValidLayoutDirectionInNestedTree(nestedTreeHolder, cachedLayout);
// Transfer the cached layout to the node without releasing it if it's compatible.
|
package com.infogen.server.model;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.atomic.LongAdder;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.infogen.http.InfoGen_HTTP;
import com.infogen.http.callback.Http_Callback;
import com.infogen.thrift.Message;
import com.infogen.thrift.Request;
import com.infogen.thrift.Response;
import com.infogen.util.CODE;
import com.infogen.util.Return;
/**
*
*
* @author larry
* @email larrylv@outlook.com
* @version 20141024 4:27:17
* @ rest,rpc,
*/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE)
public class NativeNode extends AbstractNode {
@JsonIgnore
public static final Logger logger = Logger.getLogger(NativeNode.class.getName());
@JsonIgnore
private transient LongAdder sequence = new LongAdder();
@JsonIgnore
private transient Integer connect_timeout = 3000;
/**
*
*
* @param session
* @param method
* @param name_value_pair
* @return
* @throws TException
* @throws Exception
*/
public Return call_once(String session, String method, Map<String, String> name_value_pair) throws TException {
TTransport transport = new TSocket(ip, rpc_port);
TProtocol protocol = new TCompactProtocol(transport);
Message.Client client = new Message.Client(protocol);
try {
transport.open();
Request request = new Request();
request.setSessionID(session);
sequence.increment();
request.setSequence(sequence.longValue());
request.setMethod(method);
Map<String, String> call_map = new HashMap<>();
for (Entry<String, String> basicNameValuePair : name_value_pair.entrySet()) {
call_map.put(basicNameValuePair.getKey(), basicNameValuePair.getValue());
}
request.setParameters(call_map);
Response call = client.call(request);
String data = call.getData();
if (data == null) {
return Return.SUCCESS(CODE._200.code, CODE._200.note);
}
return Return.create(data);
} finally {
transport.close();
}
}
// ///////////////////////////////////////////http////////////////////////////////////////////////
public enum RequestType {
POST, GET
}
public enum NetType {
NET, LOCAL
}
public Http_Callback async_http(String method, Map<String, String> name_value_pair, RequestType request_type, NetType net_type) throws IOException {
StringBuffer async_http_sbf = new StringBuffer();
if (request_type == RequestType.GET) {
if (net_type == NetType.LOCAL) {
async_http_sbf.append(http_protocol).append("://").append(ip).append(":").append(http_port).append("/").append(method);
} else {
async_http_sbf.append(http_protocol).append("://").append(net_ip).append(":").append(http_port).append("/").append(method);
}
return InfoGen_HTTP.do_async_get(async_http_sbf.toString(), name_value_pair);
} else {
if (net_type == NetType.LOCAL) {
async_http_sbf.append(http_protocol).append("://").append(ip).append(":").append(http_port).append("/").append(method);
} else {
async_http_sbf.append(http_protocol).append("://").append(net_ip).append(":").append(http_port).append("/").append(method);
}
return InfoGen_HTTP.do_async_post(async_http_sbf.toString(), name_value_pair);
}
}
public String http(String method, Map<String, String> name_value_pair, RequestType request_type, NetType net_type) throws IOException {
StringBuffer blocking_http_sbf = new StringBuffer();
if (request_type == RequestType.GET) {
if (net_type == NetType.LOCAL) {
blocking_http_sbf.append(http_protocol).append("://").append(ip).append(":").append(http_port).append("/").append(method);
} else {
blocking_http_sbf.append(http_protocol).append("://").append(net_ip).append(":").append(http_port).append("/").append(method);
}
return InfoGen_HTTP.do_get(blocking_http_sbf.toString(), name_value_pair);
} else {
if (net_type == NetType.LOCAL) {
blocking_http_sbf.append(http_protocol).append("://").append(ip).append(":").append(http_port).append("/").append(method);
} else {
blocking_http_sbf.append(http_protocol).append("://").append(net_ip).append(":").append(http_port).append("/").append(method);
}
return InfoGen_HTTP.do_post(blocking_http_sbf.toString(), name_value_pair);
}
}
}
|
package com.tale.controller;
import com.blade.ioc.annotation.Inject;
import com.blade.jdbc.core.Take;
import com.blade.jdbc.model.Paginator;
import com.blade.kit.StringKit;
import com.blade.mvc.Const;
import com.blade.mvc.annotation.*;
import com.blade.mvc.http.Request;
import com.blade.mvc.http.Response;
import com.blade.mvc.http.Session;
import com.blade.mvc.ui.RestResponse;
import com.blade.security.web.csrf.CsrfToken;
import com.blade.validator.annotation.Valid;
import com.tale.exception.TipException;
import com.tale.extension.Commons;
import com.tale.init.TaleConst;
import com.tale.model.dto.Archive;
import com.tale.model.dto.ErrorCode;
import com.tale.model.dto.MetaDto;
import com.tale.model.dto.Types;
import com.tale.model.entity.Comments;
import com.tale.model.entity.Contents;
import com.tale.model.entity.Metas;
import com.tale.service.CommentsService;
import com.tale.service.ContentsService;
import com.tale.service.MetasService;
import com.tale.service.SiteService;
import com.tale.utils.TaleUtils;
import com.vdurmont.emoji.EmojiParser;
import lombok.extern.slf4j.Slf4j;
import java.net.URLEncoder;
import java.util.List;
@Slf4j
@Path
public class IndexController extends BaseController {
@Inject
private ContentsService contentsService;
@Inject
private MetasService metasService;
@Inject
private CommentsService commentsService;
@Inject
private SiteService siteService;
/**
*
*
* @return
*/
@GetRoute
public String index(Request request, @Param(defaultValue = "12") int limit) {
return this.index(request, 1, limit);
}
@CsrfToken(newToken = true)
@GetRoute(value = {"/:cid", "/:cid.html"})
public String page(@PathParam String cid, Request request) {
Contents contents = contentsService.getContents(cid);
if (null == contents) {
return this.render_404();
}
if (contents.getAllow_comment()) {
int cp = request.queryInt("cp", 1);
request.attribute("cp", cp);
}
request.attribute("article", contents);
updateArticleHit(contents.getCid(), contents.getHits());
if (Types.ARTICLE.equals(contents.getType())) {
return this.render("post");
}
if (Types.PAGE.equals(contents.getType())) {
return this.render("page");
}
return this.render_404();
}
/**
*
*
* @param request
* @param page
* @param limit
* @return
*/
@GetRoute(value = {"page/:page", "page/:page.html"})
public String index(Request request, @PathParam int page, @Param(defaultValue = "12") int limit) {
page = page < 0 || page > TaleConst.MAX_PAGE ? 1 : page;
Take take = new Take(Contents.class).eq("type", Types.ARTICLE).eq("status", Types.PUBLISH).page(page, limit, "created desc");
Paginator<Contents> articles = contentsService.getArticles(take);
request.attribute("articles", articles);
if (page > 1) {
this.title(request, "" + page + "");
}
request.attribute("is_home", true);
request.attribute("page_prefix", "/page");
return this.render("index");
}
@CsrfToken(newToken = true)
@GetRoute(value = {"article/:cid", "article/:cid.html"})
public String post(Request request, @PathParam String cid) {
Contents contents = contentsService.getContents(cid);
if (null == contents || Types.DRAFT.equals(contents.getStatus())) {
return this.render_404();
}
request.attribute("article", contents);
request.attribute("is_post", true);
if (contents.getAllow_comment()) {
int cp = request.queryInt("cp", 1);
request.attribute("cp", cp);
}
updateArticleHit(contents.getCid(), contents.getHits());
return this.render("post");
}
private void updateArticleHit(Integer cid, Integer chits) {
Integer hits = cache.hget(Types.C_ARTICLE_HITS, cid.toString());
hits = null == hits ? 1 : hits + 1;
if (hits >= TaleConst.HIT_EXCEED) {
Contents temp = new Contents();
temp.setCid(cid);
temp.setHits(chits + hits);
contentsService.update(temp);
cache.hset(Types.C_ARTICLE_HITS, cid.toString(), 1);
} else {
cache.hset(Types.C_ARTICLE_HITS, cid.toString(), hits);
}
}
/**
*
*
* @return
*/
@GetRoute(value = {"category/:keyword", "category/:keyword.html"})
public String categories(Request request, @PathParam String keyword, @Param(defaultValue = "12") int limit) {
return this.categories(request, keyword, 1, limit);
}
@GetRoute(value = {"category/:keyword/:page", "category/:keyword/:page.html"})
public String categories(Request request, @PathParam String keyword,
@PathParam int page, @Param(defaultValue = "12") int limit) {
page = page < 0 || page > TaleConst.MAX_PAGE ? 1 : page;
MetaDto metaDto = metasService.getMeta(Types.CATEGORY, keyword);
if (null == metaDto) {
return this.render_404();
}
Paginator<Contents> contentsPaginator = contentsService.getArticles(metaDto.getMid(), page, limit);
request.attribute("articles", contentsPaginator);
request.attribute("meta", metaDto);
request.attribute("type", "");
request.attribute("keyword", keyword);
request.attribute("is_category", true);
request.attribute("page_prefix", "/category/" + keyword);
return this.render("page-category");
}
/**
*
*
* @param name
* @return
*/
@GetRoute(value = {"tag/:name", "tag/:name.html"})
public String tags(Request request, @PathParam String name, @Param(defaultValue = "12") int limit) {
return this.tags(request, name, 1, limit);
}
/**
*
*
* @param request
* @param name
* @param page
* @param limit
* @return
*/
@GetRoute(value = {"tag/:name/:page", "tag/:name/:page.html"})
public String tags(Request request, @PathParam String name, @PathParam int page, @Param(defaultValue = "12") int limit) {
page = page < 0 || page > TaleConst.MAX_PAGE ? 1 : page;
MetaDto metaDto = metasService.getMeta(Types.TAG, name);
if (null == metaDto) {
return this.render_404();
}
Paginator<Contents> contentsPaginator = contentsService.getArticles(metaDto.getMid(), page, limit);
request.attribute("articles", contentsPaginator);
request.attribute("meta", metaDto);
request.attribute("type", "");
request.attribute("keyword", name);
request.attribute("is_tag", true);
request.attribute("page_prefix", "/tag/" + name);
return this.render("page-category");
}
/**
*
*
* @param keyword
* @return
*/
@GetRoute(value = {"search/:keyword", "search/:keyword.html"})
public String search(Request request, @PathParam String keyword, @Param(defaultValue = "12") int limit) {
return this.search(request, keyword, 1, limit);
}
@GetRoute(value = {"search", "search.html"})
public String search(Request request, @Param(defaultValue = "12") int limit) {
String keyword = request.query("s").orElse("");
return this.search(request, keyword, 1, limit);
}
@GetRoute(value = {"search/:keyword/:page", "search/:keyword/:page.html"})
public String search(Request request, @PathParam String keyword, @PathParam int page, @Param(defaultValue = "12") int limit) {
page = page < 0 || page > TaleConst.MAX_PAGE ? 1 : page;
Take take = new Take(Contents.class).eq("type", Types.ARTICLE).eq("status", Types.PUBLISH)
.like("title", "%" + keyword + "%").page(page, limit, "created desc");
Paginator<Contents> articles = contentsService.getArticles(take);
request.attribute("articles", articles);
request.attribute("type", "");
request.attribute("keyword", keyword);
request.attribute("page_prefix", "/search/" + keyword);
return this.render("page-category");
}
/**
*
*
* @return
*/
@GetRoute(value = {"archives", "archives.html"})
public String archives(Request request) {
List<Archive> archives = siteService.getArchives();
request.attribute("archives", archives);
request.attribute("is_archive", true);
return this.render("archives");
}
/**
*
*
* @return
*/
@CsrfToken(newToken = true)
@GetRoute(value = {"links", "links.html"})
public String links(Request request) {
List<Metas> links = metasService.getMetas(Types.LINK);
request.attribute("links", links);
return this.render("links");
}
/**
* feed
*
* @return
*/
@GetRoute(value = {"feed", "feed.xml"})
public void feed(Response response) {
Paginator<Contents> contentsServiceArticles = contentsService.getArticles(new Take(Contents.class)
.eq("type", Types.ARTICLE).eq("status", Types.PUBLISH).eq("allow_feed", true).page(1, TaleConst.MAX_POSTS, "created desc"));
try {
String xml = TaleUtils.getRssXml(contentsServiceArticles.getList());
response.contentType("text/xml; charset=utf-8");
response.body(xml);
} catch (Exception e) {
log.error("RSS", e);
}
}
/**
*
*
* @param session
* @param response
*/
@Route(value = "logout")
public void logout(Session session, Response response) {
TaleUtils.logout(session, response);
}
@CsrfToken(valid = true)
@PostRoute(value = "comment")
@JSON
public RestResponse comment(Request request, Response response,
@HeaderParam String Referer, @Valid Comments comments) {
// if (StringKit.isBlank(Referer)) {
// return RestResponse.fail(ErrorCode.BAD_REQUEST);
if (!Referer.startsWith(Commons.site_url())) {
return RestResponse.fail("");
}
String val = request.address() + ":" + comments.getCid();
Integer count = cache.hget(Types.COMMENTS_FREQUENCY, val);
if (null != count && count > 0) {
return RestResponse.fail("");
}
comments.setAuthor(TaleUtils.cleanXSS(comments.getAuthor()));
comments.setContent(TaleUtils.cleanXSS(comments.getContent()));
comments.setAuthor(EmojiParser.parseToAliases(comments.getAuthor()));
comments.setContent(EmojiParser.parseToAliases(comments.getContent()));
comments.setIp(request.address());
comments.setParent(comments.getCoid());
try {
commentsService.saveComment(comments);
response.cookie("tale_remember_author", URLEncoder.encode(comments.getAuthor(), "UTF-8"), 7 * 24 * 60 * 60);
response.cookie("tale_remember_mail", URLEncoder.encode(comments.getMail(), "UTF-8"), 7 * 24 * 60 * 60);
if (StringKit.isNotBlank(comments.getUrl())) {
response.cookie("tale_remember_url", URLEncoder.encode(comments.getUrl(), "UTF-8"), 7 * 24 * 60 * 60);
}
cache.hset(Types.COMMENTS_FREQUENCY, val, 1, 30);
siteService.cleanCache(Types.C_STATISTICS);
return RestResponse.ok();
} catch (Exception e) {
String msg = "";
if (e instanceof TipException) {
msg = e.getMessage();
} else {
log.error(msg, e);
}
return RestResponse.fail(msg);
}
}
}
|
package com.tomgibara.hashing;
import java.math.BigInteger;
import com.tomgibara.streams.AbstractWriteStream;
final class MurmurIntHash implements Hash<MurmurIntHash.MurmurStream> {
static final int c1 = 0xcc9e2d51;
static final int c2 = 0x1b873593;
private static MurmurIntHash instance = new MurmurIntHash(0);
static MurmurIntHash instance() { return instance; }
static MurmurIntHash instance(int seed) { return seed == 0 ? instance : new MurmurIntHash(seed); }
private final int seed;
private MurmurIntHash(int seed) {
this.seed = seed;
}
@Override
public HashSize getSize() {
return HashSize.INT_SIZE;
}
@Override
public MurmurStream newStream() {
return new MurmurStream(seed);
}
@Override
public int intHashValue(MurmurStream s) {
return s.hash();
}
@Override
public long longHashValue(MurmurStream s) {
return s.hash() & 0xffffffffL;
}
@Override
public BigInteger bigHashValue(MurmurStream s) {
return BigInteger.valueOf(longHashValue(s));
}
@Override
public HashValue hashValue(MurmurStream s) {
return new IntHashValue(s.hash());
}
// inner classes
static class MurmurStream extends AbstractWriteStream {
private int k1;
private int h1;
private int len;
MurmurStream(int seed) {
k1 = 0;
h1 = seed;
len = 0;
}
@Override
public void writeByte(byte v) {
k1 = (v << 24) | (k1 >>> 8);
// process body
if (((++len) & 3) == 0) {
k1 *= c1;
k1 = Integer.rotateLeft(k1, 15);
k1 *= c2;
h1 ^= k1;
h1 = Integer.rotateLeft(h1, 13);
h1 = h1 * 5 + 0xe6546b64;
}
}
public int hash() {
// process tail
int rem = len & 3;
if (rem != 0) {
k1 >>>= (4 - rem) << 3;
k1 *= c1;
k1 = Integer.rotateLeft(k1, 15);
k1 *= c2;
h1 ^= k1;
}
// finalize
h1 ^= len;
h1 ^= h1 >>> 16;
h1 *= 0x85ebca6b;
h1 ^= h1 >>> 13;
h1 *= 0xc2b2ae35;
h1 ^= h1 >>> 16;
// return
return h1;
}
}
}
|
package com.vzome.core.editor;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.OutputStream;
import java.io.StringWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.vzome.core.algebra.AlgebraicField;
import com.vzome.core.algebra.AlgebraicNumber;
import com.vzome.core.algebra.AlgebraicVector;
import com.vzome.core.algebra.PentagonField;
import com.vzome.core.commands.AbstractCommand;
import com.vzome.core.commands.Command;
import com.vzome.core.commands.XmlSaveFormat;
import com.vzome.core.construction.Construction;
import com.vzome.core.construction.FreePoint;
import com.vzome.core.construction.Point;
import com.vzome.core.construction.Polygon;
import com.vzome.core.construction.Segment;
import com.vzome.core.construction.SegmentCrossProduct;
import com.vzome.core.construction.SegmentJoiningPoints;
import com.vzome.core.editor.Snapshot.SnapshotAction;
import com.vzome.core.exporters.Exporter3d;
import com.vzome.core.exporters.OpenGLExporter;
import com.vzome.core.exporters.POVRayExporter;
import com.vzome.core.exporters.PartGeometryExporter;
import com.vzome.core.math.DomUtils;
import com.vzome.core.math.Projection;
import com.vzome.core.math.RealVector;
import com.vzome.core.math.symmetry.Axis;
import com.vzome.core.math.symmetry.Direction;
import com.vzome.core.math.symmetry.IcosahedralSymmetry;
import com.vzome.core.math.symmetry.OrbitSet;
import com.vzome.core.math.symmetry.QuaternionicSymmetry;
import com.vzome.core.math.symmetry.Symmetry;
import com.vzome.core.model.Connector;
import com.vzome.core.model.Exporter;
import com.vzome.core.model.Manifestation;
import com.vzome.core.model.ManifestationChanges;
import com.vzome.core.model.Panel;
import com.vzome.core.model.RealizedModel;
import com.vzome.core.model.Strut;
import com.vzome.core.model.VefModelExporter;
import com.vzome.core.render.Color;
import com.vzome.core.render.Colors;
import com.vzome.core.render.RenderedModel;
import com.vzome.core.render.RenderedModel.OrbitSource;
import com.vzome.core.viewing.Camera;
import com.vzome.core.viewing.Lights;
public class DocumentModel implements Snapshot .Recorder, UndoableEdit .Context, Tool .Registry
{
private final RealizedModel mRealizedModel;
private final Point originPoint;
private final Selection mSelection;
private final EditorModel mEditorModel;
private SymmetrySystem symmetrySystem;
private final EditHistory mHistory;
private final LessonModel lesson = new LessonModel();
private final AlgebraicField mField;
private final Map<String, Tool> tools = new LinkedHashMap<>();
private final Command.FailureChannel failures;
private int changes = 0;
private boolean migrated = false;
private final Element mXML;
private RenderedModel renderedModel;
private Camera defaultView;
private final String coreVersion;
private static final Logger logger = Logger .getLogger( "com.vzome.core.editor" );
private static final Logger thumbnailLogger = Logger.getLogger( "com.vzome.core.thumbnails" );
// 2013-05-26
// I thought about leaving these two in EditorModel, but reconsidered. Although they are in-memory
// state only, not saved in the file, they are still necessary for non-interactive use such as lesson export.
private RenderedModel[] snapshots = new RenderedModel[8];
private int numSnapshots = 0;
private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport( this );
private final Map<String, Object> commands; // TODO: DJH: Don't allow non-Command objects in this Map.
private final Map<String,SymmetrySystem> symmetrySystems = new HashMap<>();
private final Lights sceneLighting;
public void addPropertyChangeListener( PropertyChangeListener listener )
{
propertyChangeSupport .addPropertyChangeListener( listener );
}
public void removePropertyChangeListener( PropertyChangeListener listener )
{
propertyChangeSupport .removePropertyChangeListener( listener );
}
protected void firePropertyChange( String propertyName, Object oldValue, Object newValue )
{
propertyChangeSupport .firePropertyChange( propertyName, oldValue, newValue );
}
protected void firePropertyChange( String propertyName, int oldValue, int newValue )
{
propertyChangeSupport .firePropertyChange( propertyName, oldValue, newValue );
}
public DocumentModel( final AlgebraicField field, Command.FailureChannel failures, Element xml, final Application app )
{
super();
this .mField = field;
AlgebraicVector origin = field .origin( 3 );
this .originPoint = new FreePoint( origin );
this .failures = failures;
this .mXML = xml;
this .commands = app .getCommands();
this .sceneLighting = app .getLights();
this .coreVersion = app .getCoreVersion();
this .mRealizedModel = new RealizedModel( field, new Projection.Default( field ) );
this .mSelection = new Selection();
Symmetry[] symms = field .getSymmetries();
for (Symmetry symm : symms) {
SymmetrySystem osm = new SymmetrySystem( null, symm, app .getColors(), app .getGeometries( symm ), true );
// one of these will be overwritten below, if we are loading from a file that has it set
this .symmetrySystems .put( osm .getName(), osm );
try {
String name = symm .getName();
makeTool( name + ".builtin/" + name + " around origin", name, this, symm ) .perform();
} catch ( Command.Failure e ) {
logger .severe( "Failed to create " + symm .getName() + " tool." );
}
}
if ( xml != null ) {
NodeList nl = xml .getElementsByTagName( "SymmetrySystem" );
if ( nl .getLength() != 0 )
xml = (Element) nl .item( 0 );
else
xml = null;
}
String symmName = ( xml != null )? xml .getAttribute( "name" ) : symms[ 0 ] .getName();
Symmetry symmetry = field .getSymmetry( symmName );
this .symmetrySystem = new SymmetrySystem( xml, symmetry, app .getColors(), app .getGeometries( symmetry ), true );
this .symmetrySystems .put( symmName, this .symmetrySystem );
try {
makeTool( "tetrahedral.builtin/tetrahedral around origin", "tetrahedral", this, symmetry ) .perform();
makeTool( "point reflection.builtin/reflection through origin", "point reflection", this, symmetry ) .perform();
makeTool( "scaling.builtin/scale up", "scale up", this, symmetry ) .perform();
makeTool( "scaling.builtin/scale down", "scale down", this, symmetry ) .perform();
makeTool( "translation.builtin/move right", "translation", this, symmetry ) .perform();
makeTool( "mirror.builtin/reflection through XY plane", "mirror", this, symmetry ) .perform();
makeTool( "bookmark.builtin/ball at origin", "bookmark", this, symmetry ) .perform();
if ( symmetry instanceof IcosahedralSymmetry ) {
makeTool( "rotation.builtin/rotate around red through origin", "rotation", this, symmetry ) .perform();
makeTool( "axial symmetry.builtin/symmetry around red through origin", "axial symmetry", this, symmetry ) .perform();
}
} catch ( Command.Failure e ) {
logger .severe( "Failed to create built-in tools." );
}
this .renderedModel = new RenderedModel( field, this .symmetrySystem );
this .mRealizedModel .addListener( this .renderedModel ); // just setting the default
// the renderedModel must either be disabled, or have shapes here, so the origin ball gets rendered
this .mEditorModel = new EditorModel( this .mRealizedModel, this .mSelection, /*oldGroups*/ false, originPoint );
this .defaultView = new Camera();
Element views = ( this .mXML == null )? null : (Element) this .mXML .getElementsByTagName( "Viewing" ) .item( 0 );
if ( views != null ) {
NodeList nodes = views .getChildNodes();
for ( int i = 0; i < nodes .getLength(); i++ ) {
Node node = nodes .item( i );
if ( node instanceof Element ) {
Element viewElem = (Element) node;
String name = viewElem .getAttribute( "name" );
if ( ( name == null || name .isEmpty() )
|| ( "default" .equals( name ) ) )
{
this .defaultView = new Camera( viewElem );
}
}
}
}
mHistory = new EditHistory();
mHistory .setListener( new EditHistory.Listener() {
@Override
public void showCommand( Element xml, int editNumber )
{
String str = editNumber + ": " + DomUtils .toString( xml );
DocumentModel.this .firePropertyChange( "current.edit.xml", null, str );
}
});
lesson .addPropertyChangeListener( new PropertyChangeListener()
{
@Override
public void propertyChange( PropertyChangeEvent change )
{
if ( "currentSnapshot" .equals( change .getPropertyName() ) )
{
int id = ((Integer) change .getNewValue());
RenderedModel newSnapshot = snapshots[ id ];
firePropertyChange( "currentSnapshot", null, newSnapshot );
}
else if ( "currentView" .equals( change .getPropertyName() ) )
{
// forward to doc listeners
firePropertyChange( "currentView", change .getOldValue(), change .getNewValue() );
}
else if ( "thumbnailChanged" .equals( change .getPropertyName() ) )
{
// forward to doc listeners
firePropertyChange( "thumbnailChanged", change .getOldValue(), change .getNewValue() );
}
}
} );
}
public int getChangeCount()
{
return this .changes;
}
public boolean isMigrated()
{
return this .migrated;
}
public void setRenderedModel( RenderedModel renderedModel )
{
this .mRealizedModel .removeListener( this .renderedModel );
this .renderedModel = renderedModel;
this .mRealizedModel .addListener( renderedModel );
// "re-render" the origin
Manifestation m = this .mRealizedModel .findConstruction( originPoint );
m .setRenderedObject( null );
this .mRealizedModel .show( m );
}
@Override
public UndoableEdit createEdit( Element xml, boolean groupInSelection )
{
UndoableEdit edit = null;
String name = xml .getLocalName();
switch (name) {
case "Snapshot":
edit = new Snapshot( -1, this );
break;
case "Branch":
edit = new Branch( this );
break;
case "Delete":
edit = new Delete( this.mSelection, this.mRealizedModel );
break;
case "ShowPoint":
edit = new ShowPoint( null, this.mSelection, this.mRealizedModel, groupInSelection );
break;
case "setItemColor":
edit = new ColorManifestations( this.mSelection, this.mRealizedModel, null, groupInSelection );
break;
case "ShowHidden":
edit = new ShowHidden( this.mSelection, this.mRealizedModel, groupInSelection );
break;
case "CrossProduct":
edit = new CrossProduct( this.mSelection, this.mRealizedModel, groupInSelection );
break;
case "AffinePentagon":
edit = new AffinePentagon( this.mSelection, this.mRealizedModel, groupInSelection );
break;
case "AffineHeptagon":
edit = new AffineHeptagon( this.mSelection, this.mRealizedModel );
break;
case "AffineTransformAll":
edit = new AffineTransformAll( this.mSelection, this.mRealizedModel, this.mEditorModel.getCenterPoint(), groupInSelection );
break;
case "HeptagonSubdivision":
edit = new HeptagonSubdivision( this.mSelection, this.mRealizedModel, groupInSelection );
break;
case "DodecagonSymmetry":
edit = new DodecagonSymmetry( this.mSelection, this.mRealizedModel, this.mEditorModel.getCenterPoint(), groupInSelection );
break;
case "GhostSymmetry24Cell":
edit = new GhostSymmetry24Cell( this.mSelection, this.mRealizedModel, this.mEditorModel.getSymmetrySegment(),
groupInSelection );
break;
case "StrutCreation":
edit = new StrutCreation( null, null, null, this.mRealizedModel );
break;
case "BnPolyope":
case "B4Polytope":
edit = new B4Polytope( this.mSelection, this.mRealizedModel, this .mField, null, 0, groupInSelection );
break;
case "Polytope4d":
edit = new Polytope4d( this.mSelection, this.mRealizedModel, null, 0, null, groupInSelection );
break;
case "LoadVEF":
edit = new LoadVEF( this.mSelection, this.mRealizedModel, null, null, null );
break;
case "GroupSelection":
edit = new GroupSelection( this.mSelection, false );
break;
case "BeginBlock":
edit = new BeginBlock();
break;
case "EndBlock":
edit = new EndBlock();
break;
case "InvertSelection":
edit = new InvertSelection( this.mSelection, this.mRealizedModel, groupInSelection );
break;
case "JoinPoints":
edit = new JoinPoints( this.mSelection, this.mRealizedModel, groupInSelection );
break;
case "NewCentroid":
edit = new Centroid( this.mSelection, this.mRealizedModel, groupInSelection );
break;
case "StrutIntersection":
edit = new StrutIntersection( this.mSelection, this.mRealizedModel, groupInSelection );
break;
case "LinePlaneIntersect":
edit = new LinePlaneIntersect( this.mSelection, this.mRealizedModel, groupInSelection );
break;
case "SelectAll":
edit = new SelectAll( this.mSelection, this.mRealizedModel, groupInSelection );
break;
case "DeselectAll":
edit = new DeselectAll( this.mSelection, groupInSelection );
break;
case "DeselectByClass":
edit = new DeselectByClass( this.mSelection, false );
break;
case "SelectManifestation":
edit = new SelectManifestation( null, false, this.mSelection, this.mRealizedModel, groupInSelection );
break;
case "SelectNeighbors":
edit = new SelectNeighbors( this.mSelection, this.mRealizedModel, groupInSelection );
break;
case "SelectSimilarSize":
/*
The normal pattern is to have the edits deserialize their own parameters from the XML in setXmlAttributes()
but in the case of persisting the symmetry, it must be read here and passed into the c'tor
since this is where the map from a name to an actual SymmetrySystem is maintained.
These edits are still responsible for saving the symmetry name to XML in getXmlAttributes().
Also see the comments of commit # 8c8cb08a1e4d71f91f24669b203fef0378230b19 on 3/8/2015
*/
SymmetrySystem symmetry = this .symmetrySystems .get( xml .getAttribute( "symmetry" ) );
edit = new SelectSimilarSizeStruts( symmetry, null, null, this .mSelection, this .mRealizedModel );
break;
case "SelectParallelStruts":
// See the note above about deserializing symmetry from XML.
SymmetrySystem symmsystem = this .symmetrySystems .get( xml .getAttribute( "symmetry" ) );
edit = new SelectParallelStruts( symmsystem, this .mSelection, this .mRealizedModel );
break;
case "SelectAutomaticStruts":
// See the note above about deserializing symmetry from XML.
symmsystem = this .symmetrySystems .get( xml .getAttribute( "symmetry" ) );
edit = new SelectAutomaticStruts( symmsystem, this .mSelection, this .mRealizedModel );
break;
case "SelectCollinear":
edit = new SelectCollinear( this .mSelection, this .mRealizedModel );
break;
case "ValidateSelection":
edit = new ValidateSelection( this.mSelection );
break;
case "SymmetryCenterChange":
edit = new SymmetryCenterChange( this.mEditorModel, null );
break;
case "SymmetryAxisChange":
edit = new SymmetryAxisChange( this.mEditorModel, null );
break;
case "RunZomicScript":
edit = new RunZomicScript( this.mSelection, this.mRealizedModel, null, mEditorModel.getCenterPoint() );
break;
case "RunPythonScript":
edit = new RunPythonScript( this.mSelection, this.mRealizedModel, null, mEditorModel.getCenterPoint() );
break;
case "BookmarkTool":
edit = new BookmarkTool( name, this.mSelection, this.mRealizedModel, this );
break;
case "ModuleTool":
edit = new ModuleTool( null, mSelection, mRealizedModel, this );
break;
case "PlaneSelectionTool":
edit = new PlaneSelectionTool( null, mSelection, mField, this );
break;
case "SymmetryTool":
edit = new SymmetryTool( null, null, this.mSelection, this.mRealizedModel, this, this.originPoint );
break;
case "ScalingTool":
edit = new ScalingTool( name, null, this.mSelection, this.mRealizedModel, this, this.originPoint );
break;
case "RotationTool":
edit = new RotationTool( name, null, this.mSelection, this.mRealizedModel, this, this.originPoint );
break;
case "InversionTool":
edit = new InversionTool( name, this.mSelection, this.mRealizedModel, this, this.originPoint );
break;
case "MirrorTool":
edit = new MirrorTool( name, this.mSelection, this.mRealizedModel, this, this.originPoint );
break;
case "TranslationTool":
edit = new TranslationTool( name, this.mSelection, this.mRealizedModel, this, this.originPoint );
break;
case "LinearMapTool":
edit = new LinearMapTool( name, this.mSelection, this.mRealizedModel, this, this.originPoint, true );
break;
case "AxialStretchTool":
IcosahedralSymmetry icosasymm = (IcosahedralSymmetry) mField .getSymmetry( "icosahedral" );
edit = new AxialStretchTool( name, icosasymm, mSelection, mRealizedModel, this, false, true, false );
break;
case "LinearTransformTool":
edit = new LinearMapTool( name, this.mSelection, this.mRealizedModel, this, this.originPoint, false );
break;
case "ToolApplied":
edit = new ApplyTool( this.mSelection, this.mRealizedModel, this, false );
break;
case "ApplyTool":
edit = new ApplyTool( this.mSelection, this.mRealizedModel, this, true );
break;
case RealizeMetaParts.NAME:
edit = new RealizeMetaParts( mSelection, mRealizedModel );
break;
case ShowVertices.NAME:
edit = new ShowVertices( mSelection, mRealizedModel );
break;
case "SelectToolParameters":
edit = new SelectToolParameters( this.mSelection, this.mRealizedModel, this, null );
break;
case "Symmetry4d":
QuaternionicSymmetry h4symm = this .mField .getQuaternionSymmetry( "H_4" );
edit = new Symmetry4d( this.mSelection, this.mRealizedModel, h4symm, h4symm );
break;
}
if ( edit == null )
// any command unknown (i.e. from a newer version of vZome) becomes a CommandEdit
edit = new CommandEdit( null, mEditorModel, groupInSelection );
return edit;
}
public String copySelectionVEF()
{
StringWriter out = new StringWriter();
Exporter exporter = new VefModelExporter( out, mField );
for (Manifestation man : mSelection) {
exporter .exportManifestation( man );
}
exporter .finish();
return out .toString();
}
public void pasteVEF( String vefContent )
{
if( vefContent != null && vefContent.startsWith("vZome VEF" )) {
// Although older VEF formats don't all include the header and could possibly be successfully pasted here,
// we're going to limit it to at least something that includes a valid VEF header.
// We won't check the version number so we can still paste formats older than VERSION_W_FIRST
// as long as they at least include the minimal header.
UndoableEdit edit = new LoadVEF( this.mSelection, this.mRealizedModel, vefContent, null, null );
performAndRecord( edit );
}
}
public void applyTool( Tool tool, Tool.Registry registry, int modes )
{
UndoableEdit edit = new ApplyTool( this.mSelection, this.mRealizedModel, tool, registry, modes, true );
performAndRecord( edit );
}
public void selectToolParameters( TransformationTool tool )
{
UndoableEdit edit = new SelectToolParameters( this.mSelection, this.mRealizedModel, this, tool );
performAndRecord( edit );
}
public void applyQuaternionSymmetry( QuaternionicSymmetry left, QuaternionicSymmetry right )
{
UndoableEdit edit = new Symmetry4d( this.mSelection, this.mRealizedModel, left, right );
performAndRecord( edit );
}
public boolean doEdit( String action )
{
// TODO break all these cases out as dedicated DocumentModel methods
if ( this .mEditorModel .mSelection .isEmpty() && action .equals( "hideball" ) ) {
action = "showHidden";
}
Command command = (Command) commands .get( action );
if ( command != null )
{
CommandEdit edit = new CommandEdit( (AbstractCommand) command, mEditorModel, false );
this .performAndRecord( edit );
return true;
}
// if ( action.equals( "sixLattice" ) )
// edit = new SixLattice( mSelection, mRealizedModel, mDerivationModel );
// not supported currently, so I don't have to deal with the mTargetManifestation problem
// if ( action .equals( "reversePanel" ) )
// edit = new ReversePanel( mTargetManifestation, mSelection, mRealizedModel, mDerivationModel );
UndoableEdit edit = null;
switch (action) {
case "selectAll":
edit = mEditorModel.selectAll();
break;
case "unselectAll":
edit = mEditorModel.unselectAll();
break;
case "unselectBalls":
edit = mEditorModel.unselectConnectors();
break;
case "unselectStruts":
edit = mEditorModel.unselectStruts();
break;
case "selectNeighbors":
edit = mEditorModel.selectNeighbors();
break;
case "SelectAutomaticStruts":
edit = mEditorModel.selectAutomaticStruts(symmetrySystem);
break;
case "SelectCollinear":
edit = mEditorModel.selectCollinear();
break;
case "SelectParallelStruts":
edit = mEditorModel.selectParallelStruts(symmetrySystem);
break;
case "invertSelection":
edit = mEditorModel.invertSelection();
break;
case "group":
edit = mEditorModel.groupSelection();
break;
case "ungroup":
edit = mEditorModel.ungroupSelection();
break;
case "assertSelection":
edit = new ValidateSelection( mSelection );
break;
case "delete":
edit = new Delete( mSelection, mRealizedModel );
break;
case "createStrut":
edit = new StrutCreation( null, null, null, mRealizedModel );
break;
case "joinballs":
edit = new JoinPoints( mSelection, mRealizedModel, false, JoinPoints.JoinModeEnum.CLOSED_LOOP );
break;
case "joinBallsAllToFirst":
edit = new JoinPoints( mSelection, mRealizedModel, false, JoinPoints.JoinModeEnum.ALL_TO_FIRST );
break;
case "joinBallsAllToLast":
edit = new JoinPoints( mSelection, mRealizedModel, false, JoinPoints.JoinModeEnum.ALL_TO_LAST );
break;
case "joinBallsAllPossible":
edit = new JoinPoints( mSelection, mRealizedModel, false, JoinPoints.JoinModeEnum.ALL_POSSIBLE );
break;
case "ballAtOrigin":
edit = new ShowPoint( originPoint, mSelection, mRealizedModel, false );
break;
case "ballAtSymmCenter":
edit = new ShowPoint( mEditorModel.getCenterPoint(), mSelection, mRealizedModel, false );
break;
case "linePlaneIntersect":
edit = new LinePlaneIntersect( mSelection, mRealizedModel, false );
break;
case "lineLineIntersect":
edit = new StrutIntersection( mSelection, mRealizedModel, false );
break;
case "heptagonDivide":
edit = new HeptagonSubdivision( mSelection, mRealizedModel, false );
break;
case "crossProduct":
edit = new CrossProduct( mSelection, mRealizedModel, false );
break;
case "centroid":
edit = new Centroid( mSelection, mRealizedModel, false );
break;
case "showHidden":
edit = new ShowHidden( mSelection, mRealizedModel, false );
break;
case RealizeMetaParts.NAME:
edit = new RealizeMetaParts( mSelection, mRealizedModel );
break;
case "affinePentagon":
edit = new AffinePentagon( mSelection, mRealizedModel );
break;
case "affineHeptagon":
edit = new AffineHeptagon( mSelection, mRealizedModel );
break;
case "affineTransformAll":
edit = new AffineTransformAll( mSelection, mRealizedModel, mEditorModel.getCenterPoint(), false );
break;
case "dodecagonsymm":
edit = new DodecagonSymmetry( mSelection, mRealizedModel, mEditorModel.getCenterPoint(), false );
break;
case "ghostsymm24cell":
edit = new GhostSymmetry24Cell( mSelection, mRealizedModel, mEditorModel.getSymmetrySegment(), false );
break;
case "apiProxy":
edit = new ApiEdit( this .mSelection, this .mRealizedModel, this .originPoint );
break;
default:
if ( action.startsWith( "polytope_" ) )
{
int beginIndex = "polytope_".length();
String group = action.substring( beginIndex, beginIndex + 2 );
String suffix = action.substring( beginIndex + 2 );
System.out.println( "computing " + group + " " + suffix );
int index = Integer.parseInt( suffix, 2 );
edit = new Polytope4d( mSelection, mRealizedModel, mEditorModel.getSymmetrySegment(),
index, group, false );
} else if ( action.startsWith( "setItemColor/" ) )
{
String value = action .substring( "setItemColor/" .length() );
edit = new ColorManifestations( mSelection, mRealizedModel, new Color( value ), false );
}
else if ( ShowVertices.NAME .toLowerCase() .equals( action .toLowerCase() ) ) {
edit = new ShowVertices( mSelection, mRealizedModel );
} else if ( action .toLowerCase() .equals( "chainballs" ) ) {
edit = new JoinPoints( mSelection, mRealizedModel, false, JoinPoints.JoinModeEnum.CHAIN_BALLS );
}
}
if ( edit == null )
{
logger .warning( "no DocumentModel action for : " + action );
return false;
}
this .performAndRecord( edit );
return true;
}
@Override
public void performAndRecord( UndoableEdit edit )
{
if ( edit == null )
return;
if ( edit instanceof NoOp )
return;
try {
synchronized ( this .mHistory ) {
edit .perform();
this .mHistory .mergeSelectionChanges();
this .mHistory .addEdit( edit, DocumentModel.this );
}
}
catch ( RuntimeException re )
{
Throwable cause = re.getCause();
if ( cause instanceof Command.Failure )
this .failures .reportFailure( (Command.Failure) cause );
else if ( cause != null )
this .failures .reportFailure( new Command.Failure( cause ) );
else
this .failures .reportFailure( new Command.Failure( re ) );
}
catch ( Command.Failure failure )
{
this .failures .reportFailure( failure );
}
this .changes++;
}
public void setParameter( Construction singleConstruction, String paramName ) throws Command.Failure
{
UndoableEdit edit = null;
if ( "ball" .equals( paramName ) )
edit = mEditorModel .setSymmetryCenter( singleConstruction );
else if ( "strut" .equals( paramName ) )
edit = mEditorModel .setSymmetryAxis( (Segment) singleConstruction );
if ( edit != null )
this .performAndRecord( edit );
}
public RealVector getLocation( Construction target )
{
if ( target instanceof Point)
return ( (Point) target ).getLocation() .toRealVector();
else if ( target instanceof Segment )
return ( (Segment) target ).getStart() .toRealVector();
else if ( target instanceof Polygon )
return ( (Polygon) target ).getVertices()[ 0 ] .toRealVector();
else
return new RealVector( 0, 0, 0 );
}
public RealVector getParamLocation( String string )
{
if ( "ball" .equals( string ) )
{
Point ball = mEditorModel .getCenterPoint();
return ball .getLocation() .toRealVector();
}
return new RealVector( 0, 0, 0 );
}
public void selectCollinear( Strut strut )
{
UndoableEdit edit = new SelectCollinear( mSelection, mRealizedModel, strut );
this .performAndRecord( edit );
}
public void selectParallelStruts( Strut strut )
{
UndoableEdit edit = new SelectParallelStruts( this.symmetrySystem, mSelection, mRealizedModel, strut );
this .performAndRecord( edit );
}
public void selectSimilarStruts( Direction orbit, AlgebraicNumber length )
{
UndoableEdit edit = new SelectSimilarSizeStruts( this.symmetrySystem, orbit, length, mSelection, mRealizedModel );
this .performAndRecord( edit );
}
public Color getSelectionColor()
{
Manifestation last = null;
for (Manifestation man : mSelection) {
last = man;
}
return last == null ? null : last .getRenderedObject() .getColor();
}
public void finishLoading( boolean openUndone, boolean asTemplate ) throws Command.Failure
{
if ( mXML == null )
return;
// TODO: record the edition, version, and revision on the format, so we can report a nice
// error if we fail to understand some command in the history. If the revision is
// greater than Version .SVN_REVISION:
// "This document was created using $file.edition $file.version, and contains commands that
// $Version.edition does not understand. You may need a newer version of
// $Version.edition, or a copy of $file.edition $file.version."
// (Adjust that if $Version.edition == $file.edition, to avoid confusion.)
String tns = mXML .getNamespaceURI();
XmlSaveFormat format = XmlSaveFormat.getFormat( tns );
if ( format == null )
return; // already checked and reported version compatibility,
// up in the constructor
int scale = 0;
String scaleStr = mXML .getAttribute( "scale" );
if ( ! scaleStr .isEmpty() )
scale = Integer.parseInt( scaleStr );
OrbitSet.Field orbitSetField = new OrbitSet.Field()
{
@Override
public OrbitSet getGroup( String name )
{
SymmetrySystem system = symmetrySystems .get( name );
return system .getOrbits();
}
@Override
public QuaternionicSymmetry getQuaternionSet( String name )
{
return mField .getQuaternionSymmetry( name);
}
};
String writerVersion = mXML .getAttribute( "version" );
String buildNum = mXML .getAttribute( "buildNumber" );
if ( buildNum != null )
writerVersion += " build " + buildNum;
format .initialize( mField, orbitSetField, scale, writerVersion, new Properties() );
Element hist = (Element) mXML .getElementsByTagName( "EditHistory" ) .item( 0 );
if ( hist == null )
hist = (Element) mXML .getElementsByTagName( "editHistory" ) .item( 0 );
int editNum = Integer.parseInt( hist .getAttribute( "editNumber" ) );
List<Integer> implicitSnapshots = new ArrayList<>();
// if we're opening a template document, we don't want to inherit its lesson or saved views
if ( !asTemplate )
{
Map<String, Camera> viewPages = new HashMap<>();
Element views = (Element) mXML .getElementsByTagName( "Viewing" ) .item( 0 );
if ( views != null ) {
// make a notes page for each saved view
// ("edited" property change will be fired, to trigger migration semantics)
// migrate saved views to notes pages
NodeList nodes = views .getChildNodes();
for ( int i = 0; i < nodes .getLength(); i++ ) {
Node node = nodes .item( i );
if ( node instanceof Element ) {
Element viewElem = (Element) node;
String name = viewElem .getAttribute( "name" );
if ( name != null && ! name .isEmpty() && ! "default" .equals( name ) )
{
Camera view = new Camera( viewElem );
viewPages .put( name, view ); // named view to migrate to a lesson page
}
}
}
}
Element notesXml = (Element) mXML .getElementsByTagName( "notes" ) .item( 0 );
if ( notesXml != null )
lesson .setXml( notesXml, editNum, this .defaultView );
// add migrated views to the end of the lesson
for (Entry<String, Camera> namedView : viewPages .entrySet()) {
lesson .addPage( namedView .getKey(), "This page was a saved view created by an older version of vZome.", namedView .getValue(), -editNum );
}
for (PageModel page : lesson) {
int snapshot = page .getSnapshot();
if ( ( snapshot < 0 ) && ( ! implicitSnapshots .contains(-snapshot) ) )
implicitSnapshots .add(-snapshot);
}
Collections .sort( implicitSnapshots );
for (PageModel page : lesson) {
int snapshot = page .getSnapshot();
if ( snapshot < 0 )
page .setSnapshot( implicitSnapshots .indexOf(-snapshot) );
}
}
UndoableEdit[] explicitSnapshots = null;
if ( ! implicitSnapshots .isEmpty() )
{
Integer highest = implicitSnapshots .get( implicitSnapshots .size() - 1 );
explicitSnapshots = new UndoableEdit[ highest + 1 ];
for (int i = 0; i < implicitSnapshots .size(); i++)
{
Integer editNumInt = implicitSnapshots .get( i );
explicitSnapshots[ editNumInt ] = new Snapshot( i, this );
}
}
try {
int lastDoneEdit = openUndone? 0 : Integer.parseInt( hist .getAttribute( "editNumber" ) );
String lseStr = hist .getAttribute( "lastStickyEdit" );
int lastStickyEdit = ( ( lseStr == null ) || lseStr .isEmpty() )? -1 : Integer .parseInt( lseStr );
NodeList nodes = hist .getChildNodes();
for ( int i = 0; i < nodes .getLength(); i++ ) {
Node kid = nodes .item( i );
if ( kid instanceof Element ) {
Element editElem = (Element) kid;
mHistory .loadEdit( format, editElem, this );
}
}
mHistory .synchronize( lastDoneEdit, lastStickyEdit, explicitSnapshots );
} catch ( Throwable t )
{
String fileVersion = mXML .getAttribute( "coreVersion" );
if ( this .fileIsTooNew( fileVersion ) ) {
String message = "This file was authored with a newer version, " + format .getToolVersion( mXML );
throw new Command.Failure( message, t );
} else {
String message = "There was a problem opening this file. Please send the file to bugs@vzome.com.";
throw new Command.Failure( message, t );
}
}
this .migrated = openUndone || format.isMigration() || ! implicitSnapshots .isEmpty();
}
boolean fileIsTooNew( String fileVersion )
{
if ( fileVersion == null || "" .equals( fileVersion ) )
return false;
String[] fvTokens = fileVersion .split( "\\." );
String[] cvTokens = this .coreVersion .split( "\\." );
for (int i = 0; i < cvTokens.length; i++) {
try {
int codepart = Integer .parseInt( cvTokens[ i ] );
int filepart = Integer .parseInt( fvTokens[ i ] );
if ( filepart > codepart )
return true;
} catch ( NumberFormatException e ) {
return false;
}
}
return false;
}
public Element getDetailsXml( Document doc )
{
Element vZomeRoot = doc .createElementNS( XmlSaveFormat.CURRENT_FORMAT, "vzome:vZome" );
vZomeRoot .setAttribute( "xmlns:vzome", XmlSaveFormat.CURRENT_FORMAT );
vZomeRoot .setAttribute( "field", mField.getName() );
Element result = mHistory .getDetailXml( doc );
vZomeRoot .appendChild( result );
return vZomeRoot;
}
/**
* For backward-compatibility
* @param out
* @throws Exception
*/
public void serialize( OutputStream out ) throws Exception
{
Properties props = new Properties();
props .setProperty( "edition", "vZome" );
props .setProperty( "version", "5.0" );
this .serialize( out, props );
}
public void serialize( OutputStream out, Properties editorProps ) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance();
factory .setNamespaceAware( true );
DocumentBuilder builder = factory .newDocumentBuilder();
Document doc = builder .newDocument();
Element vZomeRoot = doc .createElementNS( XmlSaveFormat.CURRENT_FORMAT, "vzome:vZome" );
vZomeRoot .setAttribute( "xmlns:vzome", XmlSaveFormat.CURRENT_FORMAT );
String value = editorProps .getProperty( "edition" );
if ( value != null )
vZomeRoot .setAttribute( "edition", value );
value = editorProps .getProperty( "version" );
if ( value != null )
vZomeRoot .setAttribute( "version", value );
value = editorProps .getProperty( "buildNumber" );
if ( value != null )
vZomeRoot .setAttribute( "buildNumber", value );
vZomeRoot .setAttribute( "coreVersion", this .coreVersion );
vZomeRoot .setAttribute( "field", mField.getName() );
Element childElement;
{
childElement = mHistory .getXml( doc );
int edits = 0, lastStickyEdit=-1;
for (UndoableEdit undoable : mHistory) {
childElement .appendChild( undoable .getXml( doc ) );
++ edits;
if ( undoable .isSticky() )
lastStickyEdit = edits;
}
childElement .setAttribute( "lastStickyEdit", Integer .toString( lastStickyEdit ) );
}
vZomeRoot .appendChild( childElement );
doc .appendChild( vZomeRoot );
childElement = lesson .getXml( doc );
vZomeRoot .appendChild( childElement );
childElement = sceneLighting .getXml( doc );
vZomeRoot .appendChild( childElement );
childElement = doc .createElement( "Viewing" );
Element viewXml = this .defaultView .getXML( doc );
childElement .appendChild( viewXml );
vZomeRoot .appendChild( childElement );
childElement = this .symmetrySystem .getXml( doc );
vZomeRoot .appendChild( childElement );
DomUtils .serialize( doc, out );
}
public void doScriptAction( String command, String script )
{
UndoableEdit edit = null;
if ( command.equals( "runZomicScript" ) || command.equals( "zomic" ) )
{
edit = new RunZomicScript( mSelection, mRealizedModel, script, mEditorModel.getCenterPoint() );
this .performAndRecord( edit );
}
else if ( command.equals( "runPythonScript" ) || command.equals( "py" ) )
{
edit = new RunPythonScript( mSelection, mRealizedModel, script, mEditorModel.getCenterPoint() );
this .performAndRecord( edit );
}
// else if ( command.equals( "import.zomod" ) )
// edit = new RunZomodScript( mSelection, mRealizedModel, script, mEditorModel.getCenterPoint(), mField .getSymmetry( "icosahedral" ) );
else if ( command.equals( "import.vef" ) || command.equals( "vef" ) )
{
Segment symmAxis = mEditorModel .getSymmetrySegment();
AlgebraicVector quat = ( symmAxis == null ) ? null : symmAxis.getOffset();
if ( quat != null )
quat = quat .scale( mField .createPower( - 5 ) );
AlgebraicNumber scale = mField .createPower( 5 );
edit = new LoadVEF( mSelection, mRealizedModel, script, quat, scale );
this .performAndRecord( edit );
}
}
@Override
public void addTool( Tool tool )
{
String name = tool .getName();
tools .put( name, tool );
firePropertyChange( "tool.instances", null, name );
}
@Override
public Tool findEquivalent( Tool tool )
{
for ( Map.Entry<String, Tool> entry : tools .entrySet() )
{
if ( entry .getValue() .equals( tool ) )
return entry .getValue();
}
return null;
}
@Override
public Tool getTool( String toolName )
{
return tools .get( toolName );
}
public AlgebraicField getField()
{
return this .mField;
}
public void addSelectionListener( ManifestationChanges listener )
{
this .mSelection .addListener( listener );
}
private static final NumberFormat FORMAT = NumberFormat .getNumberInstance( Locale .US );
/**
* @deprecated As of 8/11/2016:
* This code will continue to function properly,
* but its functionality has been replicated in vzome-desktop.
*
* Formatting such information for display should not be a function of vzome-core.
*
* When all references to this method have been replaced,
* then it should be removed from vzome-core.
*/
@Deprecated
public String getManifestationProperties( Manifestation man, OrbitSource symmetry )
{
if ( man instanceof Connector )
{
StringBuffer buf;
AlgebraicVector loc = man .getLocation();
System .out .println( loc .getVectorExpression( AlgebraicField.EXPRESSION_FORMAT ) );
System .out .println( loc .getVectorExpression( AlgebraicField.ZOMIC_FORMAT ) );
System .out .println( loc .getVectorExpression( AlgebraicField.VEF_FORMAT ) );
buf = new StringBuffer();
buf .append( "location: " );
loc .getVectorExpression( buf, AlgebraicField.DEFAULT_FORMAT );
return buf.toString();
}
else if ( man instanceof Strut ) {
StringBuffer buf = new StringBuffer();
buf.append( "start: " );
Strut strut = Strut.class.cast(man);
strut .getLocation() .getVectorExpression( buf, AlgebraicField.DEFAULT_FORMAT );
buf.append( "\n\noffset: " );
AlgebraicVector offset = strut .getOffset();
System .out .println( offset .getVectorExpression( AlgebraicField.EXPRESSION_FORMAT ) );
System .out .println( offset .getVectorExpression( AlgebraicField.ZOMIC_FORMAT ) );
System .out .println( offset .getVectorExpression( AlgebraicField.VEF_FORMAT ) );
offset .getVectorExpression( buf, AlgebraicField.DEFAULT_FORMAT );
buf.append( "\n\nnorm squared: " );
AlgebraicNumber normSquared = offset .dot( offset );
double norm2d = normSquared .evaluate();
normSquared .getNumberExpression( buf, AlgebraicField.DEFAULT_FORMAT );
buf.append( " = " );
buf.append( FORMAT.format( norm2d ) );
if ( offset .isOrigin() )
return "zero length!";
Axis zone = symmetry .getAxis( offset );
AlgebraicNumber len = zone .getLength( offset );
len = zone .getOrbit() .getLengthInUnits( len );
buf.append( "\n\nlength in orbit units: " );
len .getNumberExpression( buf, AlgebraicField.DEFAULT_FORMAT );
if ( mField instanceof PentagonField)
{
buf.append( "\n\nlength in Zome b1 struts: " );
if (FORMAT instanceof DecimalFormat) {
((DecimalFormat) FORMAT) .applyPattern( "0.0000" );
}
buf.append( FORMAT.format( Math.sqrt( norm2d ) / PentagonField.B1_LENGTH ) );
}
return buf .toString();
}
else if ( man instanceof Panel ) {
Panel panel = Panel.class.cast(man);
StringBuffer buf = new StringBuffer();
buf .append( "vertices: " );
buf .append( panel.getVertexCount() );
String delim = "";
for( AlgebraicVector vertex : panel) {
buf.append(delim);
buf.append("\n ");
vertex .getVectorExpression( buf, AlgebraicField.DEFAULT_FORMAT );
delim = ",";
}
AlgebraicVector normal = panel .getNormal();
buf .append( "\n\nnormal: " );
normal .getVectorExpression( buf, AlgebraicField.DEFAULT_FORMAT );
buf.append("\n\nnorm squared: ");
AlgebraicNumber normSquared = normal.dot(normal);
double norm2d = normSquared.evaluate();
normSquared.getNumberExpression(buf, AlgebraicField.DEFAULT_FORMAT);
buf.append(" = ");
buf.append(FORMAT.format(norm2d));
Axis zone = symmetry .getAxis( normal );
Direction direction = zone.getDirection();
buf.append( "\n\ndirection: " );
if( direction.isAutomatic() ) {
buf.append( "Automatic " );
}
buf.append( direction.getName() );
return buf.toString();
}
return man.getClass().getSimpleName();
}
public void undo( boolean useBlocks )
{
mHistory .undo( useBlocks );
}
public void redo( boolean useBlocks ) throws Command.Failure
{
mHistory .redo( useBlocks );
}
public void undo()
{
mHistory .undo();
}
public void redo() throws Command.Failure
{
mHistory .redo();
}
public void undoToBreakpoint()
{
mHistory .undoToBreakpoint();
}
public void undoToManifestation( Manifestation man )
{
mHistory .undoToManifestation( man );
}
public void redoToBreakpoint() throws Command.Failure
{
mHistory .redoToBreakpoint();
}
public void setBreakpoint()
{
mHistory .setBreakpoint();
}
public void undoAll()
{
mHistory .undoAll();
}
public void redoAll( int i ) throws Command .Failure
{
mHistory .redoAll( i );
}
public UndoableEdit deselectAll()
{
return mEditorModel .unselectAll();
}
public UndoableEdit selectManifestation( Manifestation target, boolean replace )
{
return mEditorModel .selectManifestation( target, replace );
}
public void createStrut( Point point, Axis zone, AlgebraicNumber length )
{
UndoableEdit edit = new StrutCreation( point, zone, length, this .mRealizedModel );
this .performAndRecord( edit );
}
public boolean isToolEnabled( String group, Symmetry symmetry )
{
Tool tool = (Tool) makeTool( group + ".0/UNUSED", group, null, symmetry ); // TODO: get rid of isAutomatic() and isTetrahedral() silliness, so the string won't get parsed
return tool != null && tool .isValidForSelection();
}
public void createTool( String name, String group, Tool.Registry tools, Symmetry symmetry )
{
UndoableEdit edit = makeTool( name, group, tools, symmetry );
performAndRecord( edit );
}
private UndoableEdit makeTool( String name, String group, Tool.Registry tools, Symmetry symmetry )
{
UndoableEdit edit = null;
switch (group) {
case "bookmark":
edit = new BookmarkTool( name, mSelection, mRealizedModel, tools );
break;
case "point reflection":
edit = new InversionTool( name, mSelection, mRealizedModel, tools, originPoint );
break;
case "mirror":
edit = new MirrorTool( name, mSelection, mRealizedModel, tools, originPoint );
break;
case "translation":
edit = new TranslationTool( name, mSelection, mRealizedModel, tools, originPoint );
break;
case "linear map":
edit = new LinearMapTool( name, mSelection, mRealizedModel, tools, originPoint, false );
break;
case "rotation":
edit = new RotationTool( name, symmetry, mSelection, mRealizedModel, tools, originPoint, false );
break;
case "axial symmetry":
edit = new RotationTool( name, symmetry, mSelection, mRealizedModel, tools, originPoint, true );
break;
case "scaling":
edit = new ScalingTool( name, symmetry, mSelection, mRealizedModel, tools, originPoint );
break;
case "scale up":
edit = new ScalingTool( name, tools, getField() .createPower( 1 ), originPoint );
break;
case "scale down":
edit = new ScalingTool( name, tools, getField() .createPower( -1 ), originPoint );
break;
case "tetrahedral":
edit = new SymmetryTool( name, symmetry, mSelection, mRealizedModel, tools, originPoint );
break;
case "module":
edit = new ModuleTool( name, mSelection, mRealizedModel, tools );
break;
case "plane":
edit = new PlaneSelectionTool( name, mSelection, mField, tools );
break;
case "yellowstretch":
if ( symmetry instanceof IcosahedralSymmetry )
edit = new AxialStretchTool( name, (IcosahedralSymmetry) symmetry, mSelection, mRealizedModel, tools, true, false, false );
break;
case "yellowsquash":
if ( symmetry instanceof IcosahedralSymmetry )
edit = new AxialStretchTool( name, (IcosahedralSymmetry) symmetry, mSelection, mRealizedModel, tools, false, false, false );
break;
case "redstretch1":
if ( symmetry instanceof IcosahedralSymmetry )
edit = new AxialStretchTool( name, (IcosahedralSymmetry) symmetry, mSelection, mRealizedModel, tools, true, true, true );
break;
case "redsquash1":
if ( symmetry instanceof IcosahedralSymmetry )
edit = new AxialStretchTool( name, (IcosahedralSymmetry) symmetry, mSelection, mRealizedModel, tools, false, true, true );
break;
case "redstretch2":
if ( symmetry instanceof IcosahedralSymmetry )
edit = new AxialStretchTool( name, (IcosahedralSymmetry) symmetry, mSelection, mRealizedModel, tools, true, true, false );
break;
case "redsquash2":
if ( symmetry instanceof IcosahedralSymmetry )
edit = new AxialStretchTool( name, (IcosahedralSymmetry) symmetry, mSelection, mRealizedModel, tools, false, true, false );
break;
default:
edit = new SymmetryTool( name, symmetry, mSelection, mRealizedModel, tools, originPoint );
break;
}
return edit;
}
public Exporter3d getNaiveExporter( String format, Camera view, Colors colors, Lights lights, RenderedModel currentSnapshot )
{
Exporter3d exporter = null;
if ( format.equals( "pov" ) )
exporter = new POVRayExporter( view, colors, lights, currentSnapshot );
else if ( format.equals( "opengl" ) )
exporter = new OpenGLExporter( view, colors, lights, currentSnapshot );
boolean inArticleMode = (renderedModel != currentSnapshot);
if(exporter != null && exporter.needsManifestations() && inArticleMode ) {
throw new IllegalStateException("The " + format + " exporter can only operate on the current model, not article pages.");
}
return exporter;
}
/*
* These exporters fall in two categories: rendering and geometry. The ones that support the currentSnapshot
* (the current article page, or the main model) can do rendering export, and can work with just a rendered
* model (a snapshot), which has lost its attached Manifestation objects.
*
* The ones that require mRenderedModel need access to the RealizedModel objects hanging from it (the
* Manifestations). These are the geometry exporters. They can be aware of the structure of field elements,
* as well as the orbits and zones.
*
* POV-Ray is a bit of a special case, but only because the .pov language supports coordinate values as expressions,
* and supports enough modeling that the different strut shapes can be defined, and so on.
* OpenGL and WebGL (Web3d/json) could as well, since I can control how the data is stored and rendered.
*
* The POV-Ray export reuses shapes, etc. just as vZome does, so really works just with the RenderedManifestations
* (except when the Manifestation is available for structured coordinate expressions). Again, any rendering exporter
* could apply the same reuse tricks, working just with RenderedManifestations, so the current limitations to
* mRenderedModel for many of these is spurious.
*
* The base Exporter3d class now has a boolean needsManifestations() method which subclasses should override
* if they don't rely on Manifestations and therefore can operate on article pages.
*/
// TODO move all the parameters inside this object!
public Exporter3d getStructuredExporter( String format, Camera view, Colors colors, Lights lights, RenderedModel mRenderedModel )
{
if ( format.equals( "partgeom" ) )
return new PartGeometryExporter( view, colors, lights, mRenderedModel, mSelection );
else
return null;
}
public LessonModel getLesson()
{
return lesson;
}
@Override
public void recordSnapshot( int id )
{
RenderedModel snapshot = ( renderedModel == null )? null : renderedModel .snapshot();
if ( thumbnailLogger .isLoggable( Level.FINER ) )
thumbnailLogger .finer( "recordSnapshot: " + id );
numSnapshots = Math .max( numSnapshots, id + 1 );
if ( id >= snapshots.length )
{
int newLength = Math .max( 2 * snapshots .length, numSnapshots );
snapshots = Arrays .copyOf( snapshots, newLength );
}
snapshots[ id ] = snapshot;
}
@Override
public void actOnSnapshot( int id, SnapshotAction action )
{
RenderedModel snapshot = snapshots[ id ];
action .actOnSnapshot( snapshot );
}
public void addSnapshotPage( Camera view )
{
int id = numSnapshots;
this .performAndRecord( new Snapshot( id, this ) );
lesson .newSnapshotPage( id, view );
}
public RenderedModel getRenderedModel()
{
return this .renderedModel;
}
public Camera getViewModel()
{
return this .defaultView;
}
public void generatePolytope( String group, String renderGroup, int index, int edgesToRender, AlgebraicVector quaternion, AlgebraicNumber[] edgeScales )
{
UndoableEdit edit = new Polytope4d( mSelection, mRealizedModel, quaternion, index, group, edgesToRender, edgeScales, renderGroup );
this .performAndRecord( edit );
}
public void generatePolytope( String group, String renderGroup, int index, int edgesToRender, AlgebraicNumber[] edgeScales )
{
UndoableEdit edit = new Polytope4d( mSelection, mRealizedModel, mEditorModel.getSymmetrySegment(), index, group, edgesToRender, edgeScales, renderGroup );
this .performAndRecord( edit );
}
public Segment getSelectedSegment()
{
return (Segment) mEditorModel .getSelectedConstruction( Segment.class );
}
public Segment getSymmetryAxis()
{
return mEditorModel .getSymmetrySegment();
}
public Segment getPlaneAxis( Polygon panel )
{
AlgebraicVector[] vertices = panel.getVertices();
FreePoint p0 = new FreePoint( vertices[ 0 ] );
FreePoint p1 = new FreePoint( vertices[ 1 ] );
FreePoint p2 = new FreePoint( vertices[ 2 ] );
Segment s1 = new SegmentJoiningPoints( p0, p1 );
Segment s2 = new SegmentJoiningPoints( p1, p2 );
return new SegmentCrossProduct( s1, s2 );
}
public RealizedModel getRealizedModel()
{
return this .mRealizedModel;
}
public Iterable<Tool> getTools()
{
return this .tools .values();
}
public SymmetrySystem getSymmetrySystem()
{
return this .symmetrySystem;
}
public SymmetrySystem getSymmetrySystem( String name )
{
return this .symmetrySystems .get( name );
}
public void setSymmetrySystem( String name )
{
this .symmetrySystem = this .symmetrySystems .get( name );
}
}
|
package com.wizzardo.http.websocket;
import java.util.ArrayList;
import java.util.List;
public class Message {
private List<Frame> frames = new ArrayList<>();
public boolean isComplete() {
if (frames.isEmpty())
return false;
Frame frame = frames.get(frames.size() - 1);
return frame.isFinalFrame() && frame.isComplete();
}
void add(Frame frame) {
if (!frames.isEmpty())
frames.get(frames.size() - 1).setIsFinalFrame(false);
frames.add(frame);
}
public Message append(String s) {
return append(s.getBytes());
}
public Message append(byte[] bytes) {
return append(bytes, 0, bytes.length);
}
public Message append(byte[] bytes, int offset, int length) {
Frame frame = new Frame();
frame.setData(bytes, offset, length);
add(frame);
return this;
}
public String asString() {
return new String(asBytes());
}
public byte[] asBytes() {
int length = 0;
for (Frame frame : frames)
length += frame.getLength();
int offset = 0;
byte[] data = new byte[length];
for (Frame frame : frames) {
System.arraycopy(frame.getData(), frame.getOffset(), data, offset, frame.getLength());
offset += frame.getLength();
}
return data;
}
List<Frame> getFrames() {
return frames;
}
}
|
package controller;
import handler.ConfigHandler;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import misc.Job;
import misc.Logger;
import model.JobSetupDialogModel;
import org.apache.commons.lang3.exception.ExceptionUtils;
import view.JobSetupDialogView;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
public class JobSetupDialogController extends Stage implements EventHandler {
// todo JavaDoc
private final JobSetupDialogView view;
// todo JavaDoc
private final JobSetupDialogModel model;
/** The object that handles settings for encoding, decoding, compression, and a number of other features. */
private final ConfigHandler configHandler;
/**
* Construct a new job setup dialog controller.
* @param configHandler The object that handles settings for encoding, decoding, compression, and a number of other features.
*/
public JobSetupDialogController(final Stage primaryStage, final ConfigHandler configHandler) {
this.configHandler = configHandler;
view = new JobSetupDialogView(primaryStage, this, configHandler);
model = new JobSetupDialogModel();
// Setup Stage:
final Scene scene = new Scene(view);
scene.getStylesheets().add("global.css");
scene.getRoot().getStyleClass().add("main-root");
this.initModality(Modality.APPLICATION_MODAL);
this.getIcons().add(new Image("icon.png"));
this.setScene(scene);
}
@Override
public void handle(Event event) {
final Object source = event.getSource();
// The button to open the handler selection dialog.
if(source.equals(view.getButton_addFiles())) {
final FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Job File Selection");
final List<File> selectedFiles = fileChooser.showOpenMultipleDialog(this);
if(selectedFiles != null) {
model.getList_files().addAll(selectedFiles);
// Add all of the files to the list:
for(final File f : selectedFiles) {
view.getListView_selectedFiles().getItems().add(f.getAbsolutePath());
}
}
}
// The button to remove all files that are currently selected on the scrollpane_selectedFiles.
if(source.equals(view.getButton_removeSelectedFiles())) {
// If a copy of the observable list is not made, then errors can occur.
// These errors are caused by the ObservableList updating as items are being removed.
// This causes items that shouldn't be removed to be removed.
final ObservableList<String> copy = FXCollections.observableArrayList(view.getListView_selectedFiles().getSelectionModel().getSelectedItems());
view.getListView_selectedFiles().getItems().removeAll(copy);
// Remove Jobs from the Model while updating
// the IDs of all Jobs.
final Iterator<File> it = model.getList_files().iterator();
while(it.hasNext()) {
final File f = it.next();
if(view.getListView_selectedFiles().getItems().contains(f.getAbsolutePath()) == false) {
it.remove();
}
}
view.getListView_selectedFiles().getSelectionModel().clearSelection();
}
// The button to remove all files from the list.
if(source.equals(view.getButton_clearAllFiles())) {
model.getList_files().clear();
view.getListView_selectedFiles().getItems().clear();
view.getListView_selectedFiles().getSelectionModel().clearSelection();
}
// The radio button that says that each of the currently selected files should be archived as a single archive before encoding.
if(source.equals(view.getRadioButton_singleArchive_yes())) {
// Ensure that both the single and individual archive options aren't
// selected at the same time.
view.getRadioButton_individualArchives_no().setSelected(true);
}
// The radio button that says that each handler should be archived individually before encoding each of them individually.
if(source.equals(view.getRadioButton_individualArchives_yes())) {
// Ensure that both the single and individual archive options aren't
// selected at the same time.
view.getRadioButton_singleArchive_no().setSelected(true);
}
// The button to select the folder to output the archive to if the "Yes" radio button is selected.
if(source.equals(view.getButton_selectOutputDirectory())) {
final JFileChooser fileChooser = new JFileChooser();
fileChooser.setDragEnabled(false);
fileChooser.setMultiSelectionEnabled(false);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setDialogTitle("Directory Slection");
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
fileChooser.setApproveButtonText("Accept");
fileChooser.setApproveButtonToolTipText("Accept the selected directory.");
try {
int returnVal = fileChooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
view.getTextField_outputDirectory().setText(fileChooser.getSelectedFile().getPath() + "/");
}
} catch(final HeadlessException e) {
Logger.writeLog(e.getMessage() + "\n\n" + ExceptionUtils.getStackTrace(e), Logger.LOG_TYPE_WARNING);
}
}
// The button to close the JobCreationDialog without creating a Job.
if(source.equals(view.getButton_accept())) {
if(areSettingsCorrect() == false) {
final String name = view.getField_jobName().getText();
final String description = view.getTextArea_jobDescription().getText();
final String outputDirectory = view.getTextField_outputDirectory().getText();
final List<File> files = model.getList_files();
final boolean isEncodeJob = view.getIsEncodeJob();
final boolean combineAllFilesIntoSingleArchive = view.getRadioButton_singleArchive_yes().isSelected();
final boolean combineIntoIndividualArchives = view.getRadioButton_individualArchives_yes().isSelected();
final Job job = new Job(name, description, outputDirectory, files, isEncodeJob, combineAllFilesIntoSingleArchive, combineIntoIndividualArchives);
model.setJob(job);
this.close();
}
}
// The button to close the JobCreationDialog while creating a Job.
if(source.equals(view.getButton_cancel())) {
model.setJob(null);
this.close();
}
updateEstimatedDurationLabel();
}
// todo Javadoc
public boolean areSettingsCorrect() {
boolean wasErrorFound = false;
// Reset the error states and tooltips of any components
// that can have an error state set.
// Set the password fields back to their normal look:
view.getField_jobName().getStylesheets().remove("field_error.css");
view.getField_jobName().getStylesheets().add("global.css");
view.getField_jobName().setTooltip(null);
view.getTextField_outputDirectory().getStylesheets().remove("field_error.css");
view.getTextField_outputDirectory().getStylesheets().add("global.css");
view.getTextField_outputDirectory().setTooltip(new Tooltip("The directory in which to place the en/decoded file(s)."));
// Check to see that the Job has been given a name.
if(view.getField_jobName().getText().isEmpty()) {
view.getField_jobName().getStylesheets().remove("global.css");
view.getField_jobName().getStylesheets().add("field_error.css");
final String errorText = "Error - You need to enter a name for the Job.";
view.getField_jobName().setTooltip(new Tooltip(errorText));
wasErrorFound = true;
}
// Check to see that the output directory exists:
if(view.getTextField_outputDirectory().getText().isEmpty() || Files.exists(Paths.get(view.getTextField_outputDirectory().getText())) == false) {
view.getTextField_outputDirectory().getStylesheets().remove("global.css");
view.getTextField_outputDirectory().getStylesheets().add("field_error.css");
final Tooltip currentTooltip = view.getTextField_outputDirectory().getTooltip();
final String errorText = "Error - You need to set an output directory for the Job.";
view.getField_jobName().setTooltip(new Tooltip(currentTooltip.getText() + "\n\n" + errorText));
wasErrorFound = true;
}
if(Files.isDirectory(Paths.get(view.getTextField_outputDirectory().getText())) == false) {
view.getTextField_outputDirectory().getStylesheets().remove("global.css");
view.getTextField_outputDirectory().getStylesheets().add("field_error.css");
final Tooltip currentTooltip = view.getTextField_outputDirectory().getTooltip();
final String errorText = "Error - You need to set a valid output directory for the Job.";
view.getField_jobName().setTooltip(new Tooltip(currentTooltip.getText() + "\n\n" + errorText));
wasErrorFound = true;
}
return wasErrorFound;
}
// todo JavaDoc
public void updateEstimatedDurationLabel() {
if(model.getJob() != null) {
view.getLabel_job_estimatedDurationInMinutes().setText("Estimated Time - " + model.getJob().getEstimatedDurationInMinutes() + " Minutes");
} else {
view.getLabel_job_estimatedDurationInMinutes().setText("Estimated Time - Unknown");
}
}
////////////////////////////////////////////////////////// Getters
// todo JavaDoc
public JobSetupDialogView getView() {
return view;
}
// todo JavaDoc
public JobSetupDialogModel getModel() {
return model;
}
}
|
package de.braintags.vertx.util.url;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.commons.lang3.StringUtils;
public class UrlUtil {
private UrlUtil() {
}
public static String concatPaths(final String... paths) {
return concatPaths(false, paths);
}
public static String concatPaths(final boolean absolute, final String... paths) {
StringBuilder result = new StringBuilder();
boolean endsWithSlash = absolute;
if (absolute) {
result.append("/");
}
for (int i = 0; i < paths.length; i++) {
String path = paths[i];
if (StringUtils.isEmpty(path))
continue;
if (i != 0 || absolute) {
boolean startsWithSlash = path.charAt(0) == '/';
if (startsWithSlash && endsWithSlash) {
if (path.length() < 2)
continue;
path = path.substring(1);
} else if (!startsWithSlash && !endsWithSlash)
result.append('/');
result.append(path);
} else
result.append(path);
endsWithSlash = path.charAt(path.length() - 1) == '/';
}
return result.toString();
}
public static URI appendQuery(final String uri, final String... appendQuery) throws URISyntaxException {
URI oldUri = new URI(uri);
return appendQuery(oldUri, appendQuery);
}
public static URI appendQuery(final URI uri, final String paramName, final String paramValue) {
return appendQuery(uri, paramName + "=" + paramValue);
}
public static URI appendQuery(final URI uri, final String... appendQueries) {
String newQuery = uri.getQuery();
for (String appendQuery : appendQueries) {
if (newQuery == null) {
newQuery = appendQuery;
} else {
newQuery += "&" + appendQuery;
}
}
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), newQuery,
uri.getFragment());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public static URI ensureFolder(final URI uri) {
String path = uri.getPath();
if (!path.isEmpty() && path.charAt(path.length() - 1) == '/') {
return uri;
} else {
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), path + "/", uri.getQuery(),
uri.getFragment());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
public static URI appendPath(final URI uri, final String path) {
String oldPath = uri.getPath();
String newPath;
if (oldPath != null && !oldPath.isEmpty()) {
boolean oldEnd = oldPath.charAt(oldPath.length() - 1) == '/';
boolean pathStart = path.charAt(0) == '/';
if (oldEnd) {
if (pathStart)
newPath = oldPath + path.substring(1);
else
newPath = oldPath + path;
} else {
if (pathStart)
newPath = oldPath + path;
else
newPath = oldPath + '/' + path;
}
} else
newPath = path;
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newPath, uri.getQuery(),
uri.getFragment());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
|
package de.retest.recheck;
import java.util.List;
import org.aeonbits.owner.Config.Sources;
import org.aeonbits.owner.ConfigCache;
import org.aeonbits.owner.ConfigFactory;
import org.aeonbits.owner.Mutable;
import de.retest.recheck.configuration.ProjectRootFinderUtil;
@Sources( "file:${projectroot}/.retest/retest.properties" )
public interface RecheckProperties extends Mutable {
// Usage.
static void init() {
ProjectRootFinderUtil.getProjectRoot().ifPresent(
projectRoot -> ConfigFactory.setProperty( "projectroot", projectRoot.toAbsolutePath().toString() ) );
}
static RecheckProperties getInstance() {
return ConfigCache.getOrCreate( RecheckProperties.class, System.getProperties() );
}
default FileOutputFormat getReportOutputFormat() {
if ( rehubReportUploadEnabled() ) {
return FileOutputFormat.CLOUD;
}
final FileOutputFormat format = fileOutputFormat();
if ( format == null ) {
return FileOutputFormat.KRYO;
}
return format;
}
default FileOutputFormat getStateOutputFormat() {
final FileOutputFormat format = fileOutputFormat();
return format == FileOutputFormat.ZIP ? format : FileOutputFormat.PLAIN;
}
// Constants.
static final String PROPERTY_VALUE_SEPARATOR = ";";
static final String ZIP_FOLDER_SEPARATOR = "/";
static final String SCREENSHOT_FOLDER_NAME = "screenshot";
static final String RECHECK_FOLDER_NAME = "recheck";
static final String DEFAULT_XML_FILE_NAME = "retest.xml";
static final String RETEST_FOLDER_NAME = ".retest";
static final String RETEST_PROPERTIES_FILE_NAME = "retest.properties";
static final String GOLDEN_MASTER_FILE_EXTENSION = ".recheck";
static final String TEST_REPORT_FILE_EXTENSION = ".report";
static final String AGGREGATED_TEST_REPORT_FILE_NAME = "tests" + TEST_REPORT_FILE_EXTENSION;
// Properties.
@Key( "de.retest.recheck.ignore.attributes" )
@DefaultValue( "" )
@Separator( PROPERTY_VALUE_SEPARATOR )
List<String> ignoreAttributes();
@Key( "de.retest.recheck.elementMatchThreshold" )
@DefaultValue( "0.3" )
double elementMatchThreshold();
@Key( "de.retest.recheck.rootElementMatchThreshold" )
@DefaultValue( "0.8" )
double rootElementMatchThreshold();
@Key( "de.retest.recheck.rootElementContainedChildrenMatchThreshold" )
@DefaultValue( "0.5" )
double rootElementContainedChildrenMatchThreshold();
@Key( "de.retest.recheck.rehub.reportUploadEnabled" )
@DefaultValue( "false" )
boolean rehubReportUploadEnabled();
@Key( "de.retest.output.Format" )
FileOutputFormat fileOutputFormat();
}
|
package edu.hm.hafner.analysis;
import java.io.Serializable;
import java.util.Optional;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import edu.hm.hafner.util.PathUtil;
import edu.hm.hafner.util.TreeString;
import edu.hm.hafner.util.TreeStringBuilder;
import edu.hm.hafner.util.VisibleForTesting;
import edu.umd.cs.findbugs.annotations.Nullable;
import static edu.hm.hafner.util.IntegerParser.*;
/**
* Creates new {@link Issue issues} using the builder pattern. All properties that have not been set in the builder will
* be set to their default value.
* <p>Example:</p>
* <blockquote><pre>
* Issue issue = new IssueBuilder()
* .setFileName("affected.file")
* .setLineStart(0)
* .setCategory("JavaDoc")
* .setMessage("Missing JavaDoc")
* .setSeverity(Severity.WARNING_LOW);
* </pre></blockquote>
*
* @author Ullrich Hafner
*/
@SuppressWarnings({"InstanceVariableMayNotBeInitialized", "JavaDocMethod", "PMD.TooManyFields"})
public class IssueBuilder {
private TreeStringBuilder treeStringBuilder = new TreeStringBuilder();
private int lineStart = 0;
private int lineEnd = 0;
private int columnStart = 0;
private int columnEnd = 0;
@Nullable
private LineRangeList lineRanges;
@Nullable
private String fileName;
@Nullable
private String directory;
@Nullable
private String category;
@Nullable
private String type;
@Nullable
private Severity severity;
@Nullable
private String message;
@Nullable
private String description;
@Nullable
private String packageName;
@Nullable
private String moduleName;
@Nullable
private String origin;
@Nullable
private String reference;
@Nullable
private String fingerprint;
@Nullable
private Serializable additionalProperties;
private UUID id = UUID.randomUUID();
public IssueBuilder setId(final UUID id) {
this.id = id;
return this;
}
public IssueBuilder setAdditionalProperties(@Nullable final Serializable additionalProperties) {
this.additionalProperties = additionalProperties;
return this;
}
public IssueBuilder setFingerprint(@Nullable final String fingerprint) {
this.fingerprint = fingerprint;
return this;
}
public IssueBuilder setFileName(@Nullable final String fileName) {
if (StringUtils.isEmpty(fileName)) {
this.fileName = StringUtils.EMPTY;
}
else {
this.fileName = new PathUtil().createAbsolutePath(directory, fileName);
}
return this;
}
public IssueBuilder setDirectory(@Nullable final String directory) {
this.directory = directory;
return this;
}
public IssueBuilder setLineStart(final int lineStart) {
this.lineStart = lineStart;
return this;
}
public IssueBuilder setLineStart(@Nullable final String lineStart) {
this.lineStart = parseInt(lineStart);
return this;
}
public IssueBuilder setLineEnd(final int lineEnd) {
this.lineEnd = lineEnd;
return this;
}
public IssueBuilder setLineEnd(@Nullable final String lineEnd) {
this.lineEnd = parseInt(lineEnd);
return this;
}
public IssueBuilder setColumnStart(final int columnStart) {
this.columnStart = columnStart;
return this;
}
public IssueBuilder setColumnStart(@Nullable final String columnStart) {
this.columnStart = parseInt(columnStart);
return this;
}
public IssueBuilder setColumnEnd(final int columnEnd) {
this.columnEnd = columnEnd;
return this;
}
public IssueBuilder setColumnEnd(@Nullable final String columnEnd) {
this.columnEnd = parseInt(columnEnd);
return this;
}
public IssueBuilder setCategory(@Nullable final String category) {
this.category = category;
return this;
}
public IssueBuilder setType(@Nullable final String type) {
this.type = type;
return this;
}
public IssueBuilder setPackageName(@Nullable final String packageName) {
this.packageName = packageName;
return this;
}
public IssueBuilder setModuleName(@Nullable final String moduleName) {
this.moduleName = moduleName;
return this;
}
public IssueBuilder setOrigin(@Nullable final String origin) {
this.origin = origin;
return this;
}
public IssueBuilder setReference(@Nullable final String reference) {
this.reference = reference;
return this;
}
public IssueBuilder setSeverity(@Nullable final Severity severity) {
this.severity = severity;
return this;
}
public IssueBuilder guessSeverity(@Nullable final String severityString) {
this.severity = Severity.guessFromString(severityString);
return this;
}
public IssueBuilder setMessage(@Nullable final String message) {
this.message = message;
return this;
}
public IssueBuilder setDescription(@Nullable final String description) {
this.description = description;
return this;
}
public IssueBuilder setLineRanges(final LineRangeList lineRanges) {
this.lineRanges = new LineRangeList(lineRanges);
return this;
}
/**
* Initializes this builder with an exact copy of aal properties of the specified issue.
*
* @param copy
* the issue to copy the properties from
*
* @return the initialized builder
*/
public IssueBuilder copy(final Issue copy) {
fileName = copy.getFileName();
lineStart = copy.getLineStart();
lineEnd = copy.getLineEnd();
columnStart = copy.getColumnStart();
columnEnd = copy.getColumnEnd();
lineRanges = copy.getLineRanges();
category = copy.getCategory();
type = copy.getType();
severity = copy.getSeverity();
message = copy.getMessage();
description = copy.getDescription();
packageName = copy.getPackageName();
moduleName = copy.getModuleName();
origin = copy.getOrigin();
reference = copy.getReference();
fingerprint = copy.getFingerprint();
additionalProperties = copy.getAdditionalProperties();
return this;
}
/**
* Creates a new {@link Issue} based on the specified properties.
*
* @return the created issue
*/
public Issue build() {
Issue issue = new Issue(treeStringOfFileName(fileName), lineStart, lineEnd, columnStart, columnEnd, lineRanges,
category, type, treeStringOfPackageName(packageName), moduleName, severity,
stripToEmptyTreeString(message), stripToEmptyTreeString(description), origin, reference, fingerprint,
additionalProperties, id);
id = UUID.randomUUID(); // make sure that multiple invocations will create different IDs
return issue;
}
@VisibleForTesting
TreeString treeStringOfFileName(@Nullable final String str) {
return treeStringBuilder.intern(normalizeFileName(str));
}
@VisibleForTesting
TreeString stripToEmptyTreeString(final String string) {
return treeStringBuilder.intern(StringUtils.stripToEmpty(string));
}
@VisibleForTesting
TreeString treeStringOfPackageName(@Nullable final String str) {
return treeStringBuilder.intern(defaultString(str));
}
private static String normalizeFileName(@Nullable final String platformFileName) {
return defaultString(StringUtils.replace(
StringUtils.strip(platformFileName), "\\", "/"));
}
/**
* Creates a default String representation for undefined input parameters.
*
* @param string
* the string to check
*
* @return the valid string or a default string if the specified string is not valid
*/
private static String defaultString(@Nullable final String string) {
return StringUtils.defaultIfEmpty(string, Issue.UNDEFINED).intern();
}
/**
* Creates a new {@link Issue} based on the specified properties. The returned issue is wrapped in an {@link
* Optional}.
*
* @return the created issue
*/
public Optional<Issue> buildOptional() {
return Optional.of(build());
}
}
|
package edu.hm.hafner.analysis;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Parses an input stream for compiler warnings or issues from a static analysis tool using the provided regular
* expression. Normally, this base class should not directly be extended. Rather extend from the base classes
* {@link RegexpLineParser} or {@link LookaheadParser}.
*
* @author Ullrich Hafner
* @deprecated use RegexpLineParser
*/
@Deprecated
public abstract class RegexpParser extends IssueParser {
private static final long serialVersionUID = -82635675595933170L;
/** Pattern identifying an ant task debug output prefix. */
protected static final String ANT_TASK = "^(?:.*\\[.*\\])?\\s*";
/** Pattern of compiler warnings. */
private final Pattern pattern;
/**
* Creates a new instance of {@link RegexpParser}.
*
* @param pattern
* pattern of compiler warnings.
* @param useMultiLine
* Enables multi line mode. In multi line mode the expressions {@code ^ } and {@code $ } match just after or
* just before, respectively, a line terminator or the end of the input sequence. By default these
*/
protected RegexpParser(final String pattern, final boolean useMultiLine) {
super();
if (useMultiLine) {
this.pattern = Pattern.compile(pattern, Pattern.MULTILINE);
}
else {
this.pattern = Pattern.compile(pattern);
}
}
/**
* Parses the specified string {@code content} using a regular expression and creates a set of new issues for each
* match. The new issues are added to the provided set of {@link Report}.
*
* @param content
* the content to scan
* @param report
* the report to add the new issues to
*
* @throws ParsingException
* Signals that during parsing a non recoverable error has been occurred
* @throws ParsingCanceledException
* Signals that the parsing has been aborted by the user
*/
@SuppressWarnings({"ReferenceEquality", "PMD.CompareObjectsWithEquals"})
protected void findIssues(final String content, final Report report)
throws ParsingException, ParsingCanceledException {
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
Optional<Issue> warning = createIssue(matcher, configureIssueBuilder(new IssueBuilder()));
if (warning.isPresent()) {
report.add(warning.get());
}
if (Thread.interrupted()) {
throw new ParsingCanceledException();
}
}
}
/**
* Optionally configures the issue builder instance.
*
* @param builder
* the build to configure
*
* @return the builder
*/
protected IssueBuilder configureIssueBuilder(final IssueBuilder builder) {
return builder;
}
/**
* Creates a new issue for the specified pattern. This method is called for each matching line in the specified
* file. If a match is a false positive, then return {@link Optional#empty()} to ignore this warning.
*
* @param matcher
* the regular expression matcher
* @param builder
* the issue builder to use
*
* @return a new annotation for the specified pattern
* @throws ParsingException
* Signals that during parsing a non recoverable error has been occurred
*/
protected abstract Optional<Issue> createIssue(Matcher matcher, IssueBuilder builder) throws ParsingException;
}
|
package eu.bitwalker.useragentutils;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Enum constants for most common browsers, including e-mail clients and bots.
* @author harald
*
*/
public enum Browser {
/**
* Outlook email client
*/
OUTLOOK( Manufacturer.MICROSOFT, null, 100, "Outlook", new String[] {"MSOffice"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, "MSOffice (([0-9]+))"), // before IE7
/**
* Microsoft Outlook 2007 identifies itself as MSIE7 but uses the html rendering engine of Word 2007.
* Example user agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 1.1.4322; MSOffice 12)
*/
OUTLOOK2007( Manufacturer.MICROSOFT, Browser.OUTLOOK, 107, "Outlook 2007", new String[] {"MSOffice 12"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7
OUTLOOK2013( Manufacturer.MICROSOFT, Browser.OUTLOOK, 109, "Outlook 2013", new String[] {"Microsoft Outlook 15"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7
OUTLOOK2010( Manufacturer.MICROSOFT, Browser.OUTLOOK, 108, "Outlook 2010", new String[] {"MSOffice 14", "Microsoft Outlook 14"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7
/**
* Family of Internet Explorer browsers
*/
IE( Manufacturer.MICROSOFT, null, 1, "Internet Explorer", new String[] { "MSIE", "Trident", "IE " }, new String[]{"BingPreview", "Xbox", "Xbox One"}, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, "MSIE (([\\d]+)\\.([\\w]+))" ), // before Mozilla
/**
* Since version 7 Outlook Express is identifying itself. By detecting Outlook Express we can not
* identify the Internet Explorer version which is probably used for the rendering.
* Obviously this product is now called Windows Live Mail Desktop or just Windows Live Mail.
*/
OUTLOOK_EXPRESS7( Manufacturer.MICROSOFT, Browser.IE, 110, "Windows Live Mail", new String[] {"Outlook-Express/7.0"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.TRIDENT, null), // before IE7, previously known as Outlook Express. First released in 2006, offered with different name later
/**
* Since 2007 the mobile edition of Internet Explorer identifies itself as IEMobile in the user-agent.
* If previous versions have to be detected, use the operating system information as well.
*/
IEMOBILE11( Manufacturer.MICROSOFT, Browser.IE, 125, "IE Mobile 11", new String[] { "IEMobile/11" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE10( Manufacturer.MICROSOFT, Browser.IE, 124, "IE Mobile 10", new String[] { "IEMobile/10" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE9( Manufacturer.MICROSOFT, Browser.IE, 123, "IE Mobile 9", new String[] { "IEMobile/9" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE7( Manufacturer.MICROSOFT, Browser.IE, 121, "IE Mobile 7", new String[] { "IEMobile 7" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE6( Manufacturer.MICROSOFT, Browser.IE, 120, "IE Mobile 6", new String[] { "IEMobile 6" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE
IE_XBOX(Manufacturer.MICROSOFT, Browser.IE, 360, "Xbox", new String[] { "xbox" }, new String[] {}, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null),
IE11( Manufacturer.MICROSOFT, Browser.IE, 95, "Internet Explorer 11", new String[] { "Trident/7", "IE 11." }, new String[] {"MSIE 7", "BingPreview"}, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, "(?:Trident\\/7|IE)(?:\\.[0-9]*;)?(?:.*rv:| )(([0-9]+)\\.?([0-9]+))" ), // before Mozilla
IE10( Manufacturer.MICROSOFT, Browser.IE, 92, "Internet Explorer 10", new String[] { "MSIE 10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE9( Manufacturer.MICROSOFT, Browser.IE, 90, "Internet Explorer 9", new String[] { "MSIE 9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE8( Manufacturer.MICROSOFT, Browser.IE, 80, "Internet Explorer 8", new String[] { "MSIE 8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE7( Manufacturer.MICROSOFT, Browser.IE, 70, "Internet Explorer 7", new String[] { "MSIE 7" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE
IE6( Manufacturer.MICROSOFT, Browser.IE, 60, "Internet Explorer 6", new String[] { "MSIE 6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE5_5( Manufacturer.MICROSOFT, Browser.IE, 55, "Internet Explorer 5.5", new String[] { "MSIE 5.5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE
IE5( Manufacturer.MICROSOFT, Browser.IE, 50, "Internet Explorer 5", new String[] { "MSIE 5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
/**
* Family of Microsoft Edge browsers. Pretends to be Chrome and claims to be webkit compatible.
*/
EDGE(Manufacturer.MICROSOFT, null, 300, "Microsoft Edge", new String[] {"Edge"}, null, BrowserType.WEB_BROWSER, RenderingEngine.EDGE_HTML, "(?:Edge\\/((12)\\.([0-9]*)))"),
EDGE12(Manufacturer.MICROSOFT, Browser.EDGE, 301, "Microsoft Edge", new String[] {"Edge/12"}, new String[] {"Mobile"}, BrowserType.WEB_BROWSER, RenderingEngine.EDGE_HTML, "(?:Edge\\/((12)\\.([0-9]*)))" ),
EDGE_MOBILE12(Manufacturer.MICROSOFT, Browser.EDGE, 302, "Microsoft Edge Mobile", new String[] {"Mobile Safari", "Edge/12"}, null, BrowserType.MOBILE_BROWSER, RenderingEngine.EDGE_HTML, "(?:Edge\\/((12)\\.([0-9]*)))" ),
/**
* Google Chrome browser
*/
CHROME( Manufacturer.GOOGLE, null, 1, "Chrome", new String[] { "Chrome", "CrMo", "CriOS" }, new String[] { "OPR/", "Web Preview", "Vivaldi" } , BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Chrome\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ), // before Mozilla
CHROME_MOBILE( Manufacturer.GOOGLE, Browser.CHROME, 100, "Chrome Mobile", new String[] { "CrMo","CriOS", "Mobile Safari" }, new String[] {"OPR/"}, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, "(?:CriOS|CrMo|Chrome)\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ),
CHROME46( Manufacturer.GOOGLE, Browser.CHROME, 51, "Chrome 46", new String[] { "Chrome/46" }, new String[] { "OPR/", "Web Preview", "Vivaldi" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME45( Manufacturer.GOOGLE, Browser.CHROME, 50, "Chrome 45", new String[] { "Chrome/45" }, new String[] { "OPR/", "Web Preview", "Vivaldi" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME44( Manufacturer.GOOGLE, Browser.CHROME, 49, "Chrome 44", new String[] { "Chrome/44" }, new String[] { "OPR/", "Web Preview", "Vivaldi" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME43( Manufacturer.GOOGLE, Browser.CHROME, 48, "Chrome 43", new String[] { "Chrome/43" }, new String[] { "OPR/", "Web Preview", "Vivaldi" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME42( Manufacturer.GOOGLE, Browser.CHROME, 47, "Chrome 42", new String[] { "Chrome/42" }, new String[] { "OPR/", "Web Preview", "Vivaldi" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME41( Manufacturer.GOOGLE, Browser.CHROME, 46, "Chrome 41", new String[] { "Chrome/41" }, new String[] { "OPR/", "Web Preview", "Vivaldi" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME40( Manufacturer.GOOGLE, Browser.CHROME, 45, "Chrome 40", new String[] { "Chrome/40" }, new String[] { "OPR/", "Web Preview", "Vivaldi" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME39( Manufacturer.GOOGLE, Browser.CHROME, 44, "Chrome 39", new String[] { "Chrome/39" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME38( Manufacturer.GOOGLE, Browser.CHROME, 43, "Chrome 38", new String[] { "Chrome/38" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME37( Manufacturer.GOOGLE, Browser.CHROME, 42, "Chrome 37", new String[] { "Chrome/37" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME36( Manufacturer.GOOGLE, Browser.CHROME, 41, "Chrome 36", new String[] { "Chrome/36" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME35( Manufacturer.GOOGLE, Browser.CHROME, 40, "Chrome 35", new String[] { "Chrome/35" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME34( Manufacturer.GOOGLE, Browser.CHROME, 39, "Chrome 34", new String[] { "Chrome/34" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME33( Manufacturer.GOOGLE, Browser.CHROME, 38, "Chrome 33", new String[] { "Chrome/33" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME32( Manufacturer.GOOGLE, Browser.CHROME, 37, "Chrome 32", new String[] { "Chrome/32" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME31( Manufacturer.GOOGLE, Browser.CHROME, 36, "Chrome 31", new String[] { "Chrome/31" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME30( Manufacturer.GOOGLE, Browser.CHROME, 35, "Chrome 30", new String[] { "Chrome/30" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME29( Manufacturer.GOOGLE, Browser.CHROME, 34, "Chrome 29", new String[] { "Chrome/29" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME28( Manufacturer.GOOGLE, Browser.CHROME, 33, "Chrome 28", new String[] { "Chrome/28" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME27( Manufacturer.GOOGLE, Browser.CHROME, 32, "Chrome 27", new String[] { "Chrome/27" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME26( Manufacturer.GOOGLE, Browser.CHROME, 31, "Chrome 26", new String[] { "Chrome/26" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME25( Manufacturer.GOOGLE, Browser.CHROME, 30, "Chrome 25", new String[] { "Chrome/25" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME24( Manufacturer.GOOGLE, Browser.CHROME, 29, "Chrome 24", new String[] { "Chrome/24" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME23( Manufacturer.GOOGLE, Browser.CHROME, 28, "Chrome 23", new String[] { "Chrome/23" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME22( Manufacturer.GOOGLE, Browser.CHROME, 27, "Chrome 22", new String[] { "Chrome/22" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME21( Manufacturer.GOOGLE, Browser.CHROME, 26, "Chrome 21", new String[] { "Chrome/21" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME20( Manufacturer.GOOGLE, Browser.CHROME, 25, "Chrome 20", new String[] { "Chrome/20" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME19( Manufacturer.GOOGLE, Browser.CHROME, 24, "Chrome 19", new String[] { "Chrome/19" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME18( Manufacturer.GOOGLE, Browser.CHROME, 23, "Chrome 18", new String[] { "Chrome/18" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME17( Manufacturer.GOOGLE, Browser.CHROME, 22, "Chrome 17", new String[] { "Chrome/17" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME16( Manufacturer.GOOGLE, Browser.CHROME, 21, "Chrome 16", new String[] { "Chrome/16" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME15( Manufacturer.GOOGLE, Browser.CHROME, 20, "Chrome 15", new String[] { "Chrome/15" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME14( Manufacturer.GOOGLE, Browser.CHROME, 19, "Chrome 14", new String[] { "Chrome/14" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME13( Manufacturer.GOOGLE, Browser.CHROME, 18, "Chrome 13", new String[] { "Chrome/13" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME12( Manufacturer.GOOGLE, Browser.CHROME, 17, "Chrome 12", new String[] { "Chrome/12" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME11( Manufacturer.GOOGLE, Browser.CHROME, 16, "Chrome 11", new String[] { "Chrome/11" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME10( Manufacturer.GOOGLE, Browser.CHROME, 15, "Chrome 10", new String[] { "Chrome/10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME9( Manufacturer.GOOGLE, Browser.CHROME, 10, "Chrome 9", new String[] { "Chrome/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME8( Manufacturer.GOOGLE, Browser.CHROME, 5, "Chrome 8", new String[] { "Chrome/8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
OMNIWEB( Manufacturer.OTHER, null, 2, "Omniweb", new String[] { "OmniWeb" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null),
SAFARI( Manufacturer.APPLE, null, 1, "Safari", new String[] { "Safari" }, new String[] { "bot", "preview", "OPR/", "Coast/", "Vivaldi","CFNetwork" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Version\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)" ), // before AppleWebKit
BLACKBERRY10( Manufacturer.BLACKBERRY, Browser.SAFARI, 10, "BlackBerry", new String[] { "BB10" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, null),
MOBILE_SAFARI( Manufacturer.APPLE, Browser.SAFARI, 2, "Mobile Safari", new String[] { "Mobile Safari","Mobile/" }, new String[] { "bot", "preview", "OPR/", "Coast/", "Vivaldi", "CFNetwork" }, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, null ), // before Safari
SILK( Manufacturer.AMAZON, Browser.SAFARI, 15, "Silk", new String[] { "Silk/" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Silk\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\-[\\w]+)?)" ),
SAFARI8( Manufacturer.APPLE, Browser.SAFARI, 8, "Safari 8", new String[] { "Version/8" }, new String[] { "Applebot" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
SAFARI7( Manufacturer.APPLE, Browser.SAFARI, 7, "Safari 7", new String[] { "Version/7" }, new String[]{"bing"}, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
SAFARI6( Manufacturer.APPLE, Browser.SAFARI, 6, "Safari 6", new String[] { "Version/6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
SAFARI5( Manufacturer.APPLE, Browser.SAFARI, 3, "Safari 5", new String[] { "Version/5" }, new String[]{"Google Web Preview"}, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
SAFARI4( Manufacturer.APPLE, Browser.SAFARI, 4, "Safari 4", new String[] { "Version/4" }, new String[] { "Googlebot-Mobile" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
COAST( Manufacturer.OPERA, null, 500, "Opera", new String[] { " Coast/" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, "Coast\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
COAST1( Manufacturer.OPERA, Browser.COAST, 501, "Opera", new String[] { " Coast/1." }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, "Coast\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA( Manufacturer.OPERA, null, 1, "Opera", new String[] { " OPR/", "Opera" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Opera\\/(([\\d]+)\\.([\\w]+))"), // before MSIE
OPERA_MOBILE( Manufacturer.OPERA, Browser.OPERA, 100,"Opera Mobile", new String[] { "Mobile Safari"}, null, BrowserType.MOBILE_BROWSER, RenderingEngine.BLINK, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), // Another Opera for mobile devices
OPERA_MINI( Manufacturer.OPERA, Browser.OPERA, 20, "Opera Mini", new String[] { "Opera Mini"}, null, BrowserType.MOBILE_BROWSER, RenderingEngine.PRESTO, null), // Opera for mobile devices
OPERA30( Manufacturer.OPERA, Browser.OPERA, 30, "Opera 30", new String[] { "OPR/30." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA29( Manufacturer.OPERA, Browser.OPERA, 29, "Opera 29", new String[] { "OPR/29." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA28( Manufacturer.OPERA, Browser.OPERA, 28, "Opera 28", new String[] { "OPR/28." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA27( Manufacturer.OPERA, Browser.OPERA, 27, "Opera 27", new String[] { "OPR/27." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA26( Manufacturer.OPERA, Browser.OPERA, 26, "Opera 26", new String[] { "OPR/26." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA25( Manufacturer.OPERA, Browser.OPERA, 25, "Opera 25", new String[] { "OPR/25." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA24( Manufacturer.OPERA, Browser.OPERA, 24, "Opera 24", new String[] { "OPR/24." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA23( Manufacturer.OPERA, Browser.OPERA, 23, "Opera 23", new String[] { "OPR/23." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA20( Manufacturer.OPERA, Browser.OPERA, 21, "Opera 20", new String[] { "OPR/20." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA19( Manufacturer.OPERA, Browser.OPERA, 19, "Opera 19", new String[] { "OPR/19." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA18( Manufacturer.OPERA, Browser.OPERA, 18, "Opera 18", new String[] { "OPR/18." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA17( Manufacturer.OPERA, Browser.OPERA, 17, "Opera 17", new String[] { "OPR/17." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA16( Manufacturer.OPERA, Browser.OPERA, 16, "Opera 16", new String[] { "OPR/16." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA15( Manufacturer.OPERA, Browser.OPERA, 15, "Opera 15", new String[] { "OPR/15." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA12( Manufacturer.OPERA, Browser.OPERA, 12, "Opera 12", new String[] { "Opera/12", "Version/12." }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Version\\/(([\\d]+)\\.([\\w]+))"),
OPERA11( Manufacturer.OPERA, Browser.OPERA, 11, "Opera 11", new String[] { "Version/11." }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Version\\/(([\\d]+)\\.([\\w]+))"),
OPERA10( Manufacturer.OPERA, Browser.OPERA, 10, "Opera 10", new String[] { "Opera/9.8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Version\\/(([\\d]+)\\.([\\w]+))"),
OPERA9( Manufacturer.OPERA, Browser.OPERA, 5, "Opera 9", new String[] { "Opera/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, null),
KONQUEROR( Manufacturer.OTHER, null, 1, "Konqueror", new String[] { "Konqueror"}, new String[]{"Exabot"}, BrowserType.WEB_BROWSER, RenderingEngine.KHTML, "Konqueror\\/(([0-9]+)\\.?([\\w]+)?(-[\\w]+)?)" ),
DOLFIN2( Manufacturer.SAMSUNG, null, 1, "Samsung Dolphin 2", new String[] { "Dolfin/2" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, null ), // webkit based browser for the bada os
/*
* Apple WebKit compatible client. Can be a browser or an application with embedded browser using UIWebView.
*/
APPLE_WEB_KIT( Manufacturer.APPLE, null, 50, "Apple WebKit", new String[] { "AppleWebKit" }, new String[] { "bot", "preview", "OPR/", "Coast/", "Vivaldi" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
APPLE_ITUNES( Manufacturer.APPLE, Browser.APPLE_WEB_KIT, 52, "iTunes", new String[] { "iTunes" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
APPLE_APPSTORE( Manufacturer.APPLE, Browser.APPLE_WEB_KIT, 53, "App Store", new String[] { "MacAppStore" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
ADOBE_AIR( Manufacturer.ADOBE, Browser.APPLE_WEB_KIT, 1, "Adobe AIR application", new String[] { "AdobeAIR" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
LOTUS_NOTES( Manufacturer.OTHER, null, 3, "Lotus Notes", new String[] { "Lotus-Notes" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, "Lotus-Notes\\/(([\\d]+)\\.([\\w]+))"), // before Mozilla
CAMINO( Manufacturer.OTHER, null, 5, "Camino", new String[] { "Camino" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Camino\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)" ), // using Gecko Engine
CAMINO2( Manufacturer.OTHER, Browser.CAMINO, 17, "Camino 2", new String[] { "Camino/2" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FLOCK( Manufacturer.OTHER, null, 4, "Flock", new String[]{"Flock"}, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Flock\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)"),
FIREFOX( Manufacturer.MOZILLA, null, 10, "Firefox", new String[] { "Firefox" }, new String[] {"ggpht.com", "WordPress.com mShots"}, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Firefox\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), // using Gecko Engine
FIREFOX3MOBILE( Manufacturer.MOZILLA, Browser.FIREFOX, 31, "Firefox 3 Mobile", new String[] { "Firefox/3.5 Maemo" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX_MOBILE( Manufacturer.MOZILLA, Browser.FIREFOX, 200, "Firefox Mobile", new String[] { "Mobile" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX_MOBILE23(Manufacturer.MOZILLA, FIREFOX_MOBILE, 223, "Firefox Mobile 23", new String[] { "Firefox/23" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX42( Manufacturer.MOZILLA, Browser.FIREFOX, 219, "Firefox 42", new String[] { "Firefox/42" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX41( Manufacturer.MOZILLA, Browser.FIREFOX, 218, "Firefox 41", new String[] { "Firefox/41" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX40( Manufacturer.MOZILLA, Browser.FIREFOX, 217, "Firefox 40", new String[] { "Firefox/40" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX39( Manufacturer.MOZILLA, Browser.FIREFOX, 216, "Firefox 39", new String[] { "Firefox/39" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX38( Manufacturer.MOZILLA, Browser.FIREFOX, 215, "Firefox 38", new String[] { "Firefox/38" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX37( Manufacturer.MOZILLA, Browser.FIREFOX, 214, "Firefox 37", new String[] { "Firefox/37" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX36( Manufacturer.MOZILLA, Browser.FIREFOX, 213, "Firefox 36", new String[] { "Firefox/36" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX35( Manufacturer.MOZILLA, Browser.FIREFOX, 212, "Firefox 35", new String[] { "Firefox/35" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX34( Manufacturer.MOZILLA, Browser.FIREFOX, 211, "Firefox 34", new String[] { "Firefox/34" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX33( Manufacturer.MOZILLA, Browser.FIREFOX, 210, "Firefox 33", new String[] { "Firefox/33" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX32( Manufacturer.MOZILLA, Browser.FIREFOX, 109, "Firefox 32", new String[] { "Firefox/32" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX31( Manufacturer.MOZILLA, Browser.FIREFOX, 310, "Firefox 31", new String[] { "Firefox/31" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX30( Manufacturer.MOZILLA, Browser.FIREFOX, 300, "Firefox 30", new String[] { "Firefox/30" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX29( Manufacturer.MOZILLA, Browser.FIREFOX, 290, "Firefox 29", new String[] { "Firefox/29" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX28( Manufacturer.MOZILLA, Browser.FIREFOX, 280, "Firefox 28", new String[] { "Firefox/28" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX27( Manufacturer.MOZILLA, Browser.FIREFOX, 108, "Firefox 27", new String[] { "Firefox/27" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX26( Manufacturer.MOZILLA, Browser.FIREFOX, 107, "Firefox 26", new String[] { "Firefox/26" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX25( Manufacturer.MOZILLA, Browser.FIREFOX, 106, "Firefox 25", new String[] { "Firefox/25" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX24( Manufacturer.MOZILLA, Browser.FIREFOX, 105, "Firefox 24", new String[] { "Firefox/24" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX23( Manufacturer.MOZILLA, Browser.FIREFOX, 104, "Firefox 23", new String[] { "Firefox/23" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX22( Manufacturer.MOZILLA, Browser.FIREFOX, 103, "Firefox 22", new String[] { "Firefox/22" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX21( Manufacturer.MOZILLA, Browser.FIREFOX, 102, "Firefox 21", new String[] { "Firefox/21" }, new String[]{"WordPress.com mShots"}, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX20( Manufacturer.MOZILLA, Browser.FIREFOX, 101, "Firefox 20", new String[] { "Firefox/20" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX19( Manufacturer.MOZILLA, Browser.FIREFOX, 100, "Firefox 19", new String[] { "Firefox/19" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX18( Manufacturer.MOZILLA, Browser.FIREFOX, 99, "Firefox 18", new String[] { "Firefox/18" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX17( Manufacturer.MOZILLA, Browser.FIREFOX, 98, "Firefox 17", new String[] { "Firefox/17" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX16( Manufacturer.MOZILLA, Browser.FIREFOX, 97, "Firefox 16", new String[] { "Firefox/16" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX15( Manufacturer.MOZILLA, Browser.FIREFOX, 96, "Firefox 15", new String[] { "Firefox/15" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX14( Manufacturer.MOZILLA, Browser.FIREFOX, 95, "Firefox 14", new String[] { "Firefox/14" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX13( Manufacturer.MOZILLA, Browser.FIREFOX, 94, "Firefox 13", new String[] { "Firefox/13" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX12( Manufacturer.MOZILLA, Browser.FIREFOX, 93, "Firefox 12", new String[] { "Firefox/12" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX11( Manufacturer.MOZILLA, Browser.FIREFOX, 92, "Firefox 11", new String[] { "Firefox/11" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX10( Manufacturer.MOZILLA, Browser.FIREFOX, 91, "Firefox 10", new String[] { "Firefox/10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX9( Manufacturer.MOZILLA, Browser.FIREFOX, 90, "Firefox 9", new String[] { "Firefox/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX8( Manufacturer.MOZILLA, Browser.FIREFOX, 80, "Firefox 8", new String[] { "Firefox/8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX7( Manufacturer.MOZILLA, Browser.FIREFOX, 70, "Firefox 7", new String[] { "Firefox/7" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX6( Manufacturer.MOZILLA, Browser.FIREFOX, 60, "Firefox 6", new String[] { "Firefox/6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX5( Manufacturer.MOZILLA, Browser.FIREFOX, 50, "Firefox 5", new String[] { "Firefox/5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX4( Manufacturer.MOZILLA, Browser.FIREFOX, 40, "Firefox 4", new String[] { "Firefox/4" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX3( Manufacturer.MOZILLA, Browser.FIREFOX, 30, "Firefox 3", new String[] { "Firefox/3" }, new String[] {"ggpht.com"}, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX2( Manufacturer.MOZILLA, Browser.FIREFOX, 20, "Firefox 2", new String[] { "Firefox/2" }, new String[]{"WordPress.com mShots"}, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX1_5( Manufacturer.MOZILLA, Browser.FIREFOX, 15, "Firefox 1.5", new String[] { "Firefox/1.5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
/*
* Thunderbird email client, based on the same Gecko engine Firefox is using.
*/
THUNDERBIRD( Manufacturer.MOZILLA, null, 110, "Thunderbird", new String[] { "Thunderbird" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, "Thunderbird\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ), // using Gecko Engine
THUNDERBIRD12( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 185, "Thunderbird 12", new String[] { "Thunderbird/12" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD11( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 184, "Thunderbird 11", new String[] { "Thunderbird/11" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD10( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 183, "Thunderbird 10", new String[] { "Thunderbird/10" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD8( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 180, "Thunderbird 8", new String[] { "Thunderbird/8" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD7( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 170, "Thunderbird 7", new String[] { "Thunderbird/7" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD6( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 160, "Thunderbird 6", new String[] { "Thunderbird/6" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD3( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 130, "Thunderbird 3", new String[] { "Thunderbird/3" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD2( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 120, "Thunderbird 2", new String[] { "Thunderbird/2" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
VIVALDI(Manufacturer.OTHER, null, 108338, "Vivaldi", new String[] { "Vivaldi" }, new String[] {}, BrowserType.WEB_BROWSER, RenderingEngine.BLINK, "Vivaldi/(([\\d]+).([\\d]+).([\\d]+).([\\d]+))"),
SEAMONKEY( Manufacturer.OTHER, null, 15, "SeaMonkey", new String[]{"SeaMonkey"}, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "SeaMonkey\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)"), // using Gecko Engine
BOT( Manufacturer.OTHER, null,12, "Robot/Spider", new String[] {"Googlebot", "Mediapartners-Google", "Web Preview", "bot", "Applebot" , "spider", "crawler", "Feedfetcher", "Slurp", "Twiceler", "Nutch", "BecomeBot", "bingbot", "BingPreview", "Google Web Preview", "WordPress.com mShots", "Seznam", "facebookexternalhit" , "YandexMarket", "Teoma", "ThumbSniper", "Phantom.js"}, null, BrowserType.ROBOT, RenderingEngine.OTHER, null),
BOT_MOBILE( Manufacturer.OTHER, Browser.BOT, 20 , "Mobil Robot/Spider", new String[] {"Googlebot-Mobile"}, null, BrowserType.ROBOT, RenderingEngine.OTHER, null),
MOZILLA( Manufacturer.MOZILLA, null, 1, "Mozilla", new String[] { "Mozilla", "Moozilla" }, new String[] {"ggpht.com"}, BrowserType.WEB_BROWSER, RenderingEngine.OTHER, null), // rest of the mozilla browsers
CFNETWORK( Manufacturer.OTHER, null, 6, "CFNetwork", new String[] { "CFNetwork" }, null, BrowserType.UNKNOWN, RenderingEngine.OTHER, "CFNetwork/(([\\d]+)(?:\\.([\\d]))?(?:\\.([\\d]+))?)" ), // Mac OS X cocoa library
EUDORA( Manufacturer.OTHER, null, 7, "Eudora", new String[] { "Eudora", "EUDORA" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null ), // email client by Qualcomm
POCOMAIL( Manufacturer.OTHER, null, 8, "PocoMail", new String[] { "PocoMail" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null ),
THEBAT( Manufacturer.OTHER, null, 9, "The Bat!", new String[]{"The Bat"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null), // Email Client
NETFRONT( Manufacturer.OTHER, null, 10, "NetFront", new String[]{"NetFront"}, null, BrowserType.MOBILE_BROWSER, RenderingEngine.OTHER, null), // mobile device browser
EVOLUTION( Manufacturer.OTHER, null, 11, "Evolution", new String[]{"CamelHttpStream"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null),
LYNX( Manufacturer.OTHER, null, 13, "Lynx", new String[]{"Lynx"}, null, BrowserType.TEXT_BROWSER, RenderingEngine.OTHER, "Lynx\\/(([0-9]+)\\.([\\d]+)\\.?([\\w-+]+)?\\.?([\\w-+]+)?)"),
DOWNLOAD( Manufacturer.OTHER, null, 16, "Downloading Tool", new String[]{"cURL","wget", "ggpht.com", "Apache-HttpClient"}, null, BrowserType.TOOL, RenderingEngine.OTHER, null),
UNKNOWN( Manufacturer.OTHER, null, 14, "Unknown", new String[0], null, BrowserType.UNKNOWN, RenderingEngine.OTHER, null ),
@Deprecated
APPLE_MAIL( Manufacturer.APPLE, null, 51, "Apple Mail", new String[0], null, BrowserType.EMAIL_CLIENT, RenderingEngine.WEBKIT, null); // not detectable any longer.
/*
* An id for each browser version which is unique per manufacturer.
*/
private final short id;
private final String name;
private final String[] aliases;
private final String[] excludeList; // don't match when these values are in the agent-string
private final BrowserType browserType;
private final Manufacturer manufacturer;
private final RenderingEngine renderingEngine;
private final Browser parent;
private List<Browser> children;
private Pattern versionRegEx;
private static List<Browser> topLevelBrowsers;
private Browser(Manufacturer manufacturer, Browser parent, int versionId, String name, String[] aliases, String[] exclude, BrowserType browserType, RenderingEngine renderingEngine, String versionRegexString) {
this.id = (short) ( ( manufacturer.getId() << 8) + (byte) versionId);
this.name = name;
this.parent = parent;
this.children = new ArrayList<Browser>();
this.aliases = Utils.toLowerCase(aliases);
this.excludeList = Utils.toLowerCase(exclude);
this.browserType = browserType;
this.manufacturer = manufacturer;
this.renderingEngine = renderingEngine;
if (versionRegexString != null)
this.versionRegEx = Pattern.compile(versionRegexString);
if (this.parent == null)
addTopLevelBrowser(this);
else
this.parent.children.add(this);
}
// create collection of top level browsers during initialization
private static void addTopLevelBrowser(Browser browser) {
if(topLevelBrowsers == null)
topLevelBrowsers = new ArrayList<Browser>();
topLevelBrowsers.add(browser);
}
public short getId() {
return id;
}
public String getName() {
return name;
}
private Pattern getVersionRegEx() {
if (this.versionRegEx == null) {
if (this.getGroup() != this)
return this.getGroup().getVersionRegEx();
else
return null;
}
return this.versionRegEx;
}
/**
* Detects the detailed version information of the browser. Depends on the userAgent to be available.
* Returns null if it can not detect the version information.
* @return Version
*/
public Version getVersion(String userAgentString) {
Pattern pattern = this.getVersionRegEx();
if (userAgentString != null && pattern != null) {
Matcher matcher = pattern.matcher(userAgentString);
if (matcher.find()) {
String fullVersionString = matcher.group(1);
String majorVersion = matcher.group(2);
String minorVersion = "0";
if (matcher.groupCount() > 2) // usually but not always there is a minor version
minorVersion = matcher.group(3);
return new Version (fullVersionString,majorVersion,minorVersion);
}
}
return null;
}
/**
* @return the browserType
*/
public BrowserType getBrowserType() {
return browserType;
}
/**
* @return the manufacturer
*/
public Manufacturer getManufacturer() {
return manufacturer;
}
/**
* @return the rendering engine
*/
public RenderingEngine getRenderingEngine() {
return renderingEngine;
}
/**
* @return top level browser family
*/
public Browser getGroup() {
if (this.parent != null) {
return parent.getGroup();
}
return this;
}
/*
* Checks if the given user-agent string matches to the browser.
* Only checks for one specific browser.
*/
public boolean isInUserAgentString(String agentString)
{
if (agentString == null)
return false;
String agentStringLowerCase = agentString.toLowerCase();
return isInUserAgentLowercaseString(agentStringLowerCase);
}
private boolean isInUserAgentLowercaseString(String agentStringLowerCase) {
return Utils.contains(agentStringLowerCase, aliases);
}
private Browser checkUserAgentLowercase(String agentLowercaseString) {
if (this.isInUserAgentLowercaseString(agentLowercaseString)) {
if (this.children.size() > 0) {
for (Browser childBrowser : this.children) {
Browser match = childBrowser.checkUserAgentLowercase(agentLowercaseString);
if (match != null) {
return match;
}
}
}
// if children didn't match we continue checking the current to prevent false positives
if (!Utils.contains(agentLowercaseString, excludeList)) {
return this;
}
}
return null;
}
/**
* Iterates over all Browsers to compare the browser signature with
* the user agent string. If no match can be found Browser.UNKNOWN will
* be returned.
* Starts with the top level browsers and only if one of those matches
* checks children browsers.
* Steps out of loop as soon as there is a match.
* @param agentString
* @return Browser
*/
public static Browser parseUserAgentString(String agentString)
{
return parseUserAgentString(agentString, topLevelBrowsers);
}
public static Browser parseUserAgentLowercaseString(String agentString)
{
if (agentString == null) {
return Browser.UNKNOWN;
}
return parseUserAgentLowercaseString(agentString, topLevelBrowsers);
}
/**
* Iterates over the given Browsers (incl. children) to compare the browser
* signature with the user agent string.
* If no match can be found Browser.UNKNOWN will be returned.
* Steps out of loop as soon as there is a match.
* Be aware that if the order of the provided Browsers is incorrect or if the set is too limited it can lead to false matches!
* @param agentString
* @return Browser
*/
public static Browser parseUserAgentString(String agentString, List<Browser> browsers)
{
if (agentString != null) {
String agentLowercaseString = agentString.toLowerCase();
return parseUserAgentLowercaseString(agentLowercaseString, browsers);
}
return Browser.UNKNOWN;
}
private static Browser parseUserAgentLowercaseString(String agentLowercaseString, List<Browser> browsers) {
for (Browser browser : browsers) {
Browser match = browser.checkUserAgentLowercase(agentLowercaseString);
if (match != null) {
return match; // either current operatingSystem or a child object
}
}
return Browser.UNKNOWN;
}
public static Browser valueOf(short id)
{
for (Browser browser : Browser.values())
{
if (browser.getId() == id)
return browser;
}
// same behavior as standard valueOf(string) method
throw new IllegalArgumentException(
"No enum const for id " + id);
}
}
|
package eu.eumssi.managers.uima;
import static org.apache.uima.fit.factory.AnalysisEngineFactory.createEngineDescription;
import static org.apache.uima.fit.factory.AnalysisEngineFactory.createEngine;
import static org.apache.uima.fit.util.JCasUtil.select;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.ToIntFunction;
import java.util.Comparator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.BasicConfigurator;
import org.apache.uima.UIMAException;
import org.apache.uima.analysis_engine.AnalysisEngine;
import org.apache.uima.analysis_engine.AnalysisEngineDescription;
import org.apache.uima.fit.factory.JCasFactory;
import org.apache.uima.fit.pipeline.JCasIterable;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.ResourceInitializationException;
import org.dbpedia.spotlight.uima.SpotlightAnnotator;
import org.dbpedia.spotlight.uima.types.DBpediaResource;
import org.dbpedia.spotlight.uima.types.TopDBpediaResource;
import com.iai.uima.analysis_component.KeyPhraseAnnotator;
import com.iai.uima.jcas.tcas.KeyPhraseAnnotation;
import com.iai.uima.jcas.tcas.KeyPhraseAnnotationDeprecated;
import com.iai.uima.jcas.tcas.KeyPhraseAnnotationEnriched;
import de.tudarmstadt.ukp.dkpro.core.api.ner.type.NamedEntity;
import de.tudarmstadt.ukp.dkpro.core.languagetool.LanguageToolSegmenter;
import de.tudarmstadt.ukp.dkpro.core.stanfordnlp.StanfordNamedEntityRecognizer;
import edu.upf.glicom.uima.ae.ConfirmLinkAnnotator;
import edu.upf.glicom.uima.ts.VerifiedDBpediaResource;
import eu.eumssi.api.json.uima.JSONMeta.StatusType;
/**
* This class represents the QueryManager component which interfaces with the backend MongoDB.
*
* @author jens.grivolla
*
*/
public class UimaManager {
/**
* Logger for this class and subclasses.
*/
protected final Log log = LogFactory.getLog(getClass());
/**
* Properties files
*/
private static final String PROPERTIES_FILE = "/eu/eumssi/properties/uima.properties";
/**
* Singleton instance of QueryManager.
*/
private static UimaManager instance;
/**
* Configuration properties.
*/
private Properties properties;
private AnalysisEngine ae;
private String dbpediaService;
/**
* Return a unique instance of QueryManager (Singleton pattern).
* @return a unique instance of QueryManager
* @throws UnknownHostException
* @throws EumssiException
*/
public static UimaManager getInstance() throws UnknownHostException, EumssiException {
if (instance == null) {
instance = new UimaManager();
}
return instance;
}
/**
* Private constructor (Singleton pattern)
* @throws UnknownHostException
* @throws EumssiException
*/
private UimaManager() throws EumssiException{
try {
BasicConfigurator.configure(); // ugly hack to get it working, should use properties file instead
loadProperties();
this.dbpediaService = this.properties.getProperty("dbpediaUrl");
log.info("set dbpediaUrl to "+this.dbpediaService);
} catch (Exception e) {
log.error("Error loading properties file", e);
throw new EumssiException(StatusType.ERROR);
}
try {
setupPipeline();
} catch (ResourceInitializationException e) {
log.error("Error configuring UIMA pipeline", e);
throw new EumssiException(StatusType.ERROR_UNKNOWN);
}
}
private void setupPipeline() throws ResourceInitializationException {
AnalysisEngineDescription segmenter = createEngineDescription(LanguageToolSegmenter.class);
AnalysisEngineDescription dbpedia = createEngineDescription(SpotlightAnnotator.class,
SpotlightAnnotator.PARAM_ENDPOINT, this.dbpediaService,
SpotlightAnnotator.PARAM_CONFIDENCE, 0.35f,
SpotlightAnnotator.PARAM_ALL_CANDIDATES, false);
AnalysisEngineDescription ner = createEngineDescription(StanfordNamedEntityRecognizer.class);
AnalysisEngineDescription validate = createEngineDescription(ConfirmLinkAnnotator.class);
AnalysisEngineDescription key = createEngineDescription(KeyPhraseAnnotator.class,
KeyPhraseAnnotator.PARAM_LANGUAGE, "en",
KeyPhraseAnnotator.PARAM_KEYPHRASE_RATIO, 80
);
//this.ae = createEngine(createEngineDescription(segmenter, dbpedia, ner, validate));
this.ae = createEngine(createEngineDescription(segmenter, dbpedia, ner, validate, key));
}
/**
* Load the QueryManager properties file.
*
* @return
* @throws IOException
*/
private boolean loadProperties() throws IOException
{
this.properties = new Properties();
InputStream in = this.getClass().getResourceAsStream(PROPERTIES_FILE);
this.properties.load(in);
in.close();
return true;
}
/** convert DBpedia resource types to Stanford NER types
* @param types space separated list of DBpedia types
* @return set of matching NER types
*/
private static Set<String> convertTypes(String types) {
Set<String> typeSet = new HashSet<String>();
if (types.matches("(PERSON)|(I-PER)|(.*Person.*)")) typeSet.add("PERSON");
if (types.matches("(LOCATION)|(I-LOC)|(.*Place.*)"))
typeSet.add("LOCATION");
if (types.matches("(ORGANIZATION)|(I-ORG)|(.*Organisation.*)")) typeSet.add("ORGANIZATION");
if (types.matches("(MISC)|(I-MISC)")) typeSet.add("MISC");
if (types.matches(".*City.*"))
typeSet.add("City");
if (types.matches(".*Country.*")) typeSet.add("Country");
if (typeSet.isEmpty()) {
typeSet.add("other");
}
return typeSet;
}
/** adds entities/resources to the entityMap structure according to the entity type
* @param entityMap MongoDB structure to be filled
* @param type type of the entity to add
* @param entity the entity name/URI
*/
@SuppressWarnings("unchecked")
private static void addWithType(Map<String,Object> entityMap, String type, Map<String,Object> entity) {
List<Object> entityList = null;
// create field for each entity type
if (entityMap.containsKey(type)) {
entityList = (List<Object>) entityMap.get(type);
} else {
entityList = new ArrayList<Object>();
entityMap.put(type, entityList);
}
entityList.add(entity);
}
/**
* analyzes a given text
* @param text the text to analyze
* @return
* @throws EumssiException
*/
public Map<String, Object> analyze(String text) throws EumssiException {
Map<String, Object> analysisResult = new HashMap<String,Object>();
JCas jCas;
try {
jCas = JCasFactory.createText(text);
jCas.setDocumentLanguage("en");
this.ae.process(jCas);
Map<String, Object> dbpediaMap = new HashMap<String,Object>();
for (DBpediaResource resource : select(jCas, TopDBpediaResource.class)) {
Map<String, Object> res = new HashMap<String,Object>();
res.put("text", resource.getCoveredText());
res.put("uri", resource.getUri());
res.put("type", resource.getTypes());
res.put("begin", resource.getBegin());
res.put("end", resource.getEnd());
for (String type : convertTypes((String) res.get("type"))) {
addWithType(dbpediaMap, type, res);
}
addWithType(dbpediaMap, "all", res);
}
analysisResult.put("dbpedia", dbpediaMap);
Map<String, Object> stanfordMap = new HashMap<String,Object>();
for (NamedEntity entity : select(jCas, NamedEntity.class)) {
Map<String, Object> res = new HashMap<String,Object>();
res.put("text", entity.getCoveredText());
res.put("type", entity.getValue());
res.put("begin", entity.getBegin());
res.put("end", entity.getEnd());
for (String type : convertTypes((String) res.get("type"))) {
addWithType(stanfordMap, type, res);
}
addWithType(stanfordMap, "all", res);
}
analysisResult.put("stanford", stanfordMap);
ArrayList<Map<String, Object>> keaList = new ArrayList<Map<String, Object>>();
for (KeyPhraseAnnotation entity : select(jCas, KeyPhraseAnnotation.class)) {
if (!(entity instanceof KeyPhraseAnnotationDeprecated)) {
Map<String, Object> res = new HashMap<String,Object>();
res.put("text", entity.getCoveredText());
res.put("keyphrase", entity.getKeyPhrase());
res.put("stemmed", entity.getStem());
res.put("rank", entity.getRank());
res.put("probability", entity.getProbability());
res.put("begin", entity.getBegin());
res.put("end", entity.getEnd());
keaList.add(res);
}
}
keaList.sort(Comparator.comparingInt((Map<String, Object> k) -> (Integer) k.get("rank")));
analysisResult.put("kea", keaList);
return analysisResult;
} catch (UIMAException e) {
log.error("Error processing document", e);
throw new EumssiException(StatusType.ERROR_UNKNOWN);
}
}
}
|
package hudson.plugins.perforce;
import com.tek42.perforce.Depot;
import com.tek42.perforce.PerforceException;
import com.tek42.perforce.model.Changelist;
import com.tek42.perforce.model.Counter;
import com.tek42.perforce.model.Label;
import com.tek42.perforce.model.Workspace;
import com.tek42.perforce.parse.Counters;
import com.tek42.perforce.parse.Workspaces;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Util;
import hudson.FilePath.FileCallable;
import hudson.Launcher;
import static hudson.Util.fixNull;
import hudson.matrix.MatrixBuild;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Computer;
import hudson.model.Hudson;
import hudson.model.Node;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.remoting.VirtualChannel;
import hudson.scm.ChangeLogParser;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.util.FormValidation;
import hudson.util.StreamTaskListener;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import javax.servlet.ServletException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Extends {@link SCM} to provide integration with Perforce SCM repositories.
*
* @author Mike Wille
* @author Brian Westrich
* @author Victor Szoltysek
*/
public class PerforceSCM extends SCM {
String p4User;
String p4Passwd;
String p4Port;
String p4Client;
String projectPath;
/* This is better for build than original options: noallwrite noclobber nocompress unlocked nomodtime normdir */
String projectOptions;
String p4Label;
String p4Counter;
String p4Exe = "C:\\Program Files\\Perforce\\p4.exe";
String p4SysDrive = "C:";
String p4SysRoot = "C:\\WINDOWS";
PerforceRepositoryBrowser browser;
private static final Logger LOGGER = Logger.getLogger(PerforceSCM.class.getName());
/**
* This is being removed, including it as transient to fix exceptions on startup.
*/
transient int lastChange;
/**
* force sync is a one time trigger from the config area to force a sync with the depot.
* it is reset to false after the first checkout.
*/
boolean forceSync = false;
/**
* Always force sync the workspace when running a build
*/
boolean alwaysForceSync = false;
/**
* If true, we will manage the workspace view within the plugin. If false, we will leave the
* view alone.
*/
boolean updateView = true;
/**
* If false we add the slave hostname to the end of the client name when
* running on a slave. Defaulting to true so as not to change the behavior
* for existing users.
*/
boolean dontRenameClient = true;
/**
* If true we update the named counter to the last changelist value after the sync operation.
* If false the counter will be used as the changelist value to sync to.
* Defaulting to false since the counter name is not set to begin with.
*/
boolean updateCounterValue = false;
/**
* If true the environment value P4PASSWD will be set to the value of p4Passwd.
*/
boolean exposeP4Passwd = false;
/**
* If > 0, then will override the changelist we sync to for the first build.
*/
int firstChange = -1;
/**
* If a ticket was issued we can use it instead of the password in the environment.
*/
private String p4Ticket = null;
@DataBoundConstructor
public PerforceSCM(String p4User, String p4Passwd, String p4Client, String p4Port, String projectPath, String projectOptions,
String p4Exe, String p4SysRoot, String p4SysDrive, String p4Label, String p4Counter, boolean updateCounterValue,
boolean forceSync, boolean alwaysForceSync, boolean updateView, boolean dontRenameClient, boolean exposeP4Passwd,
int firstChange, PerforceRepositoryBrowser browser) {
this.p4User = p4User;
this.setP4Passwd(p4Passwd);
this.exposeP4Passwd = exposeP4Passwd;
this.p4Client = p4Client;
this.p4Port = p4Port;
this.projectOptions = (projectOptions != null)
? projectOptions
: "noallwrite clobber nocompress unlocked nomodtime rmdir";
// Make it backwards compatible with the old way of specifying a label
Matcher m = Pattern.compile("(@\\S+)\\s*").matcher(projectPath);
if (m.find()) {
p4Label = m.group(1);
projectPath = projectPath.substring(0,m.start(1))
+ projectPath.substring(m.end(1));
}
if (this.p4Label != null && p4Label != null) {
Logger.getLogger(PerforceSCM.class.getName()).warning(
"Label found in views and in label field. Using: "
+ p4Label);
}
this.p4Label = Util.fixEmptyAndTrim(p4Label);
this.p4Counter = Util.fixEmptyAndTrim(p4Counter);
this.updateCounterValue = updateCounterValue;
this.projectPath = projectPath;
if (p4Exe != null)
this.p4Exe = p4Exe;
if (p4SysRoot != null && p4SysRoot.length() != 0)
this.p4SysRoot = p4SysRoot;
if (p4SysDrive != null && p4SysDrive.length() != 0)
this.p4SysDrive = p4SysDrive;
// Get systemDrive,systemRoot computer environment variables from
// the current machine.
String systemDrive = null;
String systemRoot = null;
if (Hudson.isWindows()) {
try {
EnvVars envVars = Computer.currentComputer().getEnvironment();
systemDrive = envVars.get("SystemDrive");
systemRoot = envVars.get("SystemRoot");
} catch (Exception ex) {
LOGGER.log(Level.WARNING, ex.getMessage(), ex);
}
}
if (p4SysRoot != null && p4SysRoot.length() != 0) {
this.p4SysRoot = p4SysRoot;
} else {
if (systemRoot != null && !systemRoot.trim().equals("")) {
this.p4SysRoot = systemRoot;
}
}
if (p4SysDrive != null && p4SysDrive.length() != 0) {
this.p4SysDrive = p4SysDrive;
} else {
if (systemDrive != null && !systemDrive.trim().equals("")) {
this.p4SysDrive = systemDrive;
}
}
this.forceSync = forceSync;
this.alwaysForceSync = alwaysForceSync;
this.browser = browser;
this.updateView = updateView;
this.dontRenameClient = dontRenameClient;
this.firstChange = firstChange;
}
protected Depot getDepot(Launcher launcher, FilePath workspace) {
HudsonP4ExecutorFactory p4Factory = new HudsonP4ExecutorFactory(launcher,workspace);
Depot depot = new Depot(p4Factory);
depot.setUser(p4User);
PerforcePasswordEncryptor encryptor = new PerforcePasswordEncryptor();
depot.setPassword(encryptor.decryptString(p4Passwd));
depot.setPort(p4Port);
depot.setClient(p4Client);
depot.setExecutable(p4Exe);
depot.setSystemDrive(p4SysDrive);
depot.setSystemRoot(p4SysRoot);
return depot;
}
/**
* Override of SCM.buildEnvVars() in order to setup the last change we have
* sync'd to as a Hudson
* environment variable: P4_CHANGELIST
*
* @param build
* @param env
*/
@Override
public void buildEnvVars(AbstractBuild build, Map<String, String> env) {
super.buildEnvVars(build, env);
env.put("P4PORT", p4Port);
env.put("P4USER", p4User);
// if we want to allow p4 commands in script steps this helps
if (exposeP4Passwd) {
// this may help when tickets are used since we are
// not storing the ticket on the client during login
if (p4Ticket != null) {
env.put("P4PASSWD", p4Ticket);
} else {
PerforcePasswordEncryptor encryptor = new PerforcePasswordEncryptor();
env.put("P4PASSWD", encryptor.decryptString(p4Passwd));
}
}
env.put("P4CLIENT", getEffectiveClientName(build));
PerforceTagAction pta = getMostRecentTagAction(build);
if (pta != null) {
if (pta.getChangeNumber() > 0) {
int lastChange = pta.getChangeNumber();
env.put("P4_CHANGELIST", Integer.toString(lastChange));
}
else if (pta.getTag() != null) {
String label = pta.getTag();
env.put("P4_LABEL", label);
}
}
}
/**
* Perform some manipulation on the workspace URI to get a valid local path
* <p>
* Is there an issue doing this? What about remote workspaces? does that happen?
*
* @param path
* @return
* @throws IOException
* @throws InterruptedException
*/
private String getLocalPathName(FilePath path, boolean isUnix) throws IOException, InterruptedException {
String uriString = path.toURI().toString();
// Get rid of URI prefix
// NOTE: this won't handle remote files, is that a problem?
uriString = uriString.replaceAll("file:/", "");
// It seems there is a /./ to denote the root in the path on my test instance.
// I don't know if this is in production, or how it works on other platforms (non win32)
// but I am removing it here because perforce doesn't like it.
uriString = uriString.replaceAll("/./", "/");
// The URL is also escaped. We need to unescape it because %20 in path names isn't cool for perforce.
uriString = URLDecoder.decode(uriString, "UTF-8");
// Last but not least, we need to convert this to local path separators.
if (isUnix) {
// on unixen we need to prepend with /
uriString = "/" + uriString;
} else {
//just replace with sep doesn't work because java's foobar regexp replaceAll
uriString = uriString.replaceAll("/", "\\\\");
}
return uriString;
}
/*
* @see hudson.scm.SCM#checkout(hudson.model.AbstractBuild, hudson.Launcher, hudson.FilePath, hudson.model.BuildListener, java.io.File)
*/
@Override
public boolean checkout(AbstractBuild build, Launcher launcher,
FilePath workspace, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
PrintStream log = listener.getLogger();
//keep projectPath local so any modifications for slaves don't get saved
String projectPath = this.projectPath;
Depot depot = getDepot(launcher,workspace);
// If the 'master' MatrixBuild runs on the same node as any of the 'child' MatrixRuns,
// and it syncs to its own root, then the child's workspace won't get updated.
boolean dontChangeRoot = ((Object)build instanceof MatrixBuild);
try {
Workspace p4workspace = getPerforceWorkspace(depot, build.getBuiltOn(), launcher, workspace, listener, dontChangeRoot);
if (p4workspace.isNew()) {
log.println("Saving new client " + p4workspace.getName());
depot.getWorkspaces().saveWorkspace(p4workspace);
}
else if (p4workspace.isDirty()) {
log.println("Saving modified client " + p4workspace.getName());
depot.getWorkspaces().saveWorkspace(p4workspace);
}
//Get the list of changes since the last time we looked...
String p4WorkspacePath = "//" + p4workspace.getName() + "/...";
final int lastChange = getLastChange((Run)build.getPreviousBuild());
log.println("Last sync'd change: " + lastChange);
List<Changelist> changes;
int newestChange = lastChange;
if (p4Label != null) {
changes = new ArrayList<Changelist>(0);
} else {
String counterName;
if (p4Counter != null && !updateCounterValue)
counterName = p4Counter;
else
counterName = "change";
Counter counter = depot.getCounters().getCounter(counterName);
newestChange = counter.getValue();
if (lastChange >= newestChange) {
changes = new ArrayList<Changelist>(0);
} else {
List<Integer> changeNumbersTo = depot.getChanges().getChangeNumbersInRange(p4workspace, lastChange+1, newestChange);
changes = depot.getChanges().getChangelistsFromNumbers(changeNumbersTo);
}
}
if (changes.size() > 0) {
// Save the changes we discovered.
PerforceChangeLogSet.saveToChangeLog(
new FileOutputStream(changelogFile), changes);
newestChange = changes.get(0).getChangeNumber();
}
else {
// No new changes discovered (though the definition of the workspace or label may have changed).
createEmptyChangeLog(changelogFile, listener, "changelog");
// keep the newestChange to the same value except when changing
// definitions from label builds to counter builds
if (lastChange != -1)
newestChange = lastChange;
}
// Now we can actually do the sync process...
StringBuilder sbMessage = new StringBuilder("Sync'ing workspace to ");
StringBuilder sbSyncPath = new StringBuilder(p4WorkspacePath);
sbSyncPath.append("@");
if (p4Label != null) {
sbMessage.append("label ");
sbMessage.append(p4Label);
sbSyncPath.append(p4Label);
}
else {
sbMessage.append("changelist ");
sbMessage.append(newestChange);
if(!forceSync && !alwaysForceSync){
sbSyncPath.append(lastChange);
sbSyncPath.append(",@");
}
sbSyncPath.append(newestChange);
}
if (forceSync || alwaysForceSync)
sbMessage.append(" (forcing sync of unchanged files).");
else
sbMessage.append(".");
log.println(sbMessage.toString());
String syncPath = sbSyncPath.toString();
long startTime = System.currentTimeMillis();
depot.getWorkspaces().syncTo(syncPath, forceSync || alwaysForceSync);
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
log.println("Sync complete, took " + duration + " ms");
// reset one time use variables...
forceSync = false;
firstChange = -1;
if (p4Label != null) {
// Add tagging action that indicates that the build is already
// tagged (you can't label a label).
build.addAction(new PerforceTagAction(
build, depot, p4Label, projectPath));
}
else {
// Add tagging action that enables the user to create a label
// for this build.
build.addAction(new PerforceTagAction(
build, depot, newestChange, projectPath));
}
if (p4Counter != null && updateCounterValue) {
// Set or create a counter to mark this change
Counter counter = new Counter();
counter.setName(p4Counter);
counter.setValue(newestChange);
log.println("Updating counter " + p4Counter + " to " + newestChange);
depot.getCounters().saveCounter(counter);
}
//save the one time use variables...
build.getParent().save();
// remember the p4Ticket if we were issued one
p4Ticket = depot.getP4Ticket();
return true;
} catch (PerforceException e) {
log.print("Caught exception communicating with perforce. " + e.getMessage());
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
e.printStackTrace(pw);
pw.flush();
log.print(sw.toString());
throw new AbortException(
"Unable to communicate with perforce. " + e.getMessage());
} catch (InterruptedException e) {
throw new IOException(
"Unable to get hostname from slave. " + e.getMessage());
}
}
/**
* compute the path(s) that we search on to detect whether the project
* has any unsynched changes
*
* @param p4workspace the workspace
* @return a string of path(s), e.g. //mymodule1/... //mymodule2/...
*/
private String getChangesPaths(Workspace p4workspace) {
return PerforceSCMHelper.computePathFromViews(p4workspace.getViews());
}
@Override
public PerforceRepositoryBrowser getBrowser() {
return browser;
}
/*
* @see hudson.scm.SCM#createChangeLogParser()
*/
@Override
public ChangeLogParser createChangeLogParser() {
return new PerforceChangeLogParser();
}
/*
* @see hudson.scm.SCM#pollChanges(hudson.model.AbstractProject, hudson.Launcher, hudson.FilePath, hudson.model.TaskListener)
*
* When *should* this method return true?
*
* 1) When there is no previous build (might be the first, or all previous
* builds might have been deleted).
*
* 2) When the previous build did not use Perforce, in which case we can't
* be "sure" of the state of the files.
*
* 3) If the clientspec's views have changed since the last build; we don't currently
* save that info, but we should! I (James Synge) am not sure how to save it;
* should it be:
* a) in the build.xml file, and if so, how do we save it there?
* b) in the change log file (which actually makes a fair amount of sense)?
* c) in a separate file in the build directory (not workspace),
* along side the change log file?
*
* 4) p4Label has changed since the last build (either from unset to set, or from
* one label to another).
*
* 5) p4Label is set AND unchanged AND the set of file-revisions selected
* by the label in the p4 workspace has changed. Unfortunately, I don't
* know of a cheap way to do this.
*
* There may or may not have been a previous build. That build may or may not
* have been done using Perforce, and if with Perforce, may have been done
* using a label or latest, and may or may not be for the same view as currently
* defined. If any change has occurred, we'll treat that as a reason to build.
*
* Note that the launcher and workspace may operate remotely (as of 2009-06-21,
* they correspond to the node where the last build occurred, if any; if none,
* then the master is used).
*
* Note also that this method won't be called while the workspace (not job)
* is in use for building or some other polling thread.
*/
@Override
public boolean pollChanges(AbstractProject project, Launcher launcher,
FilePath workspace, TaskListener listener) throws IOException, InterruptedException {
PrintStream logger = listener.getLogger();
logger.println("Looking for changes...");
Depot depot = getDepot(launcher,workspace);
try {
Workspace p4workspace = getPerforceWorkspace(depot, project.getLastBuiltOn(), launcher, workspace, listener, false);
if (p4workspace.isNew())
return true;
Boolean needToBuild = needToBuild(p4workspace, project, depot, logger);
if (needToBuild == null) {
needToBuild = wouldSyncChangeWorkspace(project, depot, logger);
}
if (needToBuild == Boolean.FALSE) {
return false;
}
else {
logger.println("Triggering a build.");
return true;
}
} catch (PerforceException e) {
System.out.println("Problem: " + e.getMessage());
logger.println("Caught Exception communicating with perforce." + e.getMessage());
e.printStackTrace();
throw new IOException("Unable to communicate with perforce. Check log file for: " + e.getMessage());
}
}
private Boolean needToBuild(Workspace p4workspace, AbstractProject project, Depot depot,
PrintStream logger) throws IOException, InterruptedException, PerforceException {
/*
* Don't bother polling if we're already building, or soon will.
* Ideally this would be a policy exposed to the user, perhaps for all
* jobs with all types of scm, not just those using Perforce.
*/
// if (project.isBuilding() || project.isInQueue()) {
// logger.println("Job is already building or in the queue; skipping polling.");
// return Boolean.FALSE;
Run lastBuild = project.getLastBuild();
if (lastBuild == null) {
logger.println("No previous build exists.");
return null; // Unable to determine if there are changes.
}
PerforceTagAction action = lastBuild.getAction(PerforceTagAction.class);
if (action == null) {
logger.println("Previous build doesn't have Perforce info.");
return null;
}
int lastChangeNumber = action.getChangeNumber();
String lastLabelName = action.getTag();
if (lastChangeNumber <= 0 && lastLabelName != null) {
logger.println("Previous build was based on label " + lastLabelName);
// Last build was based on a label, so we want to know if:
// the definition of the label was changed;
// or the view has been changed;
// or p4Label has been changed.
if (p4Label == null) {
logger.println("Job configuration changed to build from head, not a label.");
return Boolean.TRUE;
}
if (!lastLabelName.equals(p4Label)) {
logger.println("Job configuration changed to build from label " + p4Label + ", not from head");
return Boolean.TRUE;
}
// No change in job definition (w.r.t. p4Label). Don't currently
// save enough info about the label to determine if it changed.
logger.println("Assuming that the workspace and label definitions have not changed.");
return Boolean.FALSE;
}
if (lastChangeNumber > 0) {
logger.println("Last sync'd change was " + lastChangeNumber);
if (p4Label != null) {
logger.println("Job configuration changed to build from label " + p4Label + ", not from head.");
return Boolean.TRUE;
}
int highestSelectedChangeNumber;
if (p4Counter != null && !updateCounterValue) {
// If this is a downstream build that triggers by polling the set counter
// use the counter as the value for the newest change instead of the workspace view
Counter counter = depot.getCounters().getCounter(p4Counter);
highestSelectedChangeNumber = counter.getValue();
logger.println("Latest submitted change selected by named counter is " + highestSelectedChangeNumber);
} else {
// Has any new change been submitted since then (that is selected
// by this workspace).
String root = "//" + p4workspace.getName() + "/...";
List<Integer> changeNumbers = depot.getChanges().getChangeNumbers(root, -1, 2);
if (changeNumbers.isEmpty()) {
// Wierd, this shouldn't be! I suppose it could happen if the
// view selects no files (e.g. //depot/non-existent-branch/...).
// Just in case, let's try to build.
return Boolean.TRUE;
}
highestSelectedChangeNumber = changeNumbers.get(0).intValue();
logger.println("Latest submitted change selected by workspace is " + highestSelectedChangeNumber);
}
if (lastChangeNumber >= highestSelectedChangeNumber) {
// Note, can't determine with currently saved info
// whether the workspace definition has changed.
logger.println("Assuming that the workspace definition has not changed.");
return Boolean.FALSE;
}
else {
return Boolean.TRUE;
}
}
return null;
}
// TODO Handle the case where p4Label is set.
private boolean wouldSyncChangeWorkspace(AbstractProject project, Depot depot,
PrintStream logger) throws IOException, InterruptedException, PerforceException {
Workspaces workspaces = depot.getWorkspaces();
String result = workspaces.syncDryRun().toString();
if (result.startsWith("File(s) up-to-date.")) {
logger.println("Workspace up-to-date.");
return false;
}
else {
logger.println("Workspace not up-to-date.");
return true;
}
}
public int getLastChange(Run build) {
// If we are starting a new hudson project on existing work and want to skip the prior history...
if (firstChange > 0)
return firstChange;
// If we can't find a PerforceTagAction, we will default to 0.
PerforceTagAction action = getMostRecentTagAction(build);
if (action == null)
return 0;
//log.println("Found last change: " + action.getChangeNumber());
return action.getChangeNumber();
}
private PerforceTagAction getMostRecentTagAction(Run build) {
if (build == null)
return null;
PerforceTagAction action = build.getAction(PerforceTagAction.class);
if (action != null)
return action;
// if build had no actions, keep going back until we find one that does.
return getMostRecentTagAction(build.getPreviousBuild());
}
private Workspace getPerforceWorkspace(
Depot depot, Node buildNode,
Launcher launcher, FilePath workspace, TaskListener listener, boolean dontChangeRoot)
throws IOException, InterruptedException, PerforceException
{
PrintStream log = listener.getLogger();
// If we are building on a slave node, and each node is supposed to have
// its own unique client, then adjust the client name accordingly.
// make sure each slave has a unique client name by adding it's
// hostname to the end of the client spec
String p4Client = this.p4Client;
p4Client = getEffectiveClientName(buildNode, workspace);
if (!nodeIsRemote(buildNode)) {
log.print("Using master perforce client: ");
log.println(p4Client);
}
else if (dontRenameClient) {
log.print("Using shared perforce client: ");
log.println(p4Client);
}
else {
log.println("Using remote perforce client: " + p4Client);
}
depot.setClient(p4Client);
// Get the clientspec (workspace) from perforce
Workspace p4workspace = depot.getWorkspaces().getWorkspace(p4Client);
assert p4workspace != null;
boolean creatingNewWorkspace = p4workspace.isNew();
// Ensure that the clientspec (workspace) name is set correctly
// TODO Examine why this would be necessary.
p4workspace.setName(p4Client);
// Set the workspace options according to the configuration
if (projectOptions != null)
p4workspace.setOptions(projectOptions);
// Ensure that the root is appropriate (it might be wrong if the user
// created it, or if we previously built on another node).
String localPath = getLocalPathName(workspace, launcher.isUnix());
if (!localPath.equals(p4workspace.getRoot()) && !dontChangeRoot) {
log.println("Changing P4 Client Root to: " + localPath);
p4workspace.setRoot(localPath);
}
// If necessary, rewrite the views field in the clientspec;
// TODO If dontRenameClient==false, and updateView==false, user
// has a lot of work to do to maintain the clientspecs. Seems like
// we could copy from a master clientspec to the slaves.
if (updateView || creatingNewWorkspace) {
List<String> mappingPairs = parseProjectPath(projectPath, p4Client);
if (!equalsProjectPath(mappingPairs, p4workspace.getViews())) {
log.println("Changing P4 Client View from:\n" + p4workspace.getViewsAsString());
log.println("Changing P4 Client View to: ");
p4workspace.clearViews();
for (int i = 0; i < mappingPairs.size(); ) {
String depotPath = mappingPairs.get(i++);
String clientPath = mappingPairs.get(i++);
p4workspace.addView(" " + depotPath + " " + clientPath);
log.println(" " + depotPath + " " + clientPath);
}
}
}
// If we use the same client on multiple hosts (e.g. master and slave),
// erase the host field so the client isn't tied to a single host.
if (dontRenameClient) {
p4workspace.setHost("");
}
// NOTE: The workspace is not saved.
return p4workspace;
}
private String getEffectiveClientName(AbstractBuild build) {
Node buildNode = build.getBuiltOn();
FilePath workspace = build.getWorkspace();
String p4Client = this.p4Client;
try {
p4Client = getEffectiveClientName(buildNode, workspace);
} catch (Exception e){
new StreamTaskListener(System.out).getLogger().println(
"Could not get effective client name: " + e.getMessage());
} finally {
return p4Client;
}
}
private String getEffectiveClientName(Node buildNode, FilePath workspace)
throws IOException, InterruptedException {
String nodeSuffix = "";
String p4Client = this.p4Client;
if (nodeIsRemote(buildNode) && !dontRenameClient) {
//use the 1st part of the hostname as the node suffix
String host = workspace.act(new GetHostname());
if (host.contains(".")) {
nodeSuffix = "-" + host.subSequence(0, host.indexOf('.'));
} else {
nodeSuffix = "-" + host;
}
p4Client += nodeSuffix;
}
return p4Client;
}
private boolean nodeIsRemote(Node buildNode) {
return buildNode != null && buildNode.getNodeName().length() != 0;
}
@Extension
public static final class PerforceSCMDescriptor extends SCMDescriptor<PerforceSCM> {
public PerforceSCMDescriptor() {
super(PerforceSCM.class, PerforceRepositoryBrowser.class);
load();
}
public String getDisplayName() {
return "Perforce";
}
public String isValidProjectPath(String path) {
if (!path.startsWith("
return "Path must start with '//' (Example: //depot/ProjectName/...)";
}
if (!path.endsWith("/...")) {
if (!path.contains("@")) {
return "Path must end with Perforce wildcard: '/...' (Example: //depot/ProjectName/...)";
}
}
return null;
}
protected Depot getDepotFromRequest(StaplerRequest request) {
String port = fixNull(request.getParameter("port")).trim();
String exe = fixNull(request.getParameter("exe")).trim();
String user = fixNull(request.getParameter("user")).trim();
String pass = fixNull(request.getParameter("pass")).trim();
if (port.length() == 0 || exe.length() == 0) { // Not enough entered yet
return null;
}
Depot depot = new Depot();
depot.setUser(user);
PerforcePasswordEncryptor encryptor = new PerforcePasswordEncryptor();
if (encryptor.appearsToBeAnEncryptedPassword(pass)) {
depot.setPassword(encryptor.decryptString(pass));
}
else {
depot.setPassword(pass);
}
depot.setPort(port);
depot.setExecutable(exe);
try {
Counter counter = depot.getCounters().getCounter("change");
if (counter != null)
return depot;
} catch (PerforceException e) {
}
return null;
}
/**
* Checks if the perforce login credentials are good.
*/
public FormValidation doValidatePerforceLogin(StaplerRequest req) {
Depot depot = getDepotFromRequest(req);
if (depot != null) {
try {
depot.getStatus().isValid();
} catch (PerforceException e) {
return FormValidation.error(e.getMessage());
}
}
return FormValidation.ok();
}
/**
* Checks to see if the specified workspace is valid.
*/
public FormValidation doValidateP4Client(StaplerRequest req) {
Depot depot = getDepotFromRequest(req);
if (depot == null) {
return FormValidation.error(
"Unable to check workspace against depot");
}
String workspace = Util.fixEmptyAndTrim(req.getParameter("client"));
if (workspace == null) {
return FormValidation.error("You must enter a workspaces name");
}
try {
Workspace p4Workspace =
depot.getWorkspaces().getWorkspace(workspace);
if (p4Workspace.getAccess() == null ||
p4Workspace.getAccess().equals(""))
return FormValidation.warning("Workspace does not exist. " +
"If \"Let Hudson Manage Workspace View\" is check" +
" the workspace will be automatically created.");
} catch (PerforceException e) {
return FormValidation.error(
"Error accessing perforce while checking workspace");
}
return FormValidation.ok();
}
/**
* Performs syntactical check on the P4Label
*/
public FormValidation doValidateP4Label(StaplerRequest req, @QueryParameter String label) throws IOException, ServletException {
label = Util.fixEmptyAndTrim(label);
if (label == null)
return FormValidation.ok();
Depot depot = getDepotFromRequest(req);
if (depot != null) {
try {
Label p4Label = depot.getLabels().getLabel(label);
if (p4Label.getAccess() == null || p4Label.getAccess().equals(""))
return FormValidation.error("Label does not exist");
} catch (PerforceException e) {
return FormValidation.error(
"Error accessing perforce while checking label");
}
}
return FormValidation.ok();
}
public FormValidation doValidateP4Counter(StaplerRequest req, @QueryParameter String counter) throws IOException, ServletException {
counter= Util.fixEmptyAndTrim(counter);
if (counter == null)
return FormValidation.ok();
Depot depot = getDepotFromRequest(req);
if (depot != null) {
try {
Counters counters = depot.getCounters();
Counter p4Counter = counters.getCounter(counter);
counters.saveCounter(p4Counter);
} catch (PerforceException e) {
return FormValidation.error(
"Error accessing perforce while checking counter: " + e.getLocalizedMessage());
}
}
return FormValidation.ok();
}
/**
* Checks if the value is a valid Perforce project path.
*/
public FormValidation doCheckProjectPath(@QueryParameter String value) throws IOException, ServletException {
String view = Util.fixEmptyAndTrim(value);
if (view != null) {
for (String mapping : view.split("\n")) {
if (!DEPOT_ONLY.matcher(mapping).matches() &&
!DEPOT_AND_WORKSPACE.matcher(mapping).matches() &&
!DEPOT_ONLY_QUOTED.matcher(mapping).matches() &&
!DEPOT_AND_WORKSPACE_QUOTED.matcher(mapping).matches() &&
!COMMENT.matcher(mapping).matches())
return FormValidation.error("Invalid mapping:" + mapping);
}
}
return FormValidation.ok();
}
/**
* Checks if the change list entered exists
*/
public FormValidation doCheckChangeList(StaplerRequest req) {
Depot depot = getDepotFromRequest(req);
String change = fixNull(req.getParameter("change")).trim();
if (change.length() == 0) { // nothing entered yet
return FormValidation.ok();
}
if (depot != null) {
try {
int number = Integer.parseInt(change);
Changelist changelist = depot.getChanges().getChangelist(number);
if (changelist.getChangeNumber() != number)
throw new PerforceException("broken");
} catch (Exception e) {
return FormValidation.error("Changelist: " + change + " does not exist.");
}
}
return FormValidation.ok();
}
}
/* Regular expressions for parsing view mappings.
*/
private static final Pattern COMMENT = Pattern.compile("^$|^
private static final Pattern DEPOT_ONLY = Pattern.compile("^[+-]?
private static final Pattern DEPOT_ONLY_QUOTED = Pattern.compile("^\"[+-]?
private static final Pattern DEPOT_AND_WORKSPACE =
Pattern.compile("^([+-]?//\\S+?/\\S+)\\s+//\\S+?(/\\S+)$");
private static final Pattern DEPOT_AND_WORKSPACE_QUOTED =
Pattern.compile("^\"([+-]?//\\S+?/[^\"]+)\"\\s+\"//\\S+?(/[^\"]+)\"$");
/**
* Parses the projectPath into a list of pairs of strings representing the depot and client
* paths. Even items are depot and odd items are client.
* <p>
* This parser can handle quoted or non-quoted mappings, normal two-part mappings, or one-part
* mappings with an implied right part. It can also deal with +// or -// mapping forms.
*/
static List<String> parseProjectPath(String projectPath, String p4Client) {
List<String> parsed = new ArrayList<String>();
for (String line : projectPath.split("\n")) {
Matcher depotOnly = DEPOT_ONLY.matcher(line);
if (depotOnly.find()) {
// add the trimmed depot path, plus a manufactured client path
parsed.add(line.trim());
parsed.add("//" + p4Client + depotOnly.group(1));
} else {
Matcher depotOnlyQuoted = DEPOT_ONLY_QUOTED.matcher(line);
if (depotOnlyQuoted.find()) {
// add the trimmed quoted depot path, plus a manufactured quoted client path
parsed.add(line.trim());
parsed.add("\"//" + p4Client + depotOnlyQuoted.group(1) + "\"");
} else {
Matcher depotAndWorkspace = DEPOT_AND_WORKSPACE.matcher(line);
if (depotAndWorkspace.find()) {
// add the found depot path and the clientname-tweaked client path
parsed.add(depotAndWorkspace.group(1));
parsed.add("//" + p4Client + depotAndWorkspace.group(2));
} else {
Matcher depotAndWorkspaceQuoted = DEPOT_AND_WORKSPACE_QUOTED.matcher(line);
if (depotAndWorkspaceQuoted.find()) {
// add the found depot path and the clientname-tweaked client path
parsed.add("\"" + depotAndWorkspaceQuoted.group(1) + "\"");
parsed.add("\"//" + p4Client + depotAndWorkspaceQuoted.group(2) + "\"");
}
// Assume anything else is a comment and ignore it
}
}
}
}
return parsed;
}
/**
* Compares a parsed project path pair list against a list of view
* mapping lines from a client spec.
*/
static boolean equalsProjectPath(List<String> pairs, List<String> lines) {
Iterator<String> pi = pairs.iterator();
for (String line : lines) {
if (!pi.hasNext())
return false;
String p1 = pi.next();
String p2 = pi.next(); // assuming an even number of pair items
if (!line.trim().equals(p1 + " " + p2))
return false;
}
return !pi.hasNext(); // equals iff there are no more pairs
}
/**
* @return the projectPath
*/
public String getProjectPath() {
return projectPath;
}
/**
* @param projectPath the projectPath to set
*/
public void setProjectPath(String projectPath) {
this.projectPath = projectPath;
}
/**
* @return the p4User
*/
public String getP4User() {
return p4User;
}
/**
* @param user the p4User to set
*/
public void setP4User(String user) {
p4User = user;
}
/**
* @return the p4Passwd
*/
public String getP4Passwd() {
return p4Passwd;
}
/**
* @param passwd the p4Passwd to set
*/
public void setP4Passwd(String passwd) {
PerforcePasswordEncryptor encryptor = new PerforcePasswordEncryptor();
if (encryptor.appearsToBeAnEncryptedPassword(passwd))
p4Passwd = passwd;
else
p4Passwd = encryptor.encryptString(passwd);
}
/**
* @return the p4Port
*/
public String getP4Port() {
return p4Port;
}
/**
* @param port the p4Port to set
*/
public void setP4Port(String port) {
p4Port = port;
}
/**
* @return the p4Client
*/
public String getP4Client() {
return p4Client;
}
/**
* @param client the p4Client to set
*/
public void setP4Client(String client) {
p4Client = client;
}
/**
* @return the p4SysDrive
*/
public String getP4SysDrive() {
return p4SysDrive;
}
/**
* @param sysDrive the p4SysDrive to set
*/
public void setP4SysDrive(String sysDrive) {
p4SysDrive = sysDrive;
}
/**
* @return the p4SysRoot
*/
public String getP4SysRoot() {
return p4SysRoot;
}
/**
* @param sysRoot the p4SysRoot to set
*/
public void setP4SysRoot(String sysRoot) {
p4SysRoot = sysRoot;
}
/**
* @return the p4Exe
*/
public String getP4Exe() {
return p4Exe;
}
/**
* @param exe the p4Exe to set
*/
public void setP4Exe(String exe) {
p4Exe = exe;
}
/**
* @return the p4Label
*/
public String getP4Label() {
return p4Label;
}
/**
* @param label the p4Label to set
*/
public void setP4Label(String label) {
p4Label = label;
}
/**
* @return the p4Counter
*/
public String getP4Counter() {
return p4Counter;
}
/**
* @param counter the p4Counter to set
*/
public void setP4Counter(String counter) {
p4Counter = counter;
}
/**
* @return True if the plugin should update the counter to the last change
*/
public boolean isUpdateCounterValue() {
return updateCounterValue;
}
/**
* @param updateCounterValue True if the plugin should update the counter to the last change
*/
public void setUpdateCounterValue(boolean updateCounterValue) {
this.updateCounterValue = updateCounterValue;
}
/**
* @return True if the P4PASSWD value must be set in the environment
*/
public boolean isExposeP4Passwd() {
return exposeP4Passwd;
}
/**
* @param exposeP4Passwd True if the P4PASSWD value must be set in the environment
*/
public void setExposeP4Passwd(boolean exposeP4Passwd) {
this.exposeP4Passwd = exposeP4Passwd;
}
/**
* The current perforce option set for the view.
* @return current perforce view options
*/
public String getProjectOptions() {
return projectOptions;
}
/**
* Set the perforce options for view creation.
* @param projectOptions the effective perforce options.
*/
public void setProjectOptions(String projectOptions) {
this.projectOptions = projectOptions;
}
/**
* @param update True to let the plugin manage the view, false to let the user manage it
*/
public void setUpdateView(boolean update) {
this.updateView = update;
}
/**
* @return True if the plugin manages the view, false if the user does.
*/
public boolean isUpdateView() {
return updateView;
}
/**
* @return True if we are performing a one-time force sync
*/
public boolean isForceSync() {
return forceSync;
}
/**
* @return True if we are performing a one-time force sync
*/
public boolean isAlwaysForceSync() {
return alwaysForceSync;
}
/**
* @param force True to perform a one time force sync, false to perform normal sync
*/
public void setForceSync(boolean force) {
this.forceSync = force;
}
/**
* @param force True to perform a one time force sync, false to perform normal sync
*/
public void setAlwaysForceSync(boolean force) {
this.alwaysForceSync = force;
}
/**
* @return True if we are using a label
*/
public boolean isUseLabel() {
return p4Label != null;
}
/**
* @param dontRenameClient False if the client will rename the client spec for each
* slave
*/
public void setDontRenameClient(boolean dontRenameClient) {
this.dontRenameClient = dontRenameClient;
}
/**
* @return True if the client will rename the client spec for each slave
*/
public boolean isDontRenameClient() {
return dontRenameClient;
}
/**
* This is only for the config screen. Also, it returns a string and not an int.
* This is because we want to show an empty value in the config option if it is not being
* used. The default value of -1 is not exactly empty. So if we are set to default of
* -1, we return an empty string. Anything else and we return the actual change number.
*
* @return The one time use variable, firstChange.
*/
public String getFirstChange() {
if (firstChange <= 0)
return "";
return Integer.valueOf(firstChange).toString();
}
/**
* Get the hostname of the client to use as the node suffix
*/
private static final class GetHostname implements FileCallable<String> {
public String invoke(File f, VirtualChannel channel) throws IOException {
return InetAddress.getLocalHost().getHostName();
}
private static final long serialVersionUID = 1L;
}
/**
* With Perforce the server keeps track of files in the workspace. We never
* want files deleted without the knowledge of the server so we disable the
* cleanup process.
*
* @param project
* The project that owns this {@link SCM}. This is always the same
* object for a particular instanceof {@link SCM}. Just passed in here
* so that {@link SCM} itself doesn't have to remember the value.
* @param workspace
* The workspace which is about to be deleted. Never null. This can be
* a remote file path.
* @param node
* The node that hosts the workspace. SCM can use this information to
* determine the course of action.
*
* @return
* true if {@link SCM} is OK to let Hudson proceed with deleting the
* workspace.
* False to veto the workspace deletion.
*/
@Override
public boolean processWorkspaceBeforeDeletion(AbstractProject<?,?> project, FilePath workspace, Node node) {
Logger.getLogger(PerforceSCM.class.getName()).info(
"Workspace is being deleted; enabling one-time force sync.");
forceSync = true;
return true;
}
@Override public boolean requiresWorkspaceForPolling() {
return true;
}
}
|
package imagej.ops;
import imagej.command.CommandInfo;
import imagej.command.CommandModuleItem;
import imagej.command.CommandService;
import imagej.module.Module;
import imagej.module.ModuleInfo;
import imagej.module.ModuleItem;
import imagej.module.ModuleService;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import org.scijava.Context;
import org.scijava.InstantiableException;
import org.scijava.log.LogService;
import org.scijava.plugin.AbstractSingletonService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.service.Service;
import org.scijava.util.ConversionUtils;
/**
* Default service for finding {@link Op}s which match a template.
*
* @author Curtis Rueden
*/
@Plugin(type = Service.class)
public class DefaultOpMatchingService extends
AbstractSingletonService<Optimizer> implements OpMatchingService
{
@Parameter
private Context context;
@Parameter
private ModuleService moduleService;
@Parameter
private CommandService commandService;
@Parameter
private LogService log;
// -- OpMatchingService methods --
@Override
public List<CommandInfo> getOps() {
return commandService.getCommandsOfType(Op.class);
}
@Override
public Module findModule(final String name, final Class<? extends Op> type,
final Object... args)
{
final String label = type == null ? name : type.getName();
// find candidates with matching name & type
final List<ModuleInfo> candidates = findCandidates(name, type);
if (candidates.isEmpty()) {
throw new IllegalArgumentException("No candidate '" + label + "' ops");
}
// narrow down candidates to the exact matches
final List<Module> matches = findMatches(candidates, args);
if (matches.size() == 1) {
// a single match: return it
if (log.isDebug()) {
log.debug("Selected '" + label + "' op: " +
matches.get(0).getDelegateObject().getClass().getName());
}
return optimize(matches.get(0));
}
final StringBuilder sb = new StringBuilder();
if (matches.isEmpty()) {
// no matches
sb.append("No matching '" + label + "' op\n");
}
else {
// multiple matches
final double priority = matches.get(0).getInfo().getPriority();
sb.append("Multiple '" + label + "' ops of priority " + priority + ":\n");
for (final Module module : matches) {
sb.append("\t" + getOpString(module.getInfo()) + "\n");
}
}
// fail, with information about the template and candidates
sb.append("Template:\n");
sb.append("\t" + getOpString(label, args) + "\n");
sb.append("Candidates:\n");
for (final ModuleInfo info : candidates) {
sb.append("\t" + getOpString(info) + "\n");
}
throw new IllegalArgumentException(sb.toString());
}
@Override
public List<ModuleInfo> findCandidates(final String name,
final Class<? extends Op> type)
{
final List<CommandInfo> ops = getOps();
final ArrayList<ModuleInfo> candidates = new ArrayList<ModuleInfo>();
for (final CommandInfo info : ops) {
if (isCandidate(info, name, type)) candidates.add(info);
}
return candidates;
}
@Override
public List<Module> findMatches(final List<? extends ModuleInfo> ops,
final Object... args)
{
final ArrayList<Module> matches = new ArrayList<Module>();
double priority = Double.NaN;
for (final ModuleInfo info : ops) {
final double p = info.getPriority();
if (p != priority && !matches.isEmpty()) {
// NB: Lower priority was reached; stop looking for any more matches.
break;
}
priority = p;
final Module module = match(info, args);
if (module != null) matches.add(module);
}
return matches;
}
@Override
public Module match(final ModuleInfo info, final Object... args) {
if (!info.isValid()) return null; // skip invalid modules
// check the number of args, padding optional args with null as needed
int inputCount = 0, requiredCount = 0;
for (final ModuleItem<?> item : info.inputs()) {
inputCount++;
if (item.isRequired()) requiredCount++;
}
if (args.length > inputCount) return null; // too many arguments
if (args.length < requiredCount) return null; // too few arguments
if (args.length != inputCount) {
// pad optional parameters with null (from right to left)
final int argsToPad = inputCount - args.length;
final int optionalCount = inputCount - requiredCount;
final int optionalsToFill = optionalCount - argsToPad;
final Object[] paddedArgs = new Object[inputCount];
int argIndex = 0, paddedIndex = 0, optionalIndex = 0;
for (final ModuleItem<?> item : info.inputs()) {
if (!item.isRequired() && optionalIndex++ >= optionalsToFill) {
// skip this optional parameter (pad with null)
paddedIndex++;
continue;
}
paddedArgs[paddedIndex++] = args[argIndex++];
}
return match(info, paddedArgs);
}
// check that each parameter is compatible with its argument
int i = 0;
for (final ModuleItem<?> item : info.inputs()) {
final Object arg = args[i++];
if (!canAssign(arg, item)) return null;
}
// create module and assign the inputs
final Module module = createModule(info, args);
// make sure the op itself is happy with these arguments
final Object op = module.getDelegateObject();
if (op instanceof Contingent) {
final Contingent c = (Contingent) op;
if (!c.conforms()) return null;
}
// found a match!
return module;
}
@Override
public Module assignInputs(final Module module, final Object... args) {
int i = 0;
for (final ModuleItem<?> item : module.getInfo().inputs()) {
assign(module, args[i++], item);
}
return module;
}
@Override
public Module optimize(final Module module) {
final ArrayList<Module> optimal = new ArrayList<Module>();
final ArrayList<Optimizer> optimizers = new ArrayList<Optimizer>();
double priority = Double.NaN;
for (final Optimizer optimizer : getInstances()) {
final double p = optimizer.getPriority();
if (p != priority && !optimal.isEmpty()) {
// NB: Lower priority was reached; stop looking for any more matches.
break;
}
priority = p;
final Module m = optimizer.optimize(module);
if (m != null) {
optimal.add(m);
optimizers.add(optimizer);
}
}
if (optimal.size() == 1) return optimal.get(0);
if (optimal.isEmpty()) return module;
// multiple matches
final double p = optimal.get(0).getInfo().getPriority();
final StringBuilder sb = new StringBuilder();
final String label = module.getDelegateObject().getClass().getName();
sb.append("Multiple '" + label + "' optimizations of priority " + p + ":\n");
for (int i = 0; i < optimizers.size(); i++) {
sb.append("\t" + optimizers.get(i).getClass().getName() + " produced:");
sb.append("\t\t" + getOpString(optimal.get(i).getInfo()) + "\n");
}
log.warn(sb.toString());
return module;
}
@Override
public String getOpString(final String name, final Object... args) {
final StringBuilder sb = new StringBuilder();
sb.append(name + "(");
boolean first = true;
for (final Object arg : args) {
if (first) first = false;
else sb.append(", ");
if (arg != null) sb.append(arg.getClass().getName() + " ");
if (arg instanceof Class) sb.append(((Class<?>) arg).getName());
else sb.append(arg);
}
sb.append(")");
return sb.toString();
}
@Override
public String getOpString(final ModuleInfo info) {
final StringBuilder sb = new StringBuilder();
if (!info.isValid()) sb.append("{!INVALID!} ");
sb.append("[" + info.getPriority() + "] ");
sb.append("(" + paramString(info.outputs()) + ")");
sb.append(" = " + info.getDelegateClassName());
sb.append("(" + paramString(info.inputs()) + ")");
return sb.toString();
}
@Override
public boolean isCandidate(final CommandInfo info, final String name) {
return isCandidate(info, name, null);
}
@Override
public boolean isCandidate(final CommandInfo info,
final Class<? extends Op> type)
{
return isCandidate(info, null, type);
}
@Override
public boolean isCandidate(final CommandInfo info, final String name,
final Class<? extends Op> type)
{
if (!nameMatches(info, name)) return false;
// the name matches; now check the class
final Class<?> opClass;
try {
opClass = info.loadClass();
}
catch (final InstantiableException exc) {
log.error("Invalid op: " + info.getClassName());
return false;
}
if (type != null && !type.isAssignableFrom(opClass)) return false;
return true;
}
// -- PTService methods --
@Override
public Class<Optimizer> getPluginType() {
return Optimizer.class;
}
// -- Helper methods --
private boolean nameMatches(final ModuleInfo info, final String name) {
if (name == null || name.equals(info.getName())) return true;
// check for an alias
final String alias = info.get("alias");
if (name.equals(alias)) return true;
// check for a list of aliases
final String aliases = info.get("aliases");
if (aliases != null) {
for (final String a : aliases.split(",")) {
if (name.equals(a.trim())) return true;
}
}
return false;
}
/** Helper method of {@link #match}. */
private Module createModule(final ModuleInfo info, final Object... args) {
final Module module = moduleService.createModule(info);
context.inject(module.getDelegateObject());
return assignInputs(module, args);
}
private boolean canAssign(final Object arg, final ModuleItem<?> item) {
if (arg == null) return !item.isRequired();
if (item instanceof CommandModuleItem) {
final CommandModuleItem<?> commandItem = (CommandModuleItem<?>) item;
final Type type = commandItem.getField().getGenericType();
return canConvert(arg, type);
}
return canConvert(arg, item.getType());
}
private boolean canConvert(final Object o, final Type type) {
if (o instanceof Class && ConversionUtils.canConvert((Class<?>) o, type)) {
// NB: Class argument for matching, to help differentiate op signatures.
return true;
}
return ConversionUtils.canConvert(o, type);
}
private boolean canConvert(final Object o, final Class<?> type) {
if (o instanceof Class && ConversionUtils.canConvert((Class<?>) o, type)) {
// NB: Class argument for matching, to help differentiate op signatures.
return true;
}
return ConversionUtils.canConvert(o, type);
}
/** Helper method of {@link #assignInputs}. */
private void assign(final Module module, final Object arg,
final ModuleItem<?> item)
{
if (arg != null) {
Object value;
if (item instanceof CommandModuleItem) {
final CommandModuleItem<?> commandItem = (CommandModuleItem<?>) item;
final Type type = commandItem.getField().getGenericType();
value = convert(arg, type);
}
else value = convert(arg, item.getType());
module.setInput(item.getName(), value);
}
module.setResolved(item.getName(), true);
}
private Object convert(final Object o, final Type type) {
if (o instanceof Class && ConversionUtils.canConvert((Class<?>) o, type)) {
// NB: Class argument for matching; fill with null.
return null;
}
return ConversionUtils.convert(o, type);
}
private Object convert(final Object o, final Class<?> type) {
if (o instanceof Class && ConversionUtils.canConvert((Class<?>) o, type)) {
// NB: Class argument for matching; fill with null.
return true;
}
return ConversionUtils.convert(o, type);
}
private String paramString(final Iterable<ModuleItem<?>> items) {
final StringBuilder sb = new StringBuilder();
boolean first = true;
for (final ModuleItem<?> item : items) {
if (first) first = false;
else sb.append(", ");
sb.append(item.getType().getName() + " " + item.getName());
if (!item.isRequired()) sb.append("?");
}
return sb.toString();
}
}
|
package invtweaks.container;
import invtweaks.InvTweaksConst;
import invtweaks.api.container.ContainerSection;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.inventory.GuiContainerCreative;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.ContainerHorseInventory;
import net.minecraft.inventory.Slot;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings({"unchecked", "unused"})
public class VanillaSlotMaps {
public static Map<ContainerSection, List<Slot>> containerPlayerSlots(Container container) {
Map<ContainerSection, List<Slot>> slotRefs = new HashMap<>();
slotRefs.put(ContainerSection.CRAFTING_OUT, container.inventorySlots.subList(0, 1));
slotRefs.put(ContainerSection.CRAFTING_IN, container.inventorySlots.subList(1, 5));
slotRefs.put(ContainerSection.ARMOR, container.inventorySlots.subList(5, 9));
slotRefs.put(ContainerSection.INVENTORY, container.inventorySlots.subList(9, 45));
slotRefs.put(ContainerSection.INVENTORY_NOT_HOTBAR, container.inventorySlots.subList(9, 36));
slotRefs.put(ContainerSection.INVENTORY_HOTBAR, container.inventorySlots.subList(36, 45));
return slotRefs;
}
@SideOnly(Side.CLIENT)
public static boolean containerCreativeIsInventory(GuiContainerCreative.ContainerCreative container) {
GuiScreen currentScreen = FMLClientHandler.instance().getClient().currentScreen;
return currentScreen instanceof GuiContainerCreative && ((GuiContainerCreative) currentScreen).getSelectedTabIndex() == CreativeTabs.tabInventory.getTabIndex();
}
@SideOnly(Side.CLIENT)
public static Map<ContainerSection, List<Slot>> containerCreativeSlots(GuiContainerCreative.ContainerCreative container) {
Map<ContainerSection, List<Slot>> slotRefs = new HashMap<>();
slotRefs.put(ContainerSection.ARMOR, container.inventorySlots.subList(5, 9));
slotRefs.put(ContainerSection.INVENTORY, container.inventorySlots.subList(9, 45));
slotRefs.put(ContainerSection.INVENTORY_NOT_HOTBAR, container.inventorySlots.subList(9, 36));
slotRefs.put(ContainerSection.INVENTORY_HOTBAR, container.inventorySlots.subList(36, 45));
return slotRefs;
}
public static Map<ContainerSection, List<Slot>> containerChestDispenserSlots(Container container) {
Map<ContainerSection, List<Slot>> slotRefs = new HashMap<>();
slotRefs.put(ContainerSection.CHEST, container.inventorySlots.subList(0, container.inventorySlots
.size() - InvTweaksConst.INVENTORY_SIZE));
return slotRefs;
}
public static Map<ContainerSection, List<Slot>> containerHorseSlots(ContainerHorseInventory container) {
Map<ContainerSection, List<Slot>> slotRefs = new HashMap<>();
if(container.theHorse.isChested()) { // Chest slots are only added if chest is added. Saddle/armor slots always exist.
slotRefs.put(ContainerSection.CHEST, container.inventorySlots.subList(2, container.inventorySlots.size() - InvTweaksConst.INVENTORY_SIZE));
}
return slotRefs;
}
public static boolean containerHorseIsInventory(ContainerHorseInventory container) {
return container.theHorse.isChested();
}
public static Map<ContainerSection, List<Slot>> containerFurnaceSlots(Container container) {
Map<ContainerSection, List<Slot>> slotRefs = new HashMap<>();
slotRefs.put(ContainerSection.FURNACE_IN, container.inventorySlots.subList(0, 1));
slotRefs.put(ContainerSection.FURNACE_FUEL, container.inventorySlots.subList(1, 2));
slotRefs.put(ContainerSection.FURNACE_OUT, container.inventorySlots.subList(2, 3));
return slotRefs;
}
public static Map<ContainerSection, List<Slot>> containerWorkbenchSlots(Container container) {
Map<ContainerSection, List<Slot>> slotRefs = new HashMap<>();
slotRefs.put(ContainerSection.CRAFTING_OUT, container.inventorySlots.subList(0, 1));
slotRefs.put(ContainerSection.CRAFTING_IN, container.inventorySlots.subList(1, 10));
return slotRefs;
}
public static Map<ContainerSection, List<Slot>> containerEnchantmentSlots(Container container) {
Map<ContainerSection, List<Slot>> slotRefs = new HashMap<>();
slotRefs.put(ContainerSection.ENCHANTMENT, container.inventorySlots.subList(0, 1));
return slotRefs;
}
public static Map<ContainerSection, List<Slot>> containerBrewingSlots(Container container) {
Map<ContainerSection, List<Slot>> slotRefs = new HashMap<>();
slotRefs.put(ContainerSection.BREWING_BOTTLES, container.inventorySlots.subList(0, 3));
slotRefs.put(ContainerSection.BREWING_INGREDIENT, container.inventorySlots.subList(3, 4));
return slotRefs;
}
public static Map<ContainerSection, List<Slot>> unknownContainerSlots(Container container) {
Map<ContainerSection, List<Slot>> slotRefs = new HashMap<>();
int size = container.inventorySlots.size();
if(size >= InvTweaksConst.INVENTORY_SIZE) {
// Assuming the container ends with the inventory, just like all vanilla containers.
slotRefs.put(ContainerSection.CHEST,
container.inventorySlots.subList(0, size - InvTweaksConst.INVENTORY_SIZE));
} else {
slotRefs.put(ContainerSection.CHEST, container.inventorySlots.subList(0, size));
}
return slotRefs;
}
}
|
package io.leangen.graphql.util;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ClassInfo;
import io.github.classgraph.ScanResult;
import io.leangen.geantyref.GenericTypeReflector;
import io.leangen.graphql.annotations.GraphQLIgnore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.AnnotatedType;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Enables discovery of classes that extend or implement a given class.
* Instances maintain a cache of search results and should be reused for better performance.
* The cache is thread-safe but allows for multiple search requests to go through if they arrive at exactly the same time.
* This class operates in best-effort manner and only logs (never rethrows) any exceptions that occur during the search or class loading.
*/
public class ClassFinder {
public final static Predicate<ClassInfo> CONCRETE = info -> !info.isAbstract() && !info.isInterface();
public final static Predicate<ClassInfo> NON_IGNORED = info ->
info.getAnnotations().directOnly().stream().noneMatch(ann -> ann.getName().equals(GraphQLIgnore.class.getName()));
public final static Predicate<ClassInfo> PUBLIC = ClassInfo::isPublic;
public final static Predicate<ClassInfo> ALL = info -> true;
public static final Logger log = LoggerFactory.getLogger(ClassFinder.class);
private final Map<String, ScanResult> cache = new ConcurrentHashMap<>();
/**
* Searches for the implementations/subtypes of the given {@link AnnotatedType}. Only the matching classes are loaded.
*
* @param superType The type the implementations/subtypes of which are to be searched for
* @param packages The packages to limit the search to
*
* @return A collection of {@link AnnotatedType}s discovered that implementation/extend {@code superType}
*/
public List<AnnotatedType> findImplementations(AnnotatedType superType, Predicate<ClassInfo> filter,
boolean allowMissingGenerics, String... packages) {
Class<?> rawType = ClassUtils.getRawType(superType.getType());
return findImplementations(rawType, filter, packages).stream()
.flatMap(raw -> ClassFinder.getExactSubType(superType, raw, allowMissingGenerics))
.collect(Collectors.toList());
}
/**
* Searches for the implementations/subtypes of the given class. Only the matching classes are loaded.
*
* @param superType The type the implementations/subtypes of which are to be searched for
* @param packages The packages to limit the search to
*
* @return A collection of classes discovered that implementation/extend {@code superType}
*/
public List<Class<?>> findImplementations(Class superType, Predicate<ClassInfo> filter, String... packages) {
String[] scanPackages = Utils.emptyIfNull(packages);
String cacheKey = Arrays.stream(scanPackages).sorted().collect(Collectors.joining());
ScanResult scanResults = cache.computeIfAbsent(cacheKey, k -> new ClassGraph()
.whitelistPackages(packages)
.enableAllInfo()
.initializeLoadedClasses()
.scan());
try {
return scanResults.getAllClasses().stream()
.filter(impl -> superType.isInterface() ? impl.implementsInterface(superType.getName()) : impl.extendsSuperclass(superType.getName()))
.filter(filter == null ? info -> true : filter)
.flatMap(info -> loadClass(info, superType))
.collect(Collectors.toList());
} catch (Exception e) {
log.error("Failed to auto discover the subtypes of " + superType.getName()
+ ". Error encountered while scanning the classpath/modulepath.", e);
return Collections.emptyList();
}
}
private static Stream<AnnotatedType> getExactSubType(AnnotatedType superType, Class<?> subClass, boolean allowMissingGenerics) {
AnnotatedType subType = GenericTypeReflector.getExactSubType(superType, subClass);
if (subType == null || (!allowMissingGenerics && ClassUtils.isMissingTypeParameters(subType.getType()))) {
log.warn("Auto discovered type " + subClass.getName() + " will be ignored " +
"because the exact matching sub type of " + ClassUtils.toString(superType) + " could not be determined");
return Stream.empty();
}
return Stream.of(subType);
}
private static Stream<Class<?>> loadClass(ClassInfo classInfo, Class superType) {
try {
return Stream.of(Class.forName(classInfo.getName(), true, superType.getClassLoader()));
} catch (ClassNotFoundException e) {
log.warn(String.format("Auto discovered class %s could not be loaded using the same loader that loaded %s." +
" Trying other loaders... For details see %s",
classInfo.getName(), superType.getName(), Urls.Errors.IMPLEMENTATION_CLASS_LOADING_FAILED));
}
try {
return Stream.of(classInfo.loadClass());
} catch (Exception e) {
log.error("Auto discovered type " + classInfo.getName() + " failed to load and will be ignored", e);
return Stream.empty();
}
}
public void close() {
try {
cache.values().forEach(ScanResult::close);
cache.clear();
} catch (Exception e) {
log.warn(ScanResult.class.getName() + " did not close cleanly", e);
}
}
}
|
package io.scalecube.gateway;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Meter;
import io.scalecube.services.metrics.Metrics;
public class GatewayMetrics {
public static final String METRIC_CONNECTIONS = "connections";
public static final String METRIC_REQUESTS = "requests";
public static final String METRIC_RESPONSES = "responses";
private final Counter connectionCounter;
private final Meter requestMeter;
private final Meter responseMeter;
/**
* Constructor for gatewat metrics.
*
* @param prefix prefix for gateway metrics instance
* @param metrics microservices metrics
*/
public GatewayMetrics(String prefix, Metrics metrics) {
connectionCounter = metrics != null ? metrics.getCounter(prefix, METRIC_CONNECTIONS) : null;
requestMeter = metrics != null ? metrics.getMeter(prefix, "", METRIC_REQUESTS) : null;
responseMeter = metrics != null ? metrics.getMeter(prefix, "", METRIC_RESPONSES) : null;
}
/** Increment connection counter. */
public void incrConnection() {
if (connectionCounter != null) {
connectionCounter.inc();
}
}
/** Decrement connection counter. */
public void decrConnection() {
if (connectionCounter != null) {
connectionCounter.dec();
}
}
/** Mark request for calls/sec measurement. */
public void markRequest() {
if (requestMeter != null) {
requestMeter.mark();
}
}
/** Mark response for calls/sec measurement. */
public void markResponse() {
if (responseMeter != null) {
responseMeter.mark();
}
}
}
|
package it.geosolutions.geonetwork;
import it.geosolutions.geonetwork.op.GNMetadataAdmin;
import it.geosolutions.geonetwork.op.GNLogin;
import it.geosolutions.geonetwork.op.GNMetadataInsert;
import it.geosolutions.geonetwork.exception.GNLibException;
import it.geosolutions.geonetwork.exception.GNServerException;
import it.geosolutions.geonetwork.op.GNMetadataDelete;
import it.geosolutions.geonetwork.op.GNMetadataGet;
import it.geosolutions.geonetwork.op.GNMetadataGetInfo;
import it.geosolutions.geonetwork.op.GNMetadataGetInfo.MetadataInfo;
import it.geosolutions.geonetwork.op.GNMetadataGetVersion;
import it.geosolutions.geonetwork.op.GNMetadataSearch;
import it.geosolutions.geonetwork.op.GNMetadataUpdate;
import it.geosolutions.geonetwork.util.GNInsertConfiguration;
import it.geosolutions.geonetwork.util.GNPrivConfiguration;
import it.geosolutions.geonetwork.util.GNSearchRequest;
import it.geosolutions.geonetwork.util.GNSearchResponse;
import it.geosolutions.geonetwork.util.HTTPUtils;
import java.io.File;
import org.apache.log4j.Logger;
import org.jdom.Element;
/**
* Facade for the various GN operations
*
* @author ETj (etj at geo-solutions.it)
*/
public class GNClient {
private final static Logger LOGGER = Logger.getLogger(GNClient.class);
// create stateful (we need the cookies) connection handler
private HTTPUtils connection = new HTTPUtils();
private final String gnServiceURL;
public GNClient(String serviceURL) {
this.gnServiceURL = serviceURL;
}
/**
* Facade for {@link GNLogin#login(it.geosolutions.geonetwork.util.HTTPUtils, java.lang.String, java.lang.String, java.lang.String) }
*/
public boolean login(String username, String password) {
return GNLogin.login(connection, gnServiceURL, username, password);
}
/**
* Facade for {@link GNMetadataInsert#insertMetadata(HTTPUtils, String, File, GNInsertConfiguration)}
*/
public long insertMetadata(GNInsertConfiguration cfg, File metadataFile) throws GNLibException, GNServerException {
return GNMetadataInsert.insertMetadata(connection, gnServiceURL, metadataFile, cfg);
}
/**
* Facade for {@link GNMetadataInsert#insertRequest((HTTPUtils connection, String gnServiceURL, File inputFile))}
*/
public long insertRequest(File requestFile) throws GNLibException, GNServerException {
return GNMetadataInsert.insertRequest(connection, gnServiceURL, requestFile);
}
/**
* Facade for {@link GNMetadataAdmin#setPriv(it.geosolutions.geonetwork.util.HTTPUtils, java.lang.String, long, it.geosolutions.geonetwork.util.GNPrivConfiguration) }
*/
public void setPrivileges(long metadataId, GNPrivConfiguration cfg) throws GNLibException, GNServerException {
GNMetadataAdmin.setPriv(connection, gnServiceURL, metadataId, cfg);
}
public GNSearchResponse search(GNSearchRequest searchRequest) throws GNLibException, GNServerException {
return GNMetadataSearch.search(connection, gnServiceURL, searchRequest);
}
public GNSearchResponse search(File fileRequest) throws GNLibException, GNServerException {
return GNMetadataSearch.search(connection, gnServiceURL, fileRequest);
}
public Element get(Long id) throws GNLibException, GNServerException {
return GNMetadataGet.get(connection, gnServiceURL, id);
}
public Element get(String uuid) throws GNLibException, GNServerException {
return GNMetadataGet.get(connection, gnServiceURL, uuid);
}
public void deleteMetadata(long id) throws GNLibException, GNServerException {
GNMetadataDelete.delete(connection, gnServiceURL, id);
}
public void updateMetadata(long id, File metadataFile) throws GNLibException, GNServerException {
String version = GNMetadataGetVersion.get(connection, gnServiceURL, id);
GNMetadataUpdate.update(connection, gnServiceURL, id, version, metadataFile);
}
public void updateMetadata(long id, int version, File metadataFile) throws GNLibException, GNServerException {
GNMetadataUpdate.update(connection, gnServiceURL, id, Integer.toString(version), metadataFile);
}
public MetadataInfo getInfo(Long id, boolean forUpdate) throws GNLibException, GNServerException {
return GNMetadataGetInfo.get(connection, gnServiceURL, id, forUpdate);
}
public MetadataInfo getInfo(String uuid, boolean forUpdate) throws GNLibException, GNServerException {
return GNMetadataGetInfo.get(connection, gnServiceURL, uuid, forUpdate);
}
protected HTTPUtils getConnection() {
return connection;
}
}
|
package land.face.strife.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import land.face.strife.StrifePlugin;
import land.face.strife.data.StrifeMob;
import land.face.strife.data.effects.AreaEffect;
import land.face.strife.data.effects.TargetingComparators.DistanceComparator;
import land.face.strife.data.effects.TargetingComparators.FlatHealthComparator;
import land.face.strife.data.effects.TargetingComparators.PercentHealthComparator;
import land.face.strife.util.DamageUtil.OriginLocation;
import org.bukkit.Bukkit;
import org.bukkit.FluidCollisionMode;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Mob;
import org.bukkit.entity.Player;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.util.RayTraceResult;
import org.bukkit.util.Vector;
public class TargetingUtil {
private static DistanceComparator DISTANCE_COMPARATOR = new DistanceComparator();
private static FlatHealthComparator HEALTH_COMPARATOR = new FlatHealthComparator();
private static PercentHealthComparator PERCENT_HEALTH_COMPARATOR = new PercentHealthComparator();
public static void filterFriendlyEntities(Set<LivingEntity> targets, StrifeMob caster,
boolean friendly) {
Set<LivingEntity> friendlyEntities = getFriendlyEntities(caster, targets);
if (friendly) {
targets.clear();
targets.addAll(friendlyEntities);
} else {
targets.removeAll(friendlyEntities);
}
}
public static void filterByTargetPriority(Set<LivingEntity> areaTargets, AreaEffect effect,
StrifeMob caster, int maxTargets) {
if (areaTargets.isEmpty()) {
return;
}
List<LivingEntity> targetList = new ArrayList<>(areaTargets);
switch (effect.getPriority()) {
case RANDOM:
Collections.shuffle(targetList);
areaTargets.retainAll(targetList.subList(0, maxTargets));
return;
case CLOSEST:
DISTANCE_COMPARATOR.setLoc(caster.getEntity().getLocation());
targetList.sort(DISTANCE_COMPARATOR);
areaTargets.retainAll(targetList.subList(0, maxTargets));
return;
case FARTHEST:
DISTANCE_COMPARATOR.setLoc(caster.getEntity().getLocation());
targetList.sort(DISTANCE_COMPARATOR);
areaTargets.retainAll(
targetList.subList(targetList.size() - maxTargets, targetList.size()));
return;
case LEAST_HEALTH:
targetList.sort(HEALTH_COMPARATOR);
areaTargets.retainAll(targetList.subList(0, maxTargets));
return;
case MOST_HEALTH:
targetList.sort(HEALTH_COMPARATOR);
areaTargets.retainAll(
targetList.subList(targetList.size() - maxTargets, targetList.size()));
return;
case LEAST_PERCENT_HEALTH:
targetList.sort(PERCENT_HEALTH_COMPARATOR);
areaTargets.retainAll(targetList.subList(0, maxTargets));
return;
case MOST_PERCENT_HEALTH:
targetList.sort(PERCENT_HEALTH_COMPARATOR);
areaTargets.retainAll(
targetList.subList(targetList.size() - maxTargets, targetList.size()));
}
}
public static Set<LivingEntity> getFriendlyEntities(StrifeMob caster, Set<LivingEntity> targets) {
return targets.stream().filter(target -> isFriendly(caster, target))
.collect(Collectors.toSet());
}
public static boolean isFriendly(StrifeMob mob, LivingEntity target) {
return isFriendly(mob, StrifePlugin.getInstance().getStrifeMobManager().getStatMob(target));
}
public static boolean isFriendly(StrifeMob caster, StrifeMob target) {
if (caster.getEntity() == target.getEntity()) {
return true;
}
for (String casterFaction : caster.getFactions()) {
for (String targetFaction: target.getFactions()) {
if (casterFaction.equalsIgnoreCase(targetFaction)) {
return true;
}
}
}
if (caster.getEntity() instanceof Player && target.getEntity() instanceof Player) {
return !DamageUtil.canAttack((Player) caster.getEntity(), (Player) target.getEntity());
}
for (StrifeMob mob : caster.getMinions()) {
if (target.getEntity() == mob.getEntity()) {
return true;
}
}
// for (StrifeMob mob : getPartyMembers {
return false;
}
public static Set<LivingEntity> getEntitiesInArea(LivingEntity caster, double radius) {
Collection<Entity> targetList = Objects.requireNonNull(caster.getLocation().getWorld())
.getNearbyEntities(caster.getEyeLocation(), radius, radius, radius);
Set<LivingEntity> validTargets = new HashSet<>();
for (Entity entity : targetList) {
if (!isInvalidTarget(entity)) {
validTargets.add((LivingEntity) entity);
}
}
validTargets.removeIf(e -> !caster.hasLineOfSight(e));
return validTargets;
}
public static Set<LivingEntity> getEntitiesInCone(LivingEntity originEntity, Location origin,
Vector direction, float length, float maxConeRadius) {
Collection<Entity> targetList = Objects.requireNonNull(origin.getWorld())
.getNearbyEntities(origin, length, length, length);
targetList.removeIf(TargetingUtil::isInvalidTarget);
Set<LivingEntity> validTargets = new HashSet<>();
for (float incRange = 0; incRange <= length + 0.01; incRange += 0.8) {
Location loc = origin.clone().add(direction.clone().multiply(incRange));
for (Entity entity : targetList) {
if (entityWithinRadius(entity, loc, maxConeRadius * (incRange / length))) {
validTargets.add((LivingEntity) entity);
}
}
targetList.removeAll(validTargets);
}
validTargets.removeIf(e -> !originEntity.hasLineOfSight(e));
return validTargets;
}
public static Set<LivingEntity> getEntitiesInLine(LivingEntity caster, double range) {
Collection<Entity> targetList = Objects.requireNonNull(caster.getLocation().getWorld())
.getNearbyEntities(caster.getEyeLocation(), range, range, range);
targetList.removeIf(TargetingUtil::isInvalidTarget);
Set<LivingEntity> validTargets = new HashSet<>();
for (float incRange = 0; incRange <= range + 0.01; incRange += 0.8) {
Location loc = caster.getEyeLocation().clone()
.add(caster.getEyeLocation().getDirection().clone().multiply(incRange));
for (Entity entity : targetList) {
if (entityWithinRadius(entity, loc, 0)) {
validTargets.add((LivingEntity) entity);
}
if (loc.getBlock().getType().isSolid()) {
break;
}
}
targetList.removeAll(validTargets);
}
validTargets.removeIf(e -> !caster.hasLineOfSight(e));
return validTargets;
}
public static LivingEntity getFirstEntityInLine(LivingEntity caster, double range) {
RayTraceResult result = caster.getWorld()
.rayTraceEntities(caster.getEyeLocation(), caster.getEyeLocation().getDirection(), range,
entity -> isValidRaycastTarget(caster, entity));
if (result == null || result.getHitEntity() == null) {
return null;
}
return (LivingEntity) result.getHitEntity();
}
public static boolean isInvalidTarget(Entity e) {
if (!e.isValid() || !(e instanceof LivingEntity) || e instanceof ArmorStand) {
return true;
}
if (e.hasMetadata("NPC")) {
return true;
}
if (e instanceof Player) {
return ((Player) e).getGameMode() == GameMode.CREATIVE || ((Player) e).getGameMode() == GameMode.SPECTATOR;
}
return false;
}
public static boolean isDetectionStand(LivingEntity le) {
return le instanceof ArmorStand && le.hasMetadata("STANDO");
}
public static ArmorStand buildAndRemoveDetectionStand(Location location) {
ArmorStand stando = location.getWorld().spawn(location, ArmorStand.class,
TargetingUtil::applyDetectionStandChanges);
Bukkit.getScheduler().runTaskLater(StrifePlugin.getInstance(), stando::remove, 1L);
return stando;
}
private static void applyDetectionStandChanges(ArmorStand stando) {
stando.setVisible(false);
stando.setSmall(true);
stando.setMarker(true);
stando.setGravity(false);
stando.setCollidable(false);
stando.setMetadata("STANDO", new FixedMetadataValue(StrifePlugin.getInstance(), ""));
}
public static Set<LivingEntity> getTempStandTargetList(Location loc, float groundCheckRange) {
Set<LivingEntity> targets = new HashSet<>();
if (groundCheckRange < 1) {
targets.add(TargetingUtil.buildAndRemoveDetectionStand(loc));
return targets;
} else {
for (int i = 0; i < groundCheckRange; i++) {
if (loc.getBlock().getType().isSolid()) {
loc.setY(loc.getBlockY() + 1.3);
targets.add(TargetingUtil.buildAndRemoveDetectionStand(loc));
return targets;
}
loc.add(0, -1, 0);
}
return targets;
}
}
private static boolean isValidRaycastTarget(LivingEntity caster, Entity entity) {
return entity instanceof LivingEntity && entity != caster && entity.isValid() && !entity
.hasMetadata("NPC");
}
private static boolean entityWithinRadius(Entity e, Location loc, float radius) {
double ex = e.getLocation().getX();
double ey = e.getLocation().getY();
double ez = e.getLocation().getZ();
double width = Math.max(e.getWidth(), 0.6);
return Math.abs(loc.getX() - ex) < width + radius
&& Math.abs(loc.getZ() - ez) < width + radius
&& Math.abs(loc.getY() - ey) < Math.max(e.getHeight(), 1.2) + radius;
}
public static LivingEntity selectFirstEntityInSight(LivingEntity caster, double range) {
LivingEntity mobTarget = TargetingUtil.getMobTarget(caster);
return mobTarget != null ? mobTarget : getFirstEntityInLine(caster, range);
}
public static Location getTargetLocation(LivingEntity caster, LivingEntity target, double range,
boolean targetEntities) {
return getTargetLocation(caster, target, range, OriginLocation.CENTER, targetEntities);
}
public static Location getTargetLocation(LivingEntity caster, LivingEntity target, double range,
OriginLocation originLocation, boolean targetEntities) {
if (target != null && caster.getLocation().distance(target.getLocation()) < range && caster
.hasLineOfSight(target)) {
return getOriginLocation(target, originLocation);
}
RayTraceResult result;
if (targetEntities) {
result = caster.getWorld().rayTrace(caster.getEyeLocation(),
caster.getEyeLocation().getDirection(), range,
FluidCollisionMode.NEVER, true, 0.2,
entity -> isValidRaycastTarget(caster, entity));
} else {
result = caster.getWorld()
.rayTraceBlocks(caster.getEyeLocation(), caster.getEyeLocation().getDirection(), range,
FluidCollisionMode.NEVER, true);
}
if (result == null) {
LogUtil.printDebug(" - Using MAX RANGE location calculation");
return caster.getEyeLocation().add(
caster.getEyeLocation().getDirection().multiply(Math.max(0, range - 1)));
}
if (result.getHitEntity() != null) {
LogUtil.printDebug(" - Using ENTITY location calculation");
return getOriginLocation((LivingEntity) result.getHitEntity(), originLocation);
}
if (result.getHitBlock() != null) {
LogUtil.printDebug(" - Using BLOCK location calculation");
return result.getHitBlock().getLocation().add(0.5, 0.8, 0.5)
.add(result.getHitBlockFace().getDirection());
}
LogUtil.printDebug(" - Using HIT RANGE location calculation");
return new Location(caster.getWorld(), result.getHitPosition().getX(),
result.getHitPosition().getBlockY(), result.getHitPosition().getZ());
}
public static LivingEntity getMobTarget(StrifeMob strifeMob) {
return getMobTarget(strifeMob.getEntity());
}
public static LivingEntity getMobTarget(LivingEntity targeter) {
if (!(targeter instanceof Mob)) {
return null;
}
LivingEntity target = ((Mob) targeter).getTarget();
if (target == null || !target.isValid()) {
return null;
}
return target;
}
public static Location getOriginLocation(LivingEntity le, OriginLocation origin) {
switch (origin) {
case HEAD:
return le.getEyeLocation();
case BELOW_HEAD:
return le.getEyeLocation().clone().add(0, -0.4, 0);
case ABOVE_HEAD:
return le.getEyeLocation().clone().add(0, 0.4, 0);
case CENTER:
Vector vec = le.getEyeLocation().toVector().subtract(le.getLocation().toVector())
.multiply(0.5);
return le.getLocation().clone().add(vec);
case GROUND:
default:
return le.getLocation();
}
}
}
|
package main.java.com.bag.client;
import bftsmart.communication.client.ReplyReceiver;
import bftsmart.reconfiguration.util.RSAKeyLoader;
import bftsmart.tom.ServiceProxy;
import bftsmart.tom.core.messages.TOMMessage;
import bftsmart.tom.core.messages.TOMMessageType;
import bftsmart.tom.util.TOMUtil;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.pool.KryoFactory;
import com.esotericsoftware.kryo.pool.KryoPool;
import main.java.com.bag.operations.CreateOperation;
import main.java.com.bag.operations.DeleteOperation;
import main.java.com.bag.operations.IOperation;
import main.java.com.bag.operations.UpdateOperation;
import main.java.com.bag.util.*;
import main.java.com.bag.util.storage.NodeStorage;
import main.java.com.bag.util.storage.RelationshipStorage;
import org.jetbrains.annotations.NotNull;
import java.io.Closeable;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Class handling the client.
*/
public class TestClient extends ServiceProxy implements BAGClient, ReplyReceiver, Closeable, AutoCloseable
{
/**
* Should the transaction runNetty in secure mode?
*/
private boolean secureMode = true;
/**
* The place the local config file is. This + the cluster id will contain the concrete cluster config location.
*/
private static final String LOCAL_CONFIG_LOCATION = "local%d/config";
/**
* The place the global config files is.
*/
private static final String GLOBAL_CONFIG_LOCATION = "global/config";
/**
* Sets to log reads, updates, deletes and node creations.
*/
private ArrayList<NodeStorage> readsSetNode;
private ArrayList<RelationshipStorage> readsSetRelationship;
private ArrayList<IOperation> writeSet;
/**
* Amount of responses.
*/
private int responses = 0;
/**
* Defines if the client is currently committing.
*/
private boolean isCommitting = false;
/**
* Local timestamp of the current transaction.
*/
private long localTimestamp = -1;
/**
* Random var, instantiated only once!
*/
final Random random = new Random();
/**
* The id of the local server process the client is communicating with.
*/
private int serverProcess;
/**
* Lock object to let the thread wait for a read return.
*/
private BlockingQueue<Object> readQueue = new LinkedBlockingQueue<>();
/**
* The last object in read queue.
*/
public static final Object FINISHED_READING = new Object();
/**
* Id of the local cluster.
*/
private final int localClusterId;
/**
* Checks if its the first read of the client.
*/
private boolean firstRead = true;
/**
* The proxy to use during communication with the globalCluster.
*/
private ServiceProxy globalProxy;
/**
* Create a threadsafe version of kryo.
*/
private KryoFactory factory = () ->
{
Kryo kryo = new Kryo();
kryo.register(NodeStorage.class, 100);
kryo.register(RelationshipStorage.class, 200);
kryo.register(CreateOperation.class, 250);
kryo.register(DeleteOperation.class, 300);
kryo.register(UpdateOperation.class, 350);
return kryo;
};
public TestClient(final int processId, final int serverId, final int localClusterId)
{
super(processId, localClusterId == -1 ? GLOBAL_CONFIG_LOCATION : String.format(LOCAL_CONFIG_LOCATION, localClusterId));
if(localClusterId != -1)
{
globalProxy = new ServiceProxy(100 + getProcessId(), "global/config");
}
secureMode = true;
this.serverProcess = serverId;
this.localClusterId = localClusterId;
initClient();
Log.getLogger().warn("Starting client " + processId);
}
/**
* Initiates the client maps and registers necessary operations.
*/
private void initClient()
{
readsSetNode = new ArrayList<>();
readsSetRelationship = new ArrayList<>();
writeSet = new ArrayList<>();
}
/**
* Get the blocking queue.
* @return the queue.
*/
@Override
public BlockingQueue<Object> getReadQueue()
{
return readQueue;
}
/**
* write requests. (Only reach database on commit)
*/
@Override
public void write(final Object identifier, final Object value)
{
if(identifier == null && value == null)
{
Log.getLogger().warn("Unsupported write operation");
return;
}
//Must be a create request.
if(identifier == null)
{
handleCreateRequest(value);
return;
}
//Must be a delete request.
if(value == null)
{
handleDeleteRequest(identifier);
return;
}
handleUpdateRequest(identifier, value);
}
/**
* Fills the updateSet in the case of an update request.
* @param identifier the value to write to.
* @param value what should be written.
*/
private void handleUpdateRequest(Object identifier, Object value)
{
//todo edit create request if equal.
if(identifier instanceof NodeStorage && value instanceof NodeStorage)
{
writeSet.add(new UpdateOperation<>((NodeStorage) identifier,(NodeStorage) value));
}
else if(identifier instanceof RelationshipStorage && value instanceof RelationshipStorage)
{
writeSet.add(new UpdateOperation<>((RelationshipStorage) identifier,(RelationshipStorage) value));
}
else
{
Log.getLogger().warn("Unsupported update operation can't update a node with a relationship or vice versa");
}
}
/**
* Fills the createSet in the case of a create request.
* @param value object to fill in the createSet.
*/
private void handleCreateRequest(Object value)
{
if(value instanceof NodeStorage)
{
writeSet.add(new CreateOperation<>((NodeStorage) value));
}
else if(value instanceof RelationshipStorage)
{
readsSetNode.add(((RelationshipStorage) value).getStartNode());
readsSetNode.add(((RelationshipStorage) value).getEndNode());
writeSet.add(new CreateOperation<>((RelationshipStorage) value));
}
}
/**
* Fills the deleteSet in the case of a delete requests and deletes the node also from the create set and updateSet.
* @param identifier the object to delete.
*/
private void handleDeleteRequest(Object identifier)
{
if(identifier instanceof NodeStorage)
{
writeSet.add(new DeleteOperation<>((NodeStorage) identifier));
}
else if(identifier instanceof RelationshipStorage)
{
writeSet.add(new DeleteOperation<>((RelationshipStorage) identifier));
}
}
/**
* ReadRequests.(Directly read database) send the request to the db.
* @param identifiers list of objects which should be read, may be NodeStorage or RelationshipStorage
*/
@Override
public void read(final Object...identifiers)
{
long timeStampToSend = firstRead ? -1 : localTimestamp;
for(final Object identifier: identifiers)
{
if (identifier instanceof NodeStorage)
{
//this sends the message straight to server 0 not to the others.
sendMessageToTargets(this.serialize(Constants.READ_MESSAGE, timeStampToSend, identifier), 0, new int[] {serverProcess}, TOMMessageType.UNORDERED_REQUEST);
}
else if (identifier instanceof RelationshipStorage)
{
sendMessageToTargets(this.serialize(Constants.RELATIONSHIP_READ_MESSAGE, timeStampToSend, identifier), 0, new int[] {serverProcess}, TOMMessageType.UNORDERED_REQUEST);
}
else
{
Log.getLogger().warn("Unsupported identifier: " + identifier.toString());
}
}
firstRead = false;
}
/**
* Receiving read requests replies here
* @param reply the received message.
*/
@Override
public void replyReceived(final TOMMessage reply)
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
Log.getLogger().info("reply");
if(reply.getReqType() == TOMMessageType.UNORDERED_REQUEST)
{
final Input input = new Input(reply.getContent());
switch(kryo.readObject(input, String.class))
{
case Constants.READ_MESSAGE:
processReadReturn(input);
break;
case Constants.GET_PRIMARY:
case Constants.COMMIT_RESPONSE:
processCommitReturn(reply.getContent());
break;
default:
Log.getLogger().info("Unexpected message type!");
break;
}
input.close();
}
else if(reply.getReqType() == TOMMessageType.REPLY || reply.getReqType() == TOMMessageType.ORDERED_REQUEST)
{
Log.getLogger().info("Commit return" + reply.getReqType().name());
processCommitReturn(reply.getContent());
}
else
{
Log.getLogger().info("Receiving other type of request." + reply.getReqType().name());
}
pool.release(kryo);
super.replyReceived(reply);
}
/**
* Processes the return of a read request. Filling the readsets.
* @param input the received bytes in an input..
*/
private void processReadReturn(final Input input)
{
if(input == null)
{
Log.getLogger().warn("TimeOut, Didn't receive an answer from the server!");
return;
}
Log.getLogger().info("Process read return!");
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
final String result = kryo.readObject(input, String.class);
this.localTimestamp = kryo.readObject(input, Long.class);
if(Constants.ABORT.equals(result))
{
input.close();
pool.release(kryo);
resetSets();
readQueue.add(FINISHED_READING);
return;
}
final List nodes = kryo.readObject(input, ArrayList.class);
final List relationships = kryo.readObject(input, ArrayList.class);
if(nodes != null && !nodes.isEmpty() && nodes.get(0) instanceof NodeStorage)
{
for (final NodeStorage storage : (ArrayList<NodeStorage>) nodes)
{
final NodeStorage tempStorage = new NodeStorage(storage.getId(), storage.getProperties());
try
{
tempStorage.addProperty("hash", HashCreator.sha1FromNode(storage));
}
catch (NoSuchAlgorithmException e)
{
Log.getLogger().warn("Couldn't add hash for node", e);
}
readsSetNode.add(tempStorage);
}
}
if(relationships != null && !relationships.isEmpty() && relationships.get(0) instanceof RelationshipStorage)
{
for (final RelationshipStorage storage : (ArrayList<RelationshipStorage>)relationships)
{
final RelationshipStorage tempStorage = new RelationshipStorage(storage.getId(), storage.getProperties(), storage.getStartNode(), storage.getEndNode());
try
{
tempStorage.addProperty("hash", HashCreator.sha1FromRelationship(storage));
}
catch (NoSuchAlgorithmException e)
{
Log.getLogger().warn("Couldn't add hash for relationship", e);
}
readsSetRelationship.add(tempStorage);
}
}
readQueue.add(FINISHED_READING);
input.close();
pool.release(kryo);
}
private void processCommitReturn(final byte[] result)
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
if(result == null)
{
Log.getLogger().warn("Server returned null, something went incredibly wrong there");
return;
}
final Input input = new Input(result);
final String type = kryo.readObject(input, String.class);
if(!Constants.COMMIT_RESPONSE.equals(type))
{
Log.getLogger().warn("Incorrect response to commit message");
input.close();
return;
}
final String decision = kryo.readObject(input, String.class);
localTimestamp = kryo.readObject(input, Long.class);
Log.getLogger().info("Processing commit return: " + localTimestamp);
if(Constants.COMMIT.equals(decision))
{
Log.getLogger().info("Transaction succesfully committed");
}
else
{
Log.getLogger().info("Transaction commit denied - transaction being aborted");
}
Log.getLogger().info("Reset after commit");
resetSets();
input.close();
pool.release(kryo);
}
/**
* Commit reaches the server, if secure commit send to all, else only send to one
*/
@Override
public void commit()
{
firstRead = true;
final boolean readOnly = isReadOnly();
Log.getLogger().info("Starting commit");
if (readOnly && !secureMode)
{
//verifyReadSet();
Log.getLogger().warn(String.format("Read only unsecure Transaction with local transaction id: %d successfully committed", localTimestamp));
firstRead = true;
resetSets();
return;
}
Log.getLogger().info("Starting commit process for: " + this.localTimestamp);
final byte[] bytes = serializeAll();
if (readOnly)
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
Log.getLogger().warn(getProcessId() + " Commit with snapshotId: " + this.localTimestamp);
final byte[] answer;
if(localClusterId == -1)
{
//List of all view processes
/*final int[] currentViewProcesses = this.getViewManager().getCurrentViewProcesses();
//The servers we will actually contact
final int[] servers = new int[3];
//final int spare = servers[new Random().nextInt(currentViewProcesses.length)];
int i = 0;
for(final int processI : currentViewProcesses)
{
if(i < servers.length)
{
servers[i] = processI;
i++;
}
}
isCommitting = true;
Log.getLogger().info("Sending to: " + Arrays.toString(servers));
//sendMessageToTargets(bytes, 0, servers, TOMMessageType.UNORDERED_REQUEST);*/
answer = invokeUnordered(bytes);
}
else
{
answer = globalProxy.invokeUnordered(bytes);
}
Log.getLogger().info(getProcessId() + "Committed with snapshotId " + this.localTimestamp);
final Input input = new Input(answer);
final String messageType = kryo.readObject(input, String.class);
if (!Constants.COMMIT_RESPONSE.equals(messageType))
{
Log.getLogger().warn("Incorrect response type to client from server!" + getProcessId());
resetSets();
firstRead = true;
return;
}
final boolean commit = Constants.COMMIT.equals(kryo.readObject(input, String.class));
if (commit)
{
localTimestamp = kryo.readObject(input, Long.class);
resetSets();
firstRead = true;
Log.getLogger().info(String.format("Transaction with local transaction id: %d successfully committed", localTimestamp));
return;
}
return;
}
if (localClusterId == -1)
{
Log.getLogger().info("Distribute commit with snapshotId: " + this.localTimestamp);
this.invokeOrdered(bytes);
}
else
{
Log.getLogger().info("Commit with snapshotId directly to global cluster. TimestampId: " + this.localTimestamp);
Log.getLogger().info("WriteSet: " + writeSet.size() + " readSetNode: " + readsSetNode.size() + " readSetRs: " + readsSetRelationship.size());
processCommitReturn(globalProxy.invokeOrdered(bytes));
}
}
/**
* Method verifies readSet signatures.
*/
private void verifyReadSet()
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
for(final NodeStorage storage: readsSetNode)
{
for(final Map.Entry<String, Object> entry: storage.getProperties().entrySet())
{
if(!entry.getKey().contains("signature"))
{
continue;
}
final int key = Integer.parseInt(entry.getKey().replace("signature",""));
Log.getLogger().warn("Verifying the keys of the nodes");
final RSAKeyLoader rsaLoader = new RSAKeyLoader(key, GLOBAL_CONFIG_LOCATION, false);
try
{
if (!TOMUtil.verifySignature(rsaLoader.loadPublicKey(), storage.getBytes(), ((String) entry.getValue()).getBytes("UTF-8")))
{
Log.getLogger().warn("Signature of server: " + key + " doesn't match");
}
else
{
Log.getLogger().info("Signature matches of server: " + entry.getKey());
}
}
catch (final Exception e)
{
Log.getLogger().error("Unable to load public key on client", e);
}
}
}
Log.getLogger().warn("Verifying the keys of the relationships");
for(final RelationshipStorage storage: readsSetRelationship)
{
for(final Map.Entry<String, Object> entry: storage.getProperties().entrySet())
{
if(!entry.getKey().contains("signature"))
{
continue;
}
final int key = Integer.parseInt(entry.getKey().replace("signature",""));
Log.getLogger().warn("Verifying the keys of the nodes");
final RSAKeyLoader rsaLoader = new RSAKeyLoader(key, GLOBAL_CONFIG_LOCATION, false);
try
{
if (!TOMUtil.verifySignature(rsaLoader.loadPublicKey(), storage.getBytes(), ((String) entry.getValue()).getBytes("UTF-8")))
{
Log.getLogger().warn("Signature of server: " + key + " doesn't match");
}
else
{
Log.getLogger().info("Signature matches of server: " + entry.getKey());
}
}
catch (final Exception e)
{
Log.getLogger().error("Unable to load public key on client", e);
}
}
}
pool.release(kryo);
}
/**
* Serializes the data and returns it in byte format.
* @return the data in byte format.
*/
private byte[] serialize(@NotNull String request)
{
KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
Kryo kryo = pool.borrow();
Output output = new Output(0, 256);
kryo.writeObject(output, request);
byte[] bytes = output.getBuffer();
output.close();
pool.release(kryo);
return bytes;
}
/**
* Serializes the data and returns it in byte format.
* @return the data in byte format.
*/
private byte[] serialize(@NotNull String reason, long localTimestamp, final Object...args)
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
final Output output = new Output(0, 100024);
kryo.writeObject(output, reason);
kryo.writeObject(output, localTimestamp);
for(final Object identifier: args)
{
if(identifier instanceof NodeStorage || identifier instanceof RelationshipStorage)
{
kryo.writeObject(output, identifier);
}
}
byte[] bytes = output.getBuffer();
output.close();
pool.release(kryo);
return bytes;
}
/**
* Serializes all sets and returns it in byte format.
* @return the data in byte format.
*/
private byte[] serializeAll()
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
final Output output = new Output(0, 400024);
kryo.writeObject(output, Constants.COMMIT_MESSAGE);
//Write the timeStamp to the server
kryo.writeObject(output, localTimestamp);
//Write the readSet.
kryo.writeObject(output, readsSetNode);
kryo.writeObject(output, readsSetRelationship);
//Write the writeSet.
kryo.writeObject(output, writeSet);
byte[] bytes = output.getBuffer();
output.close();
pool.release(kryo);
return bytes;
}
/**
* Resets all the read and write sets.
*/
private void resetSets()
{
readsSetNode = new ArrayList<>();
readsSetRelationship = new ArrayList<>();
writeSet = new ArrayList<>();
isCommitting = false;
responses = 0;
int randomNumber = random.nextInt(100000);
if(randomNumber <= 65000)
{
serverProcess = 0;
return;
}
serverProcess = 1;
}
/**
* Checks if the transaction has made any changes to the update sets.
* @return true if not.
*/
private boolean isReadOnly()
{
return writeSet.isEmpty();
}
@Override
public boolean isCommitting()
{
return isCommitting;
}
/**
* Get the primary of the cluster.
* @param kryo the kryo instance.
* @return the primary id.
*/
private int getPrimary(final Kryo kryo)
{
byte[] response = invoke(serialize(Constants.GET_PRIMARY), TOMMessageType.UNORDERED_REQUEST);
if(response == null)
{
Log.getLogger().warn("Server returned null, something went incredibly wrong there");
return -1;
}
final Input input = new Input(response);
kryo.readObject(input, String.class);
final int primaryId = kryo.readObject(input, Integer.class);
Log.getLogger().info("Received id: " + primaryId);
input.close();
return primaryId;
}
}
|
package main.java.com.bag.client;
import bftsmart.communication.client.ReplyReceiver;
import bftsmart.reconfiguration.util.RSAKeyLoader;
import bftsmart.tom.ServiceProxy;
import bftsmart.tom.core.messages.TOMMessage;
import bftsmart.tom.core.messages.TOMMessageType;
import bftsmart.tom.util.TOMUtil;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.pool.KryoFactory;
import com.esotericsoftware.kryo.pool.KryoPool;
import main.java.com.bag.operations.CreateOperation;
import main.java.com.bag.operations.DeleteOperation;
import main.java.com.bag.operations.IOperation;
import main.java.com.bag.operations.UpdateOperation;
import main.java.com.bag.util.*;
import main.java.com.bag.util.storage.NodeStorage;
import main.java.com.bag.util.storage.RelationshipStorage;
import org.jetbrains.annotations.NotNull;
import java.io.Closeable;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Class handling the client.
*/
public class TestClient extends ServiceProxy implements BAGClient, ReplyReceiver, Closeable, AutoCloseable
{
/**
* Should the transaction runNetty in secure mode?
*/
private boolean secureMode = true;
/**
* The place the local config file is. This + the cluster id will contain the concrete cluster config location.
*/
private static final String LOCAL_CONFIG_LOCATION = "local%d/config";
/**
* The place the global config files is.
*/
private static final String GLOBAL_CONFIG_LOCATION = "global/config";
/**
* Sets to log reads, updates, deletes and node creations.
*/
private ArrayList<NodeStorage> readsSetNode;
private ArrayList<RelationshipStorage> readsSetRelationship;
private ArrayList<IOperation> writeSet;
/**
* Amount of responses.
*/
private int responses = 0;
/**
* Defines if the client is currently committing.
*/
private boolean isCommitting = false;
/**
* Local timestamp of the current transaction.
*/
private long localTimestamp = -1;
/**
* Random var, instantiated only once!
*/
final Random random = new Random();
/**
* The id of the local server process the client is communicating with.
*/
private int serverProcess;
/**
* Lock object to let the thread wait for a read return.
*/
private BlockingQueue<Object> readQueue = new LinkedBlockingQueue<>();
/**
* The last object in read queue.
*/
public static final Object FINISHED_READING = new Object();
/**
* Id of the local cluster.
*/
private final int localClusterId;
/**
* Checks if its the first read of the client.
*/
private boolean firstRead = true;
/**
* The proxy to use during communication with the globalCluster.
*/
private ServiceProxy globalProxy;
/**
* Create a threadsafe version of kryo.
*/
private KryoFactory factory = () ->
{
Kryo kryo = new Kryo();
kryo.register(NodeStorage.class, 100);
kryo.register(RelationshipStorage.class, 200);
kryo.register(CreateOperation.class, 250);
kryo.register(DeleteOperation.class, 300);
kryo.register(UpdateOperation.class, 350);
return kryo;
};
public TestClient(final int processId, final int serverId, final int localClusterId)
{
super(processId, localClusterId == -1 ? GLOBAL_CONFIG_LOCATION : String.format(LOCAL_CONFIG_LOCATION, localClusterId));
if(localClusterId != -1)
{
globalProxy = new ServiceProxy(100 + getProcessId(), "global/config");
}
secureMode = true;
this.serverProcess = serverId;
this.localClusterId = localClusterId;
initClient();
Log.getLogger().warn("Starting client " + processId);
}
/**
* Initiates the client maps and registers necessary operations.
*/
private void initClient()
{
readsSetNode = new ArrayList<>();
readsSetRelationship = new ArrayList<>();
writeSet = new ArrayList<>();
}
/**
* Get the blocking queue.
* @return the queue.
*/
@Override
public BlockingQueue<Object> getReadQueue()
{
return readQueue;
}
/**
* write requests. (Only reach database on commit)
*/
@Override
public void write(final Object identifier, final Object value)
{
if(identifier == null && value == null)
{
Log.getLogger().warn("Unsupported write operation");
return;
}
//Must be a create request.
if(identifier == null)
{
handleCreateRequest(value);
return;
}
//Must be a delete request.
if(value == null)
{
handleDeleteRequest(identifier);
return;
}
handleUpdateRequest(identifier, value);
}
/**
* Fills the updateSet in the case of an update request.
* @param identifier the value to write to.
* @param value what should be written.
*/
private void handleUpdateRequest(Object identifier, Object value)
{
//todo edit create request if equal.
if(identifier instanceof NodeStorage && value instanceof NodeStorage)
{
writeSet.add(new UpdateOperation<>((NodeStorage) identifier,(NodeStorage) value));
}
else if(identifier instanceof RelationshipStorage && value instanceof RelationshipStorage)
{
writeSet.add(new UpdateOperation<>((RelationshipStorage) identifier,(RelationshipStorage) value));
}
else
{
Log.getLogger().warn("Unsupported update operation can't update a node with a relationship or vice versa");
}
}
/**
* Fills the createSet in the case of a create request.
* @param value object to fill in the createSet.
*/
private void handleCreateRequest(Object value)
{
if(value instanceof NodeStorage)
{
writeSet.add(new CreateOperation<>((NodeStorage) value));
}
else if(value instanceof RelationshipStorage)
{
readsSetNode.add(((RelationshipStorage) value).getStartNode());
readsSetNode.add(((RelationshipStorage) value).getEndNode());
writeSet.add(new CreateOperation<>((RelationshipStorage) value));
}
}
/**
* Fills the deleteSet in the case of a delete requests and deletes the node also from the create set and updateSet.
* @param identifier the object to delete.
*/
private void handleDeleteRequest(Object identifier)
{
if(identifier instanceof NodeStorage)
{
writeSet.add(new DeleteOperation<>((NodeStorage) identifier));
}
else if(identifier instanceof RelationshipStorage)
{
writeSet.add(new DeleteOperation<>((RelationshipStorage) identifier));
}
}
/**
* ReadRequests.(Directly read database) send the request to the db.
* @param identifiers list of objects which should be read, may be NodeStorage or RelationshipStorage
*/
@Override
public void read(final Object...identifiers)
{
long timeStampToSend = firstRead ? -1 : localTimestamp;
for(final Object identifier: identifiers)
{
if (identifier instanceof NodeStorage)
{
//this sends the message straight to server 0 not to the others.
sendMessageToTargets(this.serialize(Constants.READ_MESSAGE, timeStampToSend, identifier), 0, new int[] {serverProcess}, TOMMessageType.UNORDERED_REQUEST);
}
else if (identifier instanceof RelationshipStorage)
{
sendMessageToTargets(this.serialize(Constants.RELATIONSHIP_READ_MESSAGE, timeStampToSend, identifier), 0, new int[] {serverProcess}, TOMMessageType.UNORDERED_REQUEST);
}
else
{
Log.getLogger().warn("Unsupported identifier: " + identifier.toString());
}
}
firstRead = false;
}
/**
* Receiving read requests replies here
* @param reply the received message.
*/
@Override
public void replyReceived(final TOMMessage reply)
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
Log.getLogger().info("reply");
if(reply.getReqType() == TOMMessageType.UNORDERED_REQUEST)
{
final Input input = new Input(reply.getContent());
switch(kryo.readObject(input, String.class))
{
case Constants.READ_MESSAGE:
processReadReturn(input);
break;
case Constants.GET_PRIMARY:
case Constants.COMMIT_RESPONSE:
processCommitReturn(reply.getContent());
break;
default:
Log.getLogger().info("Unexpected message type!");
break;
}
input.close();
}
else if(reply.getReqType() == TOMMessageType.REPLY || reply.getReqType() == TOMMessageType.ORDERED_REQUEST)
{
Log.getLogger().info("Commit return" + reply.getReqType().name());
processCommitReturn(reply.getContent());
}
else
{
Log.getLogger().info("Receiving other type of request." + reply.getReqType().name());
}
pool.release(kryo);
super.replyReceived(reply);
}
/**
* Processes the return of a read request. Filling the readsets.
* @param input the received bytes in an input..
*/
private void processReadReturn(final Input input)
{
if(input == null)
{
Log.getLogger().warn("TimeOut, Didn't receive an answer from the server!");
return;
}
Log.getLogger().info("Process read return!");
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
final String result = kryo.readObject(input, String.class);
this.localTimestamp = kryo.readObject(input, Long.class);
if(Constants.ABORT.equals(result))
{
input.close();
pool.release(kryo);
resetSets();
readQueue.add(FINISHED_READING);
return;
}
final List nodes = kryo.readObject(input, ArrayList.class);
final List relationships = kryo.readObject(input, ArrayList.class);
if(nodes != null && !nodes.isEmpty() && nodes.get(0) instanceof NodeStorage)
{
for (final NodeStorage storage : (ArrayList<NodeStorage>) nodes)
{
final NodeStorage tempStorage = new NodeStorage(storage.getId(), storage.getProperties());
try
{
tempStorage.addProperty("hash", HashCreator.sha1FromNode(storage));
}
catch (NoSuchAlgorithmException e)
{
Log.getLogger().warn("Couldn't add hash for node", e);
}
readsSetNode.add(tempStorage);
}
}
if(relationships != null && !relationships.isEmpty() && relationships.get(0) instanceof RelationshipStorage)
{
for (final RelationshipStorage storage : (ArrayList<RelationshipStorage>)relationships)
{
final RelationshipStorage tempStorage = new RelationshipStorage(storage.getId(), storage.getProperties(), storage.getStartNode(), storage.getEndNode());
try
{
tempStorage.addProperty("hash", HashCreator.sha1FromRelationship(storage));
}
catch (NoSuchAlgorithmException e)
{
Log.getLogger().warn("Couldn't add hash for relationship", e);
}
readsSetRelationship.add(tempStorage);
}
}
readQueue.add(FINISHED_READING);
input.close();
pool.release(kryo);
}
private void processCommitReturn(final byte[] result)
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
if(result == null)
{
Log.getLogger().warn("Server returned null, something went incredibly wrong there");
return;
}
final Input input = new Input(result);
final String type = kryo.readObject(input, String.class);
if(!Constants.COMMIT_RESPONSE.equals(type))
{
Log.getLogger().warn("Incorrect response to commit message");
input.close();
return;
}
final String decision = kryo.readObject(input, String.class);
localTimestamp = kryo.readObject(input, Long.class);
Log.getLogger().info("Processing commit return: " + localTimestamp);
if(Constants.COMMIT.equals(decision))
{
Log.getLogger().info("Transaction succesfully committed");
}
else
{
Log.getLogger().info("Transaction commit denied - transaction being aborted");
}
Log.getLogger().info("Reset after commit");
resetSets();
input.close();
pool.release(kryo);
}
/**
* Commit reaches the server, if secure commit send to all, else only send to one
*/
@Override
public void commit()
{
firstRead = true;
final boolean readOnly = isReadOnly();
Log.getLogger().info("Starting commit");
if (readOnly && !secureMode)
{
//verifyReadSet();
Log.getLogger().warn(String.format("Read only unsecure Transaction with local transaction id: %d successfully committed", localTimestamp));
firstRead = true;
resetSets();
return;
}
Log.getLogger().info("Starting commit process for: " + this.localTimestamp);
final byte[] bytes = serializeAll();
if (readOnly)
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
Log.getLogger().warn(getProcessId() + " Commit with snapshotId: " + this.localTimestamp);
final byte[] answer;
if(localClusterId == -1)
{
//List of all view processes
/*final int[] currentViewProcesses = this.getViewManager().getCurrentViewProcesses();
//The servers we will actually contact
final int[] servers = new int[3];
//final int spare = servers[new Random().nextInt(currentViewProcesses.length)];
int i = 0;
for(final int processI : currentViewProcesses)
{
if(i < servers.length)
{
servers[i] = processI;
i++;
}
}
isCommitting = true;
Log.getLogger().info("Sending to: " + Arrays.toString(servers));
//sendMessageToTargets(bytes, 0, servers, TOMMessageType.UNORDERED_REQUEST);*/
answer = invokeUnordered(bytes);
}
else
{
answer = globalProxy.invokeUnordered(bytes);
}
Log.getLogger().info(getProcessId() + "Committed with snapshotId " + this.localTimestamp);
final Input input = new Input(answer);
final String messageType = kryo.readObject(input, String.class);
if (!Constants.COMMIT_RESPONSE.equals(messageType))
{
Log.getLogger().warn("Incorrect response type to client from server!" + getProcessId());
resetSets();
firstRead = true;
return;
}
final boolean commit = Constants.COMMIT.equals(kryo.readObject(input, String.class));
if (commit)
{
localTimestamp = kryo.readObject(input, Long.class);
resetSets();
firstRead = true;
Log.getLogger().info(String.format("Transaction with local transaction id: %d successfully committed", localTimestamp));
return;
}
return;
}
if (localClusterId == -1)
{
Log.getLogger().info("Distribute commit with snapshotId: " + this.localTimestamp);
this.invokeOrdered(bytes);
}
else
{
Log.getLogger().info("Commit with snapshotId directly to global cluster. TimestampId: " + this.localTimestamp);
Log.getLogger().info("WriteSet: " + writeSet.size() + " readSetNode: " + readsSetNode.size() + " readSetRs: " + readsSetRelationship.size());
processCommitReturn(globalProxy.invokeOrdered(bytes));
}
}
/**
* Method verifies readSet signatures.
*/
private void verifyReadSet()
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
for(final NodeStorage storage: readsSetNode)
{
for(final Map.Entry<String, Object> entry: storage.getProperties().entrySet())
{
if(!entry.getKey().contains("signature"))
{
continue;
}
final int key = Integer.parseInt(entry.getKey().replace("signature",""));
Log.getLogger().warn("Verifying the keys of the nodes");
final RSAKeyLoader rsaLoader = new RSAKeyLoader(key, GLOBAL_CONFIG_LOCATION, false);
try
{
if (!TOMUtil.verifySignature(rsaLoader.loadPublicKey(), storage.getBytes(), ((String) entry.getValue()).getBytes("UTF-8")))
{
Log.getLogger().warn("Signature of server: " + key + " doesn't match");
}
else
{
Log.getLogger().info("Signature matches of server: " + entry.getKey());
}
}
catch (final Exception e)
{
Log.getLogger().error("Unable to load public key on client", e);
}
}
}
Log.getLogger().warn("Verifying the keys of the relationships");
for(final RelationshipStorage storage: readsSetRelationship)
{
for(final Map.Entry<String, Object> entry: storage.getProperties().entrySet())
{
if(!entry.getKey().contains("signature"))
{
continue;
}
final int key = Integer.parseInt(entry.getKey().replace("signature",""));
Log.getLogger().warn("Verifying the keys of the nodes");
final RSAKeyLoader rsaLoader = new RSAKeyLoader(key, GLOBAL_CONFIG_LOCATION, false);
try
{
if (!TOMUtil.verifySignature(rsaLoader.loadPublicKey(), storage.getBytes(), ((String) entry.getValue()).getBytes("UTF-8")))
{
Log.getLogger().warn("Signature of server: " + key + " doesn't match");
}
else
{
Log.getLogger().info("Signature matches of server: " + entry.getKey());
}
}
catch (final Exception e)
{
Log.getLogger().error("Unable to load public key on client", e);
}
}
}
pool.release(kryo);
}
/**
* Serializes the data and returns it in byte format.
* @return the data in byte format.
*/
private byte[] serialize(@NotNull String request)
{
KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
Kryo kryo = pool.borrow();
Output output = new Output(0, 256);
kryo.writeObject(output, request);
byte[] bytes = output.getBuffer();
output.close();
pool.release(kryo);
return bytes;
}
/**
* Serializes the data and returns it in byte format.
* @return the data in byte format.
*/
private byte[] serialize(@NotNull String reason, long localTimestamp, final Object...args)
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
final Output output = new Output(0, 100024);
kryo.writeObject(output, reason);
kryo.writeObject(output, localTimestamp);
for(final Object identifier: args)
{
if(identifier instanceof NodeStorage || identifier instanceof RelationshipStorage)
{
kryo.writeObject(output, identifier);
}
}
byte[] bytes = output.getBuffer();
output.close();
pool.release(kryo);
return bytes;
}
/**
* Serializes all sets and returns it in byte format.
* @return the data in byte format.
*/
private byte[] serializeAll()
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
final Output output = new Output(0, 400024);
kryo.writeObject(output, Constants.COMMIT_MESSAGE);
//Write the timeStamp to the server
kryo.writeObject(output, localTimestamp);
//Write the readSet.
kryo.writeObject(output, readsSetNode);
kryo.writeObject(output, readsSetRelationship);
//Write the writeSet.
kryo.writeObject(output, writeSet);
byte[] bytes = output.getBuffer();
output.close();
pool.release(kryo);
return bytes;
}
/**
* Resets all the read and write sets.
*/
private void resetSets()
{
readsSetNode = new ArrayList<>();
readsSetRelationship = new ArrayList<>();
writeSet = new ArrayList<>();
isCommitting = false;
responses = 0;
int randomNumber = random.nextInt(100);
if(randomNumber <= 40)
{
serverProcess = 0;
return;
}
serverProcess = 3;
}
/**
* Checks if the transaction has made any changes to the update sets.
* @return true if not.
*/
private boolean isReadOnly()
{
return writeSet.isEmpty();
}
@Override
public boolean isCommitting()
{
return isCommitting;
}
/**
* Get the primary of the cluster.
* @param kryo the kryo instance.
* @return the primary id.
*/
private int getPrimary(final Kryo kryo)
{
byte[] response = invoke(serialize(Constants.GET_PRIMARY), TOMMessageType.UNORDERED_REQUEST);
if(response == null)
{
Log.getLogger().warn("Server returned null, something went incredibly wrong there");
return -1;
}
final Input input = new Input(response);
kryo.readObject(input, String.class);
final int primaryId = kryo.readObject(input, Integer.class);
Log.getLogger().info("Received id: " + primaryId);
input.close();
return primaryId;
}
}
|
package net.atos.entng.rss.parser;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.AsyncResult;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpClientResponse;
import net.atos.entng.rss.service.FeedServiceImpl;
import io.vertx.core.Handler;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import fr.wseduc.webutils.Either;
public class RssParser extends AbstractVerticle implements Handler<Message<JsonObject>> {
private RssParserCache rssParserCache;
private static final Logger log = LoggerFactory.getLogger(FeedServiceImpl.class);
public static final long DEFAULT_CLEAN_TIMEOUT = 30; // Minutes
public static final String PARSER_ADDRESS = "rss.parser";
public static final String ACTION_CLEANUP = "cleanUp";
public static final String ACTION_GET = "get";
private HttpClient httpClient;
@Override
public void start() throws Exception {
super.start();
final long cleanTimeout = config().getLong("clean-timeout", DEFAULT_CLEAN_TIMEOUT) * 60000;
vertx.eventBus().localConsumer("rss.parser", this);
rssParserCache = new RssParserCache();
httpClient = vertx.createHttpClient(new HttpClientOptions()
.setKeepAlive(false).setConnectTimeout(5000));
vertx.setPeriodic(cleanTimeout, new Handler<Long>() {
@Override
public void handle(Long cleanTimeout) {
JsonObject message = new JsonObject();
message.put("action", RssParser.ACTION_CLEANUP);
message.put("cleanTimeout", cleanTimeout);
vertx.eventBus().send(RssParser.PARSER_ADDRESS, message, new Handler<AsyncResult<Message<JsonObject>>>() {
@Override
public void handle(AsyncResult<Message<JsonObject>> ar) {
if (ar.succeeded()) {
if (log.isDebugEnabled()) {
log.debug("Received reply: " + ar.result().body());
}
} else {
log.error("Error Receive reply.", ar.cause());
}
}
});
}
});
}
@Override
public void handle(final Message<JsonObject> message) {
JsonObject msg = message.body();
if(msg != null){
String action = msg.getString("action", "");
switch(action){
case ACTION_CLEANUP:
long cleanTimeout = msg.getLong("cleanTimeout", DEFAULT_CLEAN_TIMEOUT);
rssParserCache.cleanUp(cleanTimeout);
message.reply(new JsonObject().put("status", "ok"));
break;
case ACTION_GET:
String force = msg.getString("force", "0");
final String url = msg.getString("url", "");
if(force.equals("0") && rssParserCache.has(url)){
rssParserCache.get(url, new Handler<Either<String, JsonObject>>(){
@Override
public void handle(Either<String, JsonObject> event) {
JsonObject results = new JsonObject();
if(event.isRight()){
results = event.right().getValue();
results.put("status", 200);
}
else {
results.put("status", 204);
log.error("[FeedServiceImpl][getItems] Error : " + event.left().getValue());
}
message.reply(results);
}
});
}
else{
final HttpClientRequest req = httpClient.getAbs(url, response -> {
final JsonObject results = new JsonObject();
if (response.statusCode() == 200) {
response.bodyHandler(buffer -> {
final String content = buffer.toString();
if (content.isEmpty()) {
results.put("status", 204);
message.reply(results);
return;
}
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
DefaultHandler handler = new RssParserHandler(new Handler<JsonObject>(){
@Override
public void handle(JsonObject results1) {
rssParserCache.put(url, results1);
message.reply(results1);
}
});
parser.parse(new InputSource(new StringReader(content)), handler);
} catch (SAXException | IOException | ParserConfigurationException se) {
results.put("status", 204);
message.reply(results);
}
});
} else {
results.put("status", 204);
message.reply(results);
}
});
req.setTimeout(15000l);
req.end();
}
}
}
}
}
|
package net.darkhax.bookshelf.lib;
import java.util.Random;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Constants {
// Mod Constants
public static final String MOD_ID = "bookshelf";
public static final String MOD_NAME = "Bookshelf";
public static final String VERSION_NUMBER = "1.2.0.226";
public static final String PROXY_CLIENT = "net.darkhax.bookshelf.client.ProxyClient";
public static final String PROXY_COMMON = "net.darkhax.bookshelf.common.ProxyCommon";
// System Constants
public static final Logger LOG = LogManager.getLogger(MOD_NAME);
public static final Random RANDOM = new Random();
public static final String NEW_LINE = System.getProperty("line.separator");
}
|
package net.gtaun.wl.chat;
import net.gtaun.util.event.EventManager;
import net.gtaun.wl.chat.impl.ChatChannelServiceImpl;
import net.gtaun.wl.common.WlPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
*
* @author MK124
*/
public class ChatChannelPlugin extends WlPlugin
{
public static final Logger LOGGER = LoggerFactory.getLogger(ChatChannelPlugin.class);
private ChatChannelServiceImpl chatChannelService;
public ChatChannelPlugin()
{
}
@Override
protected void onEnable() throws Throwable
{
EventManager eventManager = getEventManager();
chatChannelService = new ChatChannelServiceImpl(eventManager);
registerService(ChatChannelService.class, chatChannelService);
if (chatChannelService.getDefaultChannel() == null)
{
ChatChannel defaultChannel = chatChannelService.createChannel("Default");
defaultChannel.setPrefixFormat("");
chatChannelService.setDefaultChannel(defaultChannel);
LOGGER.info("No default channel, create a default channel.");
}
LOGGER.info(getDescription().getName() + " " + getDescription().getVersion() + " Enabled.");
}
@Override
protected void onDisable() throws Throwable
{
unregisterService(ChatChannelService.class);
chatChannelService.uninitialize();
chatChannelService = null;
LOGGER.info(getDescription().getName() + " " + getDescription().getVersion() + " Disabled.");
}
}
|
package net.imagej.ops.image;
import net.imagej.ImgPlus;
import net.imagej.ops.AbstractNamespace;
import net.imagej.ops.Namespace;
import net.imagej.ops.OpMethod;
import net.imagej.ops.Ops;
import net.imagej.ops.image.cooccurrencematrix.MatrixOrientation;
import net.imagej.ops.special.computer.UnaryComputerOp;
import net.imglib2.Interval;
import net.imglib2.IterableInterval;
import net.imglib2.RandomAccessible;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.histogram.Histogram1d;
import net.imglib2.img.Img;
import net.imglib2.interpolation.InterpolatorFactory;
import net.imglib2.type.Type;
import net.imglib2.type.numeric.RealType;
import org.scijava.plugin.Plugin;
/**
* The image namespace contains operations relating to images.
*
* @author Curtis Rueden
*/
@Plugin(type = Namespace.class)
public class ImageNamespace extends AbstractNamespace {
// -- ascii --
/** Executes the "ascii" operation on the given arguments. */
@OpMethod(op = Ops.Image.ASCII.class)
public Object ascii(final Object... args) {
return ops().run(Ops.Image.ASCII.NAME, args);
}
/** Executes the "ascii" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.ascii.DefaultASCII.class)
public <T extends RealType<T>> String ascii(final IterableInterval<T> image) {
final String result = (String) ops().run(
net.imagej.ops.image.ascii.DefaultASCII.class, image);
return result;
}
/** Executes the "ascii" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.ascii.DefaultASCII.class)
public <T extends RealType<T>> String ascii(final IterableInterval<T> image,
final T min)
{
final String result = (String) ops().run(
net.imagej.ops.image.ascii.DefaultASCII.class, image, min);
return result;
}
/** Executes the "ascii" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.ascii.DefaultASCII.class)
public <T extends RealType<T>> String ascii(final IterableInterval<T> image,
final T min, final T max)
{
final String result = (String) ops().run(
net.imagej.ops.image.ascii.DefaultASCII.class, image, min, max);
return result;
}
// -- cooccurrence matrix --
@OpMethod(ops = {
net.imagej.ops.image.cooccurrencematrix.CooccurrenceMatrix3D.class,
net.imagej.ops.image.cooccurrencematrix.CooccurrenceMatrix2D.class })
public <T extends RealType<T>> double[][] cooccurrencematrix(
final IterableInterval<T> in, final int nrGreyLevels,
final int distance, final MatrixOrientation orientation) {
final double[][] result = (double[][]) ops().run(
Ops.Image.CooccurrenceMatrix.class, in, nrGreyLevels, distance,
orientation);
return result;
}
// -- crop --
/** Executes the "crop" operation on the given arguments. */
@OpMethod(op = Ops.Image.Crop.class)
public Object crop(final Object... args) {
return ops().run(Ops.Image.Crop.NAME, args);
}
/** Executes the "crop" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.crop.CropImgPlus.class)
public <T extends Type<T>> ImgPlus<T> crop(final ImgPlus<T> in,
final Interval interval) {
@SuppressWarnings("unchecked")
final ImgPlus<T> result = (ImgPlus<T>) ops().run(
net.imagej.ops.image.crop.CropImgPlus.class, in, interval);
return result;
}
/** Executes the "crop" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.crop.CropImgPlus.class)
public <T extends Type<T>> ImgPlus<T> crop(final ImgPlus<T> in,
final Interval interval, final boolean dropSingleDimensions) {
@SuppressWarnings("unchecked")
final ImgPlus<T> result = (ImgPlus<T>) ops().run(
net.imagej.ops.image.crop.CropImgPlus.class, in, interval,
dropSingleDimensions);
return result;
}
/** Executes the "crop" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.crop.CropRAI.class)
public <T> RandomAccessibleInterval<T> crop(
final RandomAccessibleInterval<T> in, final Interval interval) {
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result = (RandomAccessibleInterval<T>) ops()
.run(net.imagej.ops.image.crop.CropRAI.class, in, interval);
return result;
}
/** Executes the "crop" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.crop.CropRAI.class)
public <T> RandomAccessibleInterval<T> crop(
final RandomAccessibleInterval<T> in, final Interval interval,
final boolean dropSingleDimensions) {
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result = (RandomAccessibleInterval<T>) ops()
.run(net.imagej.ops.image.crop.CropRAI.class, in, interval,
dropSingleDimensions);
return result;
}
// -- equation --
/** Executes the "equation" operation on the given arguments. */
@OpMethod(op = Ops.Image.Equation.class)
public Object equation(final Object... args) {
return ops().run(Ops.Image.Equation.NAME, args);
}
/** Executes the "equation" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.equation.DefaultEquation.class)
public <T extends RealType<T>> IterableInterval<T> equation(final String in) {
@SuppressWarnings("unchecked")
final IterableInterval<T> result = (IterableInterval<T>) ops().run(
net.imagej.ops.image.equation.DefaultEquation.class, in);
return result;
}
/** Executes the "equation" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.equation.DefaultEquation.class)
public <T extends RealType<T>> IterableInterval<T> equation(
final IterableInterval<T> out, final String in) {
@SuppressWarnings("unchecked")
final IterableInterval<T> result = (IterableInterval<T>) ops().run(
net.imagej.ops.image.equation.DefaultEquation.class, out, in);
return result;
}
// -- histogram --
/** Executes the "histogram" operation on the given arguments. */
@OpMethod(op = Ops.Image.Histogram.class)
public Object histogram(final Object... args) {
return ops().run(Ops.Image.Histogram.NAME, args);
}
/** Executes the "histogram" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.histogram.HistogramCreate.class)
public <T extends RealType<T>> Histogram1d<T> histogram(final Iterable<T> in) {
@SuppressWarnings("unchecked")
final Histogram1d<T> result = (Histogram1d<T>) ops().run(
net.imagej.ops.image.histogram.HistogramCreate.class, in);
return result;
}
/** Executes the "histogram" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.histogram.HistogramCreate.class)
public <T extends RealType<T>> Histogram1d<T> histogram(
final Iterable<T> in, final int numBins) {
@SuppressWarnings("unchecked")
final Histogram1d<T> result = (Histogram1d<T>) ops().run(
net.imagej.ops.image.histogram.HistogramCreate.class, in,
numBins);
return result;
}
// -- invert --
/** Executes the "invert" operation on the given arguments. */
@OpMethod(op = Ops.Image.Invert.class)
public Object invert(final Object... args) {
return ops().run(Ops.Image.Invert.NAME, args);
}
/** Executes the "invert" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.invert.InvertII.class)
public <I extends RealType<I>, O extends RealType<O>> IterableInterval<O> invert(
final IterableInterval<O> out, final IterableInterval<I> in) {
@SuppressWarnings("unchecked")
final IterableInterval<O> result = (IterableInterval<O>) ops().run(
net.imagej.ops.image.invert.InvertII.class, out,
in);
return result;
}
// -- normalize --
/** Executes the "normalize" operation on the given arguments. */
@OpMethod(op = Ops.Image.Normalize.class)
public Object normalize(final Object... args) {
return ops().run(Ops.Image.Normalize.NAME, args);
}
@OpMethod(op = net.imagej.ops.image.normalize.NormalizeIIComputer.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> out, final IterableInterval<T> in)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops()
.run(net.imagej.ops.image.normalize.NormalizeIIComputer.class,
out, in);
return result;
}
@OpMethod(op = net.imagej.ops.image.normalize.NormalizeIIComputer.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> out, final IterableInterval<T> in,
final T sourceMin)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.image.normalize.NormalizeIIComputer.class, out,
in, sourceMin);
return result;
}
@OpMethod(op = net.imagej.ops.image.normalize.NormalizeIIComputer.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> out, final IterableInterval<T> in,
final T sourceMin, final T sourceMax)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.image.normalize.NormalizeIIComputer.class, out,
in, sourceMin, sourceMax);
return result;
}
@OpMethod(op = net.imagej.ops.image.normalize.NormalizeIIComputer.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> out, final IterableInterval<T> in,
final T sourceMin, final T sourceMax, final T targetMin)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.image.normalize.NormalizeIIComputer.class, out,
in, sourceMin, sourceMax, targetMin);
return result;
}
@OpMethod(op = net.imagej.ops.image.normalize.NormalizeIIComputer.class)
public
<T extends RealType<T>>
IterableInterval<T>
normalize(final IterableInterval<T> out, final IterableInterval<T> in,
final T sourceMin, final T sourceMax, final T targetMin, final T targetMax)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.image.normalize.NormalizeIIComputer.class, out,
in, sourceMin, sourceMax, targetMin, targetMax);
return result;
}
@OpMethod(
op = net.imagej.ops.image.normalize.NormalizeIIFunction.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> in)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.image.normalize.NormalizeIIFunction.class,
in);
return result;
}
@OpMethod(
op = net.imagej.ops.image.normalize.NormalizeIIFunction.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> in, final T sourceMin)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.image.normalize.NormalizeIIFunction.class,
in, sourceMin);
return result;
}
@OpMethod(
op = net.imagej.ops.image.normalize.NormalizeIIFunction.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> in, final T sourceMin, final T sourceMax)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.image.normalize.NormalizeIIFunction.class,
in, sourceMin, sourceMax);
return result;
}
@OpMethod(
op = net.imagej.ops.image.normalize.NormalizeIIFunction.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> in, final T sourceMin, final T sourceMax,
final T targetMin)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.image.normalize.NormalizeIIFunction.class,
in, sourceMin, sourceMax, targetMin);
return result;
}
@OpMethod(
op = net.imagej.ops.image.normalize.NormalizeIIFunction.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> in, final T sourceMin, final T sourceMax,
final T targetMin, final T targetMax)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.image.normalize.NormalizeIIFunction.class,
in, sourceMin, sourceMax, targetMin, targetMax);
return result;
}
@OpMethod(
op = net.imagej.ops.image.normalize.NormalizeIIFunction.class)
public
<T extends RealType<T>> IterableInterval<T> normalize(
final IterableInterval<T> in, final T sourceMin, final T sourceMax,
final T targetMin, final T targetMax, final boolean isLazy)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops().run(
net.imagej.ops.image.normalize.NormalizeIIFunction.class,
in, sourceMin, sourceMax, targetMin, targetMax, isLazy);
return result;
}
// -- project --
/** Executes the "project" operation on the given arguments. */
@OpMethod(op = Ops.Image.Project.class)
public Object project(final Object... args) {
return ops().run(Ops.Image.Project.NAME, args);
}
/** Executes the "project" operation on the given arguments. */
@OpMethod(ops = {
net.imagej.ops.image.project.DefaultProjectParallel.class,
net.imagej.ops.image.project.ProjectRAIToII.class })
public <T, V> IterableInterval<V> project(final IterableInterval<V> out,
final RandomAccessibleInterval<T> in,
final UnaryComputerOp<Iterable<T>, V> method, final int dim) {
@SuppressWarnings("unchecked")
final IterableInterval<V> result = (IterableInterval<V>) ops().run(
net.imagej.ops.Ops.Image.Project.class, out, in, method, dim);
return result;
}
// -- scale --
/** Executes the "scale" operation on the given arguments. */
@OpMethod(op = Ops.Image.Scale.class)
public Object scale(final Object... args) {
return ops().run(Ops.Image.Scale.NAME, args);
}
/** Executes the "scale" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.image.scale.ScaleImg.class)
public <T extends RealType<T>> Img<T> scale(final Img<T> in,
final double[] scaleFactors,
final InterpolatorFactory<T, RandomAccessible<T>> interpolator) {
@SuppressWarnings("unchecked")
final Img<T> result = (Img<T>) ops().run(
net.imagej.ops.image.scale.ScaleImg.class, in, scaleFactors,
interpolator);
return result;
}
@Override
public String getName() {
return "image";
}
}
|
package net.minecraftforge.fluids;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.block.BlockLiquid;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fluids.capability.wrappers.BlockLiquidWrapper;
import net.minecraftforge.fluids.capability.wrappers.FluidBlockWrapper;
import net.minecraftforge.fluids.capability.wrappers.FluidContainerItemWrapper;
import net.minecraftforge.fluids.capability.wrappers.FluidContainerRegistryWrapper;
import net.minecraftforge.fluids.capability.wrappers.FluidHandlerWrapper;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.ItemHandlerHelper;
import net.minecraftforge.items.wrapper.InvWrapper;
import net.minecraftforge.items.wrapper.PlayerMainInvWrapper;
public class FluidUtil
{
private FluidUtil()
{
}
/**
* Used to handle the common case of a fluid item right-clicking on a fluid handler.
* First it tries to fill the container item from the fluid handler,
* if that action fails then it tries to drain the container item into the fluid handler.
*
* Returns true if interaction was successful.
* Returns false if interaction failed.
*/
public static boolean interactWithFluidHandler(ItemStack stack, IFluidHandler fluidHandler, EntityPlayer player)
{
if (stack == null || fluidHandler == null || player == null)
{
return false;
}
IItemHandler playerInventory = new InvWrapper(player.inventory);
return tryFillContainerAndStow(stack, fluidHandler, playerInventory, Integer.MAX_VALUE, player) ||
tryEmptyContainerAndStow(stack, fluidHandler, playerInventory, Integer.MAX_VALUE, player);
}
/**
* Fill a container from the given fluidSource.
*
* @param container The container to be filled. Will not be modified.
* @param fluidSource The fluid handler to be drained.
* @param maxAmount The largest amount of fluid that should be transferred.
* @param player The player to make the filling noise. Pass null for no noise.
* @param doFill true if the container should actually be filled, false if it should be simulated.
* @return The filled container or null if the liquid couldn't be taken from the tank.
*/
public static ItemStack tryFillContainer(ItemStack container, IFluidHandler fluidSource, int maxAmount, @Nullable EntityPlayer player, boolean doFill)
{
container = container.copy(); // do not modify the input
container.stackSize = 1;
IFluidHandler containerFluidHandler = getFluidHandler(container);
if (containerFluidHandler != null)
{
FluidStack simulatedTransfer = tryFluidTransfer(containerFluidHandler, fluidSource, maxAmount, false);
if (simulatedTransfer != null)
{
if (doFill)
{
tryFluidTransfer(containerFluidHandler, fluidSource, maxAmount, true);
if (player != null)
{
SoundEvent soundevent = simulatedTransfer.getFluid().getFillSound(simulatedTransfer);
player.playSound(soundevent, 1f, 1f);
}
}
else
{
containerFluidHandler.fill(simulatedTransfer, true);
}
return container;
}
}
return null;
}
/**
* Takes a filled container and tries to empty it into the given tank.
*
* @param container The filled container. Will not be modified.
* @param fluidDestination The fluid handler to be filled by the container.
* @param maxAmount The largest amount of fluid that should be transferred.
* @param player Player for making the bucket drained sound. Pass null for no noise.
* @param doDrain true if the container should actually be drained, false if it should be simulated.
* @return The empty container if successful, null if the fluid handler couldn't be filled.
* NOTE The empty container will have a stackSize of 0 when a filled container is consumable,
* i.e. it has a "null" empty container but has successfully been emptied.
*/
@Nullable
public static ItemStack tryEmptyContainer(ItemStack container, IFluidHandler fluidDestination, int maxAmount, @Nullable EntityPlayer player, boolean doDrain)
{
container = container.copy(); // do not modify the input
container.stackSize = 1;
IFluidHandler containerFluidHandler = getFluidHandler(container);
if (containerFluidHandler != null)
{
FluidStack simulatedTransfer = tryFluidTransfer(fluidDestination, containerFluidHandler, maxAmount, false);
if (simulatedTransfer != null)
{
if (doDrain)
{
tryFluidTransfer(fluidDestination, containerFluidHandler, maxAmount, true);
if (player != null)
{
SoundEvent soundevent = simulatedTransfer.getFluid().getEmptySound(simulatedTransfer);
player.playSound(soundevent, 1f, 1f);
}
}
else
{
containerFluidHandler.drain(simulatedTransfer, true);
}
return container;
}
}
return null;
}
public static boolean tryFillContainerAndStow(ItemStack container, IFluidHandler fluidSource, IItemHandler inventory, int maxAmount, @Nullable EntityPlayer player)
{
if (container == null || container.stackSize < 1)
{
return false;
}
if (player != null && player.capabilities.isCreativeMode)
{
ItemStack filledReal = tryFillContainer(container, fluidSource, maxAmount, player, true);
if (filledReal != null)
{
return true;
}
}
else if (container.stackSize == 1) // don't need to stow anything, just fill and edit the container stack
{
ItemStack filledReal = tryFillContainer(container, fluidSource, maxAmount, player, true);
if (filledReal != null)
{
container.deserializeNBT(filledReal.serializeNBT());
return true;
}
}
else
{
ItemStack filledSimulated = tryFillContainer(container, fluidSource, maxAmount, player, false);
if (filledSimulated != null)
{
// check if we can give the itemStack to the inventory
ItemStack remainder = ItemHandlerHelper.insertItemStacked(inventory, filledSimulated, true);
if (remainder == null || player != null)
{
ItemStack filledReal = tryFillContainer(container, fluidSource, maxAmount, player, true);
remainder = ItemHandlerHelper.insertItemStacked(inventory, filledReal, false);
// give it to the player or drop it at their feet
if (remainder != null && player != null)
{
ItemHandlerHelper.giveItemToPlayer(player, remainder);
}
container.stackSize
return true;
}
}
}
return false;
}
public static boolean tryEmptyContainerAndStow(ItemStack container, IFluidHandler fluidDestination, IItemHandler inventory, int maxAmount, @Nullable EntityPlayer player)
{
if (container == null || container.stackSize < 1)
{
return false;
}
if (player != null && player.capabilities.isCreativeMode)
{
ItemStack emptiedReal = tryEmptyContainer(container, fluidDestination, maxAmount, player, true);
if (emptiedReal != null)
{
return true;
}
}
else if (container.stackSize == 1) // don't need to stow anything, just fill and edit the container stack
{
ItemStack emptiedReal = tryEmptyContainer(container, fluidDestination, maxAmount, player, true);
if (emptiedReal != null)
{
if (emptiedReal.stackSize <= 0)
{
container.stackSize
}
else
{
container.deserializeNBT(emptiedReal.serializeNBT());
}
return true;
}
}
else
{
ItemStack emptiedSimulated = tryEmptyContainer(container, fluidDestination, maxAmount, player, false);
if (emptiedSimulated != null)
{
if (emptiedSimulated.stackSize <= 0)
{
tryEmptyContainer(container, fluidDestination, maxAmount, player, true);
container.stackSize
return true;
}
else
{
// check if we can give the itemStack to the inventory
ItemStack remainder = ItemHandlerHelper.insertItemStacked(inventory, emptiedSimulated, true);
if (remainder == null || player != null)
{
ItemStack emptiedReal = tryEmptyContainer(container, fluidDestination, maxAmount, player, true);
remainder = ItemHandlerHelper.insertItemStacked(inventory, emptiedReal, false);
// give it to the player or drop it at their feet
if (remainder != null && player != null)
{
ItemHandlerHelper.giveItemToPlayer(player, remainder);
}
container.stackSize
return true;
}
}
}
}
return false;
}
/**
* Fill a destination fluid handler from a source fluid handler.
*
* @param fluidDestination The fluid handler to be filled.
* @param fluidSource The fluid handler to be drained.
* @param maxAmount The largest amount of fluid that should be transferred.
* @param doTransfer True if the transfer should actually be done, false if it should be simulated.
* @return the fluidStack that was transferred from the source to the destination. null on failure.
*/
@Nullable
public static FluidStack tryFluidTransfer(IFluidHandler fluidDestination, IFluidHandler fluidSource, int maxAmount, boolean doTransfer)
{
FluidStack drainable = fluidSource.drain(maxAmount, false);
if (drainable != null && drainable.amount > 0)
{
int fillableAmount = fluidDestination.fill(drainable, false);
if (fillableAmount > 0)
{
FluidStack drained = fluidSource.drain(fillableAmount, doTransfer);
if (drained != null)
{
drained.amount = fluidDestination.fill(drained, doTransfer);
return drained;
}
}
}
return null;
}
/**
* Helper method to get an IFluidHandler for an itemStack.
*
* The itemStack passed in here WILL be modified, the IFluidHandler acts on it directly.
*
* Note that the itemStack MUST have a stackSize of 1 if you want to fill or drain it.
* You can't fill or drain a whole stack at once, if you do then liquid is multiplied or destroyed.
*
* Vanilla buckets will be converted to universal buckets if they are enabled.
*
* Returns null if the itemStack passed in does not have a fluid handler.
*/
@Nullable
public static IFluidHandler getFluidHandler(ItemStack itemStack)
{
if (itemStack == null)
{
return null;
}
// check for capability
if (itemStack.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null))
{
return itemStack.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, null);
}
// legacy container handling
Item item = itemStack.getItem();
if (item instanceof IFluidContainerItem)
{
return new FluidContainerItemWrapper((IFluidContainerItem) item, itemStack);
}
else if (FluidContainerRegistry.isContainer(itemStack))
{
return new FluidContainerRegistryWrapper(itemStack);
}
else
{
return null;
}
}
/**
* Helper method to get the fluid contained in an itemStack
*/
@Nullable
public static FluidStack getFluidContained(ItemStack container)
{
if (container != null)
{
container = container.copy();
container.stackSize = 1;
IFluidHandler fluidHandler = FluidUtil.getFluidHandler(container);
if (fluidHandler != null)
{
return fluidHandler.drain(Integer.MAX_VALUE, false);
}
}
return null;
}
/**
* Helper method to get an IFluidHandler for at a block position.
*
* Returns null if there is no valid fluid handler.
*/
@Nullable
public static IFluidHandler getFluidHandler(World world, BlockPos blockPos, @Nullable EnumFacing side)
{
IBlockState state = world.getBlockState(blockPos);
Block block = state.getBlock();
if (block.hasTileEntity(state))
{
TileEntity tileEntity = world.getTileEntity(blockPos);
if (tileEntity != null && tileEntity.hasCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, side))
{
return tileEntity.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, side);
}
}
else if (block instanceof IFluidBlock)
{
return new FluidBlockWrapper((IFluidBlock) block, world, blockPos);
}
else if (block instanceof BlockLiquid)
{
return new BlockLiquidWrapper((BlockLiquid) block, world, blockPos);
}
return null;
}
/**
* Tries to place a fluid in the world in block form.
* Makes a fluid emptying sound when successful.
* Checks if water-like fluids should vaporize like in the nether.
*
* Modeled after {@link net.minecraft.item.ItemBucket#tryPlaceContainedLiquid(EntityPlayer, World, BlockPos)}
*
* @param player Player who places the fluid. May be null for blocks like dispensers.
* @param worldIn World to place the fluid in
* @param fluidStack The fluidStack to place.
* @param pos The position in the world to place the fluid block
* @return true if successful
*/
public static boolean tryPlaceFluid(@Nullable EntityPlayer player, World worldIn, FluidStack fluidStack, BlockPos pos)
{
if (worldIn == null || fluidStack == null || pos == null)
{
return false;
}
Fluid fluid = fluidStack.getFluid();
if (fluid == null || !fluid.canBePlacedInWorld())
{
return false;
}
// check that we can place the fluid at the destination
IBlockState destBlockState = worldIn.getBlockState(pos);
Material destMaterial = destBlockState.getMaterial();
boolean isDestNonSolid = !destMaterial.isSolid();
boolean isDestReplaceable = destBlockState.getBlock().isReplaceable(worldIn, pos);
if (!worldIn.isAirBlock(pos) && !isDestNonSolid && !isDestReplaceable)
{
return false; // Non-air, solid, unreplacable block. We can't put fluid here.
}
if (worldIn.provider.doesWaterVaporize() && fluid.doesVaporize(fluidStack))
{
fluid.vaporize(player, worldIn, pos, fluidStack);
}
else
{
if (!worldIn.isRemote && (isDestNonSolid || isDestReplaceable) && !destMaterial.isLiquid())
{
worldIn.destroyBlock(pos, true);
}
SoundEvent soundevent = fluid.getEmptySound(fluidStack);
worldIn.playSound(player, pos, soundevent, SoundCategory.BLOCKS, 1.0F, 1.0F);
IBlockState fluidBlockState = fluid.getBlock().getDefaultState();
worldIn.setBlockState(pos, fluidBlockState, 11);
}
return true;
}
/**
* Attempts to pick up a fluid in the world and put it in an empty container item.
*
* @param emptyContainer The empty container to fill. Will not be modified.
* @param playerIn The player filling the container. Optional.
* @param worldIn The world the fluid is in.
* @param pos The position of the fluid in the world.
* @param side The side of the fluid that is being drained.
* @return a filled container if it was successful. returns null on failure.
*/
@Nullable
public static ItemStack tryPickUpFluid(ItemStack emptyContainer, @Nullable EntityPlayer playerIn, World worldIn, BlockPos pos, EnumFacing side)
{
if (emptyContainer == null || worldIn == null || pos == null) {
return null;
}
IFluidHandler targetFluidHandler = FluidUtil.getFluidHandler(worldIn, pos, side);
if (targetFluidHandler != null)
{
return FluidUtil.tryFillContainer(emptyContainer, targetFluidHandler, Integer.MAX_VALUE, playerIn, true);
}
return null;
}
/**
* Returns true if interaction was successful.
* @deprecated use {@link #interactWithFluidHandler(ItemStack, IFluidHandler, EntityPlayer)}
*/
@Deprecated
public static boolean interactWithTank(ItemStack stack, EntityPlayer player, net.minecraftforge.fluids.IFluidHandler tank, EnumFacing side)
{
IFluidHandler fluidHandler = new FluidHandlerWrapper(tank, side);
return interactWithFluidHandler(stack, fluidHandler, player);
}
/**
* @deprecated use {@link #tryFillContainer(ItemStack, IFluidHandler, int, EntityPlayer, boolean)}
*/
@Deprecated
public static ItemStack tryFillBucket(ItemStack bucket, net.minecraftforge.fluids.IFluidHandler tank, EnumFacing side)
{
return tryFillBucket(bucket, tank, side, null);
}
/**
* Fill an empty bucket from the given tank. Uses the FluidContainerRegistry.
*
* @param bucket The empty bucket. Will not be modified.
* @param tank The tank to fill the bucket from
* @param side Side to access the tank from
* @return The filled bucket or null if the liquid couldn't be taken from the tank.
* @deprecated use {@link #tryFillContainer(ItemStack, IFluidHandler, int, EntityPlayer, boolean)}
*/
@Deprecated
public static ItemStack tryFillBucket(ItemStack bucket, net.minecraftforge.fluids.IFluidHandler tank, EnumFacing side, EntityPlayer player)
{
IFluidHandler newFluidHandler = new FluidHandlerWrapper(tank, side);
return tryFillContainer(bucket, newFluidHandler, Fluid.BUCKET_VOLUME, player, true);
}
/**
* @deprecated use {@link #tryEmptyContainer(ItemStack, IFluidHandler, int, EntityPlayer, boolean)}
*/
@Deprecated
public static ItemStack tryEmptyBucket(ItemStack bucket, net.minecraftforge.fluids.IFluidHandler tank, EnumFacing side)
{
return tryEmptyBucket(bucket, tank, side, null);
}
/**
* Takes a filled bucket and tries to empty it into the given tank. Uses the FluidContainerRegistry.
*
* @param bucket The filled bucket
* @param tank The tank to fill with the bucket
* @param side Side to access the tank from
* @param player Player for making the bucket drained sound.
* @return The empty bucket if successful, null if the tank couldn't be filled.
* @deprecated use {@link #tryFillContainer(ItemStack, IFluidHandler, int, EntityPlayer, boolean)}
*/
@Deprecated
public static ItemStack tryEmptyBucket(ItemStack bucket, net.minecraftforge.fluids.IFluidHandler tank, EnumFacing side, EntityPlayer player)
{
IFluidHandler destination = new FluidHandlerWrapper(tank, side);
return tryEmptyContainer(bucket, destination, Fluid.BUCKET_VOLUME, player, true);
}
/**
* Takes an IFluidContainerItem and tries to fill it from the given tank.
*
* @param container The IFluidContainerItem Itemstack to fill. WILL BE MODIFIED!
* @param tank The tank to fill from
* @param side Side to access the tank from
* @param player The player that tries to fill the bucket. Needed if the input itemstack has a stacksize > 1 to determine where the filled container goes.
* @return True if the IFluidContainerItem was filled successfully, false otherwise. The passed container will have been modified to accommodate for anything done in this method. New Itemstacks might have been added to the players inventory.
* @deprecated use {@link #tryFillContainerAndStow(ItemStack, IFluidHandler, IItemHandler, int, EntityPlayer)}
*/
@Deprecated
public static boolean tryFillFluidContainerItem(ItemStack container, net.minecraftforge.fluids.IFluidHandler tank, EnumFacing side, EntityPlayer player)
{
return tryFillFluidContainerItem(container, tank, side, new PlayerMainInvWrapper(player.inventory), -1, player);
}
/**
* @deprecated use {@link #tryEmptyContainerAndStow(ItemStack, IFluidHandler, IItemHandler, int, EntityPlayer)}
*/
@Deprecated
public static boolean tryEmptyFluidContainerItem(ItemStack container, net.minecraftforge.fluids.IFluidHandler tank, EnumFacing side, EntityPlayer player)
{
return tryEmptyFluidContainerItem(container, tank, side, new PlayerMainInvWrapper(player.inventory), -1, player);
}
/**
* Takes an IFluidContainerItem and tries to fill it from the given tank.
* If the input itemstack has a stacksize >1 new itemstacks will be created and inserted into the given inventory.
* If the inventory does not accept it, it will be given to the player or dropped at the players feet.
* If player is null in this case, the action will be aborted.
* To support buckets that are not in the FluidContainerRegistry but implement IFluidContainerItem be sure to convert
* the empty bucket to your empty bucket variant before passing it to this function.
*
* @param container The IFluidContainerItem Itemstack to fill. WILL BE MODIFIED!
* @param tank The tank to fill from
* @param side Side to access the tank from
* @param inventory An inventory where any additionally created item (filled container if multiple empty are present) are put
* @param max Maximum amount to take from the tank. Uses IFluidContainerItem capacity if <= 0
* @param player The player that gets the items the inventory can't take. Can be null, only used if the inventory cannot take the filled stack.
* @return True if the IFluidContainerItem was filled successfully, false otherwise. The passed container will have been modified to accommodate for anything done in this method. New Itemstacks might have been added to the players inventory.
* @deprecated use {@link #tryFillContainerAndStow(ItemStack, IFluidHandler, IItemHandler, int, EntityPlayer)}
*/
@Deprecated
public static boolean tryFillFluidContainerItem(ItemStack container, net.minecraftforge.fluids.IFluidHandler tank, EnumFacing side, IItemHandler inventory, int max, @Nullable EntityPlayer player)
{
if (!(container.getItem() instanceof IFluidContainerItem))
{
// not a fluid container
return false;
}
IFluidContainerItem fluidContainer = (IFluidContainerItem) container.getItem();
if (fluidContainer.getFluid(container) != null)
{
// not empty
return false;
}
// if no maximum is given, fill fully
if (max <= 0)
{
max = fluidContainer.getCapacity(container);
}
// check how much liquid we can drain from the tank
FluidStack liquid = tank.drain(side, max, false);
if (liquid != null && liquid.amount > 0)
{
// check which itemstack shall be altered by the fill call
if (container.stackSize > 1)
{
// create a copy of the container and fill it
ItemStack toFill = container.copy();
toFill.stackSize = 1;
int filled = fluidContainer.fill(toFill, liquid, false);
if (filled > 0)
{
// This manipulates the container Itemstack!
filled = fluidContainer.fill(toFill, liquid, true);
}
else
{
// IFluidContainer does not accept the fluid/amount
return false;
}
if(player == null || !player.worldObj.isRemote)
{
// check if we can give the itemstack to the inventory
ItemStack remainder = ItemHandlerHelper.insertItemStacked(inventory, toFill, true);
if (remainder != null && player == null)
{
// couldn't add to the inventory and don't have a player to drop the item at
return false;
}
remainder = ItemHandlerHelper.insertItemStacked(inventory, toFill, false);
// give it to the player or drop it at his feet
if (remainder != null && player != null)
{
ItemHandlerHelper.giveItemToPlayer(player, remainder);
}
}
// the result has been given to the player, drain the tank since everything is ok
tank.drain(side, filled, true);
// decrease its stacksize to accommodate the filled one (it was >1 from the check above)
container.stackSize
}
// just 1 empty container to fill, no special treatment needed
else
{
int filled = fluidContainer.fill(container, liquid, false);
if (filled > 0)
{
// This manipulates the container Itemstack!
filled = fluidContainer.fill(container, liquid, true);
}
else
{
// IFluidContainer does not accept the fluid/amount
return false;
}
tank.drain(side, filled, true);
}
// play sound
if(player != null)
{
SoundEvent soundevent = liquid.getFluid().getFillSound(liquid);
player.playSound(soundevent, 1f, 1f);
}
return true;
}
return false;
}
/**
* Takes an IFluidContainerItem and tries to empty it into the given tank.
* If the input itemstack has a stacksize >1 new itemstacks will be created and inserted into the given inventory.
* If the inventory does not accept it, it will be given to the player or dropped at the players feet.
* If player is null in this case, the action will be aborted.
*
* @param container The IFluidContainerItem Itemstack to empty. WILL BE MODIFIED!
* @param tank The tank to fill
* @param side Side to access the tank from
* @param inventory An inventory where any additionally created item (filled container if multiple empty are present) are put
* @param max Maximum amount to take from the tank. Uses IFluidContainerItem capacity if <= 0
* @param player The player that gets the items the inventory can't take. Can be null, only used if the inventory cannot take the emptied stack.
* @return True if the container successfully emptied at least 1 mb into the tank, false otherwise. The passed container itemstack will be modified to accommodate for the liquid transaction.
* @deprecated use {@link #tryEmptyContainerAndStow(ItemStack, IFluidHandler, IItemHandler, int, EntityPlayer)}
*/
@Deprecated
public static boolean tryEmptyFluidContainerItem(ItemStack container, net.minecraftforge.fluids.IFluidHandler tank, EnumFacing side, IItemHandler inventory, int max, EntityPlayer player)
{
if (!(container.getItem() instanceof IFluidContainerItem))
{
// not a fluid container
return false;
}
IFluidContainerItem fluidContainer = (IFluidContainerItem) container.getItem();
if (fluidContainer.getFluid(container) != null)
{
// drain out of the fluidcontainer
if (max <= 0)
{
max = fluidContainer.getCapacity(container);
}
FluidStack drained = fluidContainer.drain(container, max, false);
if (drained != null && tank.canFill(side, drained.getFluid()))
{
// check how much we can fill into the tank
int filled = tank.fill(side, drained, false);
if (filled > 0)
{
// verify that the new amount can also be drained (buckets can only extract full amounts for example)
drained = fluidContainer.drain(container, filled, false);
// actually transfer the liquid if everything went well
if (drained != null && drained.amount == filled)
{
// more than 1 filled itemstack, ensure that we can insert the changed container
if (container.stackSize > 1)
{
// create a copy of the container and drain it
ItemStack toEmpty = container.copy();
toEmpty.stackSize = 1;
drained = fluidContainer.drain(toEmpty, filled, true); // modifies the container!
if(player == null || !player.worldObj.isRemote)
{
// try adding the drained container to the inventory
ItemStack remainder = ItemHandlerHelper.insertItemStacked(inventory, toEmpty, true);
if (remainder != null && player == null)
{
// couldn't add to the inventory and don't have a player to drop the item at
return false;
}
remainder = ItemHandlerHelper.insertItemStacked(inventory, toEmpty, false);
// give it to the player or drop it at his feet
if (remainder != null && player != null)
{
ItemHandlerHelper.giveItemToPlayer(player, remainder);
}
}
// the result has been given to the player, fill the tank since everything is ok
tank.fill(side, drained, true);
// decrease its stacksize to accommodate the filled one (it was >1 from the check above)
container.stackSize
}
// itemstack of size 1, no special treatment needed
else
{
// This manipulates the container Itemstack!
drained = fluidContainer.drain(container, filled, true); // modifies the container!
tank.fill(side, drained, true);
}
// play sound
if(player != null)
{
SoundEvent soundevent = drained.getFluid().getEmptySound(drained);
player.playSound(soundevent, 1f, 1f);
}
return true;
}
}
}
}
return false;
}
}
|
package nl.dykam.dev.spector;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityTargetLivingEntityEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.*;
public class ShieldListener implements Listener {
private final SpectorManager manager;
public ShieldListener(SpectorManager manager) {
this.manager = manager;
}
@EventHandler(priority = EventPriority.LOWEST)
private void onPlayerInteract(PlayerInteractEvent event) {
SpectorShield shield = manager.getSpector(event.getPlayer()).getShield();
if(!shield.canInteract())
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOWEST)
private void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
SpectorShield shield = manager.getSpector(event.getPlayer()).getShield();
if(!shield.canInteract())
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOWEST)
private void onBlockBreak(BlockBreakEvent event) {
SpectorShield shield = manager.getSpector(event.getPlayer()).getShield();
if(!shield.canInteract())
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOWEST)
private void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
/*if (event.getEntity() instanceof Player) {
SpectorShield shield = manager.getSpector((Player) event.getEntity()).getShield();
if(shield.isInvincible())
event.setCancelled(true);
} else */if (event.getDamager() instanceof Player) {
SpectorShield shield = manager.getSpector((Player) event.getDamager()).getShield();
if(shield.isPeaceful())
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
private void onEntityDamage(EntityDamageEvent event) {
if (event.getEntity() instanceof Player) {
SpectorShield shield = manager.getSpector((Player) event.getEntity()).getShield();
if(shield.isInvincible())
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
private void onEntityTargetLivingEntity(EntityTargetLivingEntityEvent event) {
if(event.getTarget() instanceof Player) {
SpectorShield shield = manager.getSpector((Player) event.getTarget()).getShield();
if(!shield.isTargetable())
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
private void onAsyncPlayerChat(AsyncPlayerChatEvent event) {
SpectorShield shield = manager.getSpector(event.getPlayer()).getShield();
if(!shield.canChat())
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOWEST)
private void onAsyncPlayerChat(PlayerPickupItemEvent event) {
SpectorShield shield = manager.getSpector(event.getPlayer()).getShield();
if(!shield.canChat()) {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.RED + "Chat is disabled currently disabled for you");
}
}
@EventHandler(priority = EventPriority.LOWEST)
private void onPlayerDeath(PlayerDeathEvent event) {
SpectorShield shield = manager.getSpector(event.getEntity()).getShield();
if(!shield.canDrop())
event.getDrops().clear();
}
@EventHandler(priority = EventPriority.LOWEST)
private void onPlayerDropItem(PlayerDropItemEvent event) {
SpectorShield shield = manager.getSpector(event.getPlayer()).getShield();
if(!shield.canDrop())
event.setCancelled(true);
}
}
|
package nl.mpi.kinnate.svg;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashSet;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.apache.batik.dom.events.DOMMouseEvent;
import javax.swing.event.MouseInputAdapter;
import nl.mpi.arbil.ui.GuiHelper;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.kindata.EntityRelation;
import org.w3c.dom.Element;
public class MouseListenerSvg extends MouseInputAdapter implements EventListener {
private Cursor preDragCursor;
private GraphPanel graphPanel;
private Point startDragPoint = null;
static private boolean mouseActionOnNode = false;
static private boolean mouseActionIsPopupTrigger = false;
static private boolean mouseActionIsDrag = false;
static private String entityToToggle = null;
public enum ActionCode {
selectAll, selectRelated, expandSelection, deselectAll
}
public MouseListenerSvg(GraphPanel graphPanelLocal) {
graphPanel = graphPanelLocal;
}
@Override
public void mouseDragged(MouseEvent me) {
if (startDragPoint != null) {
// System.out.println("mouseDragged: " + me.toString());
if (graphPanel.selectedGroupId.size() > 0) {
checkSelectionClearRequired(me);
}
if (graphPanel.selectedGroupId.size() > 0) {
graphPanel.svgCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
// limit the drag to the distance draged not the location
graphPanel.svgUpdateHandler.updateDragNode(me.getPoint().x - startDragPoint.x, me.getPoint().y - startDragPoint.y);
} else {
graphPanel.svgUpdateHandler.dragCanvas(me.getPoint().x - startDragPoint.x, me.getPoint().y - startDragPoint.y);
}
mouseActionIsDrag = true;
} else {
graphPanel.svgUpdateHandler.startDrag();
}
startDragPoint = me.getPoint();
}
private void checkSelectionClearRequired(MouseEvent me) {
boolean shiftDown = me.isShiftDown();
if (!shiftDown && /* !mouseActionIsDrag && */ !mouseActionIsPopupTrigger && !mouseActionOnNode && me.getButton() == MouseEvent.BUTTON1) { // todo: button1 could cause issues for left handed people with swapped mouse buttons
System.out.println("Clear selection");
graphPanel.selectedGroupId.clear();
updateSelectionDisplay();
}
}
@Override
public void mouseReleased(MouseEvent me) {
// System.out.println("mouseReleased: " + me.toString());
graphPanel.svgCanvas.setCursor(preDragCursor);
startDragPoint = null;
if (!mouseActionIsDrag && entityToToggle != null) {
// toggle the highlight
graphPanel.selectedGroupId.remove(entityToToggle);
entityToToggle = null;
updateSelectionDisplay();
}
checkSelectionClearRequired(me);
mouseActionOnNode = false;
}
@Override
public void mousePressed(MouseEvent e) {
mouseActionIsDrag = false;
mouseActionIsPopupTrigger = e.isPopupTrigger();
}
@Override
public void handleEvent(Event evt) {
mouseActionOnNode = true;
boolean shiftDown = false;
if (evt instanceof DOMMouseEvent) {
shiftDown = ((DOMMouseEvent) evt).getShiftKey();
}
System.out.println("dom mouse event: " + evt.getCurrentTarget());
Element currentDraggedElement = ((Element) evt.getCurrentTarget());
preDragCursor = graphPanel.svgCanvas.getCursor();
// get the entityPath
// todo: change selected elements to use the ID not the path, but this change will affect th way the imdi path is obtained to show the table
String entityIdentifier = currentDraggedElement.getAttribute("id");
System.out.println("entityPath: " + entityIdentifier);
boolean nodeAlreadySelected = graphPanel.selectedGroupId.contains(entityIdentifier);
if (!shiftDown && !nodeAlreadySelected) {
System.out.println("Clear selection");
graphPanel.selectedGroupId.clear();
graphPanel.selectedGroupId.add(entityIdentifier);
} else {
// toggle the highlight
if (shiftDown && nodeAlreadySelected) {
// postpone until after a drag action can be tested for and only deselect if not draged
entityToToggle = entityIdentifier;
// graphPanel.selectedGroupId.remove(entityIdentifier);
} else if (!nodeAlreadySelected) {
graphPanel.selectedGroupId.add(entityIdentifier);
}
}
updateSelectionDisplay();
}
private void updateSelectionDisplay() {
graphPanel.svgUpdateHandler.updateSvgSelectionHighlights();
// update the table selection
if (graphPanel.arbilTableModel != null) {
graphPanel.arbilTableModel.removeAllArbilDataNodeRows();
try {
for (String currentSelectedId : graphPanel.selectedGroupId) {
String currentSelectedPath = graphPanel.getPathForElementId(currentSelectedId);
if (currentSelectedPath != null) {
graphPanel.arbilTableModel.addArbilDataNode(new URI(currentSelectedPath));
}
}
} catch (URISyntaxException urise) {
GuiHelper.linorgBugCatcher.logError(urise);
}
}
}
private void addRelations(int maxCount, EntityData currentEntity, HashSet<String> selectedIds) {
if (maxCount <= selectedIds.size()) {
return;
}
for (EntityRelation entityRelation : currentEntity.getVisiblyRelateNodes()) {
EntityData alterNode = entityRelation.getAlterNode();
if (alterNode.isVisible && !selectedIds.contains(alterNode.getUniqueIdentifier())) {
selectedIds.add(alterNode.getUniqueIdentifier());
addRelations(maxCount, alterNode, selectedIds);
}
}
}
public void performMenuAction(ActionCode commandCode) {
System.out.println("commandCode: " + commandCode.name());
switch (commandCode) {
case selectAll:
graphPanel.selectedGroupId.clear();
for (EntityData currentEntity : graphPanel.dataStoreSvg.graphData.getDataNodes()) {
if (currentEntity.isVisible) {
if (!graphPanel.selectedGroupId.contains(currentEntity.getUniqueIdentifier())) {
graphPanel.selectedGroupId.add(currentEntity.getUniqueIdentifier());
}
}
}
break;
case selectRelated:
HashSet<String> selectedIds = new HashSet<String>(graphPanel.selectedGroupId);
for (EntityData currentEntity : graphPanel.dataStoreSvg.graphData.getDataNodes()) {
if (currentEntity.isVisible) {
// todo: continue here
if (graphPanel.selectedGroupId.contains(currentEntity.getUniqueIdentifier())) {
addRelations(graphPanel.dataStoreSvg.graphData.getDataNodes().length, currentEntity, selectedIds);
}
}
}
graphPanel.selectedGroupId.clear();
graphPanel.selectedGroupId.addAll(selectedIds);
break;
case expandSelection:
// todo: continue here
break;
case deselectAll:
graphPanel.selectedGroupId.clear();
break;
}
updateSelectionDisplay();
}
}
|
package org.apdplat.word.corpus;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.apdplat.word.util.DictionaryMerge;
import org.apdplat.word.util.GramNormalizer;
import org.apdplat.word.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
*
*
* @author
*/
public class CorpusTools {
private static final Logger LOGGER = LoggerFactory.getLogger(CorpusTools.class);
private static final Map<String, Integer> BIGRAM = new HashMap<>();
private static final Map<String, Integer> TRIGRAM = new HashMap<>();
private static final AtomicInteger WORD_COUNT = new AtomicInteger();
private static final AtomicInteger CHAR_COUNT = new AtomicInteger();
private static final AtomicInteger LINES_COUNT = new AtomicInteger();
private static final Set<String> WORDS = new HashSet<>();
public static void main(String[] args){
process();
}
private static void process(){
analyzeCorpus();
processBiGram();
BIGRAM.clear();
processTriGram();
TRIGRAM.clear();
processWords();
WORDS.clear();
mergeWordsWithOldDic();
GramNormalizer.uniformAndNormForBigramAndTrigram();
}
private static void analyzeCorpus(){
String zipFile = "src/main/resources/corpus/corpora.zip";
LOGGER.info("");
long start = System.currentTimeMillis();
try{
analyzeCorpus(zipFile);
} catch (IOException ex) {
LOGGER.info(""+ex.getMessage());
}
long cost = System.currentTimeMillis() - start;
LOGGER.info(""+cost+"");
LOGGER.info(""+LINES_COUNT.get()+""+CHAR_COUNT.get()+""+WORD_COUNT.get()+""+WORDS.size());
}
/**
*
* @param zipFile
* @throws IOException
*/
private static void analyzeCorpus(String zipFile) throws IOException{
try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), CorpusTools.class.getClassLoader())) {
for(Path path : fs.getRootDirectories()){
LOGGER.info(""+path);
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
LOGGER.info(""+file);
Path temp = Paths.get("target/corpus-"+System.currentTimeMillis()+".txt");
Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING);
constructNGram(temp);
return FileVisitResult.CONTINUE;
}
});
}
}
}
/**
*
*
* @param file
*/
private static void constructNGram(Path file){
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file.toFile()),"utf-8"));){
String line;
while( (line = reader.readLine()) != null ){
LINES_COUNT.incrementAndGet();
line = line.trim();
if(!"".equals(line)){
String[] words = line.split(" ");
if(words == null){
continue;
}
List<String> list = new ArrayList<>();
StringBuilder phrase = new StringBuilder();
int phraseCount=0;
boolean find=false;
for(String word : words){
String[] attr = word.split("/");
if(attr == null || attr.length < 1){
continue;
}
if(attr[0].trim().startsWith("[")){
find = true;
}
String item = attr[0].replace("[", "").replace("]", "").trim();
list.add(item);
WORDS.add(item);
WORD_COUNT.incrementAndGet();
CHAR_COUNT.addAndGet(item.length());
if(find){
phrase.append(item);
phraseCount++;
}
if(phraseCount > 10){
find = false;
phraseCount = 0;
phrase.setLength(0);
}
if(find && attr.length > 1 && attr[1].trim().endsWith("]")){
find = false;
list.add(phrase.toString());
WORDS.add(phrase.toString());
WORD_COUNT.incrementAndGet();
phrase.setLength(0);
}
}
//bigram
int len = list.size();
if(len < 2){
continue;
}
for(int i=0; i<len-1; i++){
String first = list.get(i);
if(!Utils.isChineseCharAndLengthAtLeastOne(first)){
continue;
}
String second = list.get(i+1);
if(!Utils.isChineseCharAndLengthAtLeastOne(second)){
i++;
continue;
}
String key = first+":"+second;
Integer value = BIGRAM.get(key);
if(value == null){
value = 1;
}else{
value++;
}
BIGRAM.put(key, value);
}
if(len < 3){
continue;
}
//trigram
for(int i=0; i<len-2; i++){
String first = list.get(i);
if(!Utils.isChineseCharAndLengthAtLeastOne(first)){
continue;
}
String second = list.get(i+1);
if(!Utils.isChineseCharAndLengthAtLeastOne(second)){
i++;
continue;
}
String third = list.get(i+2);
if(!Utils.isChineseCharAndLengthAtLeastOne(third)){
i += 2;
continue;
}
String key = first+":"+second+":"+third;
Integer value = TRIGRAM.get(key);
if(value == null){
value = 1;
}else{
value++;
}
TRIGRAM.put(key, value);
}
}
}
}catch(Exception e){
LOGGER.info(" "+file+" "+e.getMessage());
}
}
/**
*
* 1
* bigram.txt
*/
private static void processBiGram() {
Iterator<String> iter = BIGRAM.keySet().iterator();
while(iter.hasNext()){
String key = iter.next();
if(BIGRAM.get(key) < 2){
iter.remove();
}
}
//bigram.txt
List<Entry<String, Integer>> items = Utils.getSortedMapByValue(BIGRAM);
try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("src/main/resources/bigram.txt"),"utf-8"))){
for(Entry<String, Integer> item : items){
writer.write(item.getKey()+" -> "+item.getValue()+"\n");
}
}catch(Exception e){
LOGGER.info("bigram"+e.getMessage());
}
}
/**
*
* 1
* trigram.txt
*/
private static void processTriGram() {
Iterator<String> iter = TRIGRAM.keySet().iterator();
while(iter.hasNext()){
String key = iter.next();
if(TRIGRAM.get(key) < 2){
iter.remove();
}
}
//trigram.txt
List<Entry<String, Integer>> items = Utils.getSortedMapByValue(TRIGRAM);
try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("src/main/resources/trigram.txt"),"utf-8"))){
for(Entry<String, Integer> item : items){
writer.write(item.getKey()+" -> "+item.getValue()+"\n");
}
}catch(Exception e){
LOGGER.info("trigram"+e.getMessage());
}
}
private static void processWords() {
try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("target/dic.txt"),"utf-8"))){
for(String word : WORDS){
if(Utils.isChineseCharAndLengthAtLeastTwo(word)){
writer.write(word+"\n");
}
}
}catch(Exception e){
LOGGER.info("target/dic.txt"+e.getMessage());
}
}
private static void mergeWordsWithOldDic() {
List<String> sources = new ArrayList<>();
sources.add("target/dic.txt");
sources.add("src/main/resources/dic.txt");
String target = "src/main/resources/dic.txt";
try {
DictionaryMerge.merge(sources, target);
} catch (IOException ex) {
LOGGER.info(""+ex.getMessage());
}
}
}
|
package org.broad.igv.session;
import org.apache.log4j.Logger;
import org.broad.igv.feature.RegionOfInterest;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.lists.GeneList;
import org.broad.igv.prefs.Constants;
import org.broad.igv.prefs.PreferencesManager;
import org.broad.igv.track.AttributeManager;
import org.broad.igv.track.Track;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.TrackFilter;
import org.broad.igv.ui.TrackFilterElement;
import org.broad.igv.ui.panel.FrameManager;
import org.broad.igv.ui.panel.ReferenceFrame;
import org.broad.igv.ui.panel.TrackPanel;
import org.broad.igv.util.FileUtils;
import org.broad.igv.util.ResourceLocator;
import org.broad.igv.util.Utilities;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.swing.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* @author jrobinso
*/
public class SessionWriter {
static Logger log = Logger.getLogger(SessionWriter.class);
private Session session;
private static int CURRENT_VERSION = 8;
private File outputFile;
private Document document;
/**
* Method description
*
* @param session
* @param outputFile
* @throws IOException
*/
public void saveSession(Session session, File outputFile) throws IOException {
if (session == null) {
RuntimeException e = new RuntimeException("No session found to save!");
log.error("Session Management Error", e);
}
this.session = session;
if (outputFile == null) {
log.error("Session Management Error: NULL outputFile");
}
String xmlString = createXmlFromSession(session, outputFile);
Writer fileWriter = null;
try {
fileWriter = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFile), "UTF8"));
fileWriter.write(xmlString);
} finally {
if (fileWriter != null) {
fileWriter.close();
}
}
}
public String createXmlFromSession(Session session, File outputFile) throws RuntimeException {
String xmlString = null;
this.session = session;
this.outputFile = outputFile;
try {
// Create a DOM document
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
document = documentBuilder.newDocument();
document.setStrictErrorChecking(true);
// Global root element
Element globalElement = document.createElement(SessionElement.SESSION);
globalElement.setAttribute(SessionAttribute.VERSION, String.valueOf(CURRENT_VERSION));
String genomeId = GenomeManager.getInstance().getGenomeId();
if (genomeId != null) {
// If genomeId is a file try to write it out as a relative path
boolean useRelative = outputFile != null &&
PreferencesManager.getPreferences().getAsBoolean(Constants.SESSION_RELATIVE_PATH);
if (useRelative && (new File(genomeId)).exists()) {
genomeId = FileUtils.getRelativePath(outputFile.getAbsolutePath(), genomeId);
}
globalElement.setAttribute(SessionAttribute.GENOME, genomeId);
}
String locus = session.getLocusString();
if (locus != null && !FrameManager.isGeneListMode()) {
globalElement.setAttribute(SessionAttribute.LOCUS, locus);
}
String groupBy = IGV.getInstance().getGroupByAttribute();
if (groupBy != null) {
globalElement.setAttribute(SessionAttribute.GROUP_TRACKS_BY, groupBy);
}
int nextAutoscaleGroup = session.getNextAutoscaleGroup();
if (nextAutoscaleGroup > 1) {
globalElement.setAttribute(SessionAttribute.NEXT_AUTOSCALE_GROUP, String.valueOf(nextAutoscaleGroup));
}
if (session.isRemoveEmptyPanels()) {
globalElement.setAttribute("removeEmptyTracks", "true");
}
globalElement.setAttribute(SessionAttribute.HAS_GENE_TRACK, "" + IGV.getInstance().hasGeneTrack());
globalElement.setAttribute(SessionAttribute.HAS_SEQ_TRACK, "" + IGV.getInstance().hasSequenceTrack());
// Resource Files
writeResources(outputFile, globalElement, document);
// Panels
writePanels(globalElement, document);
// Panel layout
writePanelLayout(globalElement, document);
// Regions of Interest
writeRegionsOfInterest(globalElement, document);
// Filter
writeFilters(session, globalElement, document);
if (FrameManager.isGeneListMode()) {
writeGeneList(globalElement, document);
}
// Hidden attributes
if (session.getHiddenAttributes() != null && session.getHiddenAttributes().size() > 0) {
writeHiddenAttributes(session, globalElement, document);
}
document.appendChild(globalElement);
// Transform document into XML
xmlString = Utilities.getString(document);
} catch (Exception e) {
String message = "An error has occurred while trying to create the session!";
log.error(message, e);
JOptionPane.showMessageDialog(IGV.getMainFrame(), message);
throw new RuntimeException(e);
}
return xmlString;
}
private void writeFilters(Session session, Element globalElement, Document document) {
TrackFilter trackFilter = session.getFilter();
if (trackFilter != null) {
Element filter = document.createElement(SessionElement.FILTER);
filter.setAttribute(SessionAttribute.NAME, trackFilter.getName());
if (IGV.getInstance().isFilterMatchAll()) {
filter.setAttribute(SessionAttribute.FILTER_MATCH, "all");
} else if (!IGV.getInstance().isFilterMatchAll()) {
filter.setAttribute(SessionAttribute.FILTER_MATCH, "any");
} else { // Defaults to match all
filter.setAttribute(SessionAttribute.FILTER_MATCH, "all");
}
if (IGV.getInstance().isFilterShowAllTracks()) {
filter.setAttribute(SessionAttribute.FILTER_SHOW_ALL_TRACKS, "true");
} else { // Defaults
filter.setAttribute(SessionAttribute.FILTER_SHOW_ALL_TRACKS, "false");
}
globalElement.appendChild(filter);
// Process FilterElement elements
Iterator iterator = session.getFilter().getFilterElements();
while (iterator.hasNext()) {
TrackFilterElement trackFilterElement = (TrackFilterElement) iterator.next();
Element filterElementElement =
document.createElement(SessionElement.FILTER_ELEMENT);
filterElementElement.setAttribute(SessionAttribute.ITEM,
trackFilterElement.getSelectedItem());
filterElementElement.setAttribute(
SessionAttribute.OPERATOR,
trackFilterElement.getComparisonOperator().getValue());
filterElementElement.setAttribute(SessionAttribute.VALUE,
trackFilterElement.getValue());
filterElementElement.setAttribute(
SessionAttribute.BOOLEAN_OPERATOR,
trackFilterElement.getBooleanOperator().getValue());
filter.appendChild(filterElementElement);
}
}
}
private void writeRegionsOfInterest(Element globalElement, Document document) {
Collection<RegionOfInterest> regions = session.getAllRegionsOfInterest();
if ((regions != null) && !regions.isEmpty()) {
Element regionsElement = document.createElement(SessionElement.REGIONS);
for (RegionOfInterest region : regions) {
Element regionElement = document.createElement(SessionElement.REGION);
regionElement.setAttribute(SessionAttribute.CHROMOSOME, region.getChr());
regionElement.setAttribute(SessionAttribute.START_INDEX, String.valueOf(region.getStart()));
regionElement.setAttribute(SessionAttribute.END_INDEX, String.valueOf(region.getEnd()));
if (region.getDescription() != null) {
regionElement.setAttribute(SessionAttribute.DESCRIPTION, region.getDescription());
}
regionsElement.appendChild(regionElement);
}
globalElement.appendChild(regionsElement);
}
}
private void writeHiddenAttributes(Session session, Element globalElement, Document document) {
Element hiddenAttributes = document.createElement(SessionElement.HIDDEN_ATTRIBUTES);
for (String attribute : session.getHiddenAttributes()) {
Element regionElement = document.createElement(SessionElement.ATTRIBUTE);
regionElement.setAttribute(SessionAttribute.NAME, attribute);
hiddenAttributes.appendChild(regionElement);
}
globalElement.appendChild(hiddenAttributes);
}
private void writeGeneList(Element globalElement, Document document) {
GeneList geneList = session.getCurrentGeneList();
if (geneList != null) {
Element geneListElement = document.createElement(SessionElement.GENE_LIST);
geneListElement.setAttribute(SessionAttribute.NAME, geneList.getName());
StringBuffer genes = new StringBuffer();
for (String gene : geneList.getLoci()) {
genes.append(gene);
genes.append("\n");
}
geneListElement.setTextContent(genes.toString());
globalElement.appendChild(geneListElement);
// Now store the list of frames visible
for (ReferenceFrame frame : FrameManager.getFrames()) {
Element frameElement = document.createElement(SessionElement.FRAME);
frameElement.setAttribute(SessionAttribute.NAME, frame.getName());
frameElement.setAttribute(SessionAttribute.CHR, frame.getChrName());
frameElement.setAttribute(SessionAttribute.START, String.valueOf(frame.getOrigin()));
frameElement.setAttribute(SessionAttribute.END, String.valueOf(frame.getEnd()));
geneListElement.appendChild(frameElement);
}
}
}
private void writeResources(File outputFile, Element globalElement, Document document) throws IOException {
Collection<ResourceLocator> resourceLocators = getResourceLocatorSet();
if ((resourceLocators != null) && !resourceLocators.isEmpty()) {
Element filesElement = document.createElement(SessionElement.RESOURCES);
for (ResourceLocator resourceLocator : resourceLocators) {
if (resourceLocator.exists() || !(resourceLocator.getPath() == null)) {
//RESOURCE ELEMENT
Element dataFileElement = document.createElement(SessionElement.RESOURCE);
String resourcePath = resourceLocator.getPath();
if (outputFile != null) {
boolean useRelative = PreferencesManager.getPreferences().getAsBoolean(Constants.SESSION_RELATIVE_PATH);
if (useRelative) {
resourcePath = FileUtils.getRelativePath(outputFile.getAbsolutePath(), resourcePath);
}
}
dataFileElement.setAttribute(SessionAttribute.PATH, resourcePath);
//OPTIONAL ATTRIBUTES
if (resourceLocator.getName() != null) {
dataFileElement.setAttribute(SessionAttribute.NAME, resourceLocator.getName());
}
if (resourceLocator.getDBUrl() != null) {
dataFileElement.setAttribute(SessionAttribute.SERVER_URL, resourceLocator.getDBUrl());
}
if (resourceLocator.getTrackInfoURL() != null) {
dataFileElement.setAttribute(SessionAttribute.HYPERLINK, resourceLocator.getTrackInfoURL());
}
if (resourceLocator.getFeatureInfoURL() != null) {
dataFileElement.setAttribute(SessionAttribute.FEATURE_URL, resourceLocator.getFeatureInfoURL());
}
if (resourceLocator.getDescription() != null) {
dataFileElement.setAttribute(SessionAttribute.DESCRIPTION, resourceLocator.getDescription());
}
if (resourceLocator.getType() != null) {
dataFileElement.setAttribute(SessionAttribute.TYPE, resourceLocator.getType());
}
if (resourceLocator.getIndexPath() != null) {
dataFileElement.setAttribute(SessionAttribute.INDEX, resourceLocator.getIndexPath());
}
if (resourceLocator.getCoverage() != null) {
dataFileElement.setAttribute(SessionAttribute.COVERAGE, resourceLocator.getCoverage());
}
if (resourceLocator.getMappingPath() != null) {
dataFileElement.setAttribute(SessionAttribute.MAPPING, resourceLocator.getMappingPath());
}
if (resourceLocator.getTrackLine() != null) {
dataFileElement.setAttribute(SessionAttribute.TRACK_LINE, resourceLocator.getTrackLine());
}
filesElement.appendChild(dataFileElement);
}
}
globalElement.appendChild(filesElement);
}
}
private void writePanels(Element globalElement, Document document) throws DOMException {
for (TrackPanel trackPanel : IGV.getInstance().getTrackPanels()) {
// TODO -- loop through panels groups, rather than skipping groups to tracks
List<Track> tracks = trackPanel.getTracks();
if ((tracks != null) && !tracks.isEmpty()) {
Element panelElement = document.createElement(SessionElement.PANEL);
panelElement.setAttribute("name", trackPanel.getName());
panelElement.setAttribute("height", String.valueOf(trackPanel.getHeight()));
panelElement.setAttribute("width", String.valueOf(trackPanel.getWidth()));
for (Track track : tracks) {
Element element = document.createElement("Track");
element.setAttribute("clazz", SessionElement.getXMLClassName(track.getClass()));
String id = track.getId();
boolean useRelative = PreferencesManager.getPreferences().getAsBoolean(Constants.SESSION_RELATIVE_PATH);
if (useRelative && !FileUtils.isRemote(id) && this.outputFile != null) {
id = FileUtils.getRelativePath(this.outputFile.getAbsolutePath(), id);
}
element.setAttribute("id", id);
track.marshalXML(document, element);
if (track.isNumeric() && track.getDataRange() != null) {
Element dataRangeElement = document.createElement(SessionElement.DATA_RANGE);
track.getDataRange().marshalXML(document, dataRangeElement);
element.appendChild(dataRangeElement);
}
panelElement.appendChild(element);
}
globalElement.appendChild(panelElement);
}
}
}
private void writePanelLayout(Element globalElement, Document document) {
double[] dividerFractions = IGV.getInstance().getMainPanel().getDividerFractions();
if (dividerFractions.length > 0) {
Element panelLayout = document.createElement(SessionElement.PANEL_LAYOUT);
globalElement.appendChild(panelLayout);
StringBuffer locString = new StringBuffer();
locString.append(String.valueOf(dividerFractions[0]));
for (int i = 1; i < dividerFractions.length; i++) {
locString.append("," + dividerFractions[i]);
}
panelLayout.setAttribute("dividerFractions", locString.toString());
}
}
/**
* @return A set of the load data files.
*/
public Collection<ResourceLocator> getResourceLocatorSet() {
Collection<ResourceLocator> locators = new ArrayList();
Collection<ResourceLocator> currentTrackFileLocators =
IGV.getInstance().getDataResourceLocators();
if (currentTrackFileLocators != null) {
for (ResourceLocator locator : currentTrackFileLocators) {
locators.add(locator);
}
}
Collection<ResourceLocator> loadedAttributeResources =
AttributeManager.getInstance().getLoadedResources();
if (loadedAttributeResources != null) {
for (ResourceLocator attributeLocator : loadedAttributeResources) {
locators.add(attributeLocator);
}
}
return locators;
}
}
|
package org.cs4j.core.mains;
import org.cs4j.core.SearchDomain;
import org.cs4j.core.domains.*;
import java.io.*;
public class DomainsCreation {
public static SearchDomain createGridPathFindingInstanceFromAutomaticallyGenerated(String instance) throws FileNotFoundException {
InputStream is = new FileInputStream(new File("input/gridpathfinding/generated/brc202d.map/" + instance));
return new GridPathFinding(is);
}
public static SearchDomain createGridPathFindingInstanceFromAutomaticallyGeneratedWithTDH(String instance)
throws IOException {
String mapFileName = "input/gridpathfinding/generated/brc202d";
String pivotsFileName = "input/gridpathfinding/raw/maps/" + new File(mapFileName).getName() + ".pivots";
int pivotsCount = 10;
InputStream is = new FileInputStream(new File(mapFileName + ".map/" + instance));
GridPathFinding problem = new GridPathFinding(is);
problem.setAdditionalParameter("heuristic", "tdh-furthest");
problem.setAdditionalParameter("pivots-distances-pdb-file", pivotsFileName);
problem.setAdditionalParameter("pivots-count", pivotsCount + "");
return problem;
}
// The k is for GAP-k heuristic setting
public static SearchDomain createPancakesInstanceFromAutomaticallyGenerated(int size, String instance, int k) throws FileNotFoundException {
Pancakes toReturn = null;
String filename = "input/pancakes/generated-" + size + "/" + instance;
try {
InputStream is = new FileInputStream(new File(filename));
toReturn = new Pancakes(is);
toReturn.setAdditionalParameter("GAP-k", k + "");
} catch (FileNotFoundException e) {
System.out.println("[WARNING] File " + filename + " not found");
}
return toReturn;
}
public static SearchDomain createPancakesInstanceFromAutomaticallyGenerated(String instance) throws FileNotFoundException {
String filename = "input/pancakes/generated-10/" + instance;
try {
InputStream is = new FileInputStream(new File(filename));
return new Pancakes(is);
} catch (FileNotFoundException e) {
System.out.println("[WARNING] File " + filename + " not found");
return null;
}
}
public static SearchDomain createVacuumRobotInstanceFromAutomaticallyGenerated(String instance) throws FileNotFoundException {
InputStream is = new FileInputStream(new File("input/vacuumrobot/generated/" + instance));
return new VacuumRobot(is);
}
public static SearchDomain create15PuzzleInstanceFromKorfInstances(String instance) throws FileNotFoundException {
InputStream is = new FileInputStream(new File("input/fifteenpuzzle/korf100/" + instance));
return new FifteenPuzzle(is);
}
public static SearchDomain createDockyardRobotInstanceFromAutomaticallyGenerated(String instance) throws FileNotFoundException {
InputStream is = new FileInputStream(new File("input/dockyardrobot/generated/" + instance));
return new DockyardRobot(is);
}
}
|
package org.dita.dost.reader;
import org.dita.dost.log.MessageUtils;
import org.dita.dost.module.ChunkModule.ChunkFilenameGenerator;
import org.dita.dost.module.ChunkModule.ChunkFilenameGeneratorFactory;
import org.dita.dost.module.GenMapAndTopicListModule.TempFileNameScheme;
import org.dita.dost.util.DitaClass;
import org.dita.dost.util.Job;
import org.dita.dost.util.Job.FileInfo;
import org.dita.dost.util.XMLSerializer;
import org.dita.dost.writer.AbstractDomFilter;
import org.dita.dost.writer.ChunkTopicParser;
import org.dita.dost.writer.SeparateChunkTopicParser;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.Collections.unmodifiableSet;
import static org.apache.commons.io.FilenameUtils.getBaseName;
import static org.dita.dost.util.Constants.*;
import static org.dita.dost.util.FileUtils.getFragment;
import static org.dita.dost.util.FileUtils.replaceExtension;
import static org.dita.dost.util.StringUtils.join;
import static org.dita.dost.util.StringUtils.split;
import static org.dita.dost.util.URLUtils.*;
import static org.dita.dost.util.XMLUtils.*;
/**
* ChunkMapReader class, read and filter ditamap file for chunking.
*/
// TODO rename this because this is not a reader, it's a filter
public final class ChunkMapReader extends AbstractDomFilter {
public static final String FILE_NAME_STUB_DITAMAP = "stub.ditamap";
public static final String FILE_EXTENSION_CHUNK = ".chunk";
public static final String ATTR_XTRF_VALUE_GENERATED = "generated_by_chunk";
public static final String CHUNK_SELECT_BRANCH = "select-branch";
public static final String CHUNK_SELECT_TOPIC = "select-topic";
public static final String CHUNK_SELECT_DOCUMENT = "select-document";
private static final String CHUNK_BY_DOCUMENT = "by-document";
private static final String CHUNK_BY_TOPIC = "by-topic";
public static final String CHUNK_TO_CONTENT = "to-content";
public static final String CHUNK_TO_NAVIGATION = "to-navigation";
public static final String CHUNK_PREFIX = "Chunk";
private TempFileNameScheme tempFileNameScheme;
private Collection<String> rootChunkOverride;
private String defaultChunkByToken;
// ChunkTopicParser assumes keys and values are chimera paths, i.e. systems paths with fragments.
private final LinkedHashMap<URI, URI> changeTable = new LinkedHashMap<>(128);
private final Map<URI, URI> conflictTable = new HashMap<>(128);
private boolean supportToNavigation;
private ProcessingInstruction workdir = null;
private ProcessingInstruction workdirUrl = null;
private ProcessingInstruction path2proj = null;
private ProcessingInstruction path2projUrl = null;
private ProcessingInstruction path2rootmapUrl = null;
private final ChunkFilenameGenerator chunkFilenameGenerator = ChunkFilenameGeneratorFactory.newInstance();
@Override
public void setJob(final Job job) {
super.setJob(job);
try {
tempFileNameScheme = (TempFileNameScheme) Class.forName(job.getProperty("temp-file-name-scheme")).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
tempFileNameScheme.setBaseDir(job.getInputDir());
}
public void setRootChunkOverride(final String chunkValue) {
rootChunkOverride = split(chunkValue);
}
/**
* Absolute URI to file being processed
*/
private URI currentFile;
/**
* read input file.
*
* @param inputFile filename
*/
@Override
public void read(final File inputFile) {
this.currentFile = inputFile.toURI();
super.read(inputFile);
}
@Override
public Document process(final Document doc) {
readLinks(doc);
readProcessingInstructions(doc);
final Element root = doc.getDocumentElement();
if (rootChunkOverride != null) {
final String c = join(rootChunkOverride, " ");
logger.debug("Use override root chunk \"" + c + "\"");
root.setAttribute(ATTRIBUTE_NAME_CHUNK, c);
}
final Collection<String> rootChunk = split(root.getAttribute(ATTRIBUTE_NAME_CHUNK));
defaultChunkByToken = getChunkByToken(rootChunk, "by-", CHUNK_BY_DOCUMENT);
if (rootChunk.contains(CHUNK_TO_CONTENT)) {
chunkMap(root);
} else {
for (final Element currentElem : getChildElements(root)) {
if (MAP_RELTABLE.matches(currentElem)) {
updateReltable(currentElem);
} else if (MAP_TOPICREF.matches(currentElem)) {
processTopicref(currentElem);
}
}
}
return buildOutputDocument(root);
}
private final Set<URI> chunkTopicSet = new HashSet<>();
/**
* @return absolute temporary files
*/
public Set<URI> getChunkTopicSet() {
return unmodifiableSet(chunkTopicSet);
}
private void readLinks(final Document doc) {
final Element root = doc.getDocumentElement();
readLinks(root, false, false);
}
private void readLinks(final Element elem, final boolean chunk, final boolean disabled) {
final boolean c = chunk || elem.getAttributeNode(ATTRIBUTE_NAME_CHUNK) != null;
final boolean d = disabled
|| elem.getAttribute(ATTRIBUTE_NAME_CHUNK).contains(CHUNK_TO_NAVIGATION)
|| (MAPGROUP_D_TOPICGROUP.matches(elem) && !SUBMAP.matches(elem))
|| MAP_RELTABLE.matches(elem);
final Attr href = elem.getAttributeNode(ATTRIBUTE_NAME_HREF);
if (href != null) {
final URI filename = stripFragment(currentFile.resolve(href.getValue()));
if (c && !d) {
chunkTopicSet.add(filename);
final Attr copyTo = elem.getAttributeNode(ATTRIBUTE_NAME_COPY_TO);
if (copyTo != null) {
final URI copyToFile = stripFragment(currentFile.resolve(copyTo.getValue()));
chunkTopicSet.add(copyToFile);
}
}
}
for (final Element topicref : getChildElements(elem, MAP_TOPICREF)) {
readLinks(topicref, c, d);
}
}
public static String getChunkByToken(final Collection<String> chunkValue, final String category, final String defaultToken) {
if (chunkValue.isEmpty()) {
return defaultToken;
}
for (final String token : chunkValue) {
if (token.startsWith(category)) {
return token;
}
}
return defaultToken;
}
/**
* Process map when "to-content" is specified on map element.
* <p>
* TODO: Instead of reclassing map element to be a topicref, add a topicref
* into the map root and move all map content into that topicref.
*/
private void chunkMap(final Element root) {
// create the reference to the new file on root element.
String newFilename = replaceExtension(new File(currentFile).getName(), FILE_EXTENSION_DITA);
URI newFile = currentFile.resolve(newFilename);
if (new File(newFile).exists()) {
final URI oldFile = newFile;
newFilename = chunkFilenameGenerator.generateFilename(CHUNK_PREFIX, FILE_EXTENSION_DITA);
newFile = currentFile.resolve(newFilename);
// Mark up the possible name changing, in case that references might be updated.
conflictTable.put(newFile, oldFile.normalize());
}
changeTable.put(newFile, newFile);
// change the class attribute to "topicref"
final String origCls = root.getAttribute(ATTRIBUTE_NAME_CLASS);
root.setAttribute(ATTRIBUTE_NAME_CLASS, origCls + MAP_TOPICREF.matcher);
root.setAttribute(ATTRIBUTE_NAME_HREF, toURI(newFilename).toString());
createTopicStump(newFile);
// process chunk
processTopicref(root);
// restore original root element
if (origCls != null) {
root.setAttribute(ATTRIBUTE_NAME_CLASS, origCls);
}
root.removeAttribute(ATTRIBUTE_NAME_HREF);
}
/**
* Create the new topic stump.
*/
private void createTopicStump(final URI newFile) {
try (final OutputStream newFileWriter = new FileOutputStream(new File(newFile))) {
final XMLStreamWriter o = XMLOutputFactory.newInstance().createXMLStreamWriter(newFileWriter, UTF8);
o.writeStartDocument();
o.writeProcessingInstruction(PI_WORKDIR_TARGET, UNIX_SEPARATOR + new File(newFile.resolve(".")).getAbsolutePath());
o.writeProcessingInstruction(PI_WORKDIR_TARGET_URI, newFile.resolve(".").toString());
o.writeStartElement(ELEMENT_NAME_DITA);
o.writeEndElement();
o.writeEndDocument();
o.close();
newFileWriter.flush();
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
logger.error(e.getMessage(), e);
}
}
/**
* Read processing metadata from processing instructions.
*/
private void readProcessingInstructions(final Document doc) {
final NodeList docNodes = doc.getChildNodes();
for (int i = 0; i < docNodes.getLength(); i++) {
final Node node = docNodes.item(i);
if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
final ProcessingInstruction pi = (ProcessingInstruction) node;
switch (pi.getNodeName()) {
case PI_WORKDIR_TARGET:
workdir = pi;
break;
case PI_WORKDIR_TARGET_URI:
workdirUrl = pi;
break;
case PI_PATH2PROJ_TARGET:
path2proj = pi;
break;
case PI_PATH2PROJ_TARGET_URI:
path2projUrl = pi;
break;
case PI_PATH2ROOTMAP_TARGET_URI:
path2rootmapUrl = pi;
break;
}
}
}
}
private void outputMapFile(final URI file, final Document doc) {
Result result = null;
try {
final Transformer t = TransformerFactory.newInstance().newTransformer();
result = new StreamResult(new FileOutputStream(new File(file)));
t.transform(new DOMSource(doc), result);
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
logger.error(e.getMessage(), e);
} finally {
try {
close(result);
} catch (final IOException e) {
logger.error(e.getMessage(), e);
}
}
}
private Document buildOutputDocument(final Element root) {
final Document doc = getDocumentBuilder().newDocument();
if (workdir != null) {
doc.appendChild(doc.importNode(workdir, true));
}
if (workdirUrl != null) {
doc.appendChild(doc.importNode(workdirUrl, true));
}
if (path2proj != null) {
doc.appendChild(doc.importNode(path2proj, true));
}
if (path2projUrl != null) {
doc.appendChild(doc.importNode(path2projUrl, true));
}
if (path2rootmapUrl != null) {
doc.appendChild(doc.importNode(path2rootmapUrl, true));
}
doc.appendChild(doc.importNode(root, true));
return doc;
}
private void processTopicref(final Element topicref) {
final String xtrf = getValue(topicref, ATTRIBUTE_NAME_XTRF);
if (xtrf != null && xtrf.contains(ATTR_XTRF_VALUE_GENERATED)) {
return;
}
final Collection<String> chunk = split(getValue(topicref, ATTRIBUTE_NAME_CHUNK));
final URI href = toURI(getValue(topicref, ATTRIBUTE_NAME_HREF));
final URI copyTo = toURI(getValue(topicref, ATTRIBUTE_NAME_COPY_TO));
final String scope = getCascadeValue(topicref, ATTRIBUTE_NAME_SCOPE);
final String chunkByToken = getChunkByToken(chunk, "by-", defaultChunkByToken);
if (ATTR_SCOPE_VALUE_EXTERNAL.equals(scope)
|| (href != null && !toFile(currentFile.resolve(href.toString())).exists())
|| (chunk.isEmpty() && href == null)) {
processChildTopicref(topicref);
} else if (chunk.contains(CHUNK_TO_CONTENT)) {
if (href != null || copyTo != null || topicref.hasChildNodes()) {
if (chunk.contains(CHUNK_BY_TOPIC)) {
logger.warn(MessageUtils.getMessage("DOTJ064W").setLocation(topicref).toString());
}
if (href == null) {
generateStumpTopic(topicref);
}
processCombineChunk(topicref);
}
} else if (chunk.contains(CHUNK_TO_NAVIGATION)
&& supportToNavigation) {
processChildTopicref(topicref);
processNavitation(topicref);
} else if (chunkByToken.equals(CHUNK_BY_TOPIC)) {
if (href != null) {
processSeparateChunk(topicref);
}
processChildTopicref(topicref);
} else { // chunkByToken.equals(CHUNK_BY_DOCUMENT)
URI currentPath = null;
if (copyTo != null) {
currentPath = currentFile.resolve(copyTo);
} else if (href != null) {
currentPath = currentFile.resolve(href);
}
if (currentPath != null) {
changeTable.remove(currentPath);
final String processingRole = getCascadeValue(topicref, ATTRIBUTE_NAME_PROCESSING_ROLE);
if (!ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equals(processingRole)) {
changeTable.put(currentPath, currentPath);
}
}
processChildTopicref(topicref);
}
}
/**
* Create new map and refer to it with navref.
*/
private void processNavitation(final Element topicref) {
// create new map's root element
final Element root = (Element) topicref.getOwnerDocument().getDocumentElement().cloneNode(false);
// create navref element
final Element navref = topicref.getOwnerDocument().createElement(MAP_NAVREF.localName);
final String newMapFile = chunkFilenameGenerator.generateFilename("MAPCHUNK", FILE_EXTENSION_DITAMAP);
navref.setAttribute(ATTRIBUTE_NAME_MAPREF, newMapFile);
navref.setAttribute(ATTRIBUTE_NAME_CLASS, MAP_NAVREF.toString());
// replace topicref with navref
topicref.getParentNode().replaceChild(navref, topicref);
root.appendChild(topicref);
// generate new file
final URI navmap = currentFile.resolve(newMapFile);
changeTable.put(stripFragment(navmap), stripFragment(navmap));
outputMapFile(navmap, buildOutputDocument(root));
}
/**
* Generate file name.
*
* @return generated file name
*/
private String generateFilename() {
return chunkFilenameGenerator.generateFilename(CHUNK_PREFIX, FILE_EXTENSION_DITA);
}
/**
* Generate stump topic for to-content content.
*
* @param topicref topicref without href to generate stump topic for
*/
private void generateStumpTopic(final Element topicref) {
final URI result = getResultFile(topicref);
final URI temp = tempFileNameScheme.generateTempFileName(result);
final URI absTemp = job.tempDir.toURI().resolve(temp);
final String name = getBaseName(new File(result).getName());
String navtitle = getChildElementValueOfTopicmeta(topicref, TOPIC_NAVTITLE);
if (navtitle == null) {
navtitle = getValue(topicref, ATTRIBUTE_NAME_NAVTITLE);
}
final String shortDesc = getChildElementValueOfTopicmeta(topicref, MAP_SHORTDESC);
writeChunk(absTemp, name, navtitle, shortDesc);
// update current element's @href value
final URI relativePath = getRelativePath(currentFile.resolve(FILE_NAME_STUB_DITAMAP), absTemp);
topicref.setAttribute(ATTRIBUTE_NAME_HREF, relativePath.toString());
if (MAPGROUP_D_TOPICGROUP.matches(topicref)) {
topicref.setAttribute(ATTRIBUTE_NAME_CLASS, MAP_TOPICREF.toString());
}
final URI relativeToBase = getRelativePath(job.tempDirURI.resolve("dummy"), absTemp);
final FileInfo fi = new FileInfo.Builder()
.uri(temp)
.result(result)
.format(ATTR_FORMAT_VALUE_DITA)
.build();
job.add(fi);
}
private void writeChunk(final URI outputFileName, String id, String title, String shortDesc) {
try (final OutputStream output = new FileOutputStream(new File(outputFileName))) {
final XMLSerializer serializer = XMLSerializer.newInstance(output);
serializer.writeStartDocument();
if (title == null && shortDesc == null) {
//topicgroup with no title, no shortdesc, just need a non titled stub
serializer.writeStartElement(ELEMENT_NAME_DITA);
serializer.writeAttribute(DITA_NAMESPACE, ATTRIBUTE_PREFIX_DITAARCHVERSION + ":" + ATTRIBUTE_NAME_DITAARCHVERSION, "1.3");
serializer.writeEndElement(); // dita
} else {
serializer.writeStartElement(TOPIC_TOPIC.localName);
serializer.writeAttribute(DITA_NAMESPACE, ATTRIBUTE_PREFIX_DITAARCHVERSION + ":" + ATTRIBUTE_NAME_DITAARCHVERSION, "1.3");
serializer.writeAttribute(ATTRIBUTE_NAME_ID, id);
serializer.writeAttribute(ATTRIBUTE_NAME_CLASS, TOPIC_TOPIC.toString());
serializer.writeAttribute(ATTRIBUTE_NAME_DOMAINS, "");
serializer.writeStartElement(TOPIC_TITLE.localName);
serializer.writeAttribute(ATTRIBUTE_NAME_CLASS, TOPIC_TITLE.toString());
if (title != null) {
serializer.writeCharacters(title);
}
serializer.writeEndElement(); // title
if (shortDesc != null) {
serializer.writeStartElement(TOPIC_SHORTDESC.localName);
serializer.writeAttribute(ATTRIBUTE_NAME_CLASS, TOPIC_SHORTDESC.toString());
serializer.writeCharacters(shortDesc);
serializer.writeEndElement(); // shortdesc
}
serializer.writeEndElement(); // topic
}
serializer.writeEndDocument();
serializer.close();
} catch (final IOException | SAXException e) {
logger.error("Failed to write generated chunk: " + e.getMessage(), e);
}
}
private URI getResultFile(final Element topicref) {
final FileInfo curr = job.getFileInfo(currentFile);
final URI copyTo = toURI(getValue(topicref, ATTRIBUTE_NAME_COPY_TO));
final String id = getValue(topicref, ATTRIBUTE_NAME_ID);
URI outputFileName;
if (copyTo != null) {
outputFileName = curr.result.resolve(copyTo);
} else if (id != null) {
outputFileName = curr.result.resolve(id + FILE_EXTENSION_DITA);
} else {
final Set<URI> results = job.getFileInfo().stream().map(fi -> fi.result).collect(Collectors.toSet());
do {
outputFileName = curr.result.resolve(generateFilename());
} while (results.contains(outputFileName));
}
return outputFileName;
}
/**
* get topicmeta's child(e.g navtitle, shortdesc) tag's value(text-only).
*
* @param element input element
* @return text value
*/
private String getChildElementValueOfTopicmeta(final Element element, final DitaClass classValue) {
if (element.hasChildNodes()) {
final Element topicMeta = getElementNode(element, MAP_TOPICMETA);
if (topicMeta != null) {
final Element elem = getElementNode(topicMeta, classValue);
if (elem != null) {
return getText(elem);
}
}
}
return null;
}
private void processChildTopicref(final Element node) {
final List<Element> children = getChildElements(node, MAP_TOPICREF);
for (final Element currentElem : children) {
final URI href = toURI(getValue(currentElem, ATTRIBUTE_NAME_HREF));
final String xtrf = currentElem.getAttribute(ATTRIBUTE_NAME_XTRF);
if (href == null) {
processTopicref(currentElem);
} else if (!ATTR_XTRF_VALUE_GENERATED.equals(xtrf)
&& !currentFile.resolve(href).equals(changeTable.get(currentFile.resolve(href)))) {
processTopicref(currentElem);
}
}
}
private void processSeparateChunk(final Element topicref) {
final SeparateChunkTopicParser chunkParser = new SeparateChunkTopicParser();
chunkParser.setLogger(logger);
chunkParser.setJob(job);
chunkParser.setup(changeTable, conflictTable, topicref, chunkFilenameGenerator);
chunkParser.write(currentFile);
}
private void processCombineChunk(final Element topicref) {
final ChunkTopicParser chunkParser = new ChunkTopicParser();
chunkParser.setLogger(logger);
chunkParser.setJob(job);
createChildTopicrefStubs(getChildElements(topicref, MAP_TOPICREF));
chunkParser.setup(changeTable, conflictTable, topicref, chunkFilenameGenerator);
chunkParser.write(currentFile);
}
//Before combining topics in a branch, ensure any descendant topicref with @chunk and no @href has a stub
private void createChildTopicrefStubs(final List<Element> topicrefs) {
if (!topicrefs.isEmpty()) {
for (final Element currentElem : topicrefs) {
final String href = getValue(currentElem, ATTRIBUTE_NAME_HREF);
final String chunk = getValue(currentElem,ATTRIBUTE_NAME_CHUNK);
if (href == null && chunk != null) {
generateStumpTopic(currentElem);
}
createChildTopicrefStubs(getChildElements(currentElem, MAP_TOPICREF));
}
}
}
private void updateReltable(final Element elem) {
final String href = elem.getAttribute(ATTRIBUTE_NAME_HREF);
if (href.length() != 0) {
if (changeTable.containsKey(currentFile.resolve(href))) {
URI res = getRelativePath(currentFile.resolve(FILE_NAME_STUB_DITAMAP),
currentFile.resolve(href));
final String fragment = getFragment(href);
if (fragment != null) {
res = setFragment(res, fragment);
}
elem.setAttribute(ATTRIBUTE_NAME_HREF, res.toString());
}
}
final NodeList children = elem.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
final Node current = children.item(i);
if (current.getNodeType() == Node.ELEMENT_NODE) {
final Element currentElem = (Element) current;
final String cls = currentElem.getAttribute(ATTRIBUTE_NAME_CLASS);
if (MAP_TOPICREF.matches(cls)) {
// FIXME: What should happen here?
}
}
}
}
/**
* Get changed files table.
*
* @return map of changed files, absolute temporary files
*/
public Map<URI, URI> getChangeTable() {
for (final Map.Entry<URI, URI> e : changeTable.entrySet()) {
assert e.getKey().isAbsolute();
assert e.getValue().isAbsolute();
}
return Collections.unmodifiableMap(changeTable);
}
/**
* get conflict table.
*
* @return conflict table, absolute temporary files
*/
public Map<URI, URI> getConflicTable() {
for (final Map.Entry<URI, URI> e : conflictTable.entrySet()) {
assert e.getKey().isAbsolute();
assert e.getValue().isAbsolute();
}
return conflictTable;
}
/**
* Support chunk token to-navigation.
*
* @param supportToNavigation flag to enable to-navigation support
*/
public void supportToNavigation(final boolean supportToNavigation) {
this.supportToNavigation = supportToNavigation;
}
}
|
package org.experiment.TREC;
import java.io.File;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.file.Paths;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.search.similarities.*;
import org.apache.lucene.store.*;
import org.apache.lucene.benchmark.quality.*;
import org.apache.lucene.benchmark.quality.utils.*;
import org.apache.lucene.benchmark.quality.trec.*;
public class PrecisionRecall {
public static void main(String[] args) throws Throwable {
String index = "/home/datasets/TREC/index";
String simstring = "bm25";
String field = "contents";
String docNameField = "docno";
File topicsFile = new File("/home/datasets/TREC/WT2G/topics/topics.wt2g");
File qrelsFile = new File("/home/datasets/TREC/WT2G/Golden Standard/qrels.wt2g");
Similarity simfn = null;
if ("default".equals(simstring)) {
simfn = new ClassicSimilarity();
} else if ("bm25".equals(simstring)) {
simfn = new BM25Similarity();
} else if ("dfr".equals(simstring)) {
simfn = new DFRSimilarity(new BasicModelP(), new AfterEffectL(), new NormalizationH2());
} else if ("lm".equals(simstring)) {
simfn = new LMDirichletSimilarity();
}
IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(index)));
IndexSearcher searcher = new IndexSearcher(reader);
searcher.setSimilarity(simfn);
PrintWriter logger = new PrintWriter("test-data/precision-recall.out", "UTF-8");
PrintWriter logger2 = new PrintWriter("test-data/precision-recall2.out", "UTF-8");
TrecTopicsReader qReader = new TrecTopicsReader();
QualityQuery qqs[] = qReader.readQueries(new BufferedReader(new FileReader(topicsFile)));
Judge judge = new TrecJudge(new BufferedReader(new FileReader(qrelsFile)));
judge.validateData(qqs, logger);
QualityQueryParser qqParser = new SimpleQQParser("title", "contents");
QualityBenchmark qrun = new QualityBenchmark(qqs, qqParser, searcher, docNameField);
SubmissionReport submitLog = new SubmissionReport(logger2, simstring);
//TODO
QualityStats stats[] = qrun.execute(judge, submitLog, logger);
QualityStats qualityStats = QualityStats.average(stats);
qualityStats.log("SUMMARY", 2,logger, " ");
logger.close();
// dir.close();
}
}
|
package org.globsframework.utils;
public class NanoChrono {
private long start;
public NanoChrono() {
start = System.nanoTime();
}
public static NanoChrono start() {
return new NanoChrono();
}
public void reset() {
start = System.nanoTime();
}
public double getAndResetElapsedTimeInMS() {
long tmp = System.nanoTime();
double current = ((int) ((tmp - start) / 1000.)) / 1000.;
start = tmp;
return current;
}
public double getElapsedTimeInMS() {
return ((int) ((System.nanoTime() - start) / 1000.)) / 1000.;
}
}
|
package org.hyperfresh.mc.liquidf;
import org.hyperfresh.mc.liquidf.enums.LqClickEvent;
import org.hyperfresh.mc.liquidf.enums.LqColor;
import org.hyperfresh.mc.liquidf.enums.LqFormat;
import org.hyperfresh.mc.liquidf.enums.LqHoverEvent;
import java.util.ArrayList;
import java.util.List;
/**
* Builds up a chat message to be output to JSON or legacy.
*
* @author octopod
*/
public class LqMessage
{
private final List<LqText> textList = new ArrayList<>();
LqColor color = LqColor.WHITE;
LqFormat[] formats = LqFormat.NO_FORMATS;
LqClickEvent click = null;
LqText clickValue = LqText.BLANK;
LqHoverEvent hover = null;
LqText hoverValue = LqText.BLANK;
/**
* Primes a color to be used in the next added text.
*
* @param color
* @return
*/
public LqMessage color(LqColor color)
{
this.color = color;
return this;
}
/**
* Primes formats to be used in the next added text.
*
* @param formats
* @return
*/
public LqMessage format(LqFormat... formats)
{
this.formats = formats;
return this;
}
public LqMessage text(String text)
{
if(click == null && hover == null)
{
//use LqText instead
textList.add(new LqText(text, color, formats));
}
else
{
//use LqTextFancy
textList.add(new LqTextFancy(text, color, formats,
click, clickValue, hover, hoverValue));
}
return this;
}
/**
* Returns the legacy version of this message.
*
* @return the legacy string
*/
public String toString()
{
StringBuilder sb = new StringBuilder();
textList.stream().forEach(sb::append);
return sb.toString();
}
/**
* Returns the JSON version of this message.
*
* @return the JSON string
*/
public String toJSONString()
{
}
}
|
package org.jboss.threads;
import java.util.concurrent.RejectedExecutionException;
class RejectingExecutor implements DirectExecutor {
static final RejectingExecutor INSTANCE = new RejectingExecutor();
private final String message;
private RejectingExecutor() {
message = null;
}
RejectingExecutor(final String message) {
this.message = message;
}
public void execute(final Runnable command) {
throw new RejectedExecutionException(message);
}
public String toString() {
return "Rejecting executor";
}
}
|
package org.jcodec.api.transcode;
import static org.jcodec.common.io.NIOUtils.readableFileChannel;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.sourceforge.jaad.aac.AACException;
import org.jcodec.codecs.aac.AACDecoder;
import org.jcodec.codecs.h264.BufferH264ES;
import org.jcodec.codecs.h264.H264Decoder;
import org.jcodec.codecs.h264.H264Utils;
import org.jcodec.codecs.mjpeg.JpegDecoder;
import org.jcodec.codecs.mpeg12.MPEGDecoder;
import org.jcodec.codecs.png.PNGDecoder;
import org.jcodec.codecs.prores.ProresDecoder;
import org.jcodec.codecs.raw.RAWVideoDecoder;
import org.jcodec.codecs.vpx.VP8Decoder;
import org.jcodec.codecs.wav.WavDemuxer;
import org.jcodec.common.AudioCodecMeta;
import org.jcodec.common.AudioDecoder;
import org.jcodec.common.AudioFormat;
import org.jcodec.common.Codec;
import org.jcodec.common.Demuxer;
import org.jcodec.common.DemuxerTrack;
import org.jcodec.common.DemuxerTrackMeta;
import org.jcodec.common.Format;
import org.jcodec.common.SeekableDemuxerTrack;
import org.jcodec.common.Tuple._3;
import org.jcodec.common.VideoCodecMeta;
import org.jcodec.common.VideoDecoder;
import org.jcodec.common.io.IOUtils;
import org.jcodec.common.io.NIOUtils;
import org.jcodec.common.io.SeekableByteChannel;
import org.jcodec.common.logging.Logger;
import org.jcodec.common.model.AudioBuffer;
import org.jcodec.common.model.Packet;
import org.jcodec.common.model.Packet.FrameType;
import org.jcodec.common.model.Picture8Bit;
import org.jcodec.common.model.Size;
import org.jcodec.containers.imgseq.ImageSequenceDemuxer;
import org.jcodec.containers.mkv.demuxer.MKVDemuxer;
import org.jcodec.containers.mp4.demuxer.MP4Demuxer;
import org.jcodec.containers.mps.MPSDemuxer;
import org.jcodec.containers.mps.MTSDemuxer;
import org.jcodec.containers.mps.MPEGDemuxer.MPEGDemuxerTrack;
import org.jcodec.containers.webp.WebpDemuxer;
import org.jcodec.containers.y4m.Y4MDemuxer;
/**
* A source producing uncompressed video/audio streams out of a compressed file.
*
* The buffers for the frames coming out of this source will be borrowed from a
* pixel store and must be returned to it for maximum efficiency.
*
* @author Stanislav Vitvitskiy
*/
public class SourceImpl implements Source, PacketSource {
private String sourceName;
private SeekableByteChannel sourceStream;
private Demuxer demuxVideo;
private Demuxer demuxAudio;
private Format inputFormat;
private DemuxerTrack videoInputTrack;
private DemuxerTrack audioInputTrack;
private _3<Integer, Integer, Codec> inputVideoCodec;
private _3<Integer, Integer, Codec> inputAudioCodec;
private List<VideoFrameWithPacket> frameReorderBuffer = new ArrayList<VideoFrameWithPacket>();
private List<Packet> videoPacketReorderBuffer = new ArrayList<Packet>();
private PixelStore pixelStore;
private VideoCodecMeta videoCodecMeta;
private AudioCodecMeta audioCodecMeta;
private AudioDecoder audioDecoder;
private VideoDecoder videoDecoder;
private Integer downscale;
public void initDemuxer() throws FileNotFoundException, IOException {
if (inputFormat != Format.IMG)
sourceStream = readableFileChannel(sourceName);
switch (inputFormat) {
case MOV:
demuxVideo = demuxAudio = new MP4Demuxer(sourceStream);
break;
case MKV:
demuxVideo = demuxAudio = new MKVDemuxer(sourceStream);
break;
case IMG:
demuxVideo = new ImageSequenceDemuxer(sourceName, Integer.MAX_VALUE);
break;
case WEBP:
demuxVideo = new WebpDemuxer(sourceStream);
break;
case MPEG_PS:
demuxVideo = demuxAudio = new MPSDemuxer(sourceStream);
break;
case Y4M:
Y4MDemuxer y4mDemuxer = new Y4MDemuxer(sourceStream);
demuxVideo = demuxAudio = y4mDemuxer;
videoInputTrack = y4mDemuxer;
break;
case H264:
demuxVideo = new BufferH264ES(NIOUtils.fetchFromChannel(sourceStream));
break;
case WAV:
demuxAudio = new WavDemuxer(sourceStream);
break;
case MPEG_TS:
MTSDemuxer mtsDemuxer = new MTSDemuxer(sourceStream);
MPSDemuxer mpsDemuxer = null;
if (inputVideoCodec != null) {
mpsDemuxer = new MPSDemuxer(mtsDemuxer.getProgram(inputVideoCodec.v0));
videoInputTrack = openTSTrack(mpsDemuxer, inputVideoCodec.v1);
demuxVideo = mpsDemuxer;
}
if (inputAudioCodec != null) {
if (inputVideoCodec == null || inputVideoCodec.v0 != inputAudioCodec.v0) {
mpsDemuxer = new MPSDemuxer(mtsDemuxer.getProgram(inputAudioCodec.v0));
}
audioInputTrack = openTSTrack(mpsDemuxer, inputAudioCodec.v1);
demuxAudio = mpsDemuxer;
}
for (int pid : mtsDemuxer.getPrograms()) {
if ((inputVideoCodec == null || pid != inputVideoCodec.v0)
&& (inputAudioCodec == null || pid != inputAudioCodec.v0)) {
Logger.info("Unused program: " + pid);
mtsDemuxer.getProgram(pid).close();
}
}
break;
default:
throw new RuntimeException("Input format: " + inputFormat + " is not supported.");
}
if (demuxVideo != null && inputVideoCodec != null) {
List<? extends DemuxerTrack> videoTracks = demuxVideo.getVideoTracks();
if (videoTracks.size() > 0) {
videoInputTrack = videoTracks.get(inputVideoCodec.v1);
}
}
if (demuxAudio != null && inputAudioCodec != null) {
List<? extends DemuxerTrack> audioTracks = demuxAudio.getAudioTracks();
if (audioTracks.size() > 0) {
audioInputTrack = audioTracks.get(inputAudioCodec.v1);
}
}
}
/**
* Seeks to a previous key frame prior or on the given frame, if the track
* is not seekable returns 0.
*
* @param frame
* A frame to seek
* @return Frame number of a key frame or 0 if the track is not seekable.
* @throws IOException
*/
protected int seekToKeyFrame(int frame) throws IOException {
if (videoInputTrack instanceof SeekableDemuxerTrack) {
SeekableDemuxerTrack seekable = (SeekableDemuxerTrack) videoInputTrack;
seekable.gotoSyncFrame(frame);
return (int) seekable.getCurFrame();
} else {
Logger.warn("Can not seek in " + videoInputTrack + " container.");
return -1;
}
}
private MPEGDemuxerTrack openTSTrack(MPSDemuxer demuxerVideo, Integer selectedTrack) {
int trackNo = 0;
for (MPEGDemuxerTrack track : demuxerVideo.getTracks()) {
if (trackNo == selectedTrack) {
return track;
} else
track.ignore();
++trackNo;
}
return null;
}
@Override
public Packet inputVideoPacket() throws IOException {
while (true) {
Packet packet = getNextVideoPacket();
if (packet != null)
videoPacketReorderBuffer.add(packet);
if (packet == null || videoPacketReorderBuffer.size() > Transcoder.REORDER_BUFFER_SIZE) {
if (videoPacketReorderBuffer.size() == 0)
return null;
Packet out = videoPacketReorderBuffer.remove(0);
int duration = Integer.MAX_VALUE;
for (Packet packet2 : videoPacketReorderBuffer) {
int cand = (int)(packet2.getPts() - out.getPts());
if (cand > 0 && cand < duration)
duration = cand;
}
if (duration != Integer.MAX_VALUE)
out.setDuration(duration);
return out;
}
}
}
private Packet getNextVideoPacket() throws IOException {
if (videoInputTrack == null)
return null;
Packet nextFrame = videoInputTrack.nextFrame();
// if (nextFrame != null)
// Logger.debug(String.format("Input frame: pts=%d, duration=%d",
// nextFrame.getPts(), nextFrame.getDuration()));
if (videoDecoder == null) {
videoDecoder = createVideoDecoder(inputVideoCodec.v2, downscale, nextFrame.getData(), null);
if (videoDecoder != null) {
videoCodecMeta = videoDecoder.getCodecMeta(nextFrame.getData());
}
}
return nextFrame;
}
public Format getInputFormat() {
return inputFormat;
}
@Override
public Packet inputAudioPacket() throws IOException {
if (audioInputTrack == null)
return null;
Packet audioPkt = audioInputTrack.nextFrame();
if (audioDecoder == null) {
audioDecoder = createAudioDecoder(audioPkt.getData());
audioCodecMeta = audioDecoder.getCodecMeta(audioPkt.getData());
}
return audioPkt;
}
public DemuxerTrackMeta getTrackVideoMeta() {
if (videoInputTrack == null)
return null;
return videoInputTrack.getMeta();
}
public DemuxerTrackMeta getAudioMeta() {
if (audioInputTrack == null)
return null;
return audioInputTrack.getMeta();
}
public boolean haveAudio() {
return audioInputTrack != null;
}
@Override
public void finish() {
if (sourceStream != null)
IOUtils.closeQuietly(sourceStream);
}
public SourceImpl(String sourceName, Format inputFormat, _3<Integer, Integer, Codec> inputVideoCodec,
_3<Integer, Integer, Codec> inputAudioCodec) {
this.sourceName = sourceName;
this.inputFormat = inputFormat;
this.inputVideoCodec = inputVideoCodec;
this.inputAudioCodec = inputAudioCodec;
}
@Override
public void init(PixelStore pixelStore) throws IOException {
this.pixelStore = pixelStore;
initDemuxer();
}
private AudioDecoder createAudioDecoder(ByteBuffer codecPrivate) throws AACException {
switch (inputAudioCodec.v2) {
case AAC:
return new AACDecoder(codecPrivate);
case PCM:
return new RawAudioDecoder(getAudioMeta().getAudioCodecMeta().getFormat());
}
return null;
}
private VideoDecoder createVideoDecoder(Codec codec, int downscale, ByteBuffer codecPrivate,
VideoCodecMeta videoCodecMeta) {
switch (codec) {
case H264:
return H264Decoder.createH264DecoderFromCodecPrivate(codecPrivate);
case PNG:
return new PNGDecoder();
case MPEG2:
return MPEGDecoder.createMpegDecoder(downscale);
case PRORES:
return ProresDecoder.createProresDecoder(downscale);
case VP8:
return new VP8Decoder();
case JPEG:
return JpegDecoder.createJpegDecoder(downscale);
case RAW:
Size dim = videoCodecMeta.getSize();
return new RAWVideoDecoder(dim.getWidth(), dim.getHeight());
}
return null;
}
public Picture8Bit decodeVideo(ByteBuffer data, Picture8Bit target1) {
return videoDecoder.decodeFrame8Bit(data, target1.getData());
}
protected ByteBuffer decodeAudio(ByteBuffer audioPkt) throws IOException {
if (inputAudioCodec.v2 == Codec.PCM) {
return audioPkt;
} else {
AudioBuffer decodeFrame = audioDecoder.decodeFrame(audioPkt, null);
return decodeFrame.getData();
}
}
private static class RawAudioDecoder implements AudioDecoder {
private AudioFormat format;
public RawAudioDecoder(AudioFormat format) {
this.format = format;
}
@Override
public AudioBuffer decodeFrame(ByteBuffer frame, ByteBuffer dst) throws IOException {
return new AudioBuffer(frame, format, frame.remaining() / format.getFrameSize());
}
@Override
public AudioCodecMeta getCodecMeta(ByteBuffer data) throws IOException {
return new AudioCodecMeta(format);
}
}
@Override
public void seekFrames(int seekFrames) throws IOException {
if (seekFrames == 0)
return;
// How many frames need to be skipped from the previouse key frame,
// if the track is not seekable this will be equal to the
// seekFrames.
int skipFrames = seekFrames - seekToKeyFrame(seekFrames);
// All the frames starting from the key frame must be actually
// decoded in the decoder so that the decoder is 'warmed up'
Packet inVideoPacket;
for (; skipFrames > 0 && (inVideoPacket = getNextVideoPacket()) != null;) {
Picture8Bit decodedFrame = decodeVideo(inVideoPacket.getData(), getPixelBuffer(inVideoPacket.getData()));
if (decodedFrame == null)
continue;
frameReorderBuffer.add(new VideoFrameWithPacket(inVideoPacket, decodedFrame));
if (frameReorderBuffer.size() > Transcoder.REORDER_BUFFER_SIZE) {
Collections.sort(frameReorderBuffer);
VideoFrameWithPacket removed = frameReorderBuffer.remove(0);
skipFrames
if (removed.getFrame() != null)
pixelStore.putBack(removed.getFrame());
}
}
}
private void detectFrameType(Packet inVideoPacket) {
if (inputVideoCodec.v2 != Codec.H264) {
return;
}
inVideoPacket.setFrameType(
H264Utils.isByteBufferIDRSlice(inVideoPacket.getData()) ? FrameType.KEY : FrameType.INTER);
}
/**
* Returns a pixel buffer of a suitable size to hold the given video frame.
* The video size is taken either from the video metadata or by analyzing
* the incoming video packet.
*
* @param firstFrame
* @return
*/
protected Picture8Bit getPixelBuffer(ByteBuffer firstFrame) {
VideoCodecMeta videoMeta = getVideoCodecMeta();
Size size = videoMeta.getSize();
return pixelStore.getPicture((size.getWidth() + 15) & ~0xf, (size.getHeight() + 15) & ~0xf,
videoMeta.getColor());
}
@Override
public VideoCodecMeta getVideoCodecMeta() {
DemuxerTrackMeta meta = getTrackVideoMeta();
if (meta != null && meta.getVideoCodecMeta() != null) {
return meta.getVideoCodecMeta();
}
return videoCodecMeta;
}
@Override
public VideoFrameWithPacket getNextVideoFrame() throws IOException {
Packet inVideoPacket;
while ((inVideoPacket = getNextVideoPacket()) != null) {
if (inVideoPacket.getFrameType() == FrameType.UNKOWN) {
detectFrameType(inVideoPacket);
}
Picture8Bit decodedFrame = null;
Picture8Bit pixelBuffer = getPixelBuffer(inVideoPacket.getData());
decodedFrame = decodeVideo(inVideoPacket.getData(), pixelBuffer);
if (decodedFrame == null)
continue;
frameReorderBuffer.add(new VideoFrameWithPacket(inVideoPacket, decodedFrame));
if (frameReorderBuffer.size() > Transcoder.REORDER_BUFFER_SIZE) {
return removeFirstFixDuration(frameReorderBuffer);
}
}
// We don't have any more compressed video packets
if (frameReorderBuffer.size() > 0) {
return removeFirstFixDuration(frameReorderBuffer);
}
// We don't have any more compressed video packets and nothing's in
// the buffers
return null;
}
private VideoFrameWithPacket removeFirstFixDuration(List<VideoFrameWithPacket> reorderBuffer) {
Collections.sort(reorderBuffer);
VideoFrameWithPacket frame = reorderBuffer.remove(0);
if (!reorderBuffer.isEmpty()) {
// Setting duration
VideoFrameWithPacket nextFrame = reorderBuffer.get(0);
frame.getPacket().setDuration(nextFrame.getPacket().getPts() - frame.getPacket().getPts());
}
return frame;
}
@Override
public AudioFrameWithPacket getNextAudioFrame() throws IOException {
Packet audioPkt = inputAudioPacket();
if (audioPkt == null)
return null;
AudioBuffer audioBuffer;
if (inputAudioCodec.v2 == Codec.PCM) {
DemuxerTrackMeta audioMeta = getAudioMeta();
audioBuffer = new AudioBuffer(audioPkt.getData(), audioMeta.getAudioCodecMeta().getFormat(),
audioMeta.getTotalFrames());
} else {
audioBuffer = audioDecoder.decodeFrame(audioPkt.getData(), null);
}
return new AudioFrameWithPacket(audioBuffer, audioPkt);
}
public _3<Integer, Integer, Codec> getIntputVideoCodec() {
return inputVideoCodec;
}
public _3<Integer, Integer, Codec> getInputAudioCode() {
return inputAudioCodec;
}
public void setDownscale(int downscale) {
this.downscale = downscale;
}
@Override
public void setOption(Options option, Object value) {
if (option == Options.DOWNSCALE)
downscale = (Integer) value;
}
@Override
public AudioCodecMeta getAudioCodecMeta() {
return audioCodecMeta;
}
}
|
package org.jtrfp.trcl.obj;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.Camera;
import org.jtrfp.trcl.NormalMap;
import org.jtrfp.trcl.OverworldSystem;
import org.jtrfp.trcl.RenderMode;
import org.jtrfp.trcl.SpacePartitioningGrid;
import org.jtrfp.trcl.Triangle;
import org.jtrfp.trcl.Tunnel;
import org.jtrfp.trcl.World;
import org.jtrfp.trcl.beh.Behavior;
import org.jtrfp.trcl.beh.CollidesWithTerrain;
import org.jtrfp.trcl.beh.CollidesWithTunnelWalls;
import org.jtrfp.trcl.beh.CollisionBehavior;
import org.jtrfp.trcl.beh.DamageableBehavior;
import org.jtrfp.trcl.beh.HeadingXAlwaysPositiveBehavior;
import org.jtrfp.trcl.beh.LoopingPositionBehavior;
import org.jtrfp.trcl.beh.NAVTargetableBehavior;
import org.jtrfp.trcl.core.PortalTexture;
import org.jtrfp.trcl.core.Renderer;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.file.DirectionVector;
import org.jtrfp.trcl.game.Game;
import org.jtrfp.trcl.game.TVF3Game;
import org.jtrfp.trcl.gpu.Model;
import org.jtrfp.trcl.miss.Mission;
import org.jtrfp.trcl.miss.NAVObjective;
import org.jtrfp.trcl.shell.GameShell;
public class TunnelExitObject extends PortalEntrance {
private Vector3D exitLocation, exitHeading, exitTop;
private final Tunnel tun;
private final TR tr;
private NAVObjective navObjectiveToRemove;
private boolean mirrorTerrain = false;
private boolean onlyRemoveIfTargeted=false;
private static final int NUDGE = 5000;
public TunnelExitObject(TR tr, Tunnel tun, String debugName, WorldObject approachingObject) {
super(tr,new PortalExit(tr),approachingObject);
addBehavior(new TunnelExitBehavior());
final DirectionVector v = tun.getSourceTunnel().getExit();
final NormalMap map =
new NormalMap(
tr.
getGame().
getCurrentMission().
getOverworldSystem().
getAltitudeMap());
final double exitY =
map.heightAt(TR.legacy2Modern(v.getZ()), TR.legacy2Modern(v
.getX()));
this.exitLocation = new Vector3D(TR.legacy2Modern(v.getZ()),
exitY, TR.legacy2Modern(v
.getX()));
this.tun = tun;
exitHeading = map.
normalAt(
exitLocation.getX(),
exitLocation.getZ());
this.exitLocation = exitLocation.add(exitHeading.scalarMultiply(NUDGE));
if(exitHeading.getY()<.99&&exitHeading.getNorm()>0)//If the ground is flat this doesn't work.
exitTop = (Vector3D.PLUS_J.crossProduct(exitHeading).crossProduct(exitHeading)).negate();
else exitTop = (Vector3D.PLUS_I);// ... so we create a clause for that.
this.tr = tr;
final PortalExit pExit = getPortalExit();
pExit.setPosition(exitLocation.toArray());
pExit.setHeading(exitHeading);
pExit.setTop(exitTop);
pExit.setRootGrid(((TVF3Game)tr.getGame()).getCurrentMission().getOverworldSystem());
pExit.notifyPositionChange();
this.setPortalExit(pExit);
setPortalTexture(new PortalTexture());
setVisible(true);
Triangle [] tris = Triangle.quad2Triangles(new double[]{-50000,50000,50000,-50000}, new double[]{50000,50000,-50000,-50000}, new double[]{0,0,0,0}, new double[]{0,1,1,0}, new double[]{1,1,0,0}, getPortalTexture(), RenderMode.STATIC, false, Vector3D.ZERO, "TunnelExitObject.portalModel");
//Model m = Model.buildCube(100000, 100000, 200, new PortalTexture(0), new double[]{50000,50000,100},false,tr);
Model m = new Model(false, tr,"TunnelExitObject."+debugName);
m.addTriangles(tris);
setModel(m);
}//end constructor
private class TunnelExitBehavior extends Behavior implements
CollisionBehavior, NAVTargetableBehavior {
private boolean navTargeted=false;
@Override
public void proposeCollision(WorldObject other) {
if (other instanceof Player) {
//System.out.println("TunnelExitObject relevance tally="+tr.gpu.get().rendererFactory.get().getRelevanceTallyOf(getParent())+" within range? "+TunnelExitObject.this.isWithinRange());
//We want to track the camera's crossing in deciding when to move the player.
final Camera camera = tr.mainRenderer.get().getCamera();
//System.out.println("hash: "+super.hashCode()+" Cam pos = "+camera.getPosition()[0]+" thisPos="+TunnelExitObject.this.getPosition()[0]);
if (camera.getPosition()[0] > TunnelExitObject.this
.getPosition()[0]) {
final Game game = ((TVF3Game)tr.getGame());
final Mission mission = game.getCurrentMission();
final OverworldSystem overworldSystem = mission.getOverworldSystem();
System.out.println("TunnelExitObject leaving tunnel "+tun);
if(mirrorTerrain){
tr.setRunState(new Mission.ChamberState(){});
}else tr.setRunState(new Mission.OverworldState(){});
overworldSystem.setChamberMode(mirrorTerrain);//TODO: Use PCL to set this automatically in Mission
if(mirrorTerrain)
tr.setRunState(new Mission.ChamberState(){});
else
tr.setRunState(new Mission.PlayerActivity(){});
//tr.getDefaultGrid().nonBlockingAddBranch(overworldSystem);
//tr.getDefaultGrid().nonBlockingRemoveBranch(branchToRemove)
tr.mainRenderer .get().getSkyCube().setSkyCubeGen(overworldSystem.getSkySystem().getBelowCloudsSkyCubeGen());
final Renderer portalRenderer = TunnelExitObject.this.getPortalRenderer();
if(portalRenderer == null)
throw new IllegalStateException("PortalRenderer intolerably null.");
portalRenderer.getSkyCube().setSkyCubeGen(GameShell.DEFAULT_GRADIENT);
// Teleport
final Camera secondaryCam = portalRenderer.getCamera();
other.setPosition(secondaryCam.getPosition());
other.setHeading (secondaryCam.getHeading());
other.setTop (secondaryCam.getTop());
other.notifyPositionChange();
World.relevanceExecutor.submit(new Runnable(){
@Override
public void run() {
final SpacePartitioningGrid grid = tr.getDefaultGrid();
// Tunnel off
grid.removeBranch(tun);
// World on
grid.addBranch(overworldSystem);
// Nav
//grid.addBranch(game.getNavSystem());
}});
overworldSystem.setTunnelMode(false);
// Reset player behavior
final Player player = ((TVF3Game)tr.getGame()).getPlayer();
player.setActive(false);
player.resetVelocityRotMomentum();
player.probeForBehavior(CollidesWithTunnelWalls.class)
.setEnable(false);
player.probeForBehavior(DamageableBehavior.class)
.addInvincibility(250);// Safety kludge when near
// walls.
player.probeForBehavior(CollidesWithTerrain.class)
.setEnable(true);
player.probeForBehavior(LoopingPositionBehavior.class)
.setEnable(true);
/* player.probeForBehavior(
HeadingXAlwaysPositiveBehavior.class)
.setEnable(false);*/
// Update debug data
tr.getReporter().report("org.jtrfp.Tunnel.isInTunnel?",
"false");
// Reset projectile behavior
final ProjectileFactory[] pfs = tr.getResourceManager()
.getProjectileFactories();
for (ProjectileFactory pf : pfs) {
Projectile[] projectiles = pf.getProjectiles();
for (Projectile proj : projectiles) {
((WorldObject) proj)
.probeForBehavior(
LoopingPositionBehavior.class)
.setEnable(true);
}// end for(projectiles)
}// end for(projectileFactories)
final NAVObjective navObjective = getNavObjectiveToRemove();
if (navObjective != null && (navTargeted|!onlyRemoveIfTargeted)) {
((TVF3Game)tr.getGame()).getCurrentMission().removeNAVObjective(navObjective);
}// end if(have NAV to remove
((TVF3Game)tr.getGame()).getNavSystem().updateNAVState();
player.setActive(true);
}// end if(x past threshold)
}// end if(Player)
}// end proposeCollision()
@Override
public void notifyBecomingCurrentTarget() {
navTargeted=true;
}
}// end TunnelExitBehavior
/**
* @return the navObjectiveToRemove
*/
public NAVObjective getNavObjectiveToRemove() {
return navObjectiveToRemove;
}
/**
* @param navObjectiveToRemove
* the navObjectiveToRemove to set
* @param onlyRemoveIfTargeted
*/
public void setNavObjectiveToRemove(NAVObjective navObjectiveToRemove, boolean onlyRemoveIfTargeted) {
this.onlyRemoveIfTargeted = onlyRemoveIfTargeted;
this.navObjectiveToRemove = navObjectiveToRemove;
}
public void setMirrorTerrain(boolean b) {
mirrorTerrain = b;
}
/**
* @return the exitLocation
*/
public Vector3D getExitLocation() {
return exitLocation;
}
/**
* @param exitLocation
* the exitLocation to set
*/
public void setExitLocation(Vector3D exitLocation) {
this.exitLocation = exitLocation;
}
/**
* @return the mirrorTerrain
*/
public boolean isMirrorTerrain() {
return mirrorTerrain;
}
}// end TunnelExitObject
|
package org.lantern;
import java.io.IOException;
import java.net.Socket;
import java.net.URI;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class the keeps track of P2P connections to peers, dispatching them and
* creating new ones as needed.
*/
public class DefaultPeerProxyManager implements PeerProxyManager {
private final Logger log = LoggerFactory.getLogger(getClass());
private final Executor exec = Executors.newCachedThreadPool(
new ThreadFactory() {
private int threadNumber = 0;
@Override
public Thread newThread(final Runnable r) {
final Thread t =
new Thread(r, "P2P-Socket-Creation-Thread-"+threadNumber++);
t.setDaemon(true);
return t;
}
});
/**
* Priority queue of sockets ordered by how long it took them to be
* established.
*
* Package-access for easier testing.
*/
final PriorityBlockingQueue<ConnectionTimeSocket> timedSockets =
new PriorityBlockingQueue<ConnectionTimeSocket>(40,
new Comparator<ConnectionTimeSocket>() {
@Override
public int compare(final ConnectionTimeSocket cts1,
final ConnectionTimeSocket cts2) {
return cts1.elapsed.compareTo(cts2.elapsed);
}
});
private final boolean anon;
public DefaultPeerProxyManager(final boolean anon) {
this.anon = anon;
}
@Override
public HttpRequestProcessor processRequest(
final Channel browserToProxyChannel, final ChannelHandlerContext ctx,
final MessageEvent me) throws IOException {
// This removes the highest priority socket.
final ConnectionTimeSocket cts = this.timedSockets.poll();
if (cts == null) {
log.info("No peer sockets available!!");
return null;
}
// When we use a socket, we always replace it with a new one.
onPeer(cts.peerUri);
cts.requestProcessor.processRequest(browserToProxyChannel, ctx, me);
return cts.requestProcessor;
}
@Override
public void onPeer(final URI peerUri) {
if (!LanternHub.settings().isGetMode()) {
log.info("Ingoring peer when we're in give mode");
return;
}
log.info("Received peer URI {}...attempting connection...", peerUri);
// Unclear how this count will be used for now.
final Map<URI, AtomicInteger> peerFailureCount =
new HashMap<URI, AtomicInteger>();
exec.execute(new Runnable() {
@Override
public void run() {
try {
// We open a number of sockets because in almost every
// scenario the browser makes many connections to the proxy
// to open a single page.
for (int i = 0; i < 4; i++) {
final ConnectionTimeSocket ts =
new ConnectionTimeSocket(peerUri);
final Socket sock = LanternUtils.openOutgoingPeerSocket(
peerUri, LanternHub.xmppHandler().getP2PClient(),
peerFailureCount);
log.info("Got socket and adding it for peer: {}", peerUri);
ts.onSocket(sock);
timedSockets.add(ts);
}
LanternHub.eventBus().post(
new ConnectivityStatusChangeEvent(
ConnectivityStatus.CONNECTED));
} catch (final IOException e) {
log.info("Could not create peer socket");
}
}
});
}
/**
* Class holding a socket and an HTTP request processor that also tracks
* connection times.
*
* Package-access for easier testing.
*/
final class ConnectionTimeSocket {
private final long startTime = System.currentTimeMillis();
Long elapsed;
/**
* We only store the peer URI so we can create a new connection to the
* peer when this one succeeds.
*/
private final URI peerUri;
private HttpRequestProcessor requestProcessor;
public ConnectionTimeSocket(final URI peerUri) {
this.peerUri = peerUri;
}
private void onSocket(final Socket sock) {
this.elapsed = System.currentTimeMillis() - this.startTime;
if (anon) {
this.requestProcessor =
new PeerHttpConnectRequestProcessor(sock);
} else {
this.requestProcessor =
new PeerChannelHttpRequestProcessor(sock);
//new PeerHttpRequestProcessor(sock);
}
}
}
@Override
public void closeAll() {
for (final ConnectionTimeSocket sock : this.timedSockets) {
sock.requestProcessor.close();
}
}
}
|
package org.lantern.http;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.lantern.Censored;
import org.lantern.JsonUtils;
import org.lantern.LanternClientConstants;
import org.lantern.LanternFeedback;
import org.lantern.XmppHandler;
import org.lantern.event.Events;
import org.lantern.event.InvitesChangedEvent;
import org.lantern.event.ResetEvent;
import org.lantern.state.InternalState;
import org.lantern.state.JsonModelModifier;
import org.lantern.state.LocationChangedEvent;
import org.lantern.state.Modal;
import org.lantern.state.Model;
import org.lantern.state.ModelIo;
import org.lantern.state.ModelService;
import org.lantern.state.Notification.MessageType;
import org.lantern.state.Settings.Mode;
import org.lantern.state.SyncPath;
import org.lantern.util.Desktop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.google.inject.Singleton;
@Singleton
public class InteractionServlet extends HttpServlet {
private final InternalState internalState;
private enum Interaction {
GET,
GIVE,
INVITE,
CONTINUE,
SETTINGS,
CLOSE,
RESET,
SET,
PROXIEDSITES,
CANCEL,
LANTERNFRIENDS,
RETRY,
REQUESTINVITE,
CONTACT,
ABOUT,
ACCEPT,
DECLINE
}
private final Logger log = LoggerFactory.getLogger(getClass());
/**
* Generated serialization ID.
*/
private static final long serialVersionUID = -8820179746803371322L;
private final ModelService modelService;
private final Model model;
private final ModelIo modelIo;
private final XmppHandler xmppHandler;
private final Censored censored;
private final LanternFeedback lanternFeedback;
@Inject
public InteractionServlet(final Model model,
final ModelService modelService,
final InternalState internalState,
final ModelIo modelIo, final XmppHandler xmppHandler,
final Censored censored, final LanternFeedback lanternFeedback) {
this.model = model;
this.modelService = modelService;
this.internalState = internalState;
this.modelIo = modelIo;
this.xmppHandler = xmppHandler;
this.censored = censored;
this.lanternFeedback = lanternFeedback;
Events.register(this);
}
@Override
protected void doGet(final HttpServletRequest req,
final HttpServletResponse resp) throws ServletException,
IOException {
processRequest(req, resp);
}
@Override
protected void doPost(final HttpServletRequest req,
final HttpServletResponse resp) throws ServletException,
IOException {
processRequest(req, resp);
}
protected void processRequest(final HttpServletRequest req,
final HttpServletResponse resp) {
final String uri = req.getRequestURI();
log.debug("Received URI: {}", uri);
final Map<String, String> params = HttpUtils.toParamMap(req);
log.debug("Params: {}", params);
final String interactionStr = StringUtils.substringAfterLast(uri, "/");//params.get("interaction");
if (StringUtils.isBlank(interactionStr)) {
log.debug("No interaction!!");
HttpUtils.sendClientError(resp, "interaction argument required!");
return;
}
log.debug("Headers: "+HttpUtils.getRequestHeaders(req));
if (!"XMLHttpRequest".equals(req.getHeader("X-Requested-With"))) {
HttpUtils.sendClientError(resp, "X-Requested-With header not set");
return;
}
final int cl = req.getContentLength();
String json = "";
if (cl > 0) {
try {
json = IOUtils.toString(req.getInputStream());
} catch (final IOException e) {
log.error("Could not parse json?");
}
}
log.debug("Body: '"+json+"'");
final Interaction inter =
Interaction.valueOf(interactionStr.toUpperCase());
if (inter == Interaction.CLOSE) {
handleClose(json);
}
final Modal modal = this.model.getModal();
log.debug("processRequest: modal = {}, inter = {}, mode = {}",
modal, inter, this.model.getSettings().getMode());
switch (modal) {
case welcome:
this.model.getSettings().setMode(Mode.none);
switch (inter) {
case GET:
log.debug("Setting get mode");
handleSetModeWelcome(Mode.get);
break;
case GIVE:
log.debug("Setting give mode");
handleSetModeWelcome(Mode.give);
break;
default:
if (handleModalSwitch(inter)) {
break;
}
break;
}
break;
case about:
if (handleModalSwitch(inter)) {
break;
}
this.internalState.setModalCompleted(Modal.finished);
this.internalState.advanceModal(null);
Events.syncModel(this.model);
break;
case authorize:
log.error("Processing authorize modal...");
if (handleModalSwitch(inter)) {
break;
}
this.internalState.setModalCompleted(Modal.authorize);
this.internalState.advanceModal(null);
Events.syncModel(this.model);
break;
case finished:
switch (inter) {
case CONTINUE:
log.debug("Processing continue");
this.model.setShowVis(true);
this.internalState.setModalCompleted(Modal.finished);
this.internalState.advanceModal(null);
Events.syncModel(this.model);
break;
case SET:
log.debug("Processing set in finished modal...applying JSON\n{}", json);
applyJson(json);
break;
default:
log.error("Did not handle interaction for modal {} with " +
"params: {}", modal, params);
HttpUtils.sendClientError(resp, "give or get required");
break;
}
break;
case firstInviteReceived:
log.error("Processing invite received...");
break;
case gtalkUnreachable:
log.error("Processing gtalk unreachable.");
break;
case lanternFriends:
if (handleModalSwitch(inter)) {
break;
}
switch (inter) {
case INVITE:
invite(json);
Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications());
break;
case CONTINUE:
log.debug("Processing continue for friends dialog");
this.internalState.setModalCompleted(Modal.lanternFriends);
this.internalState.advanceModal(null);
break;
case PROXIEDSITES:
log.debug("Processing proxiedSites in lanternFriends");
Events.syncModal(model, Modal.proxiedSites);
break;
case SETTINGS:
log.debug("Processing settings in lanternFriends");
Events.syncModal(model, Modal.settings);
break;
case ACCEPT:
acceptInvite(json);
Events.syncModal(model, Modal.lanternFriends);
break;
case DECLINE:
declineInvite(json);
Events.syncModal(model, Modal.lanternFriends);
break;
default:
log.error("Did not handle interaction for modal {} with " +
"params: {}", modal, params);
HttpUtils.sendClientError(resp, "give or get required");
break;
}
break;
case none:
handleModalSwitch(inter);
break;
case notInvited:
switch (inter) {
case RETRY:
Events.syncModal(model, Modal.authorize);
break;
case REQUESTINVITE:
Events.syncModal(model, Modal.requestInvite);
break;
default:
log.error("Unexpected interaction: " + inter);
break;
}
break;
case proxiedSites:
if (handleModalSwitch(inter)) {
break;
}
switch (inter) {
case CONTINUE:
this.internalState.setModalCompleted(Modal.proxiedSites);
this.internalState.advanceModal(null);
break;
case LANTERNFRIENDS:
log.debug("Processing lanternFriends from proxiedSites");
Events.syncModal(model, Modal.lanternFriends);
break;
case SET:
if (!model.getSettings().isSystemProxy()) {
String msg = "Because you are using manual proxy "
+ "configuration, you may have to restart your "
+ "browser for your updated proxied sites list "
+ "to take effect.";
model.addNotification(msg, MessageType.info);
Events.sync(SyncPath.NOTIFICATIONS,
model.getNotifications());
}
applyJson(json);
break;
case SETTINGS:
log.debug("Processing settings from proxiedSites");
Events.syncModal(model, Modal.settings);
break;
default:
log.error("Did not handle interaction {}, for modal {} with " +
"params: {}", inter, modal, params);
HttpUtils.sendClientError(resp, "unexpected interaction for proxied sites");
break;
}
break;
case requestInvite:
log.error("Processing request invite");
switch (inter) {
case CANCEL:
this.internalState.setModalCompleted(Modal.requestInvite);
this.internalState.advanceModal(Modal.notInvited);
break;
case CONTINUE:
applyJson(json);
this.internalState.setModalCompleted(Modal.proxiedSites);
//TODO: need to do something here
this.internalState.advanceModal(null);
break;
default:
log.error("Did not handle interaction {}, for modal {} with " +
"params: {}", inter, modal, params);
HttpUtils.sendClientError(resp, "unexpected interaction for request invite");
break;
}
break;
case requestSent:
log.debug("Process request sent");
break;
case settings:
if (handleModalSwitch(inter)) {
break;
}
switch (inter) {
case GET:
log.debug("Setting get mode");
// Only deal with a mode change if the mode has changed!
if (modelService.getMode() == Mode.give) {
// Break this out because it's set in the subsequent
// setMode call
final boolean everGet = model.isEverGetMode();
this.modelService.setMode(Mode.get);
if (!everGet) {
// need to do more setup to switch to get mode from
// give mode
model.setSetupComplete(false);
model.setModal(Modal.proxiedSites);
Events.syncModel(this.model);
} else {
// This primarily just triggers a setup complete event,
// which triggers connecting to proxies, setting up
// the local system proxy, etc.
model.setSetupComplete(true);
}
}
break;
case GIVE:
log.debug("Setting give mode");
this.modelService.setMode(Mode.give);
break;
case CLOSE:
log.debug("Processing settings close");
Events.syncModal(model, Modal.none);
break;
case SET:
log.debug("Processing set in setting...applying JSON\n{}", json);
applyJson(json);
break;
case RESET:
log.debug("Processing reset");
Events.syncModal(model, Modal.confirmReset);
break;
case PROXIEDSITES:
log.debug("Processing proxied sites in settings");
Events.syncModal(model, Modal.proxiedSites);
break;
case LANTERNFRIENDS:
log.debug("Processing friends in settings");
Events.syncModal(model, Modal.lanternFriends);
break;
default:
log.error("Did not handle interaction for modal {} with " +
"params: {}", modal, params);
HttpUtils.sendClientError(resp, "give or get required");
break;
}
break;
case settingsLoadFailure:
switch (inter) {
case RETRY:
modelIo.reload();
Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications());
Events.syncModal(model, model.getModal());
break;
case RESET:
try {
File backup = new File(Desktop.getDesktopPath(), "lantern-model-backup");
FileUtils.copyFile(LanternClientConstants.DEFAULT_MODEL_FILE, backup);
} catch (final IOException e) {
log.warn("Could not backup model file.");
}
Events.syncModal(model, Modal.welcome);
break;
default:
log.error("Did not handle interaction for modal {} with "
+ "params: {}", modal, params);
break;
}
break;
case systemProxy:
switch (inter) {
case CONTINUE:
log.debug("Processing continue in systemProxy", json);
applyJson(json);
this.internalState.setModalCompleted(Modal.systemProxy);
this.internalState.advanceModal(null);
break;
default:
log.error("Did not handle interaction for modal {} with " +
"params: {}", modal, params);
HttpUtils.sendClientError(resp, "error setting system proxy pref");
break;
}
break;
case updateAvailable:
switch (inter) {
case CLOSE:
this.internalState.setModalCompleted(Modal.updateAvailable);
this.internalState.advanceModal(null);
break;
default:
log.error("Did not handle interaction for modal {} with " +
"params: {}", modal, params);
break;
}
break;
case authorizeLater:
log.error("Did not handle interaction for modal {} with " +
"params: {}", modal, params);
break;
case confirmReset:
log.debug("Handling confirm reset interaction");
switch (inter) {
case CANCEL:
log.debug("Processing cancel");
Events.syncModal(model, Modal.settings);
break;
case RESET:
handleReset();
Events.syncModel(this.model);
break;
default:
log.error("Did not handle interaction for modal {} with " +
"params: {}", modal, params);
HttpUtils.sendClientError(resp, "give or get required");
break;
}
break;
case contact:
switch(inter) {
case CONTINUE:
try {
lanternFeedback.submit(json,
this.model.getProfile().getEmail());
model.addNotification("Message sent.", MessageType.success);
} catch(Exception e) {
model.addNotification(
"Failed to send message. Try again later.",
MessageType.error);
log.error("Could not post to contact form: {}", e);
}
Events.syncModal(this.model, Modal.none);
break;
default:
if (handleModalSwitch(inter)) {
break;
}
this.internalState.setModalCompleted(Modal.finished);
this.internalState.advanceModal(null);
Events.syncModel(this.model);
break;
}
break;
case giveModeForbidden:
if (inter == Interaction.CONTINUE) {
// need to do more setup to switch to get mode from give mode
model.setSetupComplete(false);
this.internalState.advanceModal(null);
Events.syncModal(model, Modal.proxiedSites);
Events.syncModel(this.model);
}
break;
default:
log.error("No matching modal for {}", modal);
}
this.modelIo.write();
}
private void handleClose(String json) {
if (StringUtils.isBlank(json)) {
return;
}
final ObjectMapper om = new ObjectMapper();
Map<String, Object> map;
try {
map = om.readValue(json, Map.class);
final String notification = (String) map.get("notification");
model.closeNotification(Integer.parseInt(notification));
Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications());
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void declineInvite(final String json) {
final String email = JsonUtils.getValueFromJson("email", json);
this.xmppHandler.unsubscribed(email);
}
private void acceptInvite(final String json) {
final String email = JsonUtils.getValueFromJson("email", json);
this.xmppHandler.subscribed(email);
// We also automatically subscribe to them in turn so we know about
// their presence.
this.xmppHandler.subscribe(email);
}
/**
* This handles the case where a user selects a modal that completely
* switches the current modal and any associated flow, such as when the
* user selects the about or contact links. Those need to override whatever
* modal is currently displayed.
*
* @param inter The interaction.
* @return <code>true</code> if the interaction results in the modal
* actually switching, otherwise <code>false</code>.
*/
private boolean handleModalSwitch(final Interaction inter) {
switch (inter) {
case SETTINGS:
log.debug("Processing settings in none");
Events.syncModal(model, Modal.settings);
return true;
case PROXIEDSITES:
log.debug("Processing proxied sites in none");
Events.syncModal(model, Modal.proxiedSites);
return true;
case LANTERNFRIENDS:
log.debug("Processing friends in none");
Events.syncModal(model, Modal.lanternFriends);
return true;
case ABOUT:
log.debug("Processing about in none");
Events.syncModal(model, Modal.about);
return true;
case CONTACT:
log.debug("Processing contact in none");
Events.syncModal(model, Modal.contact);
return true;
case RESET:
//reset is handled differently in various modals
log.error("Reset from front-end in unknown state.");
return false;
default:
return false;
}
}
static class Invite {
List<String> invite;
public Invite() {}
public List<String> getInvite() {
return invite;
}
public void setInvite(List<String> invite) {
this.invite = invite;
}
}
private void invite(String json) {
ObjectMapper om = new ObjectMapper();
try {
if (json.length() == 0) {
return;//nobody to invite
}
ArrayList<String> invites = om.readValue(json, ArrayList.class);
modelService.invite(invites);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void handleSetModeWelcome(final Mode mode) {
this.model.setModal(Modal.authorize);
this.internalState.setModalCompleted(Modal.welcome);
this.modelService.setMode(mode);
Events.syncModal(model);
}
private void applyJson(final String json) {
final JsonModelModifier mod = new JsonModelModifier(modelService);
mod.applyJson(json);
}
private void handleReset() {
// This posts the reset event to any classes that need to take action,
// avoiding coupling this class to those classes.
Events.eventBus().post(new ResetEvent());
if (LanternClientConstants.DEFAULT_MODEL_FILE.isFile()) {
try {
FileUtils.forceDelete(LanternClientConstants.DEFAULT_MODEL_FILE);
} catch (final IOException e) {
log.warn("Could not delete model file?");
}
}
final Model base = new Model();
model.setCache(base.isCache());
model.setLaunchd(base.isLaunchd());
model.setModal(base.getModal());
model.setNinvites(base.getNinvites());
model.setNodeId(base.getNodeId());
model.setProfile(base.getProfile());
model.setNproxiedSitesMax(base.getNproxiedSitesMax());
//we need to keep clientID and clientSecret, because they are application-level settings
String clientID = model.getSettings().getClientID();
String clientSecret = model.getSettings().getClientSecret();
model.setSettings(base.getSettings());
model.getSettings().setClientID(clientID);
model.getSettings().setClientSecret(clientSecret);
model.setSetupComplete(base.isSetupComplete());
model.setShowVis(base.isShowVis());
model.clearNotifications();
modelIo.write();
}
@Subscribe
public void onLocationChanged(final LocationChangedEvent e) {
Events.sync(SyncPath.LOCATION, e.getNewLocation());
if (censored.isCountryCodeCensored(e.getNewCountry())) {
if (!censored.isCountryCodeCensored(e.getOldCountry())) {
//moving from uncensored to censored
if (model.getSettings().getMode() == Mode.give) {
Events.syncModal(model, Modal.giveModeForbidden);
}
}
}
}
@Subscribe
public void onInvitesChanged(final InvitesChangedEvent e) {
int newInvites = e.getNewInvites();
if (e.getOldInvites() == 0) {
String invitation = newInvites == 1 ? "invitation" : "invitations";
String text = "You now have " + newInvites + " " + invitation;
model.addNotification(text, MessageType.info);
} else if (newInvites == 0 && e.getOldInvites() > 0) {
model.addNotification("You have no more invitations. You will be notified when you receive more.", MessageType.important);
}
}
}
|
package org.mitre.synthea.engine;
import com.google.gson.JsonObject;
import com.google.gson.internal.LinkedTreeMap;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.mitre.synthea.world.agents.Person;
/**
* Transition represents all the transition types within the generic module
* framework. This class is stateless, and calling 'follow' on an instance must
* not modify state as instances of Transition within States and Modules are
* shared across the population.
*/
public abstract class Transition {
protected List<String> remarks;
/**
* Get the name of the next state.
*
* @param person : person being processed
* @param time : time of this transition
* @return name : name of the next state
*/
public abstract String follow(Person person, long time);
/**
* Direct transitions are the simplest of transitions. They transition directly
* to the indicated state. The value of a direct_transition is simply the name
* of the state to transition to.
*/
public static class DirectTransition extends Transition {
private String transition;
public DirectTransition(String transition) {
this.transition = transition;
}
@Override
public String follow(Person person, long time) {
return transition;
}
}
/**
* A TransitionOption represents a single destination state that may be
* transitioned to.
*/
private abstract static class TransitionOption {
protected String transition;
}
/**
* A DistributedTransitionOption represents a single destination state, with a
* given distribution percentage, or a named distribution representing an
* attribute containing the distribution percentage.
*/
public static final class DistributedTransitionOption extends TransitionOption {
private Object distribution;
public Double numericDistribution;
private NamedDistribution namedDistribution;
}
/**
* Distributed transitions will transition to one of several possible states
* based on the configured distribution. Distribution values are from 0.0 to
* 1.0, such that a value of 0.55 would indicate a 55% chance of transitioning
* to the corresponding state. A distributed_transition consists of an array of
* distribution/transition pairs for which the distribution values should sum up
* to 1.0. If the distribution values do not sum up to 1.0, the remaining
* distribution will transition to the last defined transition state. For
* example, given distributions of 0.3 and 0.6, the effective distribution of
* the last transition will actually be 0.7. If the distribution values sum up
* to more than 1.0, the remaining distributions are ignored (for example, if
* distribution values are 0.75, 0.5, and 0.3, then the second transition will
* have an effective distribution of 0.25, and the last transition will have an
* effective distribution of 0.0).
*/
public static final class DistributedTransition extends Transition {
private List<DistributedTransitionOption> transitions;
public DistributedTransition(List<DistributedTransitionOption> transitions) {
this.transitions = transitions;
}
@Override
public String follow(Person person, long time) {
return pickDistributedTransition(transitions, person);
}
}
/**
* A LookupTableTransitionOption represents a destination state which will be
* chosen based on the result of a table lookup.
*/
public static final class LookupTableTransitionOption extends TransitionOption {
private String lookupTableName;
}
/**
* LookupTable transitions will transition to one of two possible states based
* on a probability extacted from a table. A LookUpTableTransition will have one
* field denoting the lookuptable to use and a field donating the probability
* that the subject of that table is true. A table may have any set of
* attributes to determine the probability based on a variety of attributes
* which will be compared to the attributes within the current person. If a
* person does not correspond to any of the sets of attributes, the probaiblity
* will default to 0.0.
*/
public static class LookupTableTransition extends Transition {
// Map of lookupTables Data
private static HashMap<String, HashMap<LookupTableKey, ArrayList<DistributedTransitionOption>>> lookupTables = new HashMap<String, HashMap<LookupTableKey, ArrayList<DistributedTransitionOption>>>();
private List<LookupTableTransitionOption> transitions;
private ArrayList<String> attributes;
public LookupTableTransition(List<LookupTableTransitionOption> lookupTableTransitions) {
this.transitions = lookupTableTransitions;
this.attributes = new ArrayList<String>();
if (!lookupTables.containsKey(transitions.get(0).lookupTableName)) {
String newTableName = transitions.get(0).lookupTableName;
System.out.println("Loading Lookup Table: " + newTableName);
// Hashmap for the new table
HashMap<LookupTableKey, ArrayList<DistributedTransitionOption>> newTable = new HashMap<LookupTableKey, ArrayList<DistributedTransitionOption>>();
// Parse CSV
File csvData = new File(
"./src/main/resources/modules/lookup_tables/" + this.transitions.get(0).lookupTableName);
CSVParser parser;
try {
parser = CSVParser.parse(csvData, Charset.defaultCharset(), CSVFormat.RFC4180);
List<CSVRecord> records = parser.getRecords();
// Parse out the list of attributes based on names of columns.
int numAttributes = records.get(0).size() - (this.transitions.size());
// First entry in CSV has extra char at beginning
int startIndex = 1;
for (int attributeName = 0; attributeName < numAttributes; attributeName++) {
this.attributes.add(records.get(0).get(attributeName).toString().substring(startIndex).toLowerCase());
startIndex = 0;
}
// Fill new table within lookupTables hashmap
for (int currentRecord = 1; currentRecord < (records.size()); currentRecord++) {
// Parse the list of attributes for current record
ArrayList<String> attributeRecords = new ArrayList<String>();
for (int currentAttribute = 0; currentAttribute < numAttributes; currentAttribute++) {
attributeRecords.add(records.get(currentRecord).get(currentAttribute));
}
LookupTableKey attributeRecordsLookupKey = new LookupTableKey(attributeRecords,
this.attributes.indexOf("age"), -1);
// Create DistributedTransitionOption Arraylist of transition probabilities
ArrayList<DistributedTransitionOption> transitionProbabilities = new ArrayList<DistributedTransitionOption>();
for (int currentTransitionProbability = 0; currentTransitionProbability < this.transitions
.size(); currentTransitionProbability++) {
DistributedTransitionOption currentOption = new DistributedTransitionOption();
currentOption.numericDistribution = Double
.parseDouble(records.get(currentRecord).get(numAttributes + currentTransitionProbability));
if (records.get(0).get(numAttributes + currentTransitionProbability)
.equals(transitions.get(currentTransitionProbability).transition)) {
currentOption.transition = transitions.get(currentTransitionProbability).transition;
transitionProbabilities.add(currentOption);
} else {
System.out.println("ERROR: COLUMN STATE NAME DOES NOT MATCH STATE TO TRANSITION TO");
}
}
// Insert new record into new table
newTable.put(attributeRecordsLookupKey, transitionProbabilities);
}
// Insert new table into lookupTables Hashmap
lookupTables.put(newTableName, newTable);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public String follow(Person person, long time) {
// Extract Person's list of relevant attributes
String personAge = "-1";
ArrayList<String> personsAttributes = new ArrayList<String>();
for (int attributeToAdd = 0; attributeToAdd < this.attributes.size(); attributeToAdd++) {
if (attributes.get(attributeToAdd).equals("age")) {
personAge = Integer.toString(person.ageInYears(time));
} else {
personsAttributes.add((String) person.attributes.get(this.attributes.get(attributeToAdd).toLowerCase()));
}
}
// Create Key to get distributions
LookupTableKey personsAttributesLookupKey = new LookupTableKey(personsAttributes, this.attributes.indexOf("age"),
Integer.parseInt(personAge));
if (lookupTables.get(this.transitions.get(0).lookupTableName).containsKey(personsAttributesLookupKey)) {
// Person matches, use the list of distributedtransitionoptions in their
// corresponding record
return pickDistributedTransition(
lookupTables.get(this.transitions.get(0).lookupTableName).get(personsAttributesLookupKey), person);
} else {
// No attribute match
// Need to Return a default value... Or should we expect that every possibility
// is taken care of? Will "*" be a necesessity/fix?
System.out.println("NO TRANSITION MATCHED");
return "Terminal";
}
}
class LookupTableKey {
ArrayList<String> recordAttributes;
int ageHigh;
int ageLow;
int ageIndex;
int personAge;
LookupTableKey(ArrayList<String> attributes, int ageIndex, int personAge) {
if (ageIndex > -1 && personAge < 0) {
String ageRange = attributes.get(ageIndex);
this.ageLow = Integer.parseInt(ageRange.substring(0, ageRange.indexOf("-")));
this.ageHigh = Integer.parseInt(ageRange.substring(ageRange.indexOf("-") + 1));
attributes.remove(ageIndex);
}
this.personAge = personAge;
this.recordAttributes = attributes;
this.ageIndex = ageIndex;
}
@Override
public int hashCode() {
return this.recordAttributes.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
ArrayList<String> personAttributes = ((LookupTableKey) obj).recordAttributes;
LookupTableKey lookupTableKey = (LookupTableKey) obj;
// If There is an age column (at ageIndex)
if (this.ageIndex > -1) {
// If this is a person
if (personAge > -1) {
return personAge >= lookupTableKey.ageLow && personAge <= lookupTableKey.ageHigh;
} else {
return attributes.equals(personAttributes);
}
} else {
// No age column. Return standard ArrayList.equals();
return this.recordAttributes.equals(personAttributes);
}
}
}
}
/**
* A ConditionalTransitionOption represents a single destination state, with a
* given logical condition that must be true in order for the state to be
* transitioned to.
*/
public static final class ConditionalTransitionOption extends TransitionOption {
private Logic condition;
}
/**
* Conditional transitions will transition to one of several possible states
* based on conditional logic. A conditional_transition consists of an array of
* condition/transition pairs which are tested in the order they are defined.
* The first condition that evaluates to true will result in a transition to its
* corresponding transition state. The last element in the condition_transition
* array may contain only a transition (with no condition) to indicate a
* "fallback transition" when all other conditions are false. If none of the
* conditions evaluated to true, and no fallback transition was specified, the
* module will transition to the last transition defined.
*/
public static class ConditionalTransition extends Transition {
private List<ConditionalTransitionOption> transitions;
public ConditionalTransition(List<ConditionalTransitionOption> transitions) {
this.transitions = transitions;
}
@Override
public String follow(Person person, long time) {
for (ConditionalTransitionOption option : transitions) {
if (option.condition == null || option.condition.test(person, time)) {
return option.transition;
}
}
// fallback, just return the last transition
TransitionOption last = transitions.get(transitions.size() - 1);
return last.transition;
}
}
/**
* A DistributedTransitionOption represents a transition option with any of: - a
* single state to transition to, - a condition that must be true, or - a set of
* distributions and transitions.
*/
public static final class ComplexTransitionOption extends TransitionOption {
private Logic condition;
private List<DistributedTransitionOption> distributions;
}
/**
* Complex transitions are a combination of direct, distributed, and conditional
* transitions. A complex_transition consists of an array of
* condition/transition pairs which are tested in the order they are defined.
* The first condition that evaluates to true will result in a transition based
* on its corresponding transition or distributions. If the module defines a
* transition, it will transition directly to that named state. If the module
* defines distributions, it will then transition to one of these according to
* the same rules as the distributed_transition. See Distributed for more
* detail. The last element in the complex_transition array may omit the
* condition to indicate a fallback transition when all other conditions are
* false. If none of the conditions evaluated to true, and no fallback
* transition was specified, the module will transition to the last transition
* defined.
*/
public static class ComplexTransition extends Transition {
private List<ComplexTransitionOption> transitions;
public ComplexTransition(List<ComplexTransitionOption> transitions) {
this.transitions = transitions;
}
@Override
public String follow(Person person, long time) {
for (ComplexTransitionOption option : transitions) {
if (option.condition == null || option.condition.test(person, time)) {
return follow(option, person);
}
}
// fallback, just return the last transition
ComplexTransitionOption last = transitions.get(transitions.size() - 1);
return follow(last, person);
}
private String follow(ComplexTransitionOption option, Person person) {
if (option.transition != null) {
return option.transition;
} else if (option.distributions != null) {
return pickDistributedTransition(option.distributions, person);
}
throw new IllegalArgumentException("Complex Transition must have either transition or distributions");
}
}
private static String pickDistributedTransition(List<DistributedTransitionOption> transitions, Person person) {
double p = person.rand();
double high = 0.0;
for (DistributedTransitionOption option : transitions) {
processDistributedTransition(option);
if (option.numericDistribution != null) {
high += option.numericDistribution;
} else {
NamedDistribution nd = option.namedDistribution;
double dist = nd.defaultDistribution;
if (person.attributes.containsKey(nd.attribute)) {
dist = (Double) person.attributes.get(nd.attribute);
}
high += dist;
}
if (p < high) {
return option.transition;
}
}
// fallback, just return the last transition
TransitionOption last = transitions.get(transitions.size() - 1);
return last.transition;
}
private static void processDistributedTransition(DistributedTransitionOption option) {
if (option.numericDistribution != null || option.namedDistribution != null) {
return;
}
if (option.distribution instanceof Double) {
option.numericDistribution = (Double) option.distribution;
} else {
@SuppressWarnings("unchecked")
LinkedTreeMap<String, Object> map = (LinkedTreeMap<String, Object>) option.distribution;
option.namedDistribution = new NamedDistribution(map);
}
}
/**
* Helper class for distributions, which may either be a double, or a
* NamedDistribution with an attribute to fetch the desired probability from and
* a default.
*/
public static class NamedDistribution {
public String attribute;
public double defaultDistribution;
public NamedDistribution(JsonObject definition) {
this.attribute = definition.get("attribute").getAsString();
this.defaultDistribution = definition.get("default").getAsDouble();
}
public NamedDistribution(LinkedTreeMap<String, ?> definition) {
this.attribute = (String) definition.get("attribute");
this.defaultDistribution = (Double) definition.get("default");
}
}
}
|
package org.scribe.oauth;
import org.scribe.builder.api.DefaultApi20;
import org.scribe.model.OAuthConfig;
import org.scribe.model.OAuthConstants;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
public class OAuth20ServiceImpl implements OAuthService
{
private static final String VERSION = "2.0";
private final DefaultApi20 api;
private final OAuthConfig config;
/**
* Default constructor
*
* @param api OAuth2.0 api information
* @param config OAuth 2.0 configuration param object
*/
public OAuth20ServiceImpl(DefaultApi20 api, OAuthConfig config)
{
this.api = api;
this.config = config;
}
/**
* {@inheritDoc}
*/
public void addScope(String scope)
{
throw new UnsupportedOperationException("OAuth 2 does not use scopes");
}
/**
* {@inheritDoc}
*/
public Token getAccessToken(Token requestToken, Verifier verifier)
{
OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
request.addQuerystringParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
request.addQuerystringParameter(OAuthConstants.CODE, verifier.getValue());
request.addQuerystringParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
Response response = request.send();
return api.getAccessTokenExtractor().extract(response.getBody());
}
/**
* {@inheritDoc}
*/
public Token getRequestToken()
{
throw new UnsupportedOperationException("Unsupported operation, please use 'getAuthorizationUrl' and redirect your users there");
}
/**
* {@inheritDoc}
*/
public String getVersion()
{
return VERSION;
}
/**
* {@inheritDoc}
*/
public void signRequest(Token accessToken, OAuthRequest request)
{
request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getToken());
}
/**
* {@inheritDoc}
*/
public String getAuthorizationUrl(Token requestToken)
{
return api.getAuthorizationUrl(config);
}
}
|
package org.signaut.common.couchdb;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.annotate.JsonAnyGetter;
import org.codehaus.jackson.annotate.JsonAnySetter;
import org.codehaus.jackson.annotate.JsonProperty;
public class Document {
@JsonProperty("_attachments")
private Map<String, Attachment> attachments;
@JsonProperty("_id")
private String id;
@JsonProperty("_rev")
private String revision;
private Map<String, Object> optionalFields = new HashMap<String, Object>();
public String getId() {
return id;
}
public Document setId(String id) {
this.id = id;
return this;
}
public String getRevision() {
return revision;
}
public Document setRevision(String revision) {
this.revision = revision;
return this;
}
public Map<String, Attachment> getAttachments() {
return attachments;
}
public void setAttachments(Map<String, Attachment> attachments) {
this.attachments = attachments;
}
public Object get(String key) {
return optionalFields.get(key);
}
@JsonAnyGetter
public Map<String, Object> getOptional() {
return optionalFields;
}
@JsonAnySetter
public Document set(String key, Object value) {
optionalFields.put(key, value);
return this;
}
static class Attachment {
@JsonProperty("content_type")
private String contentType;
private long length;
private boolean stub;
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public long getLength() {
return length;
}
public void setLength(long length) {
this.length = length;
}
public boolean isStub() {
return stub;
}
public void setStub(boolean stub) {
this.stub = stub;
}
@JsonAnySetter
public void setOptional(String key, Object value) {
// Ignore
}
}
}
|
package org.txazo.jvm.assembly;
public class AssemblyTest {
// VM Args: -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly -XX:+DebugNonSafepoints -XX:PrintAssemblyOptions=intel -XX:CompileCommand=compileonly,org/txazo/jvm/assembly/AssemblyTest::main
public static void main(String[] args) {
int a = 1;
int b = 2;
int c = a + b;
}
}
|
package org.yinwang.pysonar.ast;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.yinwang.pysonar.Binding;
import org.yinwang.pysonar.Indexer;
import org.yinwang.pysonar.Scope;
import org.yinwang.pysonar.types.FunType;
import org.yinwang.pysonar.types.Type;
import java.util.ArrayList;
import java.util.List;
public class FunctionDef extends Node {
public Name name;
public List<Node> args;
public List<Node> defaults;
@Nullable
public List<Type> defaultTypes;
public Name vararg; // *args
public Name kwarg; // **kwarg
public Node body;
private List<Node> decoratorList;
public boolean called = false;
public FunctionDef(Name name, List<Node> args, Block body, List<Node> defaults,
Name vararg, Name kwarg, int start, int end) {
super(start, end);
this.name = name;
this.args = args;
this.body = body;
this.defaults = defaults;
this.vararg = vararg;
this.kwarg = kwarg;
addChildren(name);
addChildren(args);
addChildren(defaults);
addChildren(vararg, kwarg, this.body);
}
public void setDecoratorList(List<Node> decoratorList) {
this.decoratorList = decoratorList;
addChildren(decoratorList);
}
public List<Node> getDecoratorList() {
if (decoratorList == null) {
decoratorList = new ArrayList<Node>();
}
return decoratorList;
}
@Override
public boolean isFunctionDef() {
return true;
}
@Override
public boolean bindsName() {
return true;
}
/**
* Returns the name of the function for indexing/qname purposes.
* Lambdas will return a generated name.
*/
@Nullable
protected String getBindingName(Scope s) {
return name.getId();
}
public List<Node> getArgs() {
return args;
}
public List<Node> getDefaults() {
return defaults;
}
@Nullable
public List<Type> getDefaultTypes() {
return defaultTypes;
}
public Node getBody() {
return body;
}
public Name getName() {
return name;
}
/**
* @return the vararg
*/
public Name getVararg() {
return vararg;
}
/**
* @param vararg the vararg to set
*/
public void setVararg(Name vararg) {
this.vararg = vararg;
}
/**
* @return the kwarg
*/
public Name getKwarg() {
return kwarg;
}
/**
* @param kwarg the kwarg to set
*/
public void setKwarg(Name kwarg) {
this.kwarg = kwarg;
}
/**
* A function's environment is not necessarily the enclosing scope. A
* method's environment is the scope of the most recent scope that is not a
* class.
*
* Be sure to distinguish the environment and the symbol table. The
* function's table is only used for the function's attributes like
* "im_class". Its parent should be the table of the enclosing scope, and
* its path should be derived from that scope too for locating the names
* "lexically".
*/
@NotNull
@Override
public Type resolve(@NotNull Scope outer, int tag) {
resolveList(decoratorList, outer, tag); //XXX: not handling functional transformations yet
FunType fun = new FunType(this, outer.getForwarding());
fun.getTable().setParent(outer);
fun.getTable().setPath(outer.extendPath(getName().getId()));
fun.setDefaultTypes(resolveAndConstructList(defaults, outer, tag));
Indexer.idx.addUncalled(fun);
Binding.Kind funkind;
if (outer.getScopeType() == Scope.ScopeType.CLASS) {
if ("__init__".equals(name.getId())) {
funkind = Binding.Kind.CONSTRUCTOR;
} else {
funkind = Binding.Kind.METHOD;
}
} else {
funkind = Binding.Kind.FUNCTION;
}
Type outType = outer.getType();
if (outType != null && outType.isClassType()) {
fun.setCls(outType.asClassType());
}
NameBinder.bind(outer, name, fun, funkind, tag);
return Indexer.idx.builtins.Cont;
}
@NotNull
@Override
public String toString() {
return "<Function:" + start + ":" + name + ">";
}
@Override
public void visit(@NotNull NodeVisitor v) {
if (v.visit(this)) {
visitNode(name, v);
visitNodeList(args, v);
visitNodeList(defaults, v);
visitNode(kwarg, v);
visitNode(vararg, v);
visitNode(body, v);
}
}
@Override
public boolean equals(Object obj) {
if (obj instanceof FunctionDef) {
FunctionDef fo = (FunctionDef)obj;
return (fo.getFile().equals(getFile()) && fo.start == start);
} else {
return false;
}
}
}
|
package reborncore.api.items;
import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import reborncore.common.util.ItemUtils;
public class InventoryUtils {
public static ItemStack insertItemStacked(Inventory inventory, ItemStack input, boolean simulate) {
ItemStack stack = input.copy();
for (int i = 0; i < inventory.getInvSize(); i++) {
ItemStack targetStack = inventory.getInvStack(i);
//Nice and simple, insert the item into a blank slot
if(targetStack.isEmpty()){
if(!simulate){
inventory.setInvStack(i, stack);
}
return ItemStack.EMPTY;
} else if (ItemUtils.isItemEqual(stack, targetStack, true, false)){
int freeStackSpace = targetStack.getMaxCount() - targetStack.getCount();
if(freeStackSpace > 0){
int transferAmount = Math.min(freeStackSpace, input.getCount());
if(!simulate){
targetStack.increment(transferAmount);
}
stack.decrement(transferAmount);
}
}
}
return stack;
}
}
|
package ru.org.linux.topic;
import org.springframework.web.util.UriComponentsBuilder;
import ru.org.linux.comment.CommentFilter;
public class TopicLinkBuilder {
private final Topic topic;
private final int page;
private final boolean showDeleted;
private final boolean lastmod;
private final Integer comment;
private final String filter;
private TopicLinkBuilder(
Topic topic,
int page,
boolean showDeleted,
boolean lastmod,
Integer comment,
String filter
) {
this.topic = topic;
this.page = page;
this.showDeleted = showDeleted;
this.lastmod = lastmod;
this.comment = comment;
this.filter = filter;
}
public static TopicLinkBuilder baseLink(Topic topic) {
return new TopicLinkBuilder(topic, 0, false, false, null, null);
}
public static TopicLinkBuilder pageLink(Topic topic, int page) {
return new TopicLinkBuilder(topic, page, false, false, null, null);
}
public TopicLinkBuilder showDeleted() {
if (!showDeleted) {
return new TopicLinkBuilder(topic, page, true, lastmod, comment, filter);
} else {
return this;
}
}
public TopicLinkBuilder lastmod(int messagesPerPage) {
if (!lastmod && !topic.isExpired() && topic.getPageCount(messagesPerPage) - 1 == page) {
return forceLastmod();
} else {
return this;
}
}
public TopicLinkBuilder forceLastmod() {
if (!lastmod) {
return new TopicLinkBuilder(topic, page, showDeleted, true, comment, filter);
} else {
return this;
}
}
public TopicLinkBuilder comment(int cid) {
if (comment==null || comment!=cid) {
return new TopicLinkBuilder(topic, page, showDeleted, lastmod, cid, filter);
} else {
return this;
}
}
public TopicLinkBuilder filter(int filter) { // TODO: use Enum for filter
String value = CommentFilter.toString(filter);
if (!value.equals(value)) {
return new TopicLinkBuilder(topic, page, showDeleted, lastmod, comment, value);
} else {
return this;
}
}
public String build() {
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(topic.getLinkPage(page));
if (showDeleted) {
builder.queryParam("deleted", "true");
}
if (lastmod) {
builder.queryParam("lastmod", topic.getLastModified().getTime());
}
if (comment!=null) {
builder.fragment("comment-"+comment);
}
if (filter!=null) {
builder.queryParam("filter", filter);
}
return builder.build().toUriString();
}
}
|
package seedu.tache.logic.parser;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import seedu.tache.commons.exceptions.IllegalValueException;
import seedu.tache.commons.util.StringUtil;
import seedu.tache.model.tag.Tag;
import seedu.tache.model.tag.UniqueTagList;
import seedu.tache.model.task.DateTime;
import seedu.tache.model.task.Name;
/**
* Contains utility methods used for parsing strings in the various *Parser classes
*/
public class ParserUtil {
//@@author A0139925U
private static final Pattern INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)");
private static final Pattern NAME_FORMAT = Pattern.compile("^\".+\"");
private static final Pattern DATE_FORMAT = Pattern.compile("^[0-3]?[0-9]/[0-1]?[0-9]/(?:[0-9]{2})?[0-9]{2}$"
+ "|^[0-3]?[0-9]-[0-1]?[0-9]-(?:[0-9]{2})?[0-9]{2}$"
+ "|^[0-3]{1}[0-9]{1}[0-1]{1}[0-9]{1}"
+ "(?:[0-9]{2})?[0-9]{2}$");
private static final Pattern TIME_FORMAT = Pattern.compile("^[0-2][0-9][0-5][0-9]|^([0-1][0-2]|[0-9])"
+ "([.][0-5][0-9])?\\s?(am|pm){1}");
private static final Pattern DURATION_FORMAT = Pattern.compile("^\\d+\\s?((h|hr|hrs)|(m|min|mins))");
public static final int TYPE_TASK = 0;
public static final int TYPE_DETAILED_TASK = 1;
//@@author
//@@author A0150120H
static enum DateTimeType { START, END, UNKNOWN };
public static final String[] START_DATE_IDENTIFIER = {"from"};
public static final String[] END_DATE_IDENTIFIER = {"to", "on", "by", "before"};
//@@author
/**
* Returns the specified index in the {@code command} if it is a positive unsigned integer
* Returns an {@code Optional.empty()} otherwise.
*/
public static Optional<Integer> parseIndex(String command) {
final Matcher matcher = INDEX_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String index = matcher.group("targetIndex");
if (!StringUtil.isUnsignedInteger(index)) {
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
/**
* Returns a new Set populated by all elements in the given list of strings
* Returns an empty set if the given {@code Optional} is empty,
* or if the list contained in the {@code Optional} is empty
*/
public static Set<String> toSet(Optional<List<String>> list) {
List<String> elements = list.orElse(Collections.emptyList());
return new HashSet<>(elements);
}
/**
* Splits a preamble string into ordered fields.
* @return A list of size {@code numFields} where the ith element is the ith field value if specified in
* the input, {@code Optional.empty()} otherwise.
*/
public static List<Optional<String>> splitPreamble(String preamble, int numFields) {
return Arrays.stream(Arrays.copyOf(preamble.split("\\s+", numFields), numFields))
.map(Optional::ofNullable)
.collect(Collectors.toList());
}
/**
* Parses a {@code Optional<String> name} into an {@code Optional<Name>} if {@code name} is present.
*/
public static Optional<Name> parseName(Optional<String> name) throws IllegalValueException {
assert name != null;
return name.isPresent() ? Optional.of(new Name(name.get())) : Optional.empty();
}
/**
* Parses {@code Collection<String> tags} into an {@code UniqueTagList}.
*/
public static UniqueTagList parseTags(Collection<String> tags) throws IllegalValueException {
assert tags != null;
final Set<Tag> tagSet = new HashSet<>();
for (String tagName : tags) {
tagSet.add(new Tag(tagName));
}
return new UniqueTagList(tagSet);
}
//@@author A0139925U
/**
* Returns True if input is a valid date
* Returns False otherwise.
*/
public static boolean isValidDate(String input) {
final Matcher matcher = DATE_FORMAT.matcher(input.trim());
return matcher.matches();
}
/**
* Returns True if input is a valid time
* Returns False otherwise.
*/
public static boolean isValidTime(String input) {
final Matcher matcher = TIME_FORMAT.matcher(input.trim());
return matcher.matches();
}
/**
* Returns True if input is a valid duration
* Returns False otherwise.
*/
public static boolean isValidDuration(String input) {
final Matcher matcher = DURATION_FORMAT.matcher(input.trim());
return matcher.matches();
}
/**
* Returns True if input is a valid name
* Returns False otherwise.
*/
public static boolean isValidName(String input) {
final Matcher matcher = NAME_FORMAT.matcher(input.trim());
return matcher.matches();
}
//@@author
/**
* Returns number of date parameters in input.
*/
public static boolean hasDate(String input) {
try {
parseDate(input);
return true;
} catch (IllegalValueException ex) {
return false;
}
}
/**
* Returns number of time parameters in input.
*/
public static boolean hasTime(String input) {
try {
parseTime(input);
return true;
} catch (IllegalValueException ex) {
return false;
}
}
//@@author A0150120H
/**
* Returns the first time String encountered
*/
public static String parseTime(String input) throws IllegalValueException {
String[] inputs = input.split(" ");
for (String candidate : inputs) {
Matcher matcher = TIME_FORMAT.matcher(candidate.trim());
if (matcher.lookingAt()) {
return matcher.group();
}
}
throw new IllegalValueException("Invalid Input");
}
/**
* Returns the first date String encountered
*/
public static String parseDate(String input) throws IllegalValueException {
String[] inputs = input.split(" ");
for (String candidate : inputs) {
Matcher matcher = DATE_FORMAT.matcher(candidate.trim());
if (matcher.lookingAt()) {
return matcher.group();
}
}
throw new IllegalValueException("Invalid Input");
}
/**
* Checks if the given String is a start date identifier
* @param s String to check
* @return true if it's a start date identifier, false otherwise
*/
public static boolean isStartDateIdentifier(String s) {
for (String identifier: START_DATE_IDENTIFIER) {
if (s.equalsIgnoreCase(identifier)) {
return true;
}
}
return false;
}
/**
* Checks if the given String is an end date identifier
* @param s String to check
* @return true if it's a start date identifier, false otherwise
*/
public static boolean isEndDateIdentifier(String s) {
for (String identifier: END_DATE_IDENTIFIER) {
if (s.equalsIgnoreCase(identifier)) {
return true;
}
}
return false;
}
/**
* Looks for all possible date/time strings based on identifiers
* @param input String to parse
* @return Deque of PossibleDateTime objects, each representing a possible date/time string
*/
public static Deque<PossibleDateTime> parseDateTimeIdentifiers(String input) {
String[] inputs = input.split(" ");
Deque<PossibleDateTime> result = new LinkedList<PossibleDateTime>();
PossibleDateTime current = new PossibleDateTime(PossibleDateTime.INVALID_INDEX, DateTimeType.UNKNOWN);
for (int i = 0; i < inputs.length; i++) {
String word = inputs[i];
if (isStartDateIdentifier(word)) {
result.push(current);
current = new PossibleDateTime(i, DateTimeType.START);
} else if (isEndDateIdentifier(word)) {
result.push(current);
current = new PossibleDateTime(i, DateTimeType.END);
} else {
current.appendDateTime(i, word);
}
}
result.push(current);
return result;
}
/**
* Class to describe a date/time String that was found
*
*/
static class PossibleDateTime {
int startIndex;
int endIndex;
String data;
DateTimeType type;
static final int INVALID_INDEX = -1;
PossibleDateTime(int index, DateTimeType type) {
this.startIndex = index;
this.endIndex = index;
this.type = type;
this.data = new String();
}
void appendDateTime(int index, String data) {
this.data += " " + data;
this.endIndex = index;
}
}
}
|
package seedu.task.model.task;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import seedu.address.commons.exceptions.IllegalValueException;
/**
* Represents a Task Start DateTime in the task book.
* Guarantees: immutable; is valid as declared in {@link #isValidDateTime(String)}
*/
public class StartDateTime {
public static final String MESSAGE_START_DATETIME_CONSTRAINTS =
"Start Date/Time must be in the format of DD/MM/YYYY HHMM, where time is represented in 24 hours";
public static final SimpleDateFormat START_DATETIME_FORMATTER = new SimpleDateFormat("dd/MM/yyyy HHmm");
public final Date value;
public StartDateTime(String startDateTime) throws IllegalValueException {
assert startDateTime != null;
String trimmedStartDateTime = startDateTime.trim();
try {
this.value = START_DATETIME_FORMATTER.parse(trimmedStartDateTime);
} catch (ParseException e) {
throw new IllegalValueException(MESSAGE_START_DATETIME_CONSTRAINTS);
}
}
/**
* Returns if a given string is a valid start datetime.
*/
public static boolean isValidStartDateTime(String test) {
START_DATETIME_FORMATTER.setLenient(false);
try {
START_DATETIME_FORMATTER.parse(test);
} catch(ParseException e) {
return false;
}
return true;
}
@Override
public String toString() {
return value.toString();
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof StartDateTime // instanceof handles nulls
&& this.value.equals(((StartDateTime) other).value)); // state check
}
@Override
public int hashCode() {
return value.hashCode();
}
}
|
package squire.controllers;
import com.sun.scenario.Settings;
import google.mobwrite.ShareJTextComponent;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.*;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
//import squire.FileList;
import squire.Main;
import squire.Projects.Project;
import squire.Users.User;
import javax.tools.*;
import java.awt.*;
import java.io.*;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import org.fxmisc.richtext.*;
public class EditorController implements Initializable
{
@FXML
private ImageView avatarImageView;
@FXML
private Button homeButton;
@FXML
private TreeView fileExplorer;
@FXML
private TextArea editorTextArea;
// FileList fl = new FileList();
// Compilation vars.
@FXML
private TextArea compilationOutputTextArea;
@FXML
private CodeArea sourceCodeTextArea;
@FXML
private TabPane editorTabPane;
private Project currentProject;
private User currentUser;
private File oldFile;
private ShareJTextComponent mobwriteComponent;
PrintStream compilationOutputStream;
private JavaCompiler compiler;
private DiagnosticCollector<JavaFileObject> diagnostics;
StandardJavaFileManager fileManager;
Iterable<? extends JavaFileObject> compilationUnits;
JavaCompiler.CompilationTask task;
// Compilation vars.
@Override
public void initialize(URL location, ResourceBundle resources) {
avatarImageView.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> onAvatarImageViewClick());
currentUser = Main.getCurrentUser();
currentProject = currentUser.getCurrentProject();
compilationOutputTextArea.setWrapText(true);
setupFileList();
setupMobWrite();
}
private void onAvatarImageViewClick() {
FXMLLoader loader = new FXMLLoader();
Stage dialogStage = new Stage();
dialogStage.setTitle("User Profile");
dialogStage.initModality(Modality.WINDOW_MODAL);
dialogStage.initOwner(avatarImageView.getScene().getWindow());
dialogStage.setResizable(false);
try {
Parent root = loader.load(getClass().getResource("/fxml/Preferences2.fxml"));
Scene scene = new Scene(root);
dialogStage.setScene(scene);
dialogStage.showAndWait();
} catch (Exception e) {
e.printStackTrace();
}
}
@FXML
private void onHomeButtonClick(ActionEvent event) {
try {
FXMLLoader loader = new FXMLLoader();
Parent root = loader.load(getClass().getResource("/fxml/Home.fxml"));
Stage stage = (Stage) homeButton.getScene().getWindow();
Scene scene = new Scene(root);
stage.setHeight(400);
stage.setWidth(600);
stage.setTitle("sQuire Home");
stage.setResizable(false);
stage.setScene(scene);
stage.show();
} catch (Exception exception) {
exception.printStackTrace();
}
}
public void setupFileList()
{
//Set up tree view cell factory
TreeItem<String> rootItem = new TreeItem<>(currentProject.getProjectName());
rootItem.setExpanded(true);
for (File file : currentProject.getFileList()) {
// Get just the filename
String fileName = file.getName();
TreeItem<String> item = new TreeItem<>(fileName);
rootItem.getChildren().add(item);
}
fileExplorer.setRoot(rootItem);
fileExplorer.setEditable(false);
fileExplorer.setCellFactory(p -> {
// Name used for class in oracle online demo
return new TextFieldTreeCellImpl();
});
// One way to get the clicked on cell
fileExplorer.setOnMouseClicked(new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent mouseEvent)
{
if (mouseEvent.getClickCount() == 2)
{
TreeItem<String> selectedItem = (TreeItem<String>) fileExplorer.getSelectionModel().getSelectedItem();
try
{
Scanner input = new Scanner(System.in);
// TODO: get this string to be the actual path of the file
String newFilePath = currentProject.getProjectPath() + File.separator + selectedItem
.getValue();
//String oldFilePath = "";
File file = new File(newFilePath);
CodeArea newTabCodeArea = new CodeArea();
// writeFileBackOnSwitchTab();
createNewTab(file, newTabCodeArea);
input = new Scanner(file);
writeFile(input, newTabCodeArea);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
});
}
//Create new tab programatically
public void createNewTab(File file, CodeArea newTabCodeArea)
{
Tab newTab = new Tab();
newTab.setText(file.getName());
newTabCodeArea.setLayoutX(167.0);
newTabCodeArea.setLayoutY(27.0);
newTabCodeArea.setPrefHeight(558.0);
newTabCodeArea.setPrefWidth(709.0);
AnchorPane ap = new AnchorPane(newTabCodeArea);
//Setup information from FXML
// <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">
// <children>
// <CodeArea fx:id="sourceCodeTextArea" layoutX="167.0" layoutY="27.0" prefHeight="558.0" prefWidth="709.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
// </children>
// </AnchorPane>
ap.setMinHeight(0.0);
ap.setMinWidth(0.0);
ap.setPrefHeight(180.0);
ap.setPrefWidth(200.0);
ap.setBottomAnchor(newTabCodeArea, 0.0);
ap.setTopAnchor(newTabCodeArea, 0.0);
ap.setRightAnchor(newTabCodeArea, 0.0);
ap.setLeftAnchor(newTabCodeArea, 0.0);
newTab.setContent(ap);
editorTabPane.getTabs().add(newTab);
}
// Write the file to the CodeArea
public void writeFile(Scanner input, CodeArea newTabCodeArea)
{
// Open the file on click
newTabCodeArea.positionCaret(0);
while (input.hasNextLine())
{
String line = input.nextLine();
newTabCodeArea.appendText(line + "\n");
}
input.close();
}
public void writeFileBackOnSwitchTab()
{
// // Basic way to write files back
// Tab curTab = editorTabPane.getSelectionModel().getSelectedItem();
// oldFilePath = currentProject.getProjectPath() + File.separator + curTab.getText();
// oldFile = new File (oldFilePath);
// try
// BufferedWriter bf = new BufferedWriter(new FileWriter(oldFilePath )); //+ ".tmp"));
// bf.write(newTabCodeArea.getText());
// bf.flush();
// bf.close();
// catch (IOException e)
// e.printStackTrace();
}
//TODO: create a new mobwrite component based on projectID, fileID in database that we can connect to
// TODO: every time we switch tabs
public void setupMobWrite()
{
mobwriteComponent = new ShareJTextComponent(sourceCodeTextArea, currentProject.getProjectName());
Main.getMobwriteClient().share(mobwriteComponent);
}
private final class TextFieldTreeCellImpl extends TreeCell<String> {
private TextField textField;
public TextFieldTreeCellImpl()
{
}
@Override
public void startEdit()
{
super.startEdit();
if (textField == null)
{
createTextField();
}
setText(null);
setGraphic(textField);
textField.selectAll();
}
@Override
public void cancelEdit()
{
super.cancelEdit();
setText((String) getItem());
setGraphic(getTreeItem().getGraphic());
}
@Override
public void updateItem(String item, boolean empty)
{
super.updateItem(item, empty);
if (empty)
{
setText(null);
setGraphic(null);
}
else
{
if (isEditing())
{
if (textField != null)
{
textField.setText(getString());
}
setText(null);
setGraphic(textField);
}
else
{
setText(getString());
setGraphic(getTreeItem().getGraphic());
}
}
}
private void createTextField()
{
textField = new TextField(getString());
textField.setOnKeyReleased(new EventHandler<KeyEvent>()
{
@Override
public void handle(KeyEvent t)
{
if (t.getCode() == KeyCode.ENTER)
{
commitEdit(textField.getText());
}
else if (t.getCode() == KeyCode.ESCAPE)
{
cancelEdit();
}
}
});
}
private String getString()
{
return getItem() == null ? "" : getItem().toString();
}
}
@FXML
private void onRunButtonClick(ActionEvent event) {
compileCode();
}
private void compileCode()
{
compilationOutputTextArea.appendText("Compiling...\n");
File entryPoint = currentProject.getEntryPointClassFile();
String javacPath = squire.Projects.Settings.getSettingsMap().get("jdkLocation") + File.separator + "javac";
String javaExePath = squire.Projects.Settings.getSettingsMap().get("jdkLocation") + File.separator + "java";
try
{
ProcessBuilder compilation = new ProcessBuilder(javacPath, entryPoint.getName());
compilation.directory(new File(currentProject.getProjectPath()));
Process p = compilation.start();
int errorCode = p.waitFor();
System.out.println("p1 Error Code: " + errorCode);
ProcessBuilder execution = new ProcessBuilder(javaExePath, entryPoint.getName().replace(".java", ""));
execution.directory(new File(currentProject.getProjectPath()));
Process p2 = execution.start();
p2.waitFor(5, TimeUnit.SECONDS);
int errorCode2 = p2.exitValue();
System.out.println("p2 Error Code: " + errorCode2);
String line;
BufferedReader input = new BufferedReader(new InputStreamReader(p2.getInputStream()));
while ((line = input.readLine()) != null)
{
compilationOutputTextArea.appendText(line);
compilationOutputTextArea.appendText("\n");
}
input.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
|
package tech.greenfield.vertx.irked;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Stream;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.*;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.HttpException;
import io.vertx.ext.web.impl.RoutingContextDecorator;
import tech.greenfield.vertx.irked.Controller.WebHandler;
import tech.greenfield.vertx.irked.auth.AuthorizationToken;
import tech.greenfield.vertx.irked.exceptions.MissingBodyException;
import tech.greenfield.vertx.irked.status.BadRequest;
import tech.greenfield.vertx.irked.status.OK;
/**
* Request handling wrapper which adds some useful routines for
* API writers.
*
* Can serve as a basis for local context parsers that API writers
* can use to expose path arguments from parent prefixes
*
* @author odeda
*/
public class Request extends RoutingContextDecorator {
private RoutingContext outerContext;
public Request(RoutingContext outerContext) {
super(outerContext.currentRoute(), outerContext);
this.outerContext = outerContext;
}
@Override
public void next() {
this.outerContext.next();
}
@Override
public void fail(int statusCode) {
// we're overriding the fail handlers, which for some reason the decorator
// feels should be moved to another thread. Instead, use the outer implementation
// and let it do what's right
this.outerContext.fail(statusCode);
}
/**
* Fail helper that wraps Irked HTTP errors in Vert.x-web (final?!) HttpException class
* that is better handled by the RoutingContextImpl
* @param httpError error to fail with
*/
public void fail(HttpError httpError) {
fail(new HttpException(httpError.getStatusCode(), httpError));
}
@Override
public void fail(Throwable throwable) {
// we're overriding the fail handlers, which for some reason the decorator
// feels should be moved to another thread. Instead, use the outer implementation
// and let it do what's right
this.outerContext.fail(throwable);
}
/**
* Helper failure handler for CompletableFuture users.
* Use at the end of an async chain to succinctly propagate exceptions, as
* thus: <code>.exceptionally(req::handleFailure)</code>.
* This method will call {@link #fail(Throwable)} after unwrapping
* {@link RuntimeException}s as needed.
* @param throwable A {@link Throwable} error to fail on
* @return null
*/
public Void handleFailure(Throwable throwable) {
fail(HttpError.unwrap(throwable));
return null;
}
/**
* Helper failure handler for CompletableFuture users.
* Use in the middle an async chain to succinctly propagate exceptions, or
* success values as thus: <code>.whenComplete(req::handlePossibleFailure)</code>.
* This method will call {@link Request#fail(Throwable)} if a failure occurred,
* after unwrapping {@link RuntimeException}s as needed. It will also pass on
* the success value (or null if there was a failure) for the next async
* element. Subsequent code can check whether a failure was propagated
* by calling {@link #failed()}
* @param <V> the type of previous completion value that will be returned as the completion value for completion stages running this method
* @param successValue successful completion value to return in case no failure occurred
* @param throwable A {@link Throwable} error to fail on
* @return null
*/
public <V> V handlePossibleFailure(V successValue, Throwable throwable) {
if (Objects.nonNull(throwable))
fail(HttpError.unwrap(throwable));
return successValue;
}
/**
* Helper to easily configure standard failure handlers
* @return a WebHandler that sends Irked status exceptions as HTTP responses
*/
public static WebHandler failureHandler() {
return r -> {
r.sendError(HttpError.toHttpError(r));
};
}
public <T> T getBodyAs(Class<T> type) {
String contentType = this.request().getHeader("Content-Type");
if (Objects.isNull(contentType)) contentType = "application/json"; // we love JSON
String[] ctParts = contentType.split(";\\s*");
switch (ctParts[0]) {
case "application/x-www-form-urlencoded":
JsonObject out = new JsonObject();
request().formAttributes().forEach(e -> {
Object old = out.getValue(e.getKey());
if (Objects.isNull(old)) {
out.put(e.getKey(), e.getValue());
return;
}
if (old instanceof JsonArray) {
((JsonArray)old).add(e.getValue());
return;
}
out.put(e.getKey(), new JsonArray().add(old).add(e.getValue()));
});
return out.mapTo(type);
case "application/json":
default:
try {
JsonObject body = getBodyAsJson();
if (body == null)
throw new MissingBodyException().unchecked();
return body.mapTo(type);
} catch (DecodeException e) {
throw new BadRequest("Unrecognized content-type " + ctParts[0] +
" and content does not decode as JSON: " + e.getMessage()).unchecked();
}
}
}
/**
* Helper method to terminate request processing with a success (200 OK) response
* containing a JSON body.
* @param json {@link JsonObject} containing the output to encode
*/
public void sendJSON(JsonObject json) {
sendJSON(json, new OK());
}
/**
* Helper method to terminate a request processing with a success (200 OK) response
* containing a JSON object mapped from the specified POJO
* @param data POJO containing the data to map to a JSON encoded object
*/
public void sendObject(Object data) {
sendJSON(JsonObject.mapFrom(data));
}
/**
* Helper method to terminate request processing with a success (200 OK) response
* containing a JSON body.
* @param json {@link JsonArray} containing the output to encode
*/
public void sendJSON(JsonArray json) {
sendJSON(json, new OK());
}
/**
* Helper method to terminate request processing with a custom response
* containing a JSON body and the specified status line.
* @param json {@link JsonObject} containing the output to encode
* @param status An HttpError object representing the HTTP status to be sent
*/
public void sendJSON(JsonObject json, HttpError status) {
sendContent(json.encode(), status, "application/json");
}
/**
* Helper method to terminate a request processing with a custom response
* containing a JSON object mapped from the specified POJO and the specified status line.
* @param data POJO containing the data to map to a JSON encoded object
* @param status An HttpError object representing the HTTP status to be sent
*/
public void sendObject(Object data, HttpError status) {
sendJSON(JsonObject.mapFrom(data), status);
}
/**
* Helper method to terminate request processing with a custom response
* containing a JSON body and the specified status line.
* @param json {@link JsonArray} containing the output to encode
* @param status HTTP status to send
*/
public void sendJSON(JsonArray json, HttpError status) {
sendContent(json.encode(), status, "application/json");
}
/**
* Helper method to terminate request processing with a custom response
* containing some text and the specified status line.
* @param content Text content to send in the response
* @param status An HttpError object representing the HTTP status to be sent
* @param contentType The MIME Content-Type to be set for the response
*/
public void sendContent(String content, HttpError status, String contentType) {
sendContent(Buffer.buffer(content), status, contentType);
}
/**
* Helper method to terminate request processing with a custom response
* containing some data and the specified status line.
* @param content Binary content to send in the response
* @param status An HttpError object representing the HTTP status to be sent
* @param contentType The MIME Content-Type to be set for the response
*/
public void sendContent(Buffer content, HttpError status, String contentType) {
response(status)
.putHeader("Content-Type", contentType)
.putHeader("Content-Length", String.valueOf(content.length()))
.end(content);
}
/**
* Helper method to terminate request processing with a custom response
* containing some text and the specifeid status line.
* @param content Text content to send in the response
* @param contentType The MIME Content-Type to be set for the response
*/
public void sendContent(String content, String contentType) {
sendContent(content, new OK(), contentType);
}
/**
* Helper method to terminate request processing with a custom response
* containing some text and the specifeid status line.
* @param content Text content to send in the response
* @param status An HttpError object representing the HTTP status to be sent
*/
public void sendContent(String content, HttpError status) {
sendContent(content, status, "text/plain");
}
/**
* Helper method to terminate request processing with a custom response
* containing some text and the specifeid status line.
* @param content Text content to send in the response
*/
public void sendContent(String content) {
sendContent(content, new OK(), "text/plain");
}
/**
* Helper method to terminate request processing with an HTTP error (non-200 OK) response.
* The resulting HTTP response will have the correct status line and an application/json content
* with a JSON encoded object containing the fields "status" set to "false" and "message" set
* to the {@link HttpError}'s message.
* @param status An HttpError object representing the HTTP status to be sent
*/
public void sendError(HttpError status) {
sendJSON(new JsonObject().put("status", status.getStatusCode() / 100 == 2).put("message", status.getMessage()), status);
}
/**
* Helper method to terminate request processing with an HTTP OK and a JSON response
* @param object {@link JsonObject} of data to send
*/
public void send(JsonObject object) {
sendJSON(object);
}
/**
* Helper method to terminate request processing with an HTTP OK and a JSON response
* @param list {@link JsonArray} of a list of data to send
*/
public void send(JsonArray list) {
sendJSON(list);
}
/**
* Helper method to terminate request processing with an HTTP OK and a text/plain response
* @param content text to send
*/
public void send(String content) {
sendContent(content);
}
/**
* Helper method to terminate request processing with an HTTP OK and a application/octet-stream response
* @param buffer binary data to send
*/
public void send(Buffer buffer) {
sendContent(buffer, new OK(), "application/octet-stream");
}
/**
* Helper method to terminate request processing with a non-OK HTTP response with default text
* @param status {@link HttpError} to send
*/
public void send(HttpError status) {
sendError(status);
}
/**
* Helper method to terminate request processing with an HTTP OK and an application/json
* response containing a list of {@link io.vertx.core.json.Json}-encoded objects
* @param <G> type of objects in the list
* @param list List to convert to a JSON array for sending
*/
public <G> void sendList(List<G> list) {
sendStream(list.stream());
}
/**
* Helper method to terminate request processing with an HTTP OK and an application/json
* response containing a stream of {@link io.vertx.core.json.Json}-encoded objects.
* Please note that the response will be buffered in memory using a {@link io.vertx.core.json.JsonArray}
* based collector.
* @param <G> type of objects in the stream
* @param stream Stream to convert to a JSON array for sending
*/
public <G> void sendStream(Stream<G> stream) {
sendJSON(stream.map(this::encodeToJsonType).collect(JsonArray::new, JsonArray::add, JsonArray::addAll));
}
/**
* Helper method to terminate request processing with an HTTP OK and a JSON response
* @param object custom object to process through Jackson's {@link ObjectMapper} to generate JSON content
*/
@SuppressWarnings("unchecked")
public void send(Object object) {
if (object instanceof List)
sendList((List<Object>)object);
else if (object instanceof Stream)
sendStream((Stream<Object>)object);
else
sendObject(object);
}
/**
* Helper method to generate response with the specified HTTP status
* @param status HTTP status code and text to set on the response
* @return HTTP response created using {@link RoutingContext#response()}
*/
public HttpServerResponse response(HttpError status) {
HttpServerResponse res = response();
for (Entry<String, String> h : status.getHeaders())
res.putHeader(h.getKey(), h.getValue());
return res.setStatusCode(status.getStatusCode()).setStatusMessage(status.getStatusText());
}
/**
* Check if the client requested a connection upgrade, regardless which type
* of upgrade is required.
* @return {@literal true} if the request includes a 'Connection: upgrade' header.
*/
public boolean needUpgrade() {
return needUpgrade(null);
}
/**
* check if the client requested a specific connection upgrade.
* @param type What upgrade type to test against, case insensitive
* @return {@literal true} if the request includes a 'Connection: upgrade' header and an 'Upgrade' header with the specified type.
*/
public boolean needUpgrade(String type) {
HttpServerRequest req = request();
return req.getHeader("Connection").equalsIgnoreCase("upgrade") && (Objects.isNull(type) || req.getHeader("Upgrade").equalsIgnoreCase(type));
}
/**
* Helper for authorization header parsing
* @return A parsed {@link AuthorizationToken}
*/
public AuthorizationToken getAuthorization() {
return AuthorizationToken.parse(request().getHeader("Authorization"));
}
/**
* Helper method to encode arbitrary types to a type that Vert.x
* @{link io.vertx.json.JsonObject} and @{link io.vertx.json.JsonArray}
* will accept.
*
* This implementation recognizes some types as Vert.x JSON "safe" (i.e. can
* be used with <code>JsonArray::add</code> but not all the types that would be
* accepted. Ideally we would use Json.checkAndCopy() but it is not visible.
* @param value object to recode to a valid JSON type
* @return a type that will be accepted by JsonArray.add();
*/
private Object encodeToJsonType(Object value) {
if (value instanceof Boolean ||
value instanceof Number ||
value instanceof String ||
value instanceof JsonArray ||
value instanceof List ||
value instanceof JsonObject ||
value instanceof Map)
return value;
return JsonObject.mapFrom(value);
}
}
|
package uk.ac.soton.ecs.comp3005;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import org.openimaj.content.slideshow.Slide;
import org.openimaj.content.slideshow.SlideshowApplication;
import org.openimaj.image.DisplayUtilities;
import org.openimaj.image.DisplayUtilities.ImageComponent;
import org.openimaj.image.ImageUtilities;
import org.openimaj.image.MBFImage;
import org.openimaj.image.colour.ColourSpace;
import org.openimaj.image.colour.RGBColour;
import org.openimaj.knn.DoubleNearestNeighboursExact;
import org.openimaj.math.geometry.point.Point2dImpl;
import org.openimaj.math.geometry.shape.Circle;
import org.openimaj.util.array.ArrayUtils;
import org.openimaj.util.pair.IntDoublePair;
import org.openimaj.video.VideoDisplay;
import org.openimaj.video.VideoDisplayListener;
import uk.ac.soton.ecs.comp3005.utils.VideoCaptureComponent;
public class KMeansDemo implements Slide, ActionListener, VideoDisplayListener<MBFImage> {
private static final String[] CLASSES = { "RED", "BLUE" };
private Float[][] COLOURS = { RGBColour.RED, RGBColour.BLUE };
private VideoCaptureComponent vc;
private ColourSpace colourSpace = ColourSpace.HS;
private JTextField featureField;
private MBFImage image;
private ImageComponent imageComp;
private BufferedImage bimg;
private JSpinner kField;
private List<double[]> points = new ArrayList<double[]>();
private List<Integer> classes = new ArrayList<Integer>();
private JComboBox<String> classType;
private double[] lastMean;
private JTextField guess;
@Override
public Component getComponent(int width, int height) throws IOException {
vc = new VideoCaptureComponent(320, 240);
vc.getDisplay().addVideoListener(this);
// the main panel
final JPanel base = new JPanel();
base.setOpaque(false);
base.setPreferredSize(new Dimension(width, height));
base.setLayout(new GridBagLayout());
// left hand side (video, features)
final Box videoCtrls = Box.createVerticalBox();
videoCtrls.add(vc);
videoCtrls.add(Box.createVerticalStrut(10));
final JPanel colourspacesPanel = createColourSpaceButtons();
videoCtrls.add(colourspacesPanel);
createFeatureField();
videoCtrls.add(Box.createVerticalStrut(10));
videoCtrls.add(featureField);
base.add(videoCtrls);
// right hand box
final Box rightPanel = Box.createVerticalBox();
image = new MBFImage(400, 400, ColourSpace.RGB);
image.fill(RGBColour.WHITE);
imageComp = new DisplayUtilities.ImageComponent(true);
imageComp.setShowPixelColours(false);
imageComp.setShowXYPosition(false);
imageComp.setAllowZoom(false);
imageComp.setAllowPanning(false);
rightPanel.add(imageComp);
final JPanel classCtrlsCnt = new JPanel(new GridLayout(1, 2));
// learning controls
final JPanel learnCtrls = new JPanel(new GridLayout(0, 1));
classType = new JComboBox<String>();
for (final String c : CLASSES)
classType.addItem(c);
learnCtrls.add(classType);
final JButton learnButton = new JButton("Learn");
learnButton.setActionCommand("button.learn");
learnButton.addActionListener(this);
learnCtrls.add(learnButton);
classCtrlsCnt.add(learnCtrls);
// classification controls
final JPanel classCtrls = new JPanel(new GridLayout(0, 1));
final JPanel cnt = new JPanel();
cnt.add(new JLabel("K:"));
cnt.add(kField = new JSpinner(new SpinnerNumberModel(1, 1, 10, 1)));
classCtrls.add(cnt);
guess = new JTextField(8);
guess.setFont(Font.decode("Monaco-24"));
guess.setHorizontalAlignment(JTextField.CENTER);
guess.setEditable(false);
classCtrls.add(guess);
classCtrlsCnt.add(classCtrls);
rightPanel.add(classCtrlsCnt);
base.add(rightPanel);
redraw();
return base;
}
private void createFeatureField() {
featureField = new JTextField();
featureField.setFont(Font.decode("Monaco-24"));
featureField.setHorizontalAlignment(JTextField.CENTER);
featureField.setEditable(false);
featureField.setBorder(null);
}
private JPanel createColourSpaceButtons() {
final JPanel colourspacesPanel = new JPanel();
colourspacesPanel.setLayout(new BoxLayout(colourspacesPanel, BoxLayout.X_AXIS));
colourspacesPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
final ButtonGroup group = new ButtonGroup();
createRadioButton(colourspacesPanel, group, ColourSpace.HUE);
createRadioButton(colourspacesPanel, group, ColourSpace.HS);
createRadioButton(colourspacesPanel, group, ColourSpace.H1H2);
return colourspacesPanel;
}
/**
* Create a radio button
*
* @param colourspacesPanel
* the panel to add the button too
* @param group
* the radio button group
* @param cs
* the colourSpace that the button represents
*/
private void createRadioButton(final JPanel colourspacesPanel, final ButtonGroup group, final ColourSpace cs) {
final String name = cs.name();
final JRadioButton button = new JRadioButton(name);
button.setActionCommand("ColourSpace." + name);
colourspacesPanel.add(button);
group.add(button);
button.setSelected(cs == ColourSpace.HS);
button.addActionListener(this);
}
@Override
public void close() {
vc.close();
}
@Override
public void actionPerformed(ActionEvent e) {
final String rawcmd = e.getActionCommand();
final String cmd = rawcmd.substring(rawcmd.indexOf(".") + 1);
if (rawcmd.startsWith("ColourSpace.")) {
// change the colour space to the one selected
this.colourSpace = ColourSpace.valueOf(cmd);
} else if (rawcmd.startsWith("button.")) {
if (cmd.equals("learn")) {
doLearn(lastMean, this.classType.getSelectedIndex());
}
}
}
private void doClassify(double[] mean) {
if (points.size() > 0) {
final int k = (Integer) kField.getValue();
final DoubleNearestNeighboursExact nn = new DoubleNearestNeighboursExact(
points.toArray(new double[points.size()][]));
final List<IntDoublePair> neighbours = nn.searchKNN(mean, k);
final int[] counts = new int[CLASSES.length];
for (final IntDoublePair p : neighbours) {
counts[this.classes.get(p.first)]++;
final double[] pt = this.points.get(p.first);
final Point2dImpl pti = new Point2dImpl();
pti.x = 50 + (float) (300 * pt[0]);
if (pt.length == 2)
pti.y = 350 - (float) (300 * pt[1]);
else
pti.y = 350;
image.drawPoint(pti, RGBColour.MAGENTA, 3);
image.drawShape(new Circle(pti, 5), RGBColour.GREEN);
}
imageComp.setImage(bimg = ImageUtilities.createBufferedImageForDisplay(image, bimg));
final int[] indices = ArrayUtils.range(0, counts.length - 1);
ArrayUtils.parallelQuicksortDescending(counts, indices);
if (counts.length == 1 || counts[0] > counts[1]) {
guess.setText(this.classType.getItemAt(indices[0]));
return;
}
}
guess.setText("unknown");
}
private void doLearn(double[] mean, int clazz) {
this.points.add(mean);
this.classes.add(clazz);
redraw();
}
private void redraw() {
this.image.fill(RGBColour.WHITE);
// draw saved points
final Point2dImpl pti = new Point2dImpl();
for (int i = 0; i < points.size(); i++) {
final double[] pt = points.get(i);
pti.x = 50f + (float) (300 * pt[0]);
if (pt.length == 2)
pti.y = 350 - (float) (300 * pt[1]);
else
pti.y = 350;
image.drawPoint(pti, COLOURS[classes.get(i)], 3);
}
// draw current point
if (lastMean != null) {
pti.x = 50 + (float) (300 * lastMean[0]);
if (lastMean.length == 2)
pti.y = 350 - (float) (300 * lastMean[1]);
else
pti.y = 350;
image.drawPoint(pti, RGBColour.MAGENTA, 3);
}
image.drawLine(50, 45, 50, 355, RGBColour.BLACK);
image.drawLine(125, 50, 125, 355, RGBColour.GRAY);
image.drawLine(200, 50, 200, 355, RGBColour.GRAY);
image.drawLine(275, 50, 275, 355, RGBColour.GRAY);
image.drawLine(350, 50, 350, 355, RGBColour.GRAY);
image.drawLine(45, 350, 355, 350, RGBColour.BLACK);
image.drawLine(45, 50, 350, 50, RGBColour.GRAY);
image.drawLine(45, 125, 350, 125, RGBColour.GRAY);
image.drawLine(45, 200, 350, 200, RGBColour.GRAY);
image.drawLine(45, 275, 350, 275, RGBColour.GRAY);
imageComp.setImage(bimg = ImageUtilities.createBufferedImageForDisplay(image, bimg));
}
@Override
public void afterUpdate(VideoDisplay<MBFImage> display) {
// do nothing
}
@Override
public void beforeUpdate(MBFImage frame) {
ColourSpacesDemo.convertColours(frame, colourSpace);
lastMean = SimpleMeanColourFeatureDemo.computeMean(frame, colourSpace);
featureField.setText(SimpleMeanColourFeatureDemo.formatVector(lastMean));
redraw();
doClassify(lastMean);
}
public static void main(String[] args) throws IOException {
new SlideshowApplication(new KMeansDemo(), 1024, 768);
}
}
|
package za.redbridge.simulator;
import java.util.HashMap;
import java.util.Map;
import za.redbridge.simulator.phenotype.Phenotype;
public class FitnessStats {
private final Map<Phenotype,Double> phenotypeFitnesses = new HashMap<>();
private double teamFitness = 0.0;
private final double totalResourceValue;
private int maxSteps;
public FitnessStats(double totalResourceValue, int maxSteps) {
this.totalResourceValue = totalResourceValue;
this.maxSteps = maxSteps;
}
/**
* Increment a phenotype's fitness.
* @param phenotype the phenotype who's score will be adjusted
* @param adjustedValue the adjusted value of the resource
*/
public void addToPhenotypeFitness(Phenotype phenotype, double adjustedValue) {
phenotypeFitnesses.put(phenotype, getPhenotypeFitness(phenotype) + adjustedValue);
}
public double getPhenotypeFitness(Phenotype phenotype) {
return phenotypeFitnesses.getOrDefault(phenotype, 0.0);
}
/**
* Increment the team fitness.
* @param value the unadjusted resource value
*/
public void addToTeamFitness(double value) {
teamFitness += value;
}
/** Gets the normalized team fitness including time bonus (out of 120) */
public double getTeamFitnessWithTimeBonus(long stepsTaken) {
return (teamFitness / totalResourceValue) * 100 + (stepsTaken / maxSteps) * 20;
}
/** Gets the normalized team fitness (out of 100) */
public double getTeamFitness() {
return (teamFitness / totalResourceValue) * 100;
}
public Map<Phenotype,Double> getPhenotypeFitnessMap() {
return phenotypeFitnesses;
}
public double getTotalResourceValue() {
return totalResourceValue;
}
}
|
package net.sourceforge.jtds.jdbcx;
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.naming.*;
import javax.sql.*;
import net.sourceforge.jtds.jdbc.*;
/**
* A plain <code>DataSource</code> implementation.
*
* @author Alin Sinplean
* @since jTDS 0.3
*/
public class TdsDataSource
implements ConnectionPoolDataSource, DataSource, Referenceable, Serializable {
private int _loginTimeout;
private String _databaseName = "";
private String _description;
private String _password = "";
private int _portNumber = 1433;
private String _serverName;
private String _user;
private String _tdsVersion = "7.0";
private int _serverType = Tds.SQLSERVER;
private String _domain = "";
private String _instance = "";
private boolean _sendStringParametersAsUnicode = true;
/**
* Constructs a new datasource.
*/
public TdsDataSource() {
}
/**
* Returns a new database connection.
*
* @return a new database connection
* @throws SQLException if an error occurs
*/
public Connection getConnection() throws SQLException {
return getConnection(_user, _password);
}
/**
* Returns a new database connection for the user and password specified.
*
* @param user the user name to connect with
* @param password the password to connect with
* @return a new database connection
* @throws SQLException if an error occurs
*/
public Connection getConnection(String user, String password)
throws SQLException {
Properties props = new Properties();
props.setProperty(Tds.PROP_HOST, _serverName);
props.setProperty(Tds.PROP_SERVERTYPE, String.valueOf(_serverType));
props.setProperty(Tds.PROP_PORT, String.valueOf(_portNumber));
props.setProperty(Tds.PROP_DBNAME, _databaseName);
props.setProperty(Tds.PROP_TDS, _tdsVersion);
props.setProperty(Tds.PROP_DOMAIN, _domain);
props.setProperty(Tds.PROP_INSTANCE, _instance);
props.setProperty(Tds.PROP_USEUNICODE,
String.valueOf(_sendStringParametersAsUnicode));
props.setProperty(Tds.PROP_USER, user);
props.setProperty(Tds.PROP_PASSWORD, password);
return net.sourceforge.jtds.jdbc.Driver.getConnection(props);
}
/**
* Returns a new pooled database connection.
*
* @return a new pooled database connection
* @throws SQLException if an error occurs
*/
public javax.sql.PooledConnection getPooledConnection()
throws SQLException {
return getPooledConnection(_user, _password);
}
/**
* Returns a new pooled database connection for the user and password specified.
*
* @param user the user name to connect with
* @param password the password to connect with
* @return a new pooled database connection
* @throws SQLException if an error occurs
*/
public synchronized javax.sql.PooledConnection getPooledConnection(String user,
String password)
throws SQLException {
return new net.sourceforge.jtds.jdbcx.PooledConnection(getConnection(user, password));
}
public PrintWriter getLogWriter() throws SQLException {
throw new java.lang.UnsupportedOperationException("Method getLogWriter() not yet implemented.");
}
public void setLogWriter(PrintWriter out) throws SQLException {
throw new java.lang.UnsupportedOperationException("Method setLogWriter() not yet implemented.");
}
public void setLoginTimeout(int loginTimeout) throws SQLException {
_loginTimeout = loginTimeout;
}
public int getLoginTimeout() throws SQLException {
return _loginTimeout;
}
public Reference getReference() throws NamingException {
Reference ref = new Reference(getClass().getName(),
TdsObjectFactory.class.getName(),
null);
ref.add(new StringRefAddr("serverName", _serverName));
ref.add(new StringRefAddr("portNumber", String.valueOf(_portNumber)));
ref.add(new StringRefAddr("databaseName", _databaseName));
ref.add(new StringRefAddr("user", _user));
ref.add(new StringRefAddr("password", _password));
ref.add(new StringRefAddr("tdsVersion", _tdsVersion));
ref.add(new StringRefAddr("serverType", String.valueOf(_serverType)));
ref.add(new StringRefAddr("domain", _domain));
ref.add(new StringRefAddr("instance", _instance));
ref.add(new StringRefAddr("sendStringParametersAsUnicode",
String.valueOf(_sendStringParametersAsUnicode)));
return ref;
}
public void setDatabaseName(String databaseName) {
_databaseName = databaseName;
}
public String getDatabaseName() {
return _databaseName;
}
public void setDescription(String description) {
_description = description;
}
public String getDescription() {
return _description;
}
public void setPassword(String password) {
_password = password;
}
public String getPassword() {
return _password;
}
public void setPortNumber(int portNumber) {
_portNumber = portNumber;
}
public int getPortNumber() {
return _portNumber;
}
public void setServerName(String serverName) {
_serverName = serverName;
}
public String getServerName() {
return _serverName;
}
public void setUser(String user) {
_user = user;
}
public String getUser() {
return _user;
}
public void setTdsVersion(String tdsVersion) {
_tdsVersion = tdsVersion;
}
public String getTdsVersion() {
return _tdsVersion;
}
public void setServerType(int serverType) {
_serverType = serverType;
}
public int getServerType() {
return _serverType;
}
public String getDomain() {
return _domain;
}
public void setDomain(String domain) {
_domain = domain;
}
public String getInstance() {
return _instance;
}
public void setInstance(String instance) {
_instance = instance;
}
public boolean getSendStringParametersAsUnicode() {
return _sendStringParametersAsUnicode;
}
public void setSendStringParametersAsUnicode(boolean sendStringParametersAsUnicode) {
_sendStringParametersAsUnicode = sendStringParametersAsUnicode;
}
}
|
package storm;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.networktables.NetworkTable;
import storm.interfaces.*;
import storm.modules.*;
public abstract class RobotState {
/*
private static RobotState instance;
public static RobotState getInstance() {
if (instance == null)
instance = new RobotState();
return instance;
}
*/
private RobotState() {}
//
// Motors
public static final int PORT_MOTOR_DRIVE_LEFT = 8;
public static final int PORT_MOTOR_DRIVE_RIGHT = 3;
public static final int PORT_MOTOR_SHOOTER_WHEEL = 5;
public static final int PORT_MOTOR_3BA = 10;
public static final int PORT_MOTOR_BRIDGE_MANIPULATOR = 1;
public static final int PORT_MOTOR_KANAYERBELT_FEEDER = 4;
public static final int PORT_MOTOR_KANAYERBELT_BOTTOM = 6;
public static final int PORT_MOTOR_KANAYERBELT_TOP = 9;
// Joysticks
public static final int PORT_JOYSTICK_DRIVE = 1;
public static final int PORT_JOYSTICK_SHOOT = 2;
// Joystick Axiseses
public static final int JOYSTICK_1_AXIS_DRIVE_LEFT = 2;
public static final int JOYSTICK_1_AXIS_DRIVE_RIGHT = 4;
public static final int JOYSTICK_1_AXIS_DRIVE_BOTH = 6;
public static final int JOYSTICK_2_AXIS_3BA = 2;
public static final int JOYSTICK_2_AXIS_BRIDGE_MANIPULATOR = 4;
public static final int JOYSTICK_2_AXIS_ELEVATOR = 6;
// Joystick Buttons
public static final int JOYSTICK_1_BUTTON_SWITCH_GEARS = 5;
public static final int JOYSTICK_1_BUTTON_SPEED_MODIFIER = 6;
public static final int JOYSTICK_1_BUTTON_DIRECT_DRIVE = 8;
public static final int JOYSTICK_2_BUTTON_DECREASE_OFFSET = 1;
public static final int JOYSTICK_2_BUTTON_RESET_OFFSET = 2;
public static final int JOYSTICK_2_BUTTON_INCREASE_OFFSET = 3;
public static final int JOYSTICK_2_BUTTON_TOGGLE_DISTANCE = 5;
public static final int JOYSTICK_2_BUTTON_SHOOT = 6;
public static final int JOYSTICK_2_BUTTON_3BA_SAFETY = 7;
public static final int JOYSTICK_2_BUTTON_PRESHOOT = 8;
// Sensors
public static final int PORT_IR_BALL_IN_1 = 6;
public static final int PORT_IR_BALL_IN_2 = 7;
public static final int PORT_IR_BALL_READY = 9;
public static final int PORT_LIMIT_SWITCH_3BA_FRONT = 11;
public static final int PORT_LIMIT_SWITCH_3BA_BACK = 10;
// Gyro
public static final int PORT_GYRO_ROBOT_ROTATION = 1;
// Encoders
public static final int PORT_ENCODER_DRIVE_LEFT_A = 1;
public static final int PORT_ENCODER_DRIVE_LEFT_B = 2;
public static final int PORT_ENCODER_DRIVE_LEFT_A_BACKUP = 1;
public static final int PORT_ENCODER_DRIVE_LEFT_B_BACKUP = 2;
public static final int PORT_ENCODER_DRIVE_RIGHT_A = 3;
public static final int PORT_ENCODER_DRIVE_RIGHT_B = 4;
public static final int PORT_ENCODER_DRIVE_RIGHT_A_BACKUP = 3;
public static final int PORT_ENCODER_DRIVE_RIGHT_B_BACKUP = 4;
public static final int PORT_ENCODER_SHOOTER_SPEED = 5;
public static final int PORT_ENCODER_BRIDGE_MANIPULATOR = 2; // <-- ANALOG
// Solenoids
public static final int PORT_SOLENOID_HIGH_GEAR = 1;
public static final int PORT_SOLENOID_LOW_GEAR = 2;
// Info
public static final double DRIVE_SPEED_REDUCTION_VALUE = 0.65;
public static final double DRIVE_SPEED_NORMAL_VALUE = 1.0;
// Global State
public static int BALL_CONTAINMENT_COUNT = 0;
public static final NetworkTable DASHBOARD_FEEDBACK = NetworkTable.getTable("Feedback");
//Analog Channels
//public static final int HYBRID_TYPE_ANALOG = 1337;
//
// Joysticks
public static final Joystick joystickDrive;
public static final Joystick joystickShoot;
// Modules
public static final IDriveTrain driveTrain;
public static final IBallCollector ballCollector;
public static final IBridgeManipulator bridgeManipulator;
public static final IShooter shooter;
public static final I3BA threeBA;
public static final ITargetTracker targetTracker;
public static final BallController ballController;
static {
joystickDrive = new Joystick(PORT_JOYSTICK_DRIVE);
joystickShoot = new Joystick(PORT_JOYSTICK_SHOOT);
driveTrain = new DriveTrain(PORT_MOTOR_DRIVE_LEFT, PORT_MOTOR_DRIVE_RIGHT, PORT_SOLENOID_HIGH_GEAR, PORT_SOLENOID_LOW_GEAR);
ballCollector = new BallCollector(PORT_MOTOR_KANAYERBELT_FEEDER, PORT_MOTOR_KANAYERBELT_BOTTOM, PORT_IR_BALL_IN_1, PORT_IR_BALL_IN_2);
bridgeManipulator = new BridgeManipulator(PORT_MOTOR_BRIDGE_MANIPULATOR, PORT_ENCODER_BRIDGE_MANIPULATOR);
shooter = new Shooter(PORT_MOTOR_SHOOTER_WHEEL, PORT_MOTOR_KANAYERBELT_TOP, PORT_IR_BALL_READY, PORT_ENCODER_SHOOTER_SPEED);
threeBA = new ThreeBA(PORT_MOTOR_3BA, PORT_LIMIT_SWITCH_3BA_FRONT, PORT_LIMIT_SWITCH_3BA_BACK);
targetTracker = new TargetTracker(driveTrain, PORT_GYRO_ROBOT_ROTATION);
ballController = new BallController(ballCollector, shooter);
}
}
|
package sys.dht;
import static sys.dht.catadupa.Config.Config;
import static sys.utils.Log.Log;
import org.hamcrest.Factory;
import sys.dht.api.DHT;
import sys.dht.catadupa.Node;
import sys.dht.discovery.Discovery;
import sys.dht.impl.DHT_ClientStub;
import sys.dht.impl.DHT_NodeImpl;
import sys.net.api.Endpoint;
import sys.pubsub.impl.PubSubService;
import sys.utils.Threading;
import static sys.Sys.*;
public class DHT_Node extends DHT_NodeImpl {
public static final String DHT_ENDPOINT = "DHT_ENDPOINT";
protected DHT_Node() {
super.init();
}
public boolean isHandledLocally(final DHT.Key key) {
return super.resolve( key ).key == self.key;
}
synchronized public static DHT getStub() {
if (clientStub == null) {
String name = DHT_ENDPOINT + Sys.getDatacenter();
Endpoint dhtEndpoint = Discovery.lookup(name, 5000);
if (dhtEndpoint != null) {
clientStub = new DHT_ClientStub(dhtEndpoint);
} else {
Log.severe("Failed to discovery DHT access endpoint...");
return null;
}
}
return clientStub;
}
public static void setHandler(DHT.MessageHandler handler) {
serverStub.setHandler(handler);
}
synchronized public static void start() {
if (singleton == null) {
singleton = new DHT_Node();
}
while (!singleton.isReady())
Threading.sleep(50);
}
private static DHT_Node singleton;
}
|
package tankattack;
import Sprites.*;
import java.util.*;
import javafx.animation.*;
import javafx.event.*;
import javafx.geometry.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.image.*;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.scene.text.*;
import javafx.stage.*;
import javafx.util.*;
/**
*
* @author Ruslan
*/
public abstract class World {
public static boolean isListeningForInput = true;
private Stage myStage;
public static World sharedInstance;
private Scene scene;
private Group root;
private Circle myEnemy;
private Point2D myEnemyVelocity;
private Random myGenerator = new Random();
private ArrayList<Sprite> sprites;
private ArrayList<Sprite> spritesToRemove;
private ArrayList<Bullet> bullets;
private ArrayList<Bullet> bulletsToRemove;
private Player playerSprite;
private Timeline timeline;
// Setters, Getters
public void addSprite(Sprite s) {
if (s instanceof Bullet) {
if (bullets == null) {
bullets = new ArrayList();
}
bullets.add((Bullet)s);
}
else {
if (sprites == null) {
sprites = new ArrayList();
}
sprites.add(s);
}
root.getChildren().add(s);
}
public void removeSprite(Sprite s) {
if (sprites == null) {
return;
}
sprites.remove(s);
root.getChildren().remove(s);
}
public void setPlayerSprite(Player player) {
playerSprite = player;
}
public Player getPlayerSprite() {
return playerSprite;
}
public Group getGroup() {
return this.root;
}
public void setGroup(Group root) {
this.root = root;
}
public Scene getScene() {
return this.scene;
}
public void setScene(Scene scene) {
this.scene = scene;
}
// Real Methods
// Constructors
// Create Scene, Then Init Animation. Rest of methods are helpers.
public World() {
throw new UnsupportedOperationException("need to pass in a stage");
}
public World(Stage stage) {
this.myStage = stage;
World.sharedInstance = this;
}
public Scene createScene() {
root = new Group();
createInitialSprites();
scene = new Scene(root, TankAttack.gameWidth, TankAttack.gameHeight, Color.CORNFLOWERBLUE);
scene.setOnKeyPressed(e -> handleKeyInput(e));
scene.setOnKeyReleased(e -> handleKeyRelease(e));
return scene;
}
public void initAnimation() {
KeyFrame frame = new KeyFrame(Duration.millis(1000 / TankAttack.NUM_FRAMES_PER_SECOND), e -> updateSprites());
if (timeline == null) {
timeline = new Timeline();
}
timeline.setCycleCount(Animation.INDEFINITE);
timeline.getKeyFrames().add(frame);
timeline.play();
}
public abstract void createInitialSprites();
public void createPlayerSprite() {
Player player = new Player(TankAttack.gameWidth/2 , TankAttack.gameHeight / 2, this);
setPlayerSprite(player);
}
private void updateSprites() {
// System.out.println("All is well. Printing animation 60 times a second.");
////// DONE ////////////////////////////
playerSprite.updateLocation();
// Handle Player Firing
handleFiring();
// Other Updates
updateEnemySprites(); // also handles enemy fire
// Bullet Movement
updateBulletMovements();
////// DONE ////////////////////////////
////// IMPLEMENT ////////////////////////////
// Register Collisions With Tanks
handleCollision();
// Register Collisions Between Sprites & Bullets
handleCollisionBullets();
updateAllSpritesToCheckForDeath();
// Check for win
checkForWin();
////// IMPLEMENT ////////////////////////////
}
private void endOfLevelSuccess() {
timeline.pause();
// TODO: Display level success.
showEndOfLevelTextSuccess();
Timeline fiveSecondDelay = new Timeline(new KeyFrame(Duration.seconds(5), new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
// Tell TankAttack to put up the next world.
signalEndOfLevel();
}
}));
fiveSecondDelay.setCycleCount(1);
fiveSecondDelay.play();
}
public void endOfLevelFailure() {
timeline.pause();
// TODO: Display level failure.
showEndOfLevelFailure();
Timeline fiveSecondDelay = new Timeline(new KeyFrame(Duration.seconds(5), new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
// Display Main Menu
TankAttack.sharedInstance.displayStartMenu();
}
}));
fiveSecondDelay.setCycleCount(1);
fiveSecondDelay.play();
}
public void showEndOfLevelTextSuccess() {
Label l = new Label("SUCCESS");
l.setFont(new Font("Arial", 60));
l.setTextFill(Color.GREEN);
l.setTranslateY(TankAttack.gameHeight / 2.5);
// TODO The x is hardcoded. fix it in case game dimensions change
l.setTranslateX(180);
root.getChildren().add(l);
}
private void showEndOfLevelFailure() {
Label l = new Label("FAILURE");
l.setFont(new Font("Arial", 60));
l.setTextFill(Color.RED);
l.setTranslateY(TankAttack.gameHeight / 2.5);
// TODO The x is hardcoded. fix it in case game dimensions change
l.setTranslateX(180);
root.getChildren().add(l);
}
public abstract void signalEndOfLevel();
public void handleKeyInput(KeyEvent e) {
modifyDirControllerState(e, true);
}
public void handleKeyRelease(KeyEvent e) {
modifyDirControllerState(e, false);
}
private void modifyDirControllerState(KeyEvent key, boolean newState) {
KeyCode keyCode = key.getCode();
if (keyCode == KeyCode.RIGHT) {
DirController.rightPressed = newState;
}
else if (keyCode == KeyCode.LEFT) {
DirController.leftPressed = newState;
}
else if (keyCode == KeyCode.UP) {
DirController.upPressed = newState;
}
else if (keyCode == KeyCode.DOWN) {
DirController.downPressed = newState;
}
else if (keyCode == KeyCode.SPACE) {
DirController.spacePressed = newState;
}
// TODO: Implement space bar to shoot, and cheat codes, here.
}
private void checkForWin() {
// Temporary end to game
if (sprites.size() == 1) {
endOfLevelSuccess();
// TODO Implement this.
// Player is left all alone. Stop animation. Level defeated.
}
}
private void handleCollision() {
for (Sprite s : sprites) {
if (!s.equals(playerSprite)) {
if (playerSprite.getBoundsInParent().intersects(s.getBoundsInParent())){
System.out.println("COLLISION WITH SPRITE: " + s);
System.out.println("TODO: Implement player dying here");
handleCollisionWithEnemy();
}
}
}
}
private void updateEnemySprites() {
Enemy enemy;
for (Sprite s : sprites) {
if (s instanceof Enemy) {
enemy = (Enemy)s;
// Movement
enemy.updateEnemyXY();
// Firing
if (enemy.isFiring()) {
handleEnemyFiring(enemy);
}
}
}
}
// Player firing, NOT enemy firing.
private void handleFiring() {
// Check if space bar pressed, create new bullets for Player
if (DirController.spacePressed) {
new Bullet(playerSprite.getBulletOffsetX(), playerSprite.getBulletOffsetY(), this, true);
}
}
private void handleEnemyFiring(Enemy enemy) {
new Bullet(enemy.getBulletOffsetX(), enemy.getBulletOffsetY(), this, false);
}
private void updateBulletMovements() {
Bullet b;
if (bullets == null) {
bullets = new ArrayList<Bullet>();
return;
}
for (Sprite s : bullets) {
if (s instanceof Bullet) {
b = (Bullet)s;
b.updateXY();
}
}
removeOutOfBoundaryBullets();
}
private void removeOutOfBoundaryBullets() {
if (bulletsToRemove == null) {
return;
}
for (Bullet b : bulletsToRemove) {
bullets.remove(b);
root.getChildren().remove(b);
}
bulletsToRemove.clear();
}
public void addToOutOfBoundaryBulletsArray(Bullet b) {
if (bulletsToRemove == null) {
bulletsToRemove = new ArrayList<Bullet>();
}
bulletsToRemove.add(b);
}
private void handleCollisionBullets() {
for (Sprite s : sprites) {
for (Bullet b : bullets) {
if (s.getBoundsInParent().intersects(b.getBoundsInParent())) {
b.addSelfToRemoveFromWorldArray();
s.health -= TankAttack.BULLET_DAMAGE;
}
}
}
}
private void handleCollisionWithEnemy(Enemy s) {
playerSprite.health = 0;
s.health = 0;
}
private void updateAllSpritesToCheckForDeath() {
for (Sprite s : sprites) {
s.checkForDeathAndReactAppropriately();
}
}
public void addSpriteToRemove(Sprite s) {
if (spritesToRemove == null) {
spritesToRemove = new ArrayList<Sprite>();
}
spritesToRemove.add(s);
}
public void removeSpritesToRemove() {
if (spritesToRemove == null) {
return;
}
for (Sprite s : spritesToRemove) {
sprites.remove(s);
root.getChildren().remove(s);
}
spritesToRemove.clear();
}
}
|
package com.melodies.bandup;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.melodies.bandup.MainScreenActivity.MainScreenActivity;
import com.melodies.bandup.listeners.BandUpErrorListener;
import com.melodies.bandup.listeners.BandUpResponseListener;
import com.melodies.bandup.setup.Instruments;
import com.melodies.bandup.setup.SetupShared;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Calendar;
import java.util.Date;
public class Login extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener, DatePickable {
// server url location for login
private String url;
private GoogleApiClient mGoogleApiClient;
private static final int RC_SIGN_IN = 9001;
private static final String TAG = "SignInActivity";
private ProgressDialog loginDialog;
private EditText etUsername;
private EditText etPassword;
private LinearLayout linearLayoutParent;
private LinearLayout mainLinearLayout;
private LinearLayout linearLayoutInput;
private TextInputLayout tilUsername;
private TextInputLayout tilPassword;
private SetupShared sShared;
private Date dateOfBirth = null;
private DatePickerFragment datePickerFragment = null;
private CallbackManager callbackManager = CallbackManager.Factory.create();
private static boolean hasSoftNavigation(Context context) {
return !ViewConfiguration.get(context).hasPermanentMenuKey();
}
private int getSoftButtonsBarHeight() {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int usableHeight = metrics.heightPixels;
getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
int realHeight = metrics.heightPixels;
if (realHeight > usableHeight)
return realHeight - usableHeight;
else
return 0;
}
private int getIconCenter() {
final ImageView imageView = (ImageView) findViewById(R.id.band_up_login_logo);
int screenHeight = Login.this.getResources().getDisplayMetrics().heightPixels;
int parentHeight = linearLayoutParent.getHeight();
int activityHeight = mainLinearLayout.getHeight();
int statusBarHeight = screenHeight - parentHeight;
int paddingTop = getResources().getInteger(R.integer.login_image_padding_top);
System.out.println("HEIGHTS");
System.out.println(parentHeight);
System.out.println(statusBarHeight);
System.out.println(activityHeight);
System.out.println(parentHeight - activityHeight);
if (hasSoftNavigation(Login.this)) {
return ((activityHeight - imageView.getHeight()) / 2 - statusBarHeight / 2 + getSoftButtonsBarHeight() / 2) - paddingTop + (parentHeight-activityHeight);
} else {
return ((activityHeight - imageView.getHeight()) / 2 - statusBarHeight / 2) - paddingTop + (parentHeight - activityHeight);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext()); // need to initialize facebook before view
setContentView(R.layout.activity_main);
mainLinearLayout = (LinearLayout) findViewById(R.id.login_ll);
linearLayoutParent = (LinearLayout) findViewById(R.id.login_parent_ll);
linearLayoutInput = (LinearLayout) findViewById(R.id.login_ll_input);
sShared = new SetupShared();
getAd();
String route = "/login-local";
url = getResources().getString(R.string.api_address).concat(route);
loginDialog = new ProgressDialog(Login.this);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
etPassword.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
try {
Login.this.onClickSignIn(findViewById(R.id.btnSignIn));
} catch (JSONException e) {
e.printStackTrace();
}
return true;
}
return false;
}
});
tilUsername = (TextInputLayout) findViewById(R.id.tilUsername);
tilPassword = (TextInputLayout) findViewById(R.id.tilPassword);
etUsername.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
tilUsername.setError(null);
}
@Override
public void afterTextChanged(Editable s) {
}
});
etPassword.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
tilPassword.setError(null);
}
@Override
public void afterTextChanged(Editable s) {
}
});
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button_facebook);
loginButton.setReadPermissions("email");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(final LoginResult loginResult) {
facebookCreateUser(loginResult);
}
@Override
public void onCancel() {
System.out.println("Login Cancelled");
Toast.makeText(Login.this, "Login Cancelled", Toast.LENGTH_LONG).show();
}
@Override
public void onError(FacebookException error) {
System.out.println("hit an error");
Toast.makeText(Login.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
// Button listener
findViewById(R.id.login_button_google).setOnClickListener(this);
// configuring simple Google+ sign in requesting userId and email and basic profile (included in DEFAULT_SIGN_IN)
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestId()
.requestEmail()
.build();
// Google client with access to the Google SignIn API and the options specified by gso.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// Google+ Sign In button design
SignInButton signInButton = (SignInButton) findViewById(R.id.login_button_google);
signInButton.setSize(SignInButton.SIZE_STANDARD);
signInButton.setScopes(gso.getScopeArray());
btnSoundCloud = (ImageView) findViewById(R.id.login_button_soundcloud);
}
// creates advertisment
private void getAd() {
MobileAds.initialize(getApplicationContext(), "ca-app-pub-3940256099942544~3347511713");
AdView mAdview = (AdView)findViewById(R.id.adView);
AdRequest mAdRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // this line makes ads on emulator
.build();
mAdview.loadAd(mAdRequest);
}
/**
* take result from facebook login process and create user in backend
* <p>
* side effect: starts up instrument activity if succesfull
*
* @param loginResult facebook loginResult
*/
private void facebookCreateUser(LoginResult loginResult) {
try {
url = getResources().getString(R.string.api_address).concat("/login-facebook");
JSONObject jsonObject = new JSONObject();
jsonObject.put("access_token", loginResult.getAccessToken().getToken());
jsonObject.put("dateOfBirth", dateOfBirth);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url,
jsonObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
sShared.saveUserId(Login.this, response);
openCorrectIntent(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Login.this, error.getMessage(), Toast.LENGTH_LONG).show();
errorHandlerLogin(error);
}
});
VolleySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
} catch (JSONException ex) {
System.out.println(ex.getMessage());
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...)
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
} else {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
// Accessing user data from Google & storing on server
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
Toast.makeText(getApplicationContext(), "Signed In", Toast.LENGTH_SHORT).show();
// Logged in, accessing user data
GoogleSignInAccount acct = result.getSignInAccount();
final String idToken = acct.getIdToken();
sendGoogleUserToServer(idToken);
}
}
private void openCorrectIntent(JSONObject response) {
Boolean hasFinishedSetup = null;
try {
hasFinishedSetup = response.getBoolean("hasFinishedSetup");
if (hasFinishedSetup) {
Intent userListIntent = new Intent(Login.this, MainScreenActivity.class);
Login.this.startActivity(userListIntent);
overridePendingTransition(R.anim.slide_in_right, R.anim.no_change);
finish();
} else {
//showDatePickerDialog();
Intent instrumentsIntent = new Intent(Login.this, Instruments.class);
Login.this.startActivity(instrumentsIntent);
overridePendingTransition(R.anim.slide_in_right, R.anim.no_change);
finish();
}
} catch (JSONException e) {
Intent instrumentsIntent = new Intent(Login.this, Instruments.class);
Login.this.startActivity(instrumentsIntent);
overridePendingTransition(R.anim.slide_in_right, R.anim.no_change);
finish();
}
}
public void showDatePickerDialog() {
if (datePickerFragment == null) {
datePickerFragment = new DatePickerFragment();
}
datePickerFragment.show(getFragmentManager(), "datePicker");
}
// Sending user info to server
private void sendGoogleUserToServer(String idToken) {
try {
url = getResources().getString(R.string.api_address).concat("/login-google");
JSONObject jsonObject = new JSONObject();
jsonObject.put("access_token", idToken);
jsonObject.put("dateOfBirth", dateOfBirth);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url,
jsonObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
sShared.saveUserId(Login.this, response);
openCorrectIntent(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
errorHandlerLogin(error);
}
});
VolleySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
// Google buttons
public void onClick(View v) {
switch (v.getId()) {
case R.id.login_button_google:
signIn();
break;
}
}
// Unresorvable error occured and Google API will not be available
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed:" + connectionResult);
Toast.makeText(getApplicationContext(), "Google+ SignIn Error!", Toast.LENGTH_SHORT).show();
}
// Google+ Sign In
public void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
ImageView btnSoundCloud;
public void onClickSoundCloud(View v) {
switch (v.getId()) {
case R.id.login_button_soundcloud:
Intent intent = new Intent(this,SoundCloud.class);
startActivity(intent);
break;
}
}
// when Sign In is Clicked grab data and ...
public void onClickSignIn(View v) throws JSONException {
// catching views into variables
// converting into string
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
if (v.getId() == R.id.btnSignIn) {
// Check for empty field in the form
Boolean isValid = true;
if (username.isEmpty()) {
isValid = false;
tilUsername.setError(getString(R.string.login_username_validation));
etUsername.requestFocus();
}
if (password.isEmpty()) {
isValid = false;
tilPassword.setError(getString(R.string.login_password_validation));
}
if (isValid) {
loginDialog = ProgressDialog.show(this, getString(R.string.login_progress_title), getString(R.string.login_progress_description), true, false);
createloginRequest(username, password);
}
}
}
// Login user into app
private void createloginRequest(String username, String password) {
// create request for Login
JSONObject user = new JSONObject();
try {
user.put("username", username);
user.put("password", password);
} catch (JSONException e) {
e.printStackTrace();
}
DatabaseSingleton.getInstance(getApplicationContext()).getBandUpDatabase().local_login(
user,
new BandUpResponseListener() {
@Override
public void onBandUpResponse(Object response) {
JSONObject responseObj = null;
if (response instanceof JSONObject) {
responseObj = (JSONObject) response;
}
sShared.saveUserId(Login.this, responseObj);
Toast.makeText(Login.this, R.string.login_success, Toast.LENGTH_SHORT).show();
openCorrectIntent(responseObj);
loginDialog.dismiss();
}
},
new BandUpErrorListener() {
@Override
public void onBandUpErrorResponse(VolleyError error) {
loginDialog.dismiss();
errorHandlerLogin(error);
}
}
);
}
// Handling errors that can occur while SignIn request
private void errorHandlerLogin(VolleyError error) {
if (error instanceof AuthFailureError) {
Toast.makeText(this, R.string.login_credentials_incorrect, Toast.LENGTH_SHORT).show();
return;
}
VolleySingleton.getInstance(Login.this).checkCauseOfError(error);
}
// when Sign Up is Clicked go to Registration View
public void onClickSignUp(View v) {
if (v.getId() == R.id.btnSignUp) {
Intent signUpIntent = new Intent(Login.this, Register.class);
Login.this.startActivity(signUpIntent);
}
}
@Override
public void onDateSet(int year, int month, int day) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, day);
// Calendar to Date object.
dateOfBirth = cal.getTime();
datePickerFragment.ageCalculator(year, month, day);
Intent instrumentsIntent = new Intent(Login.this, Instruments.class);
Login.this.startActivity(instrumentsIntent);
overridePendingTransition(R.anim.slide_in_right, R.anim.no_change);
finish();
}
}
|
package com.wsfmn.model;
import com.wsfmn.controller.HabitHistoryController;
import java.util.ArrayList;
import java.util.List;
public class HabitList {
private ArrayList<Habit> habits;
public HabitList() {
this.habits = new ArrayList<Habit>();
}
public HabitList(ArrayList<Habit> habits) {
this.habits = habits;
}
// add Habit to HabitList
public void addHabit(Habit habit){
habits.add(habit);
}
// delete the Habit from HabitList
public void deleteHabit(Habit habit){
habits.remove(habit);
}
public void deleteHabitAt(int index){
habits.remove(index);
}
public int size() {
return habits.size();
}
public void addAllHabits(List<Habit> habitsToAdd) {
habits.addAll(habitsToAdd);
}
public Habit getHabit(int index){
return habits.get(index);
}
public void setHabit(int index, Habit habit){
habits.set(index, habit);
}
public boolean hasHabit(Habit habit){
return habits.contains(habit);
}
// TODO alsobaie: added this, needs testing
public ArrayList<Habit> getHabitList(){
return habits;
}
public ArrayList<Habit> getHabitsForToday(){
ArrayList<Habit> habitsForToday = new ArrayList<Habit>();
Date today = new Date();
int dayOfWeek = today.getDayOfWeek();
for(int i = 0; i < habits.size(); i++){
int com = habits.get(i).getDate().compareDate(today);
if(com == -1 || com == 0){
if(habits.get(i).getWeekDays().getDay(dayOfWeek-1))
habitsForToday.add(habits.get(i));
}
}
HabitHistoryController c = HabitHistoryController.getInstance();
for(int i = 0; i < habitsForToday.size(); i++){
for(int j = 0; j < c.size(); j++){
if(c.get(j).getHabit().equal(habitsForToday.get(i))
&& c.get(j).getDate().compareDate(today) == 0)
habitsForToday.remove(i);
}
}
return habitsForToday;
}
}
|
package org.openlmis.core;
import android.app.Application;
import android.content.Context;
import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.core.CrashlyticsCore;
import io.fabric.sdk.android.Fabric;
import roboguice.RoboGuice;
public class LMISApp extends Application {
private static Context applicationContext;
@Override
public void onCreate() {
super.onCreate();
RoboGuice.getInjector(this).injectMembersWithoutViews(this);
applicationContext=getApplicationContext();
setupFabric();
}
protected void setupFabric(){
Fabric.with(this, new Crashlytics.Builder()
.core(new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build())
.build());
}
public static Context getContext() {
return applicationContext;
}
}
|
package backend;
import java.util.ArrayList;
import org.json.JSONObject;
import backend.Series;
import networking.Access;
public class BackEnd {
static ArrayList<Series> series;
Access a;
public BackEnd()
{
a=new Access();
series = getSeries();
}
public static void main(String [] args)
{
BackEnd b = new BackEnd();
System.out.println(b.series.get(0).title);
b.getSeasons(series.get(0).id);
}
public ArrayList<Series> getSeries()
{
ArrayList<Series> s=new ArrayList<Series>();
ArrayList<Integer> i=a.getShows();
for(int j :i)
{
JSONObject temp =a.getShow(j);
Series t =new Series(temp.getString("name"),temp.getString("total length"),temp.getInt("id"),temp.getInt("episodes"),temp.getInt("seasons"));
s.add(t);
}
return s;
}
public ArrayList<Season> getSeasons(int showID)
{
ArrayList<Season> s =new ArrayList<Season>();
ArrayList<JSONObject> j = a.getSeasons(showID);
for(JSONObject k : j)
{
k.toString();
s.add(new Season(k.getString("length"),k.getInt("parent"),k.getInt("number"),k.getInt("id"),k.getInt("episodes")));
}
return s;
}
public ArrayList<Episode> getEpisode(int showID, int seasonID)
{
ArrayList<Episode> s=new ArrayList<Episode>();
ArrayList<JSONObject> i=a.getEpisodes(showID, seasonID);
for(JSONObject j :i)
{
s.add(new Episode(j.getString("name"),j.getString("time"),j.getInt("number"),j.getInt("rating"),j.getInt("season"),j.getInt("series")));
}
return s;
}
public void addSeason(Season s)
{
a.addSeason(s);
}
public void addShow(Series s)
{
a.addShow(s);
}
public void addEpisode(Episode e)
{
a.addEpisode(e);
}
}
|
package bamboo.task;
import bamboo.util.Urls;
import com.codepoetics.protonpack.StreamUtils;
import org.apache.commons.lang.StringUtils;
import org.archive.io.ArchiveReader;
import org.archive.io.ArchiveRecord;
import org.archive.io.ArchiveRecordHeader;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class Cdx {
public static Stream<CdxRecord> records(ArchiveReader warcReader) {
Stream<CdxRecord> stream = Stream.generate(new CdxRecordProducer(warcReader)::next);
return StreamUtils.takeWhile(stream, (record) -> record != null);
}
public static void writeCdx(Path warc, Writer out) throws IOException {
records(Warcs.open(warc)).forEach(record -> {
try {
out.write(record.toCdxLine() + "\n");
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
static class CdxRecordProducer {
final static Pattern PANDORA_URL_MAP = Pattern.compile("^http://pandora.nla.gov.au/pan/([0-9]+/[0-9-]+)/url.map$");
private final ArchiveReader warc;
private final Iterator<ArchiveRecord> iterator;
private Iterator<Alias> urlMapIterator = null;
CdxRecordProducer(ArchiveReader warc) {
this.warc = warc;
iterator = warc.iterator();
}
public CdxRecord next() {
try {
if (urlMapIterator != null && urlMapIterator.hasNext()) {
return urlMapIterator.next();
}
while (iterator.hasNext()) {
ArchiveRecord record = iterator.next();
Matcher m = PANDORA_URL_MAP.matcher(record.getHeader().getUrl());
if (m.matches()) {
String piAndDate = m.group(1);
BufferedReader reader = new BufferedReader(new InputStreamReader(record, StandardCharsets.US_ASCII));
urlMapIterator = reader.lines().flatMap((line) -> parseUrlMapLine(line, piAndDate)).iterator();
return next();
} else {
Capture capture = Capture.parseWarcRecord(warc.getFileName(), record);
if (capture != null) {
return capture;
}
}
}
return null;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
public interface CdxRecord {
String toCdxLine();
}
/**
* Parses a line from a PANDORA url.map file and returns a list of corresponding aliases.
*
* Sometimes HTTrack's url-rewriting is only partially successful, often due to JavaScript constructing
* URLs. So we return two aliases, one using HTTrack's rewritten URL and the other using the original URL
* but relative to the PANDORA instance.
*/
static Stream<Alias> parseUrlMapLine(String line, String piAndDate) {
String[] fields = line.trim().split("\\^\\^");
String target = Urls.addImplicitScheme(fields[0]);
String instanceBaseUrl = "http://pandora.nla.gov.au/pan/" + piAndDate + "/";
String alias1 = instanceBaseUrl + cleanHttrackPath(fields[1], piAndDate);
String alias2 = instanceBaseUrl + Urls.removeScheme(target);
if (alias1.equals(alias2)) {
return Stream.of(new Alias(alias1, target));
} else {
return Stream.of(new Alias(alias1, target), new Alias(alias2, target));
}
}
/**
* Strips the pi and instance date from a PANDORA path if present.
*/
static String cleanHttrackPath(String path, String piAndDate) {
path = StringUtils.removeStart(path, "/");
String piAndLegacyDate = StringUtils.removeEnd(piAndDate, "-0000");
if (path.startsWith(piAndDate + "/")) {
return path.substring(piAndDate.length() + 1); // 1234/20010101-1234/(example.org/index.html)
} else if (path.startsWith(piAndLegacyDate + "/")){
return path.substring(piAndLegacyDate.length() + 1); // 1234/20010101/(example.org/index.html)
} else {
return path; // (example.org/index.html)
}
}
public static class Alias implements CdxRecord {
public String alias;
public String target;
public Alias(String alias, String target) {
this.alias = alias;
this.target = target;
}
@Override
public String toCdxLine() {
return "@alias " + alias + " " + target;
}
}
public static class Capture implements CdxRecord {
public String contentType;
public int status;
public String location;
public String date;
public String url;
public long contentLength;
public long offset;
public String filename;
public String digest;
public String toCdxLine() {
return String.join(" ", "-", date, url, optional(contentType),
status == -1 ? "-" : Integer.toString(status), optional(digest),
optional(location), "-", Long.toString(contentLength),
Long.toString(offset), filename);
}
private static String optional(String s) {
if (s == null) {
return "-";
}
return s.replace(" ", "%20").replace("\n", "%0A").replace("\r", "%0D");
}
static Capture parseWarcRecord(String filename, ArchiveRecord record) throws IOException {
ArchiveRecordHeader header = record.getHeader();
Capture capture = new Capture();
capture.url = Warcs.getCleanUrl(header);
if (Warcs.isResponseRecord(header)) {
HttpHeader http = HttpHeader.parse(record, capture.url);
if (http == null) {
return null;
}
capture.contentType = http.getCleanContentType();
capture.status = http.status;
capture.location = http.location;
} else if (Warcs.isResourceRecord(header)) {
capture.contentType = header.getMimetype();
capture.status = 200;
capture.location = null;
} else {
return null;
}
capture.date = Warcs.getArcDate(header);
capture.contentLength = header.getContentLength();
capture.offset = header.getOffset();
capture.filename = filename;
capture.digest = Warcs.getOrCalcDigest(record);
return capture;
}
}
}
|
package org.jetel.data.parser;
import java.io.IOException;
import java.io.InputStream;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.DataRecord;
import org.jetel.data.Defaults;
import org.jetel.exception.BadDataFormatException;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.IParserExceptionHandler;
import org.jetel.exception.JetelException;
import org.jetel.exception.PolicyType;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.util.bytes.CloverBuffer;
import org.jetel.util.string.QuotingDecoder;
import org.jetel.util.string.StringUtils;
/**
* Parsing plain text data.
*
* Known bugs:
* - Method skip() doesn't recognize records without final delimiter/recordDelimiter,
* for example last record in file without termination enter.
* That's why skip() doesn't count unfinished records.
*
* @author Martin Zatopek, David Pavlis
* @since September 29, 2005
* @see Parser
* @see org.jetel.data.Defaults
* @revision $Revision: 1.9 $
*/
public class DataParser extends AbstractTextParser {
private static final int RECORD_DELIMITER_IDENTIFIER = -1;
private static final int DEFAULT_FIELD_DELIMITER_IDENTIFIER = -2;
private final static Log logger = LogFactory.getLog(DataParser.class);
private IParserExceptionHandler exceptionHandler;
private ReadableByteChannel reader;
private CharBuffer charBuffer;
private ByteBuffer byteBuffer;
private StringBuilder fieldBuffer;
private CloverBuffer recordBuffer;
private CharsetDecoder decoder;
private int fieldLengths[];
private boolean[] quotedFields;
private int recordCounter;
private int numFields;
private AhoCorasick delimiterSearcher;
private StringBuilder tempReadBuffer;
private boolean[] isAutoFilling;
// private boolean[] isSkipBlanks;
private boolean[] isSkipLeadingBlanks;
private boolean[] isSkipTrailingBlanks;
private boolean[] eofAsDelimiters;
private boolean releaseInputSource = true;
private boolean hasRecordDelimiter = false;
private boolean hasDefaultFieldDelimiter = false;
private QuotingDecoder qDecoder = new QuotingDecoder();
private boolean isEof;
private int bytesProcessed;
private DataFieldMetadata[] metadataFields;
/**
* We are in the middle of process of record parsing.
*/
private boolean recordIsParsed;
public DataParser(TextParserConfiguration cfg){
super(cfg);
decoder = Charset.forName(cfg.getCharset()).newDecoder();
reader = null;
exceptionHandler = cfg.getExceptionHandler();
qDecoder.setQuoteChar(cfg.getQuoteChar());
}
/**
* Returns parser speed for specified configuration. See {@link TextParserFactory#getParser(TextParserConfiguration)}.
*/
public static Integer getParserSpeed(TextParserConfiguration cfg){
for (DataFieldMetadata field : cfg.getMetadata().getFields()) {
if (field.isByteBased() && !field.isAutoFilled()) {
logger.debug("Parser cannot be used for the specified data as they contain byte-based field '" + field + "'");
return null;
}
if (field.getShift() != 0) {
logger.debug("Parser cannot be used for the specified data as they contain field '" + field + "' with non-zero shift");
return null;
}
}
return 10;
}
/**
* @see org.jetel.data.parser.Parser#getNext()
*/
@Override
public DataRecord getNext() throws JetelException {
DataRecord record = new DataRecord(cfg.getMetadata());
record.init();
record = parseNext(record);
if(exceptionHandler != null ) { //use handler only if configured
while(exceptionHandler.isExceptionThrowed()) {
exceptionHandler.setRawRecord(getLastRawRecord());
exceptionHandler.handleException();
record = parseNext(record);
}
}
return record;
}
/**
* @see org.jetel.data.parser.Parser#getNext(org.jetel.data.DataRecord)
*/
@Override
public DataRecord getNext(DataRecord record) throws JetelException {
record = parseNext(record);
if(exceptionHandler != null ) { //use handler only if configured
while(exceptionHandler.isExceptionThrowed()) {
exceptionHandler.setRawRecord(getLastRawRecord());
exceptionHandler.handleException();
record = parseNext(record);
}
}
return record;
}
@Override
public void init() throws ComponentNotReadyException {
//init private variables
if (cfg.getMetadata() == null) {
throw new ComponentNotReadyException("Metadata are null");
}
byteBuffer = ByteBuffer.allocateDirect(Defaults.Record.RECORD_INITIAL_SIZE);
charBuffer = CharBuffer.allocate(Defaults.Record.RECORD_INITIAL_SIZE);
charBuffer.flip(); // initially empty
fieldBuffer = new StringBuilder(Defaults.Record.FIELD_INITIAL_SIZE);
recordBuffer = CloverBuffer.allocate(Defaults.Record.RECORD_INITIAL_SIZE, Defaults.Record.RECORD_LIMIT_SIZE);
tempReadBuffer = new StringBuilder(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE);
numFields = cfg.getMetadata().getNumFields();
isAutoFilling = new boolean[numFields];
// isSkipBlanks = new boolean[numFields];
isSkipLeadingBlanks = new boolean[numFields];
isSkipTrailingBlanks = new boolean[numFields];
eofAsDelimiters = new boolean[numFields];
//aho-corasick initialize
delimiterSearcher = new AhoCorasick();
// create array of delimiters & initialize them
String[] delimiters;
for (int i = 0; i < numFields; i++) {
if(cfg.getMetadata().getField(i).isDelimited()) {
delimiters = cfg.getMetadata().getField(i).getDelimiters();
if(delimiters != null && delimiters.length > 0) { //it is possible in case eofAsDelimiter tag is set
for(int j = 0; j < delimiters.length; j++) {
delimiterSearcher.addPattern(delimiters[j], i);
}
} else {
delimiterSearcher.addPattern(null, i);
}
}
isAutoFilling[i] = cfg.getMetadata().getField(i).getAutoFilling() != null;
isSkipLeadingBlanks[i] = isSkipFieldLeadingBlanks(i);
// isSkipBlanks[i] = skipLeadingBlanks
// || trim == Boolean.TRUE
// || (trim == null && metadata.getField(i).isTrim());
isSkipTrailingBlanks[i] = isSkipFieldTrailingBlanks(i);
eofAsDelimiters[i] = cfg.getMetadata().getField(i).isEofAsDelimiter();
}
//aho-corasick initialize
if(cfg.getMetadata().isSpecifiedRecordDelimiter()) {
hasRecordDelimiter = true;
delimiters = cfg.getMetadata().getRecordDelimiters();
for(int j = 0; j < delimiters.length; j++) {
delimiterSearcher.addPattern(delimiters[j], RECORD_DELIMITER_IDENTIFIER);
}
}
if(cfg.getMetadata().isSpecifiedFieldDelimiter()) {
hasDefaultFieldDelimiter = true;
delimiters = cfg.getMetadata().getFieldDelimiters();
for(int j = 0; j < delimiters.length; j++) {
delimiterSearcher.addPattern(delimiters[j], DEFAULT_FIELD_DELIMITER_IDENTIFIER);
}
}
delimiterSearcher.compile();
// create array of field sizes and quoting & initialize them
fieldLengths = new int[numFields];
quotedFields = new boolean[numFields];
for (int i = 0; i < numFields; i++) {
if(cfg.getMetadata().getField(i).isFixed()) {
fieldLengths[i] = cfg.getMetadata().getField(i).getSize();
}
char type = cfg.getMetadata().getFieldType(i);
quotedFields[i] = cfg.isQuotedStrings()
&& type != DataFieldMetadata.BYTE_FIELD
&& type != DataFieldMetadata.BYTE_FIELD_COMPRESSED;
}
metadataFields = cfg.getMetadata().getFields();
}
@Override
public void setReleaseDataSource(boolean releaseInputSource) {
this.releaseInputSource = releaseInputSource;
}
@Override
public void setDataSource(Object inputDataSource) throws IOException {
if (releaseInputSource) releaseDataSource();
decoder.reset();// reset CharsetDecoder
byteBuffer.clear();
byteBuffer.flip();
charBuffer.clear();
charBuffer.flip();
fieldBuffer.setLength(0);
recordBuffer.clear();
tempReadBuffer.setLength(0);
recordCounter = 0;// reset record counter
bytesProcessed = 0;
if (inputDataSource == null) {
reader = null;
isEof = true;
} else {
isEof = false;
if (inputDataSource instanceof CharBuffer) {
reader = null;
charBuffer = (CharBuffer) inputDataSource;
} else if (inputDataSource instanceof ReadableByteChannel) {
reader = ((ReadableByteChannel)inputDataSource);
} else {
reader = Channels.newChannel((InputStream)inputDataSource);
}
}
}
/**
* Discard bytes for incremental reading.
*
* @param bytes
* @throws IOException
*/
private void discardBytes(int bytes) throws IOException {
while (bytes > 0) {
if (reader instanceof FileChannel) {
((FileChannel)reader).position(bytes);
return;
}
byteBuffer.clear();
if (bytes < Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE) byteBuffer.limit(bytes);
try {
reader.read(byteBuffer);
} catch (IOException e) {
break;
}
bytes =- Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE;
}
byteBuffer.clear();
byteBuffer.flip();
}
/**
* Release data source
* @throws IOException
*
*/
private void releaseDataSource() throws IOException {
if (reader == null) {
return;
}
reader.close();
reader = null;
}
/**
* @see org.jetel.data.parser.Parser#close()
*/
@Override
public void close() throws IOException {
if(reader != null && reader.isOpen()) {
reader.close();
}
}
private DataRecord parseNext(DataRecord record) {
int fieldCounter;
int character = -1;
int mark;
boolean inQuote, quoteFound;
boolean skipLBlanks, skipTBlanks;
boolean quotedField;
recordCounter++;
if (cfg.isVerbose()) {
recordBuffer.clear();
}
recordIsParsed = false;
for (fieldCounter = 0; fieldCounter < numFields; fieldCounter++) {
// skip all fields that are internally filled
if (isAutoFilling[fieldCounter]) {
continue;
}
skipLBlanks = isSkipLeadingBlanks[fieldCounter];
skipTBlanks = isSkipTrailingBlanks[fieldCounter];
quotedField = quotedFields[fieldCounter];
fieldBuffer.setLength(0);
if (fieldLengths[fieldCounter] == 0) { //delimited data field
inQuote = false;
quoteFound = false;
try {
while ((character = readChar()) != -1) {
recordIsParsed = true;
//delimiter update
delimiterSearcher.update((char) character);
//skip leading blanks
if (skipLBlanks && !Character.isWhitespace(character)) {
skipLBlanks = false;
}
//quotedStrings
if (quotedField) {
if (fieldBuffer.length() == 0 && !inQuote) { //first quote character
if (qDecoder.isStartQuote((char) character)) {
inQuote = true;
continue;
}
} else {
if (inQuote && qDecoder.isEndQuote((char) character)) { //quote character found in quoted field
if (!quoteFound) { // do nothing, we will see if we get one more quoting character next time
quoteFound = true;
continue;
} else { //we found double quotes "" - will be handled as a escape sequence for single quote
quoteFound = false;
}
} else {
if (quoteFound) {
//final quote character for field found (no double quote) so we return the last read character back to reading stream
//and check whether the field delimiter follows
tempReadBuffer.append((char) character);
if (!followFieldDelimiter(fieldCounter)) { //after ending quote can i find delimiter
findFirstRecordDelimiter();
return parsingErrorFound("Bad quote format", record, fieldCounter);
}
break;
}
}
}
}
//fieldDelimiter update
if(!skipLBlanks) {
fieldBuffer.append((char) character);
if (fieldBuffer.length() > Defaults.Record.FIELD_LIMIT_SIZE) {
return parsingErrorFound("Field delimiter was not found (this could be caused by insufficient field buffer size - Record.FIELD_LIMIT_SIZE=" + Defaults.Record.FIELD_LIMIT_SIZE + " - increase the constant if necessary)", record, fieldCounter);
}
}
//test field delimiter
if (!inQuote) {
if(delimiterSearcher.isPattern(fieldCounter)) {
// fieldBuffer.setLength(fieldBuffer.length() - delimiterSearcher.getMatchLength());
if(!skipLBlanks) {
fieldBuffer.setLength(Math.max(0, fieldBuffer.length() - delimiterSearcher.getMatchLength()));
}
if (skipTBlanks) {
StringUtils.trimTrailing(fieldBuffer);
}
if(cfg.isTreatMultipleDelimitersAsOne())
while(followFieldDelimiter(fieldCounter));
delimiterSearcher.reset(); // CL-1859 Fix: We don't want prefix of some other delimiter to be already matched
break;
}
//test default field delimiter
if(defaultFieldDelimiterFound()) {
findFirstRecordDelimiter();
return parsingErrorFound("Unexpected default field delimiter, probably record has too many fields.", record, fieldCounter);
}
//test record delimiter
if(recordDelimiterFound()) {
return parsingErrorFound("Unexpected record delimiter, probably record has too few fields.", record, fieldCounter);
}
}
}
} catch (Exception ex) {
throw new RuntimeException(getErrorMessage(ex.getMessage(), null, metadataFields[fieldCounter]), ex);
}
} else { //fixlen data field
mark = 0;
fieldBuffer.setLength(0);
try {
for(int i = 0; i < fieldLengths[fieldCounter]; i++) {
//end of file
if ((character = readChar()) == -1) {
break;
} else {
recordIsParsed = true;
}
//delimiter update
delimiterSearcher.update((char) character);
//test record delimiter
if(recordDelimiterFound()) {
return parsingErrorFound("Unexpected record delimiter, probably record is too short.", record, fieldCounter);
}
//skip leading blanks
if (skipLBlanks)
if(Character.isWhitespace(character)) continue;
else skipLBlanks = false;
//keep track of trailing blanks
if(!Character.isWhitespace(character)) {
mark = i;
}
fieldBuffer.append((char) character);
}
//removes tailing blanks
if(/*skipTBlanks && */character != -1 && fieldBuffer.length() > 0) {
fieldBuffer.setLength(fieldBuffer.length() -
(fieldLengths[fieldCounter] - mark - 1));
}
//check record delimiter presence for last field
if(hasRecordDelimiter && fieldCounter + 1 == numFields && character != -1) {
int followRecord = followRecordDelimiter();
if(followRecord>0) { //record delimiter is not found
return parsingErrorFound("Too many characters found", record, fieldCounter);
}
if(followRecord<0) { //record delimiter is not found
return parsingErrorFound("Unexpected record delimiter, probably record is too short.", record, fieldCounter);
}
}
} catch (Exception ex) {
throw new RuntimeException(getErrorMessage(ex.getMessage(), null, metadataFields[fieldCounter]), ex);
}
}
// did we have EOF situation ?
if (character == -1) {
try {
if (!recordIsParsed) {
reader.close();
return null;
} else {
//maybe the field has EOF delimiter
if(eofAsDelimiters[fieldCounter]) {
populateField(record, fieldCounter, fieldBuffer);
return record;
}
return parsingErrorFound("Unexpected end of file", record, fieldCounter);
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e1) {
throw new RuntimeException(getErrorMessage(e1.getMessage(), null, metadataFields[fieldCounter]), e1);
}
}
//populate field
populateField(record, fieldCounter, fieldBuffer);
}
return record;
}
private DataRecord parsingErrorFound(String exceptionMessage, DataRecord record, int fieldNum) {
if(exceptionHandler != null) {
exceptionHandler.populateHandler("Parsing error: " + exceptionMessage, record, recordCounter, fieldNum , getLastRawRecord(), new BadDataFormatException("Parsing error: " + exceptionMessage));
return record;
} else {
throw new RuntimeException("Parsing error: " + exceptionMessage + " (" + getLastRawRecord() + ")");
}
}
private int readChar() throws IOException {
final char character;
final int size;
CoderResult result;
if(tempReadBuffer.length() > 0) { // the tempReadBuffer is used as a cache of already read characters which should be read again
character = tempReadBuffer.charAt(0);
tempReadBuffer.deleteCharAt(0);
return character;
}
if (charBuffer.hasRemaining()) {
character = charBuffer.get();
if (cfg.isVerbose()) {
try {
recordBuffer.putChar(character);
} catch (BufferOverflowException e) {
throw new RuntimeException("Parse error: The size of data buffer for data record is only " + recordBuffer.limit() + ". Set appropriate parameter in defaultProperties file.", e);
}
}
return character;
}
if (isEof || reader == null)
return -1;
charBuffer.clear();
if (byteBuffer.hasRemaining())
byteBuffer.compact();
else
byteBuffer.clear();
if ((size = reader.read(byteBuffer)) == -1) {
isEof = true;
} else {
bytesProcessed += size;
}
byteBuffer.flip();
result = decoder.decode(byteBuffer, charBuffer, isEof);
// if (result == CoderResult.UNDERFLOW) {
// // try to load additional data
// byteBuffer.compact();
// if (reader.read(byteBuffer) == -1) {
// isEof = true;
// byteBuffer.flip();
// decoder.decode(byteBuffer, charBuffer, isEof);
// } else
if (result.isError()) {
throw new IOException(result.toString()+" when converting from "+decoder.charset());
}
if (isEof) {
result = decoder.flush(charBuffer);
if (result.isError()) {
throw new IOException(result.toString()+" when converting from "+decoder.charset());
}
}
charBuffer.flip();
if (charBuffer.hasRemaining()) {
final int ret = charBuffer.get();
if (cfg.isVerbose()) {
try {
recordBuffer.putChar((char) ret);
} catch (BufferOverflowException e) {
throw new RuntimeException("Parse error: The size of data buffer for data record is only " + recordBuffer.limit() + ". Set appropriate parameter in defaultProperties file.", e);
}
}
return ret;
} else {
return -1;
}
}
/**
* Assembles error message when exception occures during parsing
*
* @param exceptionMessage
* message from exception getMessage() call
* @param recNo
* recordNumber
* @param fieldNo
* fieldNumber
* @return error message
* @since September 19, 2002
*/
private String getErrorMessage(String exceptionMessage, CharSequence value, DataFieldMetadata metadataField) {
StringBuffer message = new StringBuffer();
message.append(exceptionMessage);
message.append(" when parsing record
message.append(recordCounter);
if (metadataField != null) {
message.append(" field ");
message.append(metadataField.getName());
}
if (value != null) {
message.append(" value \"").append(value).append("\"");
}
return message.toString();
}
/**
* Finish incomplete fields <fieldNumber, metadata.getNumFields()>.
*
* @param record
* incomplete record
* @param fieldNumber
* first incomlete field in record
*/
// private void finishRecord(DataRecord record, int fieldNumber) {
// for(int i = fieldNumber; i < metadata.getNumFields(); i++) {
// record.getField(i).setToDefaultValue();
/**
* Populate field.
*
* @param record
* @param fieldNum
* @param data
*/
private final void populateField(DataRecord record, int fieldNum, StringBuilder data) {
try {
record.getField(fieldNum).fromString(data);
} catch(BadDataFormatException bdfe) {
if(exceptionHandler != null) {
exceptionHandler.populateHandler(bdfe.getMessage(), record,
recordCounter, fieldNum , data.toString(), bdfe);
} else {
bdfe.setRecordNumber(recordCounter);
bdfe.setFieldNumber(fieldNum);
bdfe.setOffendingValue(data);
throw bdfe;
}
} catch(Exception ex) {
throw new RuntimeException(getErrorMessage(ex.getMessage(), null, metadataFields[fieldNum]));
}
}
/**
* Find first record delimiter in input channel.
*/
private boolean findFirstRecordDelimiter() throws JetelException {
if(!cfg.getMetadata().isSpecifiedRecordDelimiter()) {
return false;
}
int character;
int currentField = 0;
boolean inQuote = false;
try {
while ((character = readChar()) != -1) {
if (currentField < numFields &&
((!quotedFields[currentField] || !inQuote)) &&
recordDelimiterFound()) {
//end of field
currentField++;
inQuote = false;
}
if (quotedFields[currentField] && isQuoteChar(character)) {
inQuote = !inQuote;
}
delimiterSearcher.update((char) character);
//test record delimiter
if ((!quotedFields[currentField] || !inQuote) && recordDelimiterFound()) {
return true;
}
}
} catch (IOException e) {
throw new JetelException("Can not find a record delimiter.", e);
}
//end of file
return false;
}
private boolean isQuoteChar(int charToTest) {
if (cfg.getMetadata().getQuoteChar() == null) {
return (charToTest == '\'' || charToTest == '\"');
} else {
return cfg.getMetadata().getQuoteChar() == charToTest;
}
}
/**
* Find end of record for metadata without record delimiter specified.
* @throws JetelException
*/
private boolean findEndOfRecord(int fieldNum) throws JetelException {
int character = 0;
try {
for(int i = fieldNum; i < numFields; i++) {
if (isAutoFilling[i]) continue;
if (metadataFields[i].isDelimited()) {
while((character = readChar()) != -1) {
delimiterSearcher.update((char) character);
if(delimiterSearcher.isPattern(i)) {
break;
}
}
} else { //data field is fixlen
for (int j = 0; j < fieldLengths[i]; j++) {
//end of file
if ((character = readChar()) == -1) {
break;
}
}
}
}
} catch (IOException e) {
throw new JetelException("Can not find end of record.", e);
}
return (character != -1);
}
// private void shiftToNextRecord(int fieldNum) {
// if(metadata.isSpecifiedRecordDelimiter()) {
// findFirstRecordDelimiter();
// } else {
// findEndOfRecord(fieldNum);
/**
* Is record delimiter in the input channel?
* @return
*/
private boolean recordDelimiterFound() {
if(hasRecordDelimiter) {
return delimiterSearcher.isPattern(RECORD_DELIMITER_IDENTIFIER);
} else {
return false;
}
}
/**
* Is default field delimiter in the input channel?
* @return
*/
private boolean defaultFieldDelimiterFound() {
if(hasDefaultFieldDelimiter) {
return delimiterSearcher.isPattern(DEFAULT_FIELD_DELIMITER_IDENTIFIER);
} else {
return false;
}
}
/**
* Follow field delimiter in the input channel?
* @param fieldNum field delimiter identifier
* @return
*/
StringBuffer temp = new StringBuffer();
private boolean followFieldDelimiter(int fieldNum) {
int character;
temp.setLength(0);
try {
while ((character = readChar()) != -1) {
temp.append((char) character);
delimiterSearcher.update((char) character);
if(delimiterSearcher.isPattern(fieldNum)) {
return true;
}
if(delimiterSearcher.getMatchLength() == 0) {
tempReadBuffer.append(temp);
return false;
}
}
} catch (IOException e) {
throw new RuntimeException(getErrorMessage(e.getMessage(), null, null));
}
//end of file
return false;
}
/**
* Follow record delimiter in the input channel?
* @return 0 if record delimiter follows. -1 if record is too short, 1 if record is longer
*/
private int followRecordDelimiter() {
int count = 1;
int character;
try {
while ((character = readChar()) != -1) {
delimiterSearcher.update((char) character);
if(recordDelimiterFound()) {
return (count - delimiterSearcher.getMatchLength());
}
count++;
}
} catch (IOException e) {
throw new RuntimeException(getErrorMessage(e.getMessage(), null, null));
}
//end of file
return -1;
}
public boolean endOfInputChannel() {
return reader == null || !reader.isOpen();
}
public int getRecordCount() {
return recordCounter;
}
public String getLastRawRecord() {
if (cfg.isVerbose()) {
recordBuffer.flip();
String lastRawRecord = recordBuffer.asCharBuffer().toString();
recordBuffer.position(recordBuffer.limit()); //it is necessary for repeated invocation of this method for the same record
return lastRawRecord;
} else {
return "<Raw record data is not available, please turn on verbose mode.>";
}
}
// /**
// * Skip first line/record in input channel.
// */
// public void skipFirstLine() {
// int character;
// try {
// while ((character = readChar()) != -1) {
// delimiterSearcher.update((char) character);
// if(delimiterSearcher.isPattern(-2)) {
// break;
// if(character == -1) {
// throw new RuntimeException("Skipping first line: record delimiter not found.");
// } catch (IOException e) {
// throw new RuntimeException(getErrorMessage(e.getMessage(), null, -1));
@Override
public int skip(int count) throws JetelException {
int skipped;
if(cfg.getMetadata().isSpecifiedRecordDelimiter()) {
for(skipped = 0; skipped < count; skipped++) {
if(!findFirstRecordDelimiter()) {
break;
}
recordBuffer.clear();
}
} else {
for(skipped = 0; skipped < count; skipped++) {
if(!findEndOfRecord(0)) {
break;
}
recordBuffer.clear();
}
}
return skipped;
}
@Override
public void setExceptionHandler(IParserExceptionHandler handler) {
this.exceptionHandler = handler;
}
@Override
public IParserExceptionHandler getExceptionHandler() {
return exceptionHandler;
}
@Override
public PolicyType getPolicyType() {
if(exceptionHandler != null) {
return exceptionHandler.getType();
}
return null;
}
@Override
public void reset() {
if (releaseInputSource) {
try {
releaseDataSource();
} catch (IOException e) {
e.printStackTrace(); //TODO
}
}
decoder.reset();// reset CharsetDecoder
recordCounter = 0;// reset record counter
bytesProcessed = 0;
}
@Override
public Object getPosition() {
return bytesProcessed;
}
@Override
public void movePosition(Object position) throws IOException {
int pos = 0;
if (position instanceof Integer) {
pos = ((Integer) position).intValue();
} else if (position != null) {
pos = Integer.parseInt(position.toString());
}
if (pos > 0) {
discardBytes(pos);
bytesProcessed = pos;
}
}
@Override
public void preExecute() throws ComponentNotReadyException {
}
@Override
public void postExecute() throws ComponentNotReadyException {
reset();
}
@Override
public void free() throws IOException {
close();
}
}
|
package org.jetel.database;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import org.jetel.data.DataRecord;
import org.jetel.data.HashKey;
import org.jetel.data.RecordKey;
import org.jetel.data.lookup.LookupTable;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.JetelException;
import org.jetel.graph.GraphElement;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.SimpleCache;
/**
* Database table/SQLquery based lookup table which gets data by performing SQL
* query. Caching of found values can be provided - if the constructor with
* <code>numCached</code> parameter is used. The caching is performed by WeakHashMap so
* it can happend that even the frequently used entry (key-value pair) is garbage collected - thus
* removed from cache.
*
* Example using DBLookupTable:
*
*
*@author dpavlis
*@created 25. kvten 2003
*@since May 22, 2003
*/
public class DBLookupTable extends GraphElement implements LookupTable {
protected DataRecordMetadata dbMetadata;
protected DBConnection dbConnection;
protected PreparedStatement pStatement;
protected RecordKey lookupKey;
protected int[] keyFields;
protected String[] keys;
protected String sqlQuery;
protected ResultSet resultSet;
protected CopySQLData[] transMap;
protected CopySQLData[] keyTransMap;
protected DataRecord dbDataRecord;
protected DataRecord keyDataRecord = null;
protected Map resultCache;
protected int maxCached;
protected HashKey cacheKey;
/**
* Constructor for the DBLookupTable object
*
*@param dbConnection Description of the Parameter
*@param dbRecordMetadata Description of the Parameter
*@param sqlQuery Description of the Parameter
*/
public DBLookupTable(String id, DBConnection dbConnection,
DataRecordMetadata dbRecordMetadata, String sqlQuery) {
super(id);
this.dbConnection = dbConnection;
this.dbMetadata = dbRecordMetadata;
this.sqlQuery = sqlQuery;
this.maxCached = 0;
}
/**
* Constructor for the DBLookupTable object
*
*@param dbConnection Description of the Parameter
*@param dbRecordMetadata Description of the Parameter
*@param sqlQuery Description of the Parameter
* @param dbFieldTypes List containing the types of the final record
*/
public DBLookupTable(String id, DBConnection dbConnection,
DataRecordMetadata dbRecordMetadata, java.lang.String sqlQuery, java.util.List dbFieldTypes) {
this(id, dbConnection,dbRecordMetadata,sqlQuery);
}
public DBLookupTable(String id, DBConnection dbConnection,
DataRecordMetadata dbRecordMetadata, String sqlQuery, int numCached) {
super(id);
this.dbConnection = dbConnection;
this.dbMetadata = dbRecordMetadata;
this.sqlQuery = sqlQuery;
this.maxCached=numCached;
}
/**
* Gets the dbMetadata attribute of the DBLookupTable object.<br>
* <i>init() should be called prior to calling this method (unless dbMetadata
* was passed in using appropriate constructor.</i>
*
*@return The dbMetadata value
*/
public DataRecordMetadata getMetadata() {
return dbMetadata;
}
/**
* Looks-up data based on speficied key.<br>
* The key value is taken from passed-in data record. If caching is enabled, the
* internal cache is searched first, then the DB is queried.
*
*@return found DataRecord or NULL
*@since May 2, 2002
*/
public DataRecord get(DataRecord keyRecord) {
// if cached, then try to query cache first
if (resultCache!=null){
cacheKey.setDataRecord(keyRecord);
DataRecord data=(DataRecord)resultCache.get(cacheKey);
if (data!=null){
return data;
}
}
try {
pStatement.clearParameters();
// initialization of trans map if it was not already done
if (keyTransMap==null){
if (lookupKey == null) {
throw new RuntimeException("RecordKey was not defined for lookup !");
}
try {
keyTransMap = CopySQLData.jetel2sqlTransMap(
SQLUtil.getFieldTypes(pStatement.getParameterMetaData()),
keyRecord,lookupKey.getKeyFields());
} catch (JetelException ex){
throw new RuntimeException("Can't create keyRecord transmap: "+ex.getMessage());
}catch (Exception ex) {
// PreparedStatement parameterMetadata probably not implemented - use work-around
// we only guess the correct data types on JDBC side
try{
keyTransMap = CopySQLData.jetel2sqlTransMap(keyRecord,lookupKey.getKeyFields());
}catch(JetelException ex1){
throw new RuntimeException("Can't create keyRecord transmap: "+ex1.getMessage());
}catch(Exception ex1){
// some serious problem
throw new RuntimeException("Can't create keyRecord transmap: "+ex1.getClass().getName()+":"+ex1.getMessage());
}
}
}
// set prepared statement parameters
for (int i = 0; i < keyTransMap.length; i++) {
keyTransMap[i].jetel2sql(pStatement);
}
//execute query
resultSet = pStatement.executeQuery();
fetch();
} catch (SQLException ex) {
throw new RuntimeException(ex.getMessage());
}
// if cache exists, add this newly found to cache
if (resultCache!=null){
DataRecord storeRecord=dbDataRecord.duplicate();
resultCache.put(new HashKey(lookupKey, storeRecord), storeRecord);
}
return dbDataRecord;
}
/**
* Looks-up record/data based on specified array of parameters(values).
* No caching is performed.
*
*@param keys Description of the Parameter
*@return found DataRecord or NULL
*/
public DataRecord get(Object keys[]) {
try {
// set up parameters for query
// statement uses indexing from 1
pStatement.clearParameters();
for (int i = 0; i < keys.length; i++) {
pStatement.setObject(i + 1, keys[i]);
}
//execute query
resultSet = pStatement.executeQuery();
if (!fetch()) {
return null;
}
}
catch (SQLException ex) {
throw new RuntimeException(ex.getMessage());
}
return dbDataRecord;
}
/**
* Looks-up data based on specified key-string.<br>
* If caching is enabled, the
* internal cache is searched first, then the DB is queried.<br>
* <b>Warning:</b>it is not recommended to mix this call with call to <code>get(DataRecord keyRecord)</code> method.
*
*@param keyStr string representation of the key-value
*@return found DataRecord or NULL
*/
public DataRecord get(String keyStr) {
if (resultCache!=null){
DataRecord data=(DataRecord)resultCache.get(keyStr);
if (data!=null){
return data;
}
}
try {
// set up parameters for query
// statement uses indexing from 1
pStatement.clearParameters();
pStatement.setString(1, keyStr);
//execute query
resultSet = pStatement.executeQuery();
if (!fetch()) {
return null;
}
}
catch (SQLException ex) {
throw new RuntimeException(ex.getMessage());
}
if (resultCache!=null){
DataRecord storeRecord=dbDataRecord.duplicate();
resultCache.put(keyStr, storeRecord);
}
return dbDataRecord;
}
/**
* Executes query and returns data record (statement must be initialized with
* parameters prior to calling this function
*
*@return DataRecord obtained from DB or null if not found
*@exception SQLException Description of the Exception
*/
private boolean fetch() throws SQLException {
if (!resultSet.next()) {
return false;
}
// initialize trans map if needed
if (transMap==null){
initInternal();
}
//get data from results
for (int i = 0; i < transMap.length; i++) {
transMap[i].sql2jetel(resultSet);
}
return true;
}
/**
* Returns the next found record if previous get() method succeeded.<br>
* If no more records, returns NULL
*
*@return The next found record
*@exception JetelException Description of the Exception
*/
public DataRecord getNext() {
try {
if (!fetch()) {
return null;
} else {
return dbDataRecord;
}
} catch (SQLException ex) {
throw new RuntimeException(ex.getMessage());
}
}
/* (non-Javadoc)
* @see org.jetel.data.lookup.LookupTable#getNumFound()
*
* Using this method on this implementation of LookupTable
* can be time consuming as it requires sequential scan through
* the whole result set returned from DB (on some DBMSs).
* Also, it resets the position in result set. So subsequent
* calls to getNext() will start reading the data found from
* the first record.
*/
public int getNumFound() {
if (resultSet != null) {
try {
int curRow=resultSet.getRow();
resultSet.last();
int count=resultSet.getRow();
resultSet.first();
resultSet.absolute(curRow);
return count;
} catch (SQLException ex) {
return -1;
}
}
return -1;
}
/* (non-Javadoc)
* @see org.jetel.data.lookup.LookupTable#setLookupKey(java.lang.Object)
*/
public void setLookupKey(Object obj){
this.keyTransMap=null; // invalidate current transmap -if it exists
if (obj instanceof RecordKey){
this.lookupKey=((RecordKey)obj);
this.cacheKey=new HashKey(lookupKey,null);
}else{
this.lookupKey=null;
this.cacheKey=null;
}
}
/**
* Initializtaion of lookup table - loading all data into it.
*
*@exception JetelException Description of the Exception
*@since May 2, 2002
*/
public void init() throws ComponentNotReadyException {
// if caching is required, crate map to store records
if (maxCached>0){
this.resultCache= new SimpleCache(maxCached);
}
// first try to connect to db
try {
//dbConnection.connect();
pStatement = dbConnection.prepareStatement(sqlQuery);
/*ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_AT_COMMIT);*/
} catch (SQLException ex) {
throw new ComponentNotReadyException("Can't create SQL statement: " + ex.getMessage());
}
}
/**
* We assume that query has already been executed and
* we have resultSet available to get metadata.
*
*
* @throws JetelException
*/
private void initInternal() {
// obtain dbMetadata info if needed
if (dbMetadata == null) {
try {
dbMetadata = SQLUtil.dbMetadata2jetel(resultSet.getMetaData());
} catch (SQLException ex) {
throw new RuntimeException(
"Can't automatically obtain dbMetadata (use other constructor and provide metadat for output record): "
+ ex.getMessage());
}
}
// create data record for fetching data from DB
dbDataRecord = new DataRecord(dbMetadata);
dbDataRecord.init();
// create trans map which will be used for fetching data
try {
transMap = CopySQLData.sql2JetelTransMap(
SQLUtil.getFieldTypes(dbMetadata), dbMetadata,
dbDataRecord);
} catch (Exception ex) {
throw new RuntimeException(
"Can't automatically obtain dbMetadata/create transMap : "
+ ex.getMessage());
}
}
/**
* Deallocates resources
*/
public void free() {
try {
if(pStatement != null) {
pStatement.close();
}
resultCache = null;
transMap = null;
}
catch (SQLException ex) {
throw new RuntimeException(ex.getMessage());
}
}
public void setNumCached(int numCached){
if (numCached>0){
this.resultCache= new SimpleCache(numCached);
this.maxCached=numCached;
}
}
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#checkConfig()
*/
public boolean checkConfig() {
return true;
}
}
|
package com.netflix.spinnaker.fiat.config;
import com.netflix.spinnaker.fiat.roles.github.GitHubProperties;
import com.netflix.spinnaker.fiat.roles.github.client.GitHubClient;
import com.netflix.spinnaker.fiat.roles.github.client.GitHubMaster;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit.Endpoints;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
import retrofit.converter.JacksonConverter;
import javax.validation.Valid;
/**
* Converts the list of GitHub Configuration properties a collection of clients to access the GitHub hosts
*/
@Configuration
@ConditionalOnProperty(value = "auth.groupMembership.service", havingValue = "github")
@Slf4j
public class GitHubConfig {
@Autowired
@Setter
private OkClient okClient;
@Autowired
@Setter
private RestAdapter.LogLevel retrofitLogLevel;
@Bean
public GitHubMaster gitHubMasters(@Valid final GitHubProperties gitHubProperties) {
log.info("bootstrapping " + gitHubProperties.getBaseUrl() + " as github");
return new GitHubMaster()
.setGitHubClient(gitHubClient(gitHubProperties.getBaseUrl(),
gitHubProperties.getAccessToken()))
.setBaseUrl(gitHubProperties.getBaseUrl());
}
private GitHubClient gitHubClient(String address, String accessToken) {
BasicAuthRequestInterceptor interceptor = new BasicAuthRequestInterceptor();
return new RestAdapter.Builder()
.setEndpoint(Endpoints.newFixedEndpoint(address))
.setRequestInterceptor(interceptor.setAccessToken(accessToken))
.setClient(okClient)
.setConverter(new JacksonConverter())
.setLogLevel(retrofitLogLevel)
.build()
.create(GitHubClient.class);
}
private static class BasicAuthRequestInterceptor implements RequestInterceptor {
@Getter
@Setter
private String accessToken;
@Override
public void intercept(RequestFacade request) {
request.addQueryParam("access_token", accessToken);
}
}
}
|
package collabode;
import java.io.IOException;
import java.util.Hashtable;
import net.appjet.ajstdlib.execution;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.jdt.core.*;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.jdt.junit.JUnitCore;
import org.eclipse.jdt.launching.JavaRuntime;
import collabode.testing.AnnotationsInitializer;
public class Workspace {
private static IWorkspace WORKSPACE;
public static synchronized IWorkspace getWorkspace() {
if (WORKSPACE == null) {
new InstanceScope().getNode(ResourcesPlugin.PI_RESOURCES).putBoolean(ResourcesPlugin.PREF_AUTO_REFRESH, true);
Hashtable<String,String> options = getJavaCoreOptions();
options.put(JavaCore.CODEASSIST_FORBIDDEN_REFERENCE_CHECK, "enabled");
options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, "space");
JavaCore.setOptions(options);
WORKSPACE = ResourcesPlugin.getWorkspace();
}
return WORKSPACE;
}
@SuppressWarnings("unchecked")
public static Hashtable<String,String> getJavaCoreOptions() {
return JavaCore.getOptions();
}
public static IProject[] listProjects() {
return getWorkspace().getRoot().getProjects();
}
public static IProject accessProject(String projectname) {
return getWorkspace().getRoot().getProject(projectname);
}
public static IProject createProject(String projectname) throws CoreException {
final IProject project = getWorkspace().getRoot().getProject(projectname);
if ( ! project.exists()) {
getWorkspace().run(new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
project.create(null);
project.open(null);
addJavaNature(project);
setupJavaClasspath(project);
}
}, null);
}
return project;
}
public static IProject cloneProject(String projectname, String destinationname) throws CoreException {
IProject dest = getWorkspace().getRoot().getProject(destinationname);
if (dest.exists()) { return dest; }
IProject project = getWorkspace().getRoot().getProject(projectname);
project.open(null);
IProjectDescription desc = project.getDescription();
desc.setLocation(null);
desc.setName(destinationname);
project.copy(desc, false, null);
return dest;
}
public static void createDocument(String username, IFile file) throws IOException, JavaModelException {
PadDocumentOwner.of(username).create(file);
}
public static ILaunchConfiguration accessLaunchConfig(IFile file) {
return DebugPlugin.getDefault().getLaunchManager().getLaunchConfiguration(file);
}
private static void addJavaNature(IProject project) throws CoreException {
IProjectDescription description = project.getDescription();
String[] prevNatures = description.getNatureIds();
String[] newNatures = new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length] = JavaCore.NATURE_ID;
description.setNatureIds(newNatures);
project.setDescription(description, null);
}
private static void setupJavaClasspath(IProject project) throws CoreException {
IFolder srcFolder = project.getFolder("src");
srcFolder.create(true, true, null);
IFolder binFolder = project.getFolder("bin");
if ( ! binFolder.exists()) {
binFolder.create(true, true, null);
}
IJavaProject javaProject = JavaCore.create(project);
javaProject.setOutputLocation(binFolder.getFullPath(), null);
IClasspathEntry[] entries = new IClasspathEntry[] {
JavaRuntime.getDefaultJREContainerEntry(),
JavaCore.newContainerEntry(JUnitCore.JUNIT4_CONTAINER_PATH),
JavaCore.newContainerEntry(AnnotationsInitializer.PATH),
JavaCore.newSourceEntry(srcFolder.getFullPath())
};
javaProject.setRawClasspath(entries, null);
}
/**
* Schedule a JavaScript task for execution with no delay.
*/
public static void scheduleTask(String taskName, Object... args) {
execution.scheduleTaskInPool("dbwriter_infreq", taskName, 0, args); // XXX maybe a different pool?
}
}
|
package me.oskarmendel.view;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.SimpleStringProperty;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.layout.AnchorPane;
import me.oskarmendel.entities.Song;
import me.oskarmendel.model.SearchResultModel;
public class SongBrowserController implements RapidTunesController {
@FXML private AnchorPane songBrowserPane;
@FXML private TableView<Song> songList;
@FXML private TableColumn<Song, String> songListSong;
@FXML private TableColumn<Song, String> songListPublisher;
@FXML private TableColumn<Song, String> songListTime;
@FXML private TableColumn<Song, String> songListSource;
private static final Logger LOGGER = Logger.getLogger(SongBrowserController.class.getName());
private SearchResultModel searchResultModel;
@FXML
public void initialize() {
LOGGER.log(Level.FINE, "Initialized: " + this.getClass().getName());
//Define width for the TableView columns
songList.getColumns().forEach(c -> {
if(c.getText().equals("Song")) {
c.prefWidthProperty().bind(songList.widthProperty().divide(2));
} else if(c.getText().equals("Publisher")){
c.prefWidthProperty().bind(songList.widthProperty().divide(4));
} else {
c.prefWidthProperty().bind(songList.widthProperty().divide(8));
}
});
//This is how to set the value by using Property of a object
//We will switch to this way after we implemented a yt song object.
//TODO: When implementing read up on the PropertyValueFactory class.
//songListSong.setCellValueFactory(new PropertyValueFactory<Video, String>("title"));
//Manually setting the content as a simple string property.
songListSong.setCellValueFactory(c -> new SimpleStringProperty(c.getValue().getTitle()));
songListPublisher.setCellValueFactory(c -> new SimpleStringProperty(c.getValue().getArtist()));
songListTime.setCellValueFactory(c -> new SimpleStringProperty(c.getValue().getLength()));
songListSource.setCellValueFactory(c -> new SimpleStringProperty("YT"));
//Define an on-click for the table rows.
songList.setRowFactory(tv -> {
TableRow<Song> row = new TableRow<>();
row.setOnMouseClicked(event -> {
if(event.getClickCount() == 2 && (!row.isEmpty())) {
//Here we will call an even to start the song.
Song test = row.getItem();
System.out.println(test.getTitle());
}
});
return row;
});
}
/**
* Initializes the SearchResultModel which connects the list of search results between
* the SongBrowserController and the NavigationController.
* This controller will use the data within the models ObservableList and display it within
* the local ListView.
*
* @param searchResultModel - searchResultModel object to get data from.
*/
public void initSearchResultModel(SearchResultModel searchResultModel) {
//Make sure model is only set once.
if (this.searchResultModel != null) {
throw new IllegalStateException("Model can only be initialized once");
}
this.searchResultModel = searchResultModel;
songList.setItems(searchResultModel.getSearchResultList());
//Only display the title of each song in the search result list
/*songList.setCellFactory(lv -> new ListCell<SearchResult>() {
@Override
public void updateItem(SearchResult result, boolean empty) {
super.updateItem(result, empty);
if (empty) {
setText(null);
} else {
setText(result.getSnippet().getTitle());
}
}
});*/
}
}
|
package com.ecyrd.jspwiki.xmlrpc;
import com.ecyrd.jspwiki.*;
import com.ecyrd.jspwiki.attachment.Attachment;
import junit.framework.*;
import java.util.*;
import org.apache.xmlrpc.*;
public class RPCHandlerTest extends TestCase
{
TestEngine m_engine;
RPCHandler m_handler;
Properties m_props;
static final String NAME1 = "Test";
public RPCHandlerTest( String s )
{
super( s );
}
public void setUp()
throws Exception
{
m_props = new Properties();
m_props.load( TestEngine.findTestProperties() );
m_engine = new TestEngine( m_props );
m_handler = new RPCHandler();
m_handler.initialize( m_engine );
}
public void tearDown()
{
m_engine.deletePage( NAME1 );
m_engine.deleteAttachments( NAME1 );
}
public void testNonexistantPage()
{
try
{
byte[] res = m_handler.getPage( "NoSuchPage" );
fail("No exception for missing page.");
}
catch( XmlRpcException e )
{
assertEquals( "Wrong error code.", RPCHandler.ERR_NOPAGE, e.code );
}
}
public void testRecentChanges()
throws Exception
{
String text = "Foo";
String pageName = NAME1;
m_engine.saveText( pageName, text );
WikiPage directInfo = m_engine.getPage( NAME1 );
Date modDate = directInfo.getLastModified();
Calendar cal = Calendar.getInstance();
cal.setTime( modDate );
cal.add( Calendar.MINUTE, -1 );
// Go to UTC
cal.add( Calendar.MILLISECOND,
-(cal.get( Calendar.ZONE_OFFSET )+
(cal.getTimeZone().inDaylightTime( modDate ) ? cal.get( Calendar.DST_OFFSET ) : 0 ) ) );
Vector v = m_handler.getRecentChanges( cal.getTime() );
assertEquals( "wrong number of changes", 1, v.size() );
}
public void testRecentChangesWithAttachments()
throws Exception
{
String text = "Foo";
String pageName = NAME1;
m_engine.saveText( pageName, text );
Attachment att = new Attachment( NAME1, "TestAtt.txt" );
att.setAuthor( "FirstPost" );
m_engine.getAttachmentManager().storeAttachment( att, m_engine.makeAttachmentFile() );
WikiPage directInfo = m_engine.getPage( NAME1 );
Date modDate = directInfo.getLastModified();
Calendar cal = Calendar.getInstance();
cal.setTime( modDate );
cal.add( Calendar.MINUTE, -1 );
// Go to UTC
cal.add( Calendar.MILLISECOND,
-(cal.get( Calendar.ZONE_OFFSET )+
(cal.getTimeZone().inDaylightTime( modDate ) ? cal.get( Calendar.DST_OFFSET ) : 0 ) ) );
Vector v = m_handler.getRecentChanges( cal.getTime() );
assertEquals( "wrong number of changes", 1, v.size() );
}
public void testPageInfo()
throws Exception
{
String text = "Foobar.";
String pageName = NAME1;
m_engine.saveText( pageName, text );
WikiPage directInfo = m_engine.getPage( NAME1 );
Hashtable ht = m_handler.getPageInfo( NAME1 );
assertEquals( "name", (String)ht.get( "name" ), NAME1 );
Date d = (Date) ht.get( "lastModified" );
Calendar cal = Calendar.getInstance();
cal.setTime( d );
System.out.println("Real: "+directInfo.getLastModified() );
System.out.println("RPC: "+d );
// Offset the ZONE offset and DST offset away. DST only
// if we're actually in DST.
cal.add( Calendar.MILLISECOND,
(cal.get( Calendar.ZONE_OFFSET )+
(cal.getTimeZone().inDaylightTime( d ) ? cal.get( Calendar.DST_OFFSET ) : 0 ) ) );
System.out.println("RPC2: "+cal.getTime() );
assertEquals( "date", cal.getTime().getTime(),
directInfo.getLastModified().getTime() );
}
/**
* Tests if listLinks() works with a single, non-existant local page.
*/
public void testListLinks()
throws Exception
{
String text = "[Foobar]";
String pageName = NAME1;
m_engine.saveText( pageName, text );
Vector links = m_handler.listLinks( pageName );
assertEquals( "link count", 1, links.size() );
Hashtable linkinfo = (Hashtable) links.elementAt(0);
assertEquals( "name", "Foobar", linkinfo.get("page") );
assertEquals( "type", "local", linkinfo.get("type") );
assertEquals( "href", "Edit.jsp?page=Foobar", linkinfo.get("href") );
}
public void testListLinksWithAttachments()
throws Exception
{
String text = "[Foobar] [Test/TestAtt.txt]";
String pageName = NAME1;
m_engine.saveText( pageName, text );
Attachment att = new Attachment( NAME1, "TestAtt.txt" );
att.setAuthor( "FirstPost" );
m_engine.getAttachmentManager().storeAttachment( att, m_engine.makeAttachmentFile() );
// Test.
Vector links = m_handler.listLinks( pageName );
assertEquals( "link count", 2, links.size() );
Hashtable linkinfo = (Hashtable) links.elementAt(0);
assertEquals( "name", "Foobar", linkinfo.get("page") );
assertEquals( "type", "local", linkinfo.get("type") );
assertEquals( "href", "Edit.jsp?page=Foobar", linkinfo.get("href") );
linkinfo = (Hashtable) links.elementAt(1);
assertEquals( "name", NAME1+"%2FTestAtt.txt", linkinfo.get("page") );
assertEquals( "type", "local", linkinfo.get("type") );
assertEquals( "href", "attach?page="+NAME1+"%2FTestAtt.txt", linkinfo.get("href") );
}
public void testPermissions()
throws Exception
{
String text ="Blaa. [{DENY view Guest}] [{ALLOW view NamedGuest}]";
m_engine.saveText( NAME1, text );
try
{
Vector links = m_handler.listLinks( NAME1 );
fail("Didn't get an exception in listLinks()");
}
catch( XmlRpcException e ) {}
try
{
Hashtable ht = m_handler.getPageInfo( NAME1 );
fail("Didn't get an exception in getPageInfo()");
}
catch( XmlRpcException e ) {}
}
public static Test suite()
{
return new TestSuite( RPCHandlerTest.class );
}
}
|
import java.io.*;
import org.xbill.DNS.*;
/** @author Brian Wellington <bwelling@xbill.org> */
public class dig {
static Name name = null;
static int type = Type.A, dclass = DClass.IN;
static void
usage() {
System.out.println("Usage: dig [@server] name [<type>] [<class>] " +
"[options]");
System.exit(0);
}
static void
doQuery(Message response, long ms) throws IOException {
System.out.println("; java dig 0.0");
System.out.println(response);
System.out.println(";; Query time: " + ms + " ms");
}
static void
doAXFR(Message response) throws IOException {
System.out.println("; java dig 0.0 <> " + name + " axfr");
if (response.isSigned()) {
System.out.print(";; TSIG ");
if (response.isVerified())
System.out.println("ok");
else
System.out.println("failed");
}
if (response.getRcode() != Rcode.NOERROR) {
System.out.println(response);
return;
}
Record [] records = response.getSectionArray(Section.ANSWER);
for (int i = 0; i < records.length; i++)
System.out.println(records[i]);
System.out.print(";; done (");
System.out.print(response.getHeader().getCount(Section.ANSWER));
System.out.print(" records, ");
System.out.print(response.getHeader().getCount(Section.ADDITIONAL));
System.out.println(" additional)");
}
public static void
main(String argv[]) throws IOException {
String server = null;
int arg;
Message query, response;
Record rec;
Record opt = null;
Resolver res = null;
boolean printQuery = false;
long startTime, endTime;
if (argv.length < 1) {
usage();
}
try {
arg = 0;
if (argv[arg].startsWith("@"))
server = argv[arg++].substring(1);
String nameString = argv[arg++];
if (nameString.equals("-x")) {
name = ReverseMap.fromAddress(argv[arg++]);
type = Type.PTR;
dclass = DClass.IN;
}
else {
name = Name.fromString(nameString, Name.root);
type = Type.value(argv[arg]);
if (type < 0)
type = Type.A;
else
arg++;
dclass = DClass.value(argv[arg]);
if (dclass < 0)
dclass = DClass.IN;
else
arg++;
}
if (server != null)
res = new SimpleResolver(server);
else if (type == Type.AXFR)
res = new SimpleResolver();
else
res = new ExtendedResolver();
while (argv[arg].startsWith("-") && argv[arg].length() > 1) {
switch (argv[arg].charAt(1)) {
case 'p':
String portStr;
int port;
if (argv[arg].length() > 2)
portStr = argv[arg].substring(2);
else
portStr = argv[++arg];
port = Integer.parseInt(portStr);
if (port < 0 || port > 65536) {
System.out.println("Invalid port");
return;
}
res.setPort(port);
break;
case 'k':
String key;
if (argv[arg].length() > 2)
key = argv[arg].substring(2);
else
key = argv[++arg];
res.setTSIGKey(TSIG.fromString(key));
break;
case 't':
res.setTCP(true);
break;
case 'i':
res.setIgnoreTruncation(true);
break;
case 'e':
String ednsStr;
int edns;
if (argv[arg].length() > 2)
ednsStr = argv[arg].substring(2);
else
ednsStr = argv[++arg];
edns = Integer.parseInt(ednsStr);
if (edns < 0 || edns > 1) {
System.out.println("Unsupported " +
"EDNS level: " +
edns);
return;
}
res.setEDNS(edns);
break;
case 'd':
opt = new OPTRecord((short)1280, (byte)0,
(byte)0, ExtendedFlags.DO);
break;
case 'q':
printQuery = true;
break;
default:
System.out.print("Invalid option: ");
System.out.println(argv[arg]);
}
arg++;
}
}
catch (ArrayIndexOutOfBoundsException e) {
if (name == null)
usage();
}
if (res == null)
res = new ExtendedResolver();
rec = Record.newRecord(name, type, dclass);
query = Message.newQuery(rec);
if (opt != null)
query.addRecord(opt, Section.ADDITIONAL);
if (printQuery)
System.out.println(query);
startTime = System.currentTimeMillis();
response = res.send(query);
endTime = System.currentTimeMillis();
if (type == Type.AXFR)
doAXFR(response);
else
doQuery(response, endTime - startTime);
}
}
|
package org.commcare.android.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import org.commcare.dalvik.preferences.DeveloperPreferences;
import org.javarosa.core.model.data.GeoPointData;
import org.javarosa.core.model.data.UncastData;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import java.io.File;
/**
* @author ctsims
*/
public class MediaUtil {
public static final String FORM_VIDEO = "video";
public static final String FORM_AUDIO = "audio";
public static final String FORM_IMAGE = "image";
public static Bitmap getBitmapScaledToContainer(File f, int containerHeight, int containerWidth) {
Log.i("10/15", "scaling down to height " + containerHeight + " and width " + containerWidth);
// Determine dimensions of original image
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(f.getAbsolutePath(), o);
int imageHeight = o.outHeight;
int imageWidth = o.outWidth;
// Get a scale-down factor -- Powers of 2 work faster according to the docs, but we're
// just doing closest size that still fills the screen
int heightScale = Math.round((float) imageHeight / containerHeight);
int widthScale = Math.round((float) imageWidth / containerWidth);
int scale = Math.max(widthScale, heightScale);
if (scale == 0) {
// Rounding could possibly have resulted in a scale factor of 0, which is invalid
scale = 1;
}
return performSafeScaleDown(f, scale, 0);
}
/**
* @return A scaled-down bitmap for the given image file, progressively increasing the
* scale-down factor by 1 until allocating memory for the bitmap does not cause an OOM error
*/
private static Bitmap performSafeScaleDown(File f, int scale, int depth) {
if (depth == 5) {
// Limit the number of recursive calls
return null;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = scale;
try {
return BitmapFactory.decodeFile(f.getAbsolutePath(), options);
} catch (OutOfMemoryError e) {
return performSafeScaleDown(f, scale + 1, depth + 1);
}
}
/**
* @return A bitmap representation of the given image file, scaled up as close as possible to
* desiredWidth and desiredHeight, without exceeding either boundingHeight or boundingWidth
*/
private static Bitmap attemptBoundedScaleUp(File imageFile, int desiredHeight, int desiredWidth,
int boundingHeight, int boundingWidth) {
if (boundingHeight < desiredHeight || boundingWidth < desiredWidth) {
float heightScale = ((float)boundingHeight) / desiredHeight;
float widthScale = ((float)boundingWidth) / desiredWidth;
float boundingScaleDownFactor = Math.min(heightScale, widthScale);
desiredHeight = Math.round(desiredHeight * boundingScaleDownFactor);
desiredWidth = Math.round(desiredWidth * boundingScaleDownFactor);
}
Log.i("10/15", "scaling up to height " + desiredHeight + " and width " + desiredWidth);
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inScaled = false;
Bitmap originalBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), o);
try {
return Bitmap.createScaledBitmap(originalBitmap, desiredWidth, desiredHeight, false);
} catch (OutOfMemoryError e) {
return originalBitmap;
}
}
catch (OutOfMemoryError e) {
// Just inflating the image at its original size caused an OOM error, don't have a
// choice but to scale down
return performSafeScaleDown(imageFile, 2, 1);
}
}
/**
* Attempts to inflate an image from a <display> or other CommCare UI definition source.
*
* @param jrUri The image to inflate
* @param boundingWidth the width of the container this image is being inflated into, to serve
* as a max width. If passed in as -1, gets set to screen width
* @param boundingHeight the height fo the container this image is being inflated into, to
* serve as a max height. If passed in as -1, gets set to screen height
* @return A bitmap if one could be created. Null if error occurs or the image is unavailable.
*/
public static Bitmap inflateDisplayImage(Context context, String jrUri,
int boundingWidth, int boundingHeight) {
if (jrUri == null || jrUri.equals("")) {
return null;
}
try {
String imageFilename = ReferenceManager._().DeriveReference(jrUri).getLocalURI();
final File imageFile = new File(imageFilename);
if (!imageFile.exists()) {
return null;
}
Display display = ((WindowManager)
context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
if (boundingHeight == -1) {
boundingHeight = display.getHeight();
}
if (boundingWidth == -1) {
boundingWidth = display.getWidth();
}
Log.i("10/15", "bounding height: " + boundingHeight + ", bounding width: " + boundingWidth);
if (DeveloperPreferences.isSmartInflationEnabled()) {
// scale based on native density AND bounding dimens
return scaleForNativeDensity(context, jrUri, boundingHeight, boundingWidth,
DeveloperPreferences.getTargetInflationDensity());
} else {
// just scaling down if the original image is too big for its container
return getBitmapScaledToContainer(imageFile, boundingHeight, boundingWidth);
}
} catch (InvalidReferenceException e) {
Log.e("ImageInflater", "image invalid reference exception for " + e.getReferenceString());
e.printStackTrace();
}
return null;
}
public static Bitmap inflateDisplayImage(Context context, String jrUri) {
return inflateDisplayImage(context, jrUri, -1, -1);
}
private static Bitmap scaleForNativeDensity(Context context, String jrUri, int containerHeight,
int containerWidth, int targetDensity) {
if (jrUri == null || jrUri.equals("")) {
return null;
}
try {
String imageFilename = ReferenceManager._().DeriveReference(jrUri).getLocalURI();
final File imageFile = new File(imageFilename);
if (imageFile.exists()) {
Log.i("10/15", "src path: " + imageFilename);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
o.inScaled = false;
BitmapFactory.decodeFile(imageFile.getAbsolutePath(), o);
int imageHeight = o.outHeight;
int imageWidth = o.outWidth;
Log.i("10/15", "original height: " + imageHeight + ", original width: " + imageWidth);
double scaleFactor = computeScaleFactor(context, targetDensity);
int calculatedHeight = Math.round((float)(imageHeight * scaleFactor));
int calculatedWidth = Math.round((float)(imageWidth * scaleFactor));
Log.i("10/15", "calculated height: " + calculatedHeight + ", calculated width: " + calculatedWidth);
int boundingHeight = Math.min(containerHeight, calculatedHeight);
int boundingWidth = Math.min(containerWidth, calculatedWidth);
if (boundingHeight < imageHeight || boundingWidth < imageWidth) {
// scaling down
return getBitmapScaledToContainer(imageFile, boundingHeight, boundingWidth);
} else {
// scaling up
return attemptBoundedScaleUp(imageFile, calculatedHeight, calculatedWidth,
containerHeight, containerWidth);
}
}
} catch (InvalidReferenceException e) {
Log.e("ImageInflater", "image invalid reference exception for " + e.getReferenceString());
e.printStackTrace();
}
return null;
}
private static double computeScaleFactor(Context context, int targetDensity) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
final int SCREEN_DENSITY = metrics.densityDpi;
double actualNativeScaleFactor = metrics.density;
// The formula below is what Android *usually* uses to compute the value of metrics.density
// for a device. If this is in fact the value being used, we are not interested in it.
// However, if the actual value differs at all from the standard calculation, it means
// Android is taking other factors into consideration (such as straight up screen size),
// and we want to incorporate that proportionally into our own version of the scale factor
double standardNativeScaleFactor = (double)SCREEN_DENSITY / DisplayMetrics.DENSITY_DEFAULT;
double proportionalAdjustmentFactor = 1;
if (actualNativeScaleFactor > standardNativeScaleFactor) {
proportionalAdjustmentFactor = 1 +
((actualNativeScaleFactor - standardNativeScaleFactor) / standardNativeScaleFactor);
} else if (actualNativeScaleFactor < standardNativeScaleFactor) {
proportionalAdjustmentFactor = actualNativeScaleFactor / standardNativeScaleFactor;
}
Log.i("10/15", "proportional adjustment factor: " + proportionalAdjustmentFactor);
// Get our custom scale factor, based on this device's density and what the image's target
// density was
Log.i("10/15", "Target dpi: " + targetDensity);
Log.i("10/15", "This screen's dpi: " + SCREEN_DENSITY);
double customDpiScaleFactor = (double)SCREEN_DENSITY / targetDensity;
Log.i("10/15", "dpi scale factor: " + customDpiScaleFactor);
Log.i("10/15", "FINAL scale factor: " + (customDpiScaleFactor * proportionalAdjustmentFactor));
return customDpiScaleFactor * proportionalAdjustmentFactor;
}
/**
* Pass in a string representing either a GeoPoint or an address and get back a valid
* GeoURI that can be passed as an intent argument
*/
public static String getGeoIntentURI(String rawInput){
try {
GeoPointData mGeoPointData = new GeoPointData().cast(new UncastData(rawInput));
String latitude = Double.toString(mGeoPointData.getValue()[0]);
String longitude= Double.toString(mGeoPointData.getValue()[1]);
return "geo:" + latitude + "," + longitude + "?q=" + latitude + "," + longitude;
} catch(IllegalArgumentException iae){
return "geo:0,0?q=" + rawInput;
}
}
}
|
package org.commcare.android.view;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.os.Build;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import org.achartengine.ChartFactory;
import org.achartengine.chart.BarChart;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.commcare.android.models.RangeXYValueSeries;
import org.commcare.android.util.InvalidStateException;
import org.commcare.dalvik.R;
import org.commcare.suite.model.graph.AnnotationData;
import org.commcare.suite.model.graph.BubblePointData;
import org.commcare.suite.model.graph.ConfigurableData;
import org.commcare.suite.model.graph.Graph;
import org.commcare.suite.model.graph.GraphData;
import org.commcare.suite.model.graph.SeriesData;
import org.commcare.suite.model.graph.XYPointData;
import org.javarosa.core.model.utils.DateUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
/*
* View containing a graph. Note that this does not derive from View; call renderView to get a view for adding to other views, etc.
* @author jschweers
*/
public class GraphView {
private Context mContext;
private int mTextSize;
private GraphData mData;
private XYMultipleSeriesDataset mDataset;
private XYMultipleSeriesRenderer mRenderer;
public GraphView(Context context, String title) {
mContext = context;
mTextSize = (int)context.getResources().getDimension(R.dimen.text_large);
mDataset = new XYMultipleSeriesDataset();
mRenderer = new XYMultipleSeriesRenderer(2); // initialize with two scales, to support a secondary y axis
mRenderer.setChartTitle(title);
mRenderer.setChartTitleTextSize(mTextSize);
}
/*
* Set margins.
*/
private void setMargins() {
int textAllowance = (int)mContext.getResources().getDimension(R.dimen.graph_text_margin);
int topMargin = (int)mContext.getResources().getDimension(R.dimen.graph_y_margin);
if (!mRenderer.getChartTitle().equals("")) {
topMargin += textAllowance;
}
int rightMargin = (int)mContext.getResources().getDimension(R.dimen.graph_x_margin);
if (!mRenderer.getYTitle(1).equals("")) {
rightMargin += textAllowance;
}
int leftMargin = (int)mContext.getResources().getDimension(R.dimen.graph_x_margin);
if (!mRenderer.getYTitle().equals("")) {
leftMargin += textAllowance;
}
int bottomMargin = (int)mContext.getResources().getDimension(R.dimen.graph_y_margin);
if (!mRenderer.getXTitle().equals("")) {
bottomMargin += textAllowance;
}
// AChartEngine doesn't handle x label margins as desired, so do it here
if (mRenderer.isShowLabels()) {
bottomMargin += textAllowance;
}
// Bar charts have text labels that are likely to be long (names, etc.).
// At some point there'll need to be a more robust solution for setting
// margins that respond to data and screen size. For now, give them no margin
// and push the labels onto the graph area itself by manually padding the labels.
if (Graph.TYPE_BAR.equals(mData.getType()) && getOrientation().equals(XYMultipleSeriesRenderer.Orientation.VERTICAL)) {
bottomMargin = 0;
}
mRenderer.setMargins(new int[]{topMargin, leftMargin, bottomMargin, rightMargin});
}
private void render(GraphData data) throws InvalidStateException {
mRenderer.setInScroll(true);
for (SeriesData s : data.getSeries()) {
renderSeries(s);
}
renderAnnotations();
configure();
setMargins();
}
public Intent getIntent(GraphData data) throws InvalidStateException {
render(data);
setPanAndZoom(Boolean.valueOf(mData.getConfiguration("zoom", "false")));
String title = mRenderer.getChartTitle();
if (Graph.TYPE_BUBBLE.equals(mData.getType())) {
return ChartFactory.getBubbleChartIntent(mContext, mDataset, mRenderer, title);
}
if (Graph.TYPE_TIME.equals(mData.getType())) {
return ChartFactory.getTimeChartIntent(mContext, mDataset, mRenderer, getTimeFormat(), title);
}
if (Graph.TYPE_BAR.equals(mData.getType())) {
return ChartFactory.getBarChartIntent(mContext, mDataset, mRenderer, getBarChartType(), title);
}
return ChartFactory.getLineChartIntent(mContext, mDataset, mRenderer, title);
}
private BarChart.Type getBarChartType() {
if (Boolean.valueOf(mData.getConfiguration("stack", "false")).equals(Boolean.TRUE)) {
return BarChart.Type.STACKED;
}
return BarChart.Type.DEFAULT;
}
/**
* Enable or disable pan and zoom settings for this view.
*
* @param allow Whether or not to enabled pan and zoom.
*/
private void setPanAndZoom(boolean allow) {
mRenderer.setPanEnabled(allow, allow);
mRenderer.setZoomEnabled(allow, allow);
mRenderer.setZoomButtonsVisible(allow);
}
private JSONObject getC3DataConfig() throws JSONException {
// Actual data: array of arrays, where first element is a string id
// and later elements are data, either x values or y values.
JSONArray columns = new JSONArray();
// Hash that pairs up the arrays defined in columns,
// y-values-array-id => x-values-array-id
JSONObject xs = new JSONObject();
int seriesIndex = 0;
for (SeriesData s : mData.getSeries()) {
JSONArray xValues = new JSONArray();
JSONArray yValues = new JSONArray();
String xID = "x" + seriesIndex;
String yID = "y" + seriesIndex;
xs.put(yID, xID);
xValues.put(xID);
yValues.put(yID);
for (XYPointData p : s.getPoints()) {
xValues.put(p.getX());
yValues.put(p.getY());
}
columns.put(xValues);
columns.put(yValues);
seriesIndex++;
}
JSONObject config = new JSONObject();
config.put("xs", xs);
config.put("columns", columns);
return config;
}
// TODO: lighten these lines? they default to on, and are heavier than AChartEngine's
private JSONObject getC3GridConfig() throws JSONException {
JSONObject config = new JSONObject();
if (Boolean.valueOf(mData.getConfiguration("show-grid", "true")).equals(Boolean.TRUE)) {
JSONObject show = new JSONObject();
show.put("show", true);
config.put("x", show);
config.put("y", show);
}
return config;
}
private JSONObject getC3Config() {
JSONObject config = new JSONObject();
try {
config.put("data", getC3DataConfig());
config.put("grid", getC3GridConfig());
} catch (JSONException e) {
throw new RuntimeException("something broke"); // TODO: fix
}
return config;
}
/*
* Get a View object that will display this graph. This should be called after making
* any changes to graph's configuration, title, etc.
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
public View getView(GraphData data) throws InvalidStateException {
mData = data;
WebView.setWebContentsDebuggingEnabled(true); // TODO: only if in dev
WebView webView = new WebView(mContext);
configureSettings(webView);
String html =
"<html>" +
"<head>" +
"<link rel='stylesheet' type='text/css' href='file:///android_asset/graphing/c3.min.css'></link>" +
"<link rel='stylesheet' type='text/css' href='file:///android_asset/graphing/graph.css'></link>" +
"<script type='text/javascript' src='file:///android_asset/graphing/d3.min.js'></script>" +
"<script type='text/javascript' src='file:///android_asset/graphing/c3.min.js' charset='utf-8'></script>" +
"<script type='text/javascript'>var config = " + getC3Config().toString() + ";</script>" +
"<script type='text/javascript' src='file:///android_asset/graphing/graph.js'></script>" +
"</head>" +
"<body><div id='chart'></div></body>" +
"</html>";
webView.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", null);
return webView;
/*
if (Graph.TYPE_BUBBLE.equals(mData.getType())) {
return ChartFactory.getBubbleChartView(mContext, mDataset, mRenderer);
}
if (Graph.TYPE_TIME.equals(mData.getType())) {
return ChartFactory.getTimeChartView(mContext, mDataset, mRenderer, getTimeFormat());
}
if (Graph.TYPE_BAR.equals(mData.getType())) {
return ChartFactory.getBarChartView(mContext, mDataset, mRenderer, getBarChartType());
}
return ChartFactory.getLineChartView(mContext, mDataset, mRenderer);*/
}
private void configureSettings(WebView view) {
WebSettings settings = view.getSettings();
settings.setJavaScriptEnabled(true);
// Improve performance
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
settings.setSupportZoom(false);
}
/**
* Fetch date format for displaying time-based x labels.
*
* @return String, a SimpleDateFormat pattern.
*/
private String getTimeFormat() {
return mData.getConfiguration("x-labels-time-format", "yyyy-MM-dd");
}
/*
* Allow or disallow clicks on this graph - really, on the view generated by getView.
*/
public void setClickable(boolean enabled) {
mRenderer.setClickEnabled(enabled);
}
/*
* Set up a single series.
*/
private void renderSeries(SeriesData s) throws InvalidStateException {
XYSeriesRenderer currentRenderer = new XYSeriesRenderer();
mRenderer.addSeriesRenderer(currentRenderer);
configureSeries(s, currentRenderer);
XYSeries series = createSeries(Boolean.valueOf(s.getConfiguration("secondary-y", "false")).equals(Boolean.TRUE) ? 1 : 0);
series.setTitle(s.getConfiguration("name", ""));
if (Graph.TYPE_BUBBLE.equals(mData.getType())) {
if (s.getConfiguration("radius-max") != null) {
((RangeXYValueSeries)series).setMaxValue(parseYValue(s.getConfiguration("radius-max"), "radius-max"));
}
}
mDataset.addSeries(series);
// Bubble charts will throw an index out of bounds exception if given points out of order
Vector<XYPointData> sortedPoints = new Vector<XYPointData>(s.size());
for (XYPointData d : s.getPoints()) {
sortedPoints.add(d);
}
Comparator<XYPointData> comparator;
if (Graph.TYPE_BAR.equals(mData.getType())) {
String barSort = s.getConfiguration("bar-sort", "");
switch (barSort) {
case "ascending":
comparator = new AscendingValuePointComparator();
break;
case "descending":
comparator = new DescendingValuePointComparator();
break;
default:
comparator = new StringPointComparator();
break;
}
} else {
comparator = new NumericPointComparator();
}
Collections.sort(sortedPoints, comparator);
int barIndex = 1;
JSONObject barLabels = new JSONObject();
for (XYPointData p : sortedPoints) {
String description = "point (" + p.getX() + ", " + p.getY() + ")";
if (Graph.TYPE_BUBBLE.equals(mData.getType())) {
BubblePointData b = (BubblePointData)p;
description += " with radius " + b.getRadius();
((RangeXYValueSeries)series).add(parseXValue(b.getX(), description), parseYValue(b.getY(), description), parseRadiusValue(b.getRadius(), description));
} else if (Graph.TYPE_TIME.equals(mData.getType())) {
((TimeSeries)series).add(parseXValue(p.getX(), description), parseYValue(p.getY(), description));
} else if (Graph.TYPE_BAR.equals(mData.getType())) {
// In CommCare, bar graphs are specified with x as a set of text labels
// and y as a set of values. In AChartEngine, bar graphs are a subclass
// of XY graphs, with numeric x and y values. Deal with this by
// assigning an arbitrary, evenly-spaced x value to each bar and then
// populating x-labels with the user's x values.
series.add(barIndex, parseYValue(p.getY(), description));
try {
// For horizontal graphs, force labels right so they appear on the graph itself
String padding = getOrientation().equals(XYMultipleSeriesRenderer.Orientation.VERTICAL) ? " " : "";
barLabels.put(Double.toString(barIndex), padding + p.getX());
} catch (JSONException e) {
throw new InvalidStateException("Could not handle bar label '" + p.getX() + "': " + e.getMessage());
}
barIndex++;
} else {
series.add(parseXValue(p.getX(), description), parseYValue(p.getY(), description));
}
}
if (Graph.TYPE_BAR.equals(mData.getType())) {
mData.setConfiguration("x-min", Double.toString(0.5));
mData.setConfiguration("x-max", Double.toString(sortedPoints.size() + 0.5));
mData.setConfiguration("x-labels", barLabels.toString());
}
}
/*
* Get layout params for this graph, which assume that graph will fill parent
* unless dimensions have been provided via setWidth and/or setHeight.
*/
public static LinearLayout.LayoutParams getLayoutParams() {
return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
}
/**
* Get graph's desired aspect ratio.
*
* @return Ratio, expressed as a double: width / height.
*/
public double getRatio() {
// Most graphs are drawn with aspect ratio 2:1, which is mostly arbitrary
// and happened to look nice for partographs. Vertically-oriented graphs,
// however, get squished unless they're drawn as a square. Expect to revisit
// this eventually (make all graphs square? user-configured aspect ratio?).
if (Graph.TYPE_BAR.equals(mData.getType())) {
return 1;
}
return 2;
}
private XYMultipleSeriesRenderer.Orientation getOrientation() {
// AChartEngine's horizontal/vertical definitions are counter-intuitive
String orientation = mData.getConfiguration("bar-orientation", "");
if (orientation.equalsIgnoreCase("vertical")) {
return XYMultipleSeriesRenderer.Orientation.HORIZONTAL;
} else {
return XYMultipleSeriesRenderer.Orientation.VERTICAL;
}
}
/**
* Create series appropriate to the current graph type.
*
* @return An XYSeries-derived object.
*/
private XYSeries createSeries() {
return createSeries(0);
}
/**
* Create series appropriate to the current graph type.
*
* @return An XYSeries-derived object.
*/
private XYSeries createSeries(int scaleIndex) {
// TODO: Bubble and time graphs ought to respect scaleIndex, but XYValueSeries
// and TimeSeries don't expose the (String title, int scaleNumber) constructor.
if (scaleIndex > 0 && !Graph.TYPE_XY.equals(mData.getType())) {
throw new IllegalArgumentException("This series does not support a secondary y axis");
}
if (Graph.TYPE_TIME.equals(mData.getType())) {
return new TimeSeries("");
}
if (Graph.TYPE_BUBBLE.equals(mData.getType())) {
return new RangeXYValueSeries("");
}
return new XYSeries("", scaleIndex);
}
/*
* Set up any annotations.
*/
private void renderAnnotations() throws InvalidStateException {
Vector<AnnotationData> annotations = mData.getAnnotations();
if (!annotations.isEmpty()) {
// Create a fake series for the annotations
XYSeries series = createSeries();
for (AnnotationData a : annotations) {
String text = a.getAnnotation();
String description = "annotation '" + text + "' at (" + a.getX() + ", " + a.getY() + ")";
series.addAnnotation(text, parseXValue(a.getX(), description), parseYValue(a.getY(), description));
}
// Annotations won't display unless the series has some data in it
series.add(0.0, 0.0);
mDataset.addSeries(series);
XYSeriesRenderer currentRenderer = new XYSeriesRenderer();
currentRenderer.setAnnotationsTextSize(mTextSize);
currentRenderer.setAnnotationsColor(mContext.getResources().getColor(R.color.black));
mRenderer.addSeriesRenderer(currentRenderer);
}
}
/*
* Apply any user-requested look and feel changes to graph.
*/
private void configureSeries(SeriesData s, XYSeriesRenderer currentRenderer) {
// Default to circular points, but allow other shapes or no points at all
String pointStyle = s.getConfiguration("point-style", "circle").toLowerCase();
if (!pointStyle.equals("none")) {
PointStyle style = null;
switch (pointStyle) {
case "circle":
style = PointStyle.CIRCLE;
break;
case "x":
style = PointStyle.X;
break;
case "square":
style = PointStyle.SQUARE;
break;
case "triangle":
style = PointStyle.TRIANGLE;
break;
case "diamond":
style = PointStyle.DIAMOND;
break;
}
currentRenderer.setPointStyle(style);
currentRenderer.setFillPoints(true);
currentRenderer.setPointStrokeWidth(2);
mRenderer.setPointSize(6);
}
String lineColor = s.getConfiguration("line-color");
if (lineColor == null) {
currentRenderer.setColor(Color.BLACK);
} else {
currentRenderer.setColor(Color.parseColor(lineColor));
}
currentRenderer.setLineWidth(2);
fillOutsideLine(s, currentRenderer, "fill-above", XYSeriesRenderer.FillOutsideLine.Type.ABOVE);
fillOutsideLine(s, currentRenderer, "fill-below", XYSeriesRenderer.FillOutsideLine.Type.BELOW);
}
/*
* Helper function for setting up color fills above or below a series.
*/
private void fillOutsideLine(SeriesData s, XYSeriesRenderer currentRenderer, String property, XYSeriesRenderer.FillOutsideLine.Type type) {
property = s.getConfiguration(property);
if (property != null) {
XYSeriesRenderer.FillOutsideLine fill = new XYSeriesRenderer.FillOutsideLine(type);
fill.setColor(Color.parseColor(property));
currentRenderer.addFillOutsideLine(fill);
}
}
/*
* Configure graph's look and feel based on default assumptions and user-requested configuration.
*/
private void configure() throws InvalidStateException {
// Default options
mRenderer.setBackgroundColor(mContext.getResources().getColor(R.color.white));
mRenderer.setMarginsColor(mContext.getResources().getColor(R.color.white));
mRenderer.setLabelsColor(mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setXLabelsColor(mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setYLabelsColor(0, mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setYLabelsColor(1, mContext.getResources().getColor(R.color.grey_darker));
mRenderer.setXLabelsAlign(Align.CENTER);
mRenderer.setYLabelsAlign(Align.RIGHT);
mRenderer.setYLabelsAlign(Align.LEFT, 1);
mRenderer.setYAxisAlign(Align.RIGHT, 1);
mRenderer.setAxesColor(mContext.getResources().getColor(R.color.grey_lighter));
mRenderer.setLabelsTextSize(mTextSize);
mRenderer.setAxisTitleTextSize(mTextSize);
mRenderer.setApplyBackgroundColor(true);
mRenderer.setShowGrid(true);
int padding = 10;
mRenderer.setXLabelsPadding(padding);
mRenderer.setYLabelsPadding(padding);
mRenderer.setYLabelsVerticalPadding(padding);
if (Graph.TYPE_BAR.equals(mData.getType())) {
mRenderer.setBarSpacing(0.5);
}
// User-configurable options
mRenderer.setXTitle(mData.getConfiguration("x-title", ""));
mRenderer.setYTitle(mData.getConfiguration("y-title", ""));
mRenderer.setYTitle(mData.getConfiguration("secondary-y-title", ""), 1);
if (Graph.TYPE_BAR.equals(mData.getType())) {
XYMultipleSeriesRenderer.Orientation orientation = getOrientation();
mRenderer.setOrientation(orientation);
if (orientation.equals(XYMultipleSeriesRenderer.Orientation.VERTICAL)) {
mRenderer.setXLabelsAlign(Align.LEFT);
mRenderer.setXLabelsPadding(0);
}
}
if (mData.getConfiguration("x-min") != null) {
mRenderer.setXAxisMin(parseXValue(mData.getConfiguration("x-min"), "x-min"));
}
if (mData.getConfiguration("y-min") != null) {
mRenderer.setYAxisMin(parseYValue(mData.getConfiguration("y-min"), "y-min"));
}
if (mData.getConfiguration("secondary-y-min") != null) {
mRenderer.setYAxisMin(parseYValue(mData.getConfiguration("secondary-y-min"), "secondary-y-min"), 1);
}
if (mData.getConfiguration("x-max") != null) {
mRenderer.setXAxisMax(parseXValue(mData.getConfiguration("x-max"), "x-max"));
}
if (mData.getConfiguration("y-max") != null) {
mRenderer.setYAxisMax(parseYValue(mData.getConfiguration("y-max"), "y-max"));
}
if (mData.getConfiguration("secondary-y-max") != null) {
mRenderer.setYAxisMax(parseYValue(mData.getConfiguration("secondary-y-max"), "secondary-y-max"), 1);
}
String showAxes = mData.getConfiguration("show-axes", "true");
if (Boolean.valueOf(showAxes).equals(Boolean.FALSE)) {
mRenderer.setShowAxes(false);
}
// Legend
boolean showLegend = Boolean.valueOf(mData.getConfiguration("show-legend", "false"));
mRenderer.setShowLegend(showLegend);
mRenderer.setFitLegend(showLegend);
mRenderer.setLegendTextSize(mTextSize);
// Labels
boolean hasX = configureLabels("x-labels");
boolean hasY = configureLabels("y-labels");
configureLabels("secondary-y-labels");
boolean showLabels = hasX || hasY;
mRenderer.setShowLabels(showLabels);
// Tick marks are sometimes ugly, so let's be minimalist and always leave the off
mRenderer.setShowTickMarks(false);
}
/**
* Parse given string into Double for AChartEngine.
*
* @param description Something to identify the kind of value, used to augment any error message.
*/
private Double parseXValue(String value, String description) throws InvalidStateException {
if (Graph.TYPE_TIME.equals(mData.getType())) {
Date parsed = DateUtils.parseDateTime(value);
if (parsed == null) {
throw new InvalidStateException("Could not parse date '" + value + "' in " + description);
}
return parseDouble(String.valueOf(parsed.getTime()), description);
}
return parseDouble(value, description);
}
/**
* Parse given string into Double for AChartEngine.
*
* @param description Something to identify the kind of value, used to augment any error message.
*/
private Double parseYValue(String value, String description) throws InvalidStateException {
return parseDouble(value, description);
}
/**
* Parse given string into Double for AChartEngine.
*
* @param description Something to identify the kind of value, used to augment any error message.
*/
private Double parseRadiusValue(String value, String description) throws InvalidStateException {
return parseDouble(value, description);
}
/**
* Attempt to parse a double, but fail on NumberFormatException.
*
* @param description Something to identify the kind of value, used to augment any error message.
*/
private Double parseDouble(String value, String description) throws InvalidStateException {
try {
Double numeric = Double.valueOf(value);
if (numeric.isNaN()) {
throw new InvalidStateException("Could not understand '" + value + "' in " + description);
}
return numeric;
} catch (NumberFormatException nfe) {
throw new InvalidStateException("Could not understand '" + value + "' in " + description);
}
}
/**
* Customize labels.
*
* @param key One of "x-labels", "y-labels", "secondary-y-labels"
* @return True iff axis has any labels at all
*/
private boolean configureLabels(String key) throws InvalidStateException {
boolean hasLabels = true;
// The labels setting might be a JSON array of numbers,
// a JSON object of number => string, or a single number
String labelString = mData.getConfiguration(key);
if (labelString != null) {
try {
// Array: label each given value
JSONArray labels = new JSONArray(labelString);
setLabelCount(key, 0);
for (int i = 0; i < labels.length(); i++) {
String value = labels.getString(i);
addTextLabel(key, parseXValue(value, "x label '" + key + "'"), value);
}
hasLabels = labels.length() > 0;
} catch (JSONException je) {
// Assume try block failed because labelString isn't an array.
// Try parsing it as an object.
try {
// Object: each keys is a location on the axis,
// and the value is the text with which to label it
JSONObject labels = new JSONObject(labelString);
setLabelCount(key, 0);
Iterator i = labels.keys();
hasLabels = false;
while (i.hasNext()) {
String location = (String)i.next();
addTextLabel(key, parseXValue(location, "x label at " + location), labels.getString(location));
hasLabels = true;
}
} catch (JSONException e) {
// Assume labelString is just a scalar, which
// represents the number of labels the user wants.
Integer count = Integer.valueOf(labelString);
setLabelCount(key, count);
hasLabels = count != 0;
}
}
}
return hasLabels;
}
/**
* Helper for configureLabels. Adds a label to the appropriate axis.
*
* @param key One of "x-labels", "y-labels", "secondary-y-labels"
* @param location Point on axis to add label
* @param text String for label
*/
private void addTextLabel(String key, Double location, String text) {
if (isXKey(key)) {
mRenderer.addXTextLabel(location, text);
} else {
int scaleIndex = getScaleIndex(key);
if (mRenderer.getYAxisAlign(scaleIndex) == Align.RIGHT) {
text = " " + text;
}
mRenderer.addYTextLabel(location, text, scaleIndex);
}
}
/**
* Helper for configureLabels. Sets desired number of labels for the appropriate axis.
* AChartEngine will then determine how to space the labels.
*
* @param key One of "x-labels", "y-labels", "secondary-y-labels"
* @param value Number of labels
*/
private void setLabelCount(String key, int value) {
if (isXKey(key)) {
mRenderer.setXLabels(value);
} else {
mRenderer.setYLabels(value);
}
}
/**
* Helper for turning key into scale.
*
* @param key Something like "x-labels" or "y-secondary-labels"
* @return Index for passing to AChartEngine functions that accept a scale
*/
private int getScaleIndex(String key) {
return key.contains("secondary") ? 1 : 0;
}
/**
* Helper for parsing axis from configuration key.
*
* @param key Something like "x-min" or "y-labels"
* @return True iff key is relevant to x axis
*/
private boolean isXKey(String key) {
return key.startsWith("x-");
}
/**
* Comparator to sort XYPointData-derived objects by x value.
*
* @author jschweers
*/
private class NumericPointComparator implements Comparator<XYPointData> {
@Override
public int compare(XYPointData lhs, XYPointData rhs) {
try {
return parseXValue(lhs.getX(), "").compareTo(parseXValue(rhs.getX(), ""));
} catch (InvalidStateException e) {
return 0;
}
}
}
/**
* Comparator to sort XYPointData-derived objects by x value without parsing them.
* Useful for bar graphs, where x values are text.
*
* @author jschweers
*/
private class StringPointComparator implements Comparator<XYPointData> {
@Override
public int compare(XYPointData lhs, XYPointData rhs) {
return lhs.getX().compareTo(rhs.getX());
}
}
/**
* Comparator to sort XYPoint-derived data by y value, in ascending order.
* Useful for bar graphs, nonsensical for other graphs.
*
* @author jschweers
*/
private class AscendingValuePointComparator implements Comparator<XYPointData> {
@Override
public int compare(XYPointData lhs, XYPointData rhs) {
try {
return parseXValue(lhs.getY(), "").compareTo(parseXValue(rhs.getY(), ""));
} catch (InvalidStateException e) {
return 0;
}
}
}
/**
* Comparator to sort XYPoint-derived data by y value, in descending order.
* Useful for bar graphs, nonsensical for other graphs.
*
* @author jschweers
*/
private class DescendingValuePointComparator implements Comparator<XYPointData> {
@Override
public int compare(XYPointData lhs, XYPointData rhs) {
try {
return parseXValue(rhs.getY(), "").compareTo(parseXValue(lhs.getY(), ""));
} catch (InvalidStateException e) {
return 0;
}
}
}
}
|
package dr.evomodel.sitemodel;
import dr.evomodel.substmodel.FrequencyModel;
import dr.evomodel.substmodel.SubstitutionModel;
import dr.inference.model.AbstractModel;
import dr.inference.model.Model;
import dr.inference.model.Parameter;
import dr.inference.model.Variable;
import dr.math.distributions.GammaDistribution;
import dr.xml.*;
import java.util.logging.Logger;
/**
* GammaSiteModel - A SiteModel that has a gamma distributed rates across sites.
*
* @author Andrew Rambaut
* @version $Id: GammaSiteModel.java,v 1.31 2005/09/26 14:27:38 rambaut Exp $
*/
public class GammaSiteModel extends AbstractModel
implements SiteModel {
public static final String SUBSTITUTION_MODEL = "substitutionModel";
public static final String MUTATION_RATE = "mutationRate";
public static final String RELATIVE_RATE = "relativeRate";
public static final String GAMMA_SHAPE = "gammaShape";
public static final String GAMMA_CATEGORIES = "gammaCategories";
public static final String PROPORTION_INVARIANT = "proportionInvariant";
public GammaSiteModel(SubstitutionModel substitutionModel) {
this(substitutionModel,
null,
null,
0,
null);
}
public GammaSiteModel(SubstitutionModel substitutionModel, double alpha, int categoryCount) {
this(substitutionModel,
null,
new Parameter.Default(alpha),
categoryCount,
null);
}
public GammaSiteModel(SubstitutionModel substitutionModel, double pInvar) {
this(substitutionModel,
null,
null,
0,
new Parameter.Default(pInvar));
}
public GammaSiteModel(SubstitutionModel substitutionModel, double alpha, int categoryCount, double pInvar) {
this(substitutionModel,
null,
new Parameter.Default(alpha),
categoryCount,
new Parameter.Default(pInvar));
}
/**
* Constructor for gamma+invar distributed sites. Either shapeParameter or
* invarParameter (or both) can be null to turn off that feature.
*/
public GammaSiteModel(SubstitutionModel substitutionModel,
Parameter muParameter,
Parameter shapeParameter, int gammaCategoryCount,
Parameter invarParameter) {
super(SITE_MODEL);
this.substitutionModel = substitutionModel;
addModel(substitutionModel);
this.muParameter = muParameter;
if (muParameter != null) {
addVariable(muParameter);
muParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1));
}
this.shapeParameter = shapeParameter;
if (shapeParameter != null) {
this.categoryCount = gammaCategoryCount;
addVariable(shapeParameter);
// The quantile calculator fails when the shape parameter goes much below
// 1E-3 so we have put a hard lower bound on it. If this is not there then
// the category rates can go to 0 and cause a -Inf likelihood (whilst this
// is not a problem as the state will be rejected, it could mask other issues
// and this seems the better approach.
shapeParameter.addBounds(new Parameter.DefaultBounds(1.0E3, 1.0E-3, 1));
} else {
this.categoryCount = 1;
}
this.invarParameter = invarParameter;
if (invarParameter != null) {
this.categoryCount += 1;
addVariable(invarParameter);
invarParameter.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1));
}
categoryRates = new double[this.categoryCount];
categoryProportions = new double[this.categoryCount];
ratesKnown = false;
}
/**
* set mu
*/
public void setMu(double mu) {
muParameter.setParameterValue(0, mu);
}
/**
* @return mu
*/
public final double getMu() {
return muParameter.getParameterValue(0);
}
/**
* set alpha
*/
public void setAlpha(double alpha) {
shapeParameter.setParameterValue(0, alpha);
ratesKnown = false;
}
/**
* @return alpha
*/
public final double getAlpha() {
return shapeParameter.getParameterValue(0);
}
public Parameter getMutationRateParameter() {
return muParameter;
}
public Parameter getAlphaParameter() {
return shapeParameter;
}
public Parameter getPInvParameter() {
return invarParameter;
}
public void setMutationRateParameter(Parameter parameter) {
if (muParameter != null) removeVariable(muParameter);
muParameter = parameter;
if (muParameter != null) addVariable(muParameter);
}
public void setAlphaParameter(Parameter parameter) {
if (shapeParameter != null) removeVariable(shapeParameter);
shapeParameter = parameter;
if (shapeParameter != null) addVariable(shapeParameter);
}
public void setPInvParameter(Parameter parameter) {
if (invarParameter != null) removeVariable(invarParameter);
invarParameter = parameter;
if (invarParameter != null) addVariable(invarParameter);
}
// Interface SiteModel
public boolean integrateAcrossCategories() {
return true;
}
public int getCategoryCount() {
return categoryCount;
}
public int getCategoryOfSite(int site) {
throw new IllegalArgumentException("Integrating across categories");
}
public double getRateForCategory(int category) {
synchronized (this) {
if (!ratesKnown) {
calculateCategoryRates();
}
}
final double mu = (muParameter != null) ? muParameter.getParameterValue(0) : 1.0;
return categoryRates[category] * mu;
}
public double[] getCategoryRates() {
synchronized (this) {
if (!ratesKnown) {
calculateCategoryRates();
}
}
final double mu = (muParameter != null) ? muParameter.getParameterValue(0) : 1.0;
final double[] rates = new double[categoryRates.length];
for (int i = 0; i < rates.length; i++) {
rates[i] = categoryRates[i] * mu;
}
return rates;
}
public void getTransitionProbabilities(double substitutions, double[] matrix) {
substitutionModel.getTransitionProbabilities(substitutions, matrix);
}
/**
* Get the expected proportion of sites in this category.
*
* @param category the category number
* @return the proportion.
*/
public double getProportionForCategory(int category) {
synchronized (this) {
if (!ratesKnown) {
calculateCategoryRates();
}
}
return categoryProportions[category];
}
/**
* Get an array of the expected proportion of sites in this category.
*
* @return an array of the proportion.
*/
public double[] getCategoryProportions() {
synchronized (this) {
if (!ratesKnown) {
calculateCategoryRates();
}
}
return categoryProportions;
}
/**
* discretization of gamma distribution with equal proportions in each
* category
*/
private void calculateCategoryRates() {
double propVariable = 1.0;
int cat = 0;
if (invarParameter != null) {
categoryRates[0] = 0.0;
categoryProportions[0] = invarParameter.getParameterValue(0);
propVariable = 1.0 - categoryProportions[0];
cat = 1;
}
if (shapeParameter != null) {
final double a = shapeParameter.getParameterValue(0);
double mean = 0.0;
final int gammaCatCount = categoryCount - cat;
for (int i = 0; i < gammaCatCount; i++) {
categoryRates[i + cat] = GammaDistribution.quantile((2.0 * i + 1.0) / (2.0 * gammaCatCount), a, 1.0 / a);
mean += categoryRates[i + cat];
categoryProportions[i + cat] = propVariable / gammaCatCount;
}
mean = (propVariable * mean) / gammaCatCount;
for (int i = 0; i < gammaCatCount; i++) {
categoryRates[i + cat] /= mean;
}
} else {
categoryRates[cat] = 1.0 / propVariable;
categoryProportions[cat] = propVariable;
}
ratesKnown = true;
}
/**
* Get the frequencyModel for this SiteModel.
*
* @return the frequencyModel.
*/
public FrequencyModel getFrequencyModel() {
return substitutionModel.getFrequencyModel();
}
/**
* Get the substitutionModel for this SiteModel.
*
* @return the substitutionModel.
*/
public SubstitutionModel getSubstitutionModel() {
return substitutionModel;
}
// Interface ModelComponent
protected void handleModelChangedEvent(Model model, Object object, int index) {
// Substitution model has changed so fire model changed event
listenerHelper.fireModelChanged(this, object, index);
}
protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
if (variable == shapeParameter) {
ratesKnown = false;
} else if (variable == invarParameter) {
ratesKnown = false;
} else {
// is the muParameter and nothing needs to be done
}
listenerHelper.fireModelChanged(this, variable, index);
}
protected void storeState() {
} // no additional state needs storing
protected void restoreState() {
ratesKnown = false;
}
protected void acceptState() {
} // no additional state needs accepting
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String[] getParserNames() {
return new String[] {
getParserName(), "beast_"+getParserName()
};
}
public String getParserName() {
return SITE_MODEL;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
SubstitutionModel substitutionModel = (SubstitutionModel) xo.getElementFirstChild(SUBSTITUTION_MODEL);
String msg = "";
Parameter muParam = null;
if (xo.hasChildNamed(MUTATION_RATE)) {
muParam = (Parameter) xo.getElementFirstChild(MUTATION_RATE);
msg += "\n with initial substitution rate = " + muParam.getParameterValue(0);
} else if (xo.hasChildNamed(RELATIVE_RATE)) {
muParam = (Parameter) xo.getElementFirstChild(RELATIVE_RATE);
msg += "\n with initial relative rate = " + muParam.getParameterValue(0);
}
Parameter shapeParam = null;
int catCount = 4;
if (xo.hasChildNamed(GAMMA_SHAPE)) {
final XMLObject cxo = xo.getChild(GAMMA_SHAPE);
catCount = cxo.getIntegerAttribute(GAMMA_CATEGORIES);
shapeParam = (Parameter) cxo.getChild(Parameter.class);
msg += "\n " + catCount + " category discrete gamma with initial shape = " + shapeParam.getParameterValue(0);
}
Parameter invarParam = null;
if (xo.hasChildNamed(PROPORTION_INVARIANT)) {
invarParam = (Parameter) xo.getElementFirstChild(PROPORTION_INVARIANT);
msg += "\n initial proportion of invariant sites = " + invarParam.getParameterValue(0);
}
Logger.getLogger("dr.evomodel").info("Creating site model." + (msg.length() > 0 ? msg : ""));
return new GammaSiteModel(substitutionModel, muParam, shapeParam, catCount, invarParam);
}
/**
* the substitution model for these sites
*/
private SubstitutionModel substitutionModel = null;
/**
* mutation rate parameter
*/
private Parameter muParameter;
/**
* shape parameter
*/
private Parameter shapeParameter;
/**
* invariant sites parameter
*/
private Parameter invarParameter;
private boolean ratesKnown;
private int categoryCount;
private double[] categoryRates;
private double[] categoryProportions;
}
|
package dr.inference.hawkes;
import dr.inference.hmc.GradientWrtParameterProvider;
import dr.inference.model.*;
import dr.xml.*;
/**
* @author Andrew Holbrook
* @author Xiang Ji
* @author Marc Suchard
*/
public class HawkesLikelihood extends AbstractModelLikelihood implements Reportable,
GradientWrtParameterProvider {
private final static String REQUIRED_FLAGS_PROPERTY = "hph.required.flags";
private final static String HAWKES_LIKELIHOOD = "hawkesLikelihood";
public HawkesLikelihood(
int hphDimension,
HawkesParameters hawkesParameters) {
super(HAWKES_LIKELIHOOD);
this.hawkesParameters = hawkesParameters;
this.hphDimension = hphDimension;
this.locationCount = hawkesParameters.getLocationCount();
initialize(hphDimension, hawkesParameters);
}
public static class HawkesParameters {
final Parameter tauXprec;
final Parameter sigmaXprec;
final Parameter tauTprec;
final Parameter omega;
final Parameter theta;
final Parameter mu0;
final MatrixParameterInterface locationsParameter;
final Parameter times;
final CompoundParameter allParameters;
public HawkesParameters(final Parameter tauXprec,
final Parameter sigmaXprec,
final Parameter tauTprec,
final Parameter omega,
final Parameter theta,
final Parameter mu0,
final MatrixParameterInterface locationsParameter,
final Parameter times) {
this.tauXprec = tauXprec;
this.sigmaXprec = sigmaXprec;
this.tauTprec = tauTprec;
this.omega = omega;
this.theta = theta;
this.mu0 = mu0;
this.locationsParameter = locationsParameter;
this.times = times;
this.allParameters = new CompoundParameter("hphModelParameter", new Parameter[]{sigmaXprec, tauXprec, tauTprec, omega, theta, mu0});
checkDimensions();
}
private void checkDimensions() {
if (times.getDimension() != getLocationCount()) {
throw new RuntimeException("Times dimension doesn't match location count.");
}
}
public CompoundParameter getCompoundParameter() {
return allParameters;
}
public MatrixParameterInterface getLocationsParameter() {
return locationsParameter;
}
public double[] getParameterValues() {
return allParameters.getParameterValues();
}
public int getLocationCount() {
return locationsParameter.getColumnDimension();
}
}
protected int initialize(
final int hphDimension,
final HawkesParameters hawkesParameters) {
this.hphCore = getCore();
System.err.println("Initializing with flags: " + flags);
this.hphCore.initialize(hphDimension, locationCount, flags);
this.hawkesParameters = hawkesParameters;
int internalDimension = hphCore.getInternalDimension();
setupLocationsParameter(hawkesParameters.getLocationsParameter());
addVariable(hawkesParameters.getCompoundParameter());
hphCore.setParameters(hawkesParameters.getParameterValues());
updateAllLocations(hawkesParameters.getLocationsParameter());
// make sure everything is calculated on first evaluation
// makeDirty();
return internalDimension;
}
@Override
public String getReport() {
return getId() + ": " + getLogLikelihood();
}
@Override
public Likelihood getLikelihood() {
return this;
}
@Override
public Parameter getParameter() {
return hawkesParameters.getLocationsParameter();
}
@Override
public int getDimension() {
return hawkesParameters.getLocationsParameter().getDimension();
}
@Override
public double[] getGradientLogDensity() {
// TODO Cache !!!
if (gradient == null) {
gradient = new double[hawkesParameters.getLocationsParameter().getDimension()];
}
hphCore.getGradient(gradient);
return gradient; // TODO Do not expose internals
}
public enum ObservationType {
POINT,
UPPER_BOUND,
LOWER_BOUND,
MISSING
}
public MatrixParameterInterface getMatrixParameter() { return hawkesParameters.getLocationsParameter(); }
private HawkesCore getCore() {
long computeMode = 0;
String r = System.getProperty(REQUIRED_FLAGS_PROPERTY);
if (r != null) {
computeMode = Long.parseLong(r.trim());
}
HawkesCore core;
//if (computeMode >= HawkesCore.USE_NATIVE_HPH) {
System.err.println("Attempting to use a native HPH core with flag: " + computeMode + "; may the force be with you ....");
core = new MassivelyParallelHPHImpl();
flags = computeMode;
//} else {
//System.err.println("Computer mode found: " + computeMode + " vs. " + r);
//core = new HawkesCoreImpl();
return core;
}
public int getHphDimension() { return hphDimension; }
public int getLocationCount() { return locationCount; }
private void updateAllLocations(MatrixParameterInterface locationsParameter) {
// TODO Can make more efficient (if necessary) using vectorDimension padding
hphCore.updateLocation(-1, locationsParameter.getParameterValues());
}
private void setupLocationsParameter(MatrixParameterInterface locationsParameter) {
final boolean exisitingParameter = locationsParameter.getColumnDimension() > 0;
if (exisitingParameter){
if (locationsParameter.getColumnDimension() != locationCount){
throw new RuntimeException("locationsParameter column dimension ("+locationsParameter.getColumnDimension()+") is not equal to the locationCount ("+locationCount+")");
}
if (locationsParameter.getRowDimension() != hphDimension){
throw new RuntimeException("locationsParameter row dimension ("+locationsParameter.getRowDimension()+") is not equal to the hphDimension ("+hphDimension+")");
}
} else {
throw new IllegalArgumentException("Dimensions on matrix must be set");
}
// for (int i = 0; i < locationLabels.length; i++) {
// if (locationsParameter.getParameter(i).getParameterName().compareTo(locationLabels[i]) != 0) {
// throw new RuntimeException("Mismatched trait parameter name (" + locationsParameter.getParameter(i).getParameterName() +
// ") and data dimension name (" + locationLabels[i] + ")");
for (int i = 0; i < locationsParameter.getColumnDimension(); ++i) {
Parameter param = locationsParameter.getParameter(i);
try {
param.getBounds();
} catch (NullPointerException exception) {
param.addBounds(new Parameter.DefaultBounds(
Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, param.getDimension()));
}
}
}
@Override
protected void handleModelChangedEvent(Model model, Object object, int index) { }
@Override
protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) {
// TODO Flag which cachedDistances or hphPrecision need to be updated
// if (variable == locationsParameter) {
// if (index == -1) {
// updateAllLocations(locationsParameter);
// } else {
// int locationIndex = index / hphDimension;
// hphCore.updateLocation(locationIndex, locationsParameter.getColumnValues(locationIndex));
// else if (variable == hphPrecisionParameter) {
// hphCore.setParameters(hphPrecisionParameter.getParameterValues());
likelihoodKnown = false;
}
@Override
protected void storeState() {
storedLogLikelihood = logLikelihood;
hphCore.storeState();
}
@Override
protected void restoreState() {
logLikelihood = storedLogLikelihood;
likelihoodKnown = true;
hphCore.restoreState();
}
@Override
protected void acceptState() {
hphCore.acceptState();
// do nothing
}
public void makeDirty() {
likelihoodKnown = false;
hphCore.makeDirty();
}
public Model getModel() {
return this;
}
public double getLogLikelihood() {
if (!likelihoodKnown) {
updateAllLocations(hawkesParameters.getLocationsParameter());
logLikelihood = hphCore.calculateLogLikelihood();
likelihoodKnown = true;
}
return logLikelihood;
}
// XMLObjectParser
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
final static String LOCATIONS = "locations";
final static String TIMES = "times";
final static String HPH_DIMENSION = "hphDimension";
final static String SIGMA_PRECISON = "sigmaXprec";
final static String TAU_X_PRECISION = "tauXprec";
final static String TAU_T_PRECISION = "tauTprec";
final static String OMEGA = "omega";
final static String THETA = "theta";
final static String MU = "mu0";
public String getParserName() {
return HAWKES_LIKELIHOOD;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
int hphDimension = xo.getIntegerAttribute(HPH_DIMENSION);
MatrixParameterInterface locationsParameter = (MatrixParameterInterface) xo.getElementFirstChild(LOCATIONS);
Parameter times = (Parameter) xo.getElementFirstChild(TIMES);
Parameter sigmaXprec = (Parameter) xo.getElementFirstChild(SIGMA_PRECISON);
Parameter tauXprec = (Parameter) xo.getElementFirstChild(TAU_X_PRECISION);
Parameter tauTprec = (Parameter) xo.getElementFirstChild(TAU_T_PRECISION);
Parameter omega = (Parameter) xo.getElementFirstChild(OMEGA);
Parameter theta = (Parameter) xo.getElementFirstChild(THETA);
Parameter mu0 = (Parameter) xo.getElementFirstChild(MU);
HawkesParameters hawkesParameters = new HawkesParameters(tauXprec, sigmaXprec, tauTprec, omega, theta, mu0, locationsParameter, times);
return new HawkesLikelihood(hphDimension, hawkesParameters);
}
|
package dr.inference.markovchain;
import dr.inference.model.Likelihood;
import dr.inference.model.Model;
import dr.inference.model.CompoundLikelihood;
import dr.inference.operators.*;
import dr.inference.prior.Prior;
import java.util.ArrayList;
/**
* A concrete markov chain. This is final as the only things that should need overriding
* are in the delegates (prior, likelihood, schedule and acceptor). The design of this
* class is to be fairly immutable as far as settings goes.
*
* @author Alexei Drummond
* @author Andrew Rambaut
*
* @version $Id: MarkovChain.java,v 1.10 2006/06/21 13:34:42 rambaut Exp $
*/
public final class MarkovChain {
private final OperatorSchedule schedule;
private final Acceptor acceptor;
private final Prior prior;
private final Likelihood likelihood;
private boolean pleaseStop = false;
private boolean isStopped = false;
private double bestScore, currentScore, initialScore;
private int currentLength;
private boolean useCoercion = true;
private final int fullEvaluationCount;
private static final int MAX_FAILURE_COUNTS = 10;
public MarkovChain(Prior prior,
Likelihood likelihood,
OperatorSchedule schedule,
Acceptor acceptor,
int fullEvaluationCount,
boolean useCoercion) {
currentLength = 0;
this.prior = prior;
this.likelihood = likelihood;
this.schedule = schedule;
this.acceptor = acceptor;
this.useCoercion = useCoercion;
this.fullEvaluationCount = fullEvaluationCount;
currentScore = evaluate(likelihood, prior);
}
/**
* Resets the markov chain
*/
public void reset() {
currentLength = 0;
// reset operator acceptance levels
for (int i = 0; i < schedule.getOperatorCount(); i++) {
schedule.getOperator(i).reset();
}
}
/**
* Run the chain for a given number of states.
* @param length number of states to run the chain.
* @param length number of states to run the chain.
*/
public int chain(int length, boolean disableCoerce) {
currentScore = evaluate(likelihood, prior);
int currentState = currentLength;
final Model currentModel = likelihood.getModel();
if (currentState == 0) {
initialScore = currentScore;
bestScore = currentScore;
fireBestModel(currentState, currentModel);
}
if (currentScore == Double.NEGATIVE_INFINITY) {
// identify which component of the score is zero...
if (prior != null) {
double logPrior = prior.getLogPrior(likelihood.getModel());
if (logPrior == Double.NEGATIVE_INFINITY) {
throw new IllegalArgumentException("The initial model is invalid because one of the priors has zero probability.");
}
}
throw new IllegalArgumentException("The initial likelihood is zero!");
}
pleaseStop = false;
isStopped = false;
int testFailureCount = 0;
double[] logr = new double[] {0.0};
while (!pleaseStop && (currentState < (currentLength + length))) {
// periodically log states
fireCurrentModel(currentState, currentModel);
if (pleaseStop) {
isStopped = true;
break;
}
// Get the operator
final int op = schedule.getNextOperatorIndex();
final MCMCOperator mcmcOperator = schedule.getOperator(op);
final double oldScore = currentScore;
String oldMessage = ((CompoundLikelihood)likelihood).getDiagnosis();
// assert Profiler.startProfile("Store");
// The current model is stored here in case the proposal fails
if (currentModel != null) {
currentModel.storeModelState();
}
// assert Profiler.stopProfile("Store");
boolean operatorSucceeded = true;
double hastingsRatio = 1.0;
boolean accept = false;
logr[0] = -Double.MAX_VALUE;
try {
// The new model is proposed
// assert Profiler.startProfile("Operate");
// System.out.println("Operator: " + mcmcOperator.getOperatorName());
hastingsRatio = mcmcOperator.operate();
// assert Profiler.stopProfile("Operate");
} catch (OperatorFailedException e) {
operatorSucceeded = false;
}
double score = 0.0;
double deviation = 0.0;
if (operatorSucceeded) {
// The new model is proposed
// assert Profiler.startProfile("Evaluate");
// The new model is evaluated
score = evaluate(likelihood, prior);
// assert Profiler.stopProfile("Evaluate");
if (score > bestScore) {
bestScore = score;
fireBestModel(currentState, currentModel);
}
accept = mcmcOperator instanceof GibbsOperator || acceptor.accept(oldScore, score, hastingsRatio, logr);
deviation = score - oldScore;
}
// The new model is accepted or rejected
if (accept) {
// System.out.println("Move accepted: new score = " + score + ", old score = " + oldScore);
mcmcOperator.accept(deviation);
currentModel.acceptModelState();
currentScore = score;
} else {
// System.out.println("Move rejected: new score = " + score + ", old score = " + oldScore);
mcmcOperator.reject();
// assert Profiler.startProfile("Restore");
currentModel.restoreModelState();
// assert Profiler.stopProfile("Restore");
// This is a test that the state is correctly restored. The restored
// state is fully evaluated and the likelihood compared with that before
// the operation was made.
if (currentState < fullEvaluationCount) {
likelihood.makeDirty();
final double testScore = evaluate(likelihood, prior);
if (Math.abs(testScore - oldScore) > 1e-6) {
System.err.println("State was not correctly restored after reject step.");
System.err.println("Likelihood before: " + oldScore + " Likelihood after: " + testScore);
System.err.println("Operator: " + mcmcOperator + " " + mcmcOperator.getOperatorName());
testFailureCount ++;
}
if (testFailureCount > MAX_FAILURE_COUNTS) {
throw new RuntimeException("Too many test failures: stopping chain.");
}
}
}
if (!disableCoerce && mcmcOperator instanceof CoercableMCMCOperator) {
coerceAcceptanceProbability((CoercableMCMCOperator)mcmcOperator, logr[0]);
}
currentState += 1;
}
currentLength = currentState;
fireFinished(currentLength);
// Profiler.report();
return currentLength;
}
public Prior getPrior() {
return prior;
}
public Likelihood getLikelihood() {
return likelihood;
}
public Model getModel() {
return likelihood.getModel();
}
public OperatorSchedule getSchedule() {
return schedule;
}
public Acceptor getAcceptor() {
return acceptor;
}
public double getInitialScore() {
return initialScore;
}
public double getBestScore() {
return bestScore;
}
public int getCurrentLength() {
return currentLength;
}
public double getCurrentScore() {
return currentScore;
}
public void pleaseStop() {
pleaseStop = true;
}
public boolean isStopped() {
return isStopped;
}
private double evaluate(Likelihood likelihood, Prior prior) {
double logPosterior = 0.0;
if (prior != null) {
final double logPrior = prior.getLogPrior(likelihood.getModel());
if (logPrior == Double.NEGATIVE_INFINITY) {
return Double.NEGATIVE_INFINITY;
}
logPosterior += logPrior;
}
final double logLikelihood = likelihood.getLogLikelihood();
if (Double.isNaN(logLikelihood)) {
return Double.NEGATIVE_INFINITY;
}
//System.err.println("** " + logPosterior + " + " + logLikelihood + " = " + (logPosterior + logLikelihood));
logPosterior += logLikelihood;
return logPosterior;
}
/**
* Updates the proposal parameter, based on the target acceptance probability
* This method relies on the proposal parameter being a decreasing function of
* acceptance probability.
* @param op
* @param logr
*/
private void coerceAcceptanceProbability(CoercableMCMCOperator op, double logr) {
if (isCoercable(op)) {
double p = op.getCoercableParameter();
int i = MCMCOperator.Utils.getOperationCount(op);
double target = op.getTargetAcceptanceProbability();
double newp = p + ((1.0 / (i + 1.0)) * (Math.exp(logr)-target));
if (newp > -Double.MAX_VALUE && newp < Double.MAX_VALUE) {
op.setCoercableParameter(newp);
} else {
}
}
}
private boolean isCoercable(CoercableMCMCOperator op) {
return op.getMode() == CoercableMCMCOperator.COERCION_ON ||
(op.getMode() != CoercableMCMCOperator.COERCION_OFF && useCoercion);
}
public void addMarkovChainListener(MarkovChainListener listener) {
listeners.add(listener);
}
public void removeMarkovChainListener(MarkovChainListener listener) {
listeners.remove(listener);
}
public void fireBestModel(int state, Model bestModel) {
for (MarkovChainListener listener : listeners) {
listener.bestState(state, bestModel);
}
}
public void fireCurrentModel(int state, Model currentModel) {
for (MarkovChainListener listener : listeners) {
listener.currentState(state, currentModel);
}
}
public void fireFinished(int chainLength) {
for (MarkovChainListener listener : listeners) {
listener.finished(chainLength);
}
}
private final ArrayList<MarkovChainListener> listeners = new ArrayList<MarkovChainListener>();
}
|
package me.coley.recaf.config.impl;
import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonValue;
import me.coley.logging.Level;
import me.coley.recaf.config.Conf;
import me.coley.recaf.config.Config;
/**
* Options for user-interface.
*
* @author Matt
*/
public class ConfDisplay extends Config {
/**
* Simplify descriptor displays.
*/
@Conf(category = "display", key = "simplfy")
public boolean simplify = true;
/**
* Show in-line hints
*/
@Conf(category = "display", key = "jumphelp")
public boolean jumpHelp = true;
/**
* Editor windows become topmost.
*/
@Conf(category = "display", key = "topmost")
public boolean topmost;
/**
* Editor windows become topmost.
*/
@Conf(category = "display", key = "showsearchmethodtype")
public boolean showSearchMethodType;
/**
* UI language.
*/
@Conf(category = "display", key = "language")
public String language = "en";
/**
* Stylesheet group to use.
*/
@Conf(category = "display", key = "style")
public String style = "flat";
/**
* Logging level to display in UI.
*/
@Conf(category = "display", key = "loglevel")
public Level loglevel = Level.INFO;
/**
* Show button bar in main window. Disable and relaunch for more vertical
* space.
*/
@Conf(category = "display", key = "buttonbar")
public boolean toolbar = true;
/**
* Max length of class-name shown in class tree. Helpful for obfuscated
* programs with long names.
*/
@Conf(category = "display", key = "maxlength.tree")
public int maxLengthTree = 75;
public ConfDisplay() {
super("rc_display");
load();
}
@Override
protected JsonValue convert(Class<?> type, Object value) {
if (type.equals(Level.class)) {
return Json.value(((Level) value).name());
}
return null;
}
@Override
protected Object parse(Class<?> type, JsonValue value) {
if (type.equals(Level.class)) {
return Level.valueOf(value.asString());
}
return null;
}
/**
* Static getter.
*
* @return ConfDisplay instance.
*/
public static ConfDisplay instance() {
return ConfDisplay.instance(ConfDisplay.class);
}
}
|
package edu.wheaton.simulator.entity;
|
package edu.wheaton.simulator.entity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableList;
import net.sourceforge.jeval.EvaluationException;
import edu.wheaton.simulator.expression.AbstractExpressionFunction;
import edu.wheaton.simulator.expression.Expression;
public class Trigger implements Comparable<Trigger> {
/**
* A name to reference a trigger by
*/
private String name;
/**
* Determines when this trigger should be evaluated. Only affects the order
* of triggers within its particular Agent in LinearUpdate. That is, the
* order of importance in LinearUpdate for triggers is when the Owning Agent
* is reached->the trigger's priority.
*
* In PriorityUpdate, priority supercedes Agent ordering, that is trigger's
* priority->when the Owning Agent is reached.
*
*/
private int priority;
/**
* Used for AtomicUpdate In each iteration, the condition is evaluated, and
* the result is stored hear. It is later checked to see whether or not the
* behavior should be fired.
*/
private boolean atomicConditionResult;
/**
* Represents the conditions of whether or not the trigger fires.
*/
private Expression conditionExpression;
/**
* The behavior that is executed when the trigger condition is met
*/
private Expression behaviorExpression;
/**
* Observers to watch this trigger
*/
private static Set<TriggerObserver> observers = new HashSet<TriggerObserver>();
/**
* Constructor
*
* @param priority
* Triggers are checked in order of priority, with lower numbers
* coming first
* @param conditions
* boolean expression this trigger represents
*/
public Trigger(String name, int priority, Expression conditionExpression,
Expression behavior) {
this.name = name;
this.priority = priority;
this.conditionExpression = conditionExpression;
this.behaviorExpression = behavior;
}
/**
* Clone Constructor. Deep copy is not necessary at this point.
*
* @param parent
* The trigger from which to clone.
*/
public Trigger(Trigger parent) {
name = parent.getName();
priority = parent.getPriority();
conditionExpression = parent.getConditions();
behaviorExpression = parent.getBehavior();
}
/**
* Evaluates the boolean expression represented by this object and fires if
* all conditions evaluate to true.
*
* If someone wants to evaluate an expression to something other than
* boolean, they will need to change this method or fire.
*
* @return Boolean
* @throws EvaluationException
* if the expression was invalid
*/
public void evaluate(Agent xThis, int step) throws EvaluationException {
Expression condition = conditionExpression.clone();
Expression behavior = behaviorExpression.clone();
condition.importEntity("this", xThis);
behavior.importEntity("this", xThis);
boolean conditionResult = false;
try {
conditionResult = condition.evaluateBool();
} catch (Exception e) {
conditionResult = false;
}
if (conditionResult) {
fire(xThis, this, behavior, step);
}
}
/**
* Just evaluates the condition and stores the result in
* atomicConditionResult for later use (to see if the behavior is fired).
* Vital for AtomicUpdate
*
* @param xThis
* the owning Agent
* @throws EvaluationException
*/
public void evaluateCond(Agent xThis) throws EvaluationException {
Expression condition = conditionExpression.clone();
condition.importEntity("this", xThis);
atomicConditionResult = false;
try {
atomicConditionResult = condition.evaluateBool();
} catch (EvaluationException e) {
atomicConditionResult = false;
throw e;
}
}
/**
* Checks atomicConditionResult to see whether or not the behavior should be
* fired rather than evaluating the condition on the spot Vital for
* AtomicUpdate
*
* @param xThis
* @throws EvaluationException
*/
public void atomicFire(Agent xThis, int step) throws EvaluationException {
Expression behavior = behaviorExpression.clone();
behavior.importEntity("this", xThis);
if (atomicConditionResult)
fire(xThis, this, behavior, step);
}
/**
* Fires the trigger. Will depend on the Behavior object for this trigger.
*
* @param a
* @param t
* @param behavior
* @param step
* @throws EvaluationException
*/
private static void fire(Agent a, Trigger t, Expression behavior, int step) throws EvaluationException {
try {
if (behavior.evaluateBool() == false) {
}
else {
}
} catch (EvaluationException e) {
throw new EvaluationException("Behavior");
}
notifyObservers(a.getID(), t, step);
}
/**
* Compares this trigger to another trigger based on priority
*
* @param other
* The other trigger to compare to.
* @return -1 if less, 0 if same, 1 if greater.
*/
@Override
public int compareTo(Trigger other) {
if (priority == other.priority) {
return 0;
} else if (priority > other.priority) {
return 1;
} else {
return -1;
}
}
public String getName() {
return name;
}
public Expression getConditions() {
return conditionExpression;
}
public Expression getBehavior() {
return behaviorExpression;
}
public int getPriority() {
return priority;
}
@Override
public String toString(){
return name;
}
public static class Builder {
/**
* Current version of the trigger, will be returned when built
*/
private Trigger trigger;
/**
* HashMap of simple values to actual JEval appropriate input
* <name, Jeval equivalent>
*/
private HashBiMap<String, String> converter;
/**
* Simple (user readable) values for creating conditionals
*/
private List<String> conditionalValues;
/**
* Simple (user readable) values for creating behaviors
*/
private List<String> behavioralValues;
/**
* Reference to prototype that is being created
*/
private Prototype prototype;
/**
* HashMap of the names and the actual object of the functions.
*/
private Map<String, AbstractExpressionFunction> functions;
/**
* Strings to give the gui so that they can edit it. Obtained from parsing
* triggers into something that can be read by users.
*/
private String conditionString;
private String behaviorString;
/**
* Constructor for the trigger builder starting from scratch.
*
* @param p
* A prototype with just fields
*/
public Builder(Prototype p) {
prototype = p;
trigger = new Trigger("", 0, null, null);
converter = HashBiMap.create();
conditionalValues = new ArrayList<String>();
behavioralValues = new ArrayList<String>();
functions= new HashMap<String, AbstractExpressionFunction>();
functions.putAll(Expression.getBehaviorFunction());
functions.putAll(Expression.getConditionFunction());
loadFieldValues(p);
loadOperations();
loadBehaviorFunctions();
loadConditionalFunctions();
conditionString = "";
behaviorString = "";
}
/**
* Constructor for the trigger builder starting with a trigger
* @param t
* @param p
*/
public Builder(Trigger t, Prototype p){
this(p);
parseTrigger(t);
}
/**
* Converts a JEval formed trigger to something that be read by a human and makes sense.
*
* @param t
*/
private void parseTrigger(Trigger t) {
if (t == null){
return;
}
if (t.conditionExpression == null || t.behaviorExpression == null)
return;
String condition = t.getConditions().toString();
String behavior = t.getBehavior().toString();
for (String s : converter.inverse().keySet()){
if (condition.contains(s)){
condition = condition.replace(s, converter.inverse().get(s)+ " ");
}
if (behavior.contains(s)){
behavior = behavior.replace(s, converter.inverse().get(s)+" ");
}
}
if (condition.charAt(condition.length()-1)==(' ')){
condition= condition.substring(0, condition.length()-1);
}
conditionString = condition;
if (behavior.charAt(behavior.length()-1)==(' ')){
behavior= behavior.substring(0, behavior.length()-1);
}
behaviorString = behavior;
}
/**
* get the string parsed behavior
* @return
*/
public String getBehaviorString(){
return behaviorString;
}
/**
* get the string parsed condition.
* @return
*/
public String getConditionString(){
return conditionString;
}
/**
* Method to initialize conditionalValues and behaviorableValues
*/
private void loadFieldValues(Prototype p) {
conditionalValues.add("-- Values --");
behavioralValues.add("-- Values --");
for (Map.Entry<String, String> entry : p.getFieldMap().entrySet()) {
converter.put(entry.getKey(), "this." + entry.getKey());
conditionalValues.add(entry.getKey());
behavioralValues.add(entry.getKey());
}
}
/**
* Method to store common operations and initialize them when a Builder
* is initialized.
*/
private void loadOperations() {
conditionalValues.add("-- Operations --");
behavioralValues.add("-- Operations --");
converter.put("(", "(");
conditionalValues.add("(");
behavioralValues.add("(");
converter.put(")", ")");
conditionalValues.add(")");
behavioralValues.add(")");
converter.put(",", ",");
conditionalValues.add(",");
behavioralValues.add(",");
converter.put("OR", "||");
conditionalValues.add("OR");
behavioralValues.add("OR");
converter.put("AND", "&&");
conditionalValues.add("AND");
behavioralValues.add("AND");
converter.put("NOT_EQUALS", "!=");
conditionalValues.add("NOT_EQUALS");
behavioralValues.add("NOT_EQUALS");
converter.put("EQUALS", "==");
conditionalValues.add("EQUALS");
behavioralValues.add("EQUALS");
converter.put(">", ">");
conditionalValues.add(">");
behavioralValues.add(">");
converter.put("<", "<");
conditionalValues.add("<");
behavioralValues.add("<");
}
/**
* Method to store and initialize all the functions that a trigger may
* use.
*/
private void loadConditionalFunctions() {
conditionalValues.add("--Functions
conditionalValues.add("True");
for (String s : Expression.getConditionFunction().keySet()){
conditionalValues.add(convertCamelCaseToNormal(s));
converter.put(convertCamelCaseToNormal(s), s);
}
}
/**
* Loads all of the behaviors that we are using and their JEval
* equivalent.
*
* @param p
*/
private void loadBehaviorFunctions() {
behavioralValues.add("--Functions
for (String s : Expression.getBehaviorFunction().keySet()){
behavioralValues.add(convertCamelCaseToNormal(s));
converter.put(convertCamelCaseToNormal(s), s);
}
}
/**
* Sets the name of the Trigger
* @param n
*/
public void addName(String n) {
trigger.name = n;
}
/**
* Sets the priority of the Trigger
*
* @param n
*/
public void addPriority(int p) {
trigger.priority = p;
}
/**
* Returns a set of conditional values
*
* @return Set of Strings
*/
public ImmutableList<String> conditionalValues() {
ImmutableList.Builder<String> builder = new ImmutableList.Builder<String>();
builder.addAll(conditionalValues);
return builder.build();
}
/**
* Gets a set of possible behavioral values
*
* @return Set of Strings
*/
public ImmutableList<String> behavioralValues() {
ImmutableList.Builder<String> builder = new ImmutableList.Builder<String>();
builder.addAll(behavioralValues);
return builder.build();
}
/**
* Passes the builder a string of values separated with a space the
* correspond to a conditional
*
* @param c
*/
public void addConditional(String c) {
conditionString = c;
String condition = "";
String[] stringArray = c.split(" ");
for (String a : stringArray) {
condition += (findMatches(a) + " ");
}
if (condition.charAt(condition.length()-1)==(' ')){
condition= condition.substring(0, condition.length()-1);
}
trigger.conditionExpression = (new Expression(condition));
}
/**
* Passes the builder a string of values separated with a space the
* correspond to a behavior
*
* @param b
*/
public void addBehavioral(String b) {
behaviorString = b;
String behavior = "";
String[] stringArray = b.split(" ");
for (String a : stringArray) {
behavior += (findMatches(a)+" ");
}
if (behavior.charAt(behavior.length()-1)==(' ')){
behavior= behavior.substring(0, behavior.length()-1);
}
trigger.behaviorExpression= (new Expression(behavior));
}
/**
* Provides the expression appropriate version of the inputed string.
* If not are found, it just gives back the String so the user can enter
* own input.
*
* @param s
* @return
*/
private String findMatches(String s) {
String match = converter.get(s);
return (match == null) ? s : match;
}
/**
* Whether or not the last conditional and behavioral are a valid
* trigger
*
* @return True if it works. Otherwise throws an exception
* telling what went wrong
*/
public boolean isValid() throws Exception{
try{
if (trigger.priority < 0){
throw new Exception("Trigger priority cannot be negative");
}
if (trigger.conditionExpression == null)
throw new Exception("Trigger condition is blank");
if (trigger.behaviorExpression == null)
throw new Exception("Trigger behavior is blank");
new Expression(isValidHelper(trigger.conditionExpression.toString())).evaluateBool();
new Expression(isValidHelper(trigger.behaviorExpression.toString())).evaluateBool();
return true;
}
catch (Exception e){
throw e;
}
}
/**
* Helper method for isValid method to change this.xxxx to the value of xxxx
* in the prototype.
* @param s
* @return simplified expression that we can evaluate
*/
private String isValidHelper(String s) throws Exception{
while(s.indexOf("this.") != -1){
int index = s.indexOf("this.");
String beginning = s.substring(0, index);
s = s.substring(index+5);
Map<String, String> map = prototype.getFieldMap();
for (String a : map.keySet()){
if (s.indexOf(a) == 0){
String value = map.get(a);
s = value + s.substring(a.length());
break;
}
}
s = beginning + s;
}
return isValidHelper2(s);
}
/**
* Helper method for isValid method to check functions for correct number of
* arguments and the
* @param s
* @return simplified expression that we can evaluate
*/
private String isValidHelper2(String s) throws Exception{
for (String f : functions.keySet()){
while (s.indexOf(f)!= -1){
int index = s.indexOf(f);
String beginning = s.substring(0, index);
s= s.substring(index);
String test = isValidHelper2(s.substring(s.indexOf("(", index)));
System.out.println(test);
String[] numArgs = test.split(",");
if (numArgs.length != functions.get(f).numArgs()){
throw new Exception("The function: " + convertCamelCaseToNormal(functions.get(f).getName()) +
", has the wrong number of arguments");
}
s = s.substring(s.indexOf(")")+1);
s = beginning + functionType(f)+s;
}
}
return s;
}
private String functionType(String name){
switch (functions.get(name).getResultType()){
case AbstractExpressionFunction.RESULT_TYPE_BOOL: return "TRUE";
case AbstractExpressionFunction.RESULT_TYPE_STRING: return "'string'";
}
return null;
}
/**
* Provides the built trigger
*
* @return
*/
public Trigger build() {
return trigger;
}
/**
* converts thisIsCamelCase to this_is_camel_case.
* @param s
* @return
*/
private static String convertCamelCaseToNormal(String s){
String toReturn = "";
for (int i = 0; i < s.length(); i++){
if (Character.isUpperCase(s.charAt(i)))
toReturn+= "_" + Character.toLowerCase(s.charAt(i));
else
toReturn += s.charAt(i);
}
return toReturn;
}
}
/**
* Adds an observer to the trigger's list
*
* @param ob
*/
public static void addObserver(TriggerObserver ob) {
observers.add(ob);
}
/**
* Notifies all of the observers watching this grid
*
* @param caller
* @param trigger
* @param step
*/
public static void notifyObservers(AgentID caller, Trigger trigger, int step) {
for (TriggerObserver current : observers)
current.update(caller, trigger, step);
}
}
|
package edu.wustl.xipHost.gui;
import javax.swing.*;
import edu.wustl.xipHost.application.Application;
import edu.wustl.xipHost.application.ApplicationManagerFactory;
import edu.wustl.xipHost.avt2ext.AVTPanel;
import edu.wustl.xipHost.caGrid.GridPanel;
import edu.wustl.xipHost.dicom.DicomPanel;
import edu.wustl.xipHost.globalSearch.GlobalSearchPanel;
import edu.wustl.xipHost.hostControl.HostConfigurator;
import edu.wustl.xipHost.localFileSystem.FileManager;
import edu.wustl.xipHost.localFileSystem.FileManagerFactory;
import edu.wustl.xipHost.localFileSystem.HostFileChooser;
import edu.wustl.xipHost.worklist.WorklistPanel;
import edu.wustl.xipHost.xds.XDSPanel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.UUID;
public class HostMainWindow extends JFrame implements ActionListener {
static HostIconBar toolBar = new HostIconBar();
static JTabbedPane sideTabbedPane;
SideTabMouseAdapter mouseAdapter = new SideTabMouseAdapter();
//CenterTabMouseAdapter mouseAdapterCenterTabs = new CenterTabMouseAdapter();
static JPanel hostPanel = new JPanel();
JTabbedPane tabPaneCenter = new JTabbedPane();
static Rectangle appScreenSize = new Rectangle();
OptionsDialog optionsDialog = new OptionsDialog(new JFrame());
Color xipColor = new Color(51, 51, 102);
Color xipLightBlue = new Color(156, 162, 189);
Font font = new Font("Tahoma", 0, 12);
String userName;
WorklistPanel worklistPanel;
DicomPanel dicomPanel;
GridPanel gridPanel;
GlobalSearchPanel globalSearchPanel;
XDSPanel xdsPanel;
AVTPanel avt2extPanel;
static Dimension screenSize;
public HostMainWindow(){
super("XIP Host");
worklistPanel = new WorklistPanel();
dicomPanel = new DicomPanel();
gridPanel = new GridPanel();
globalSearchPanel = new GlobalSearchPanel();
avt2extPanel = new AVTPanel();
xdsPanel = new XDSPanel();
if(HostConfigurator.OS.contains("Windows")){
setUndecorated(true);
}else{
setUndecorated(false);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
}
public void display(){
UIManager.put("TabbedPane.selected", xipLightBlue);
setLayout(new BorderLayout());
toolBar.setUserName(userName);
add(toolBar, BorderLayout.NORTH);
sideTabbedPane = VerticalTextIcon.createTabbedPane(JTabbedPane.RIGHT);
sideTabbedPane.setBackground(xipColor);
add(sideTabbedPane, BorderLayout.CENTER);
sideTabbedPane.addMouseListener(mouseAdapter);
hostPanel.add(tabPaneCenter);
hostPanel.setBackground(xipColor);
buildHostPanelLayout();
VerticalTextIcon.addTab(sideTabbedPane, "Host", UUID.randomUUID(), hostPanel);
//Add tabs
ImageIcon icon = null;
tabPaneCenter.addTab("AVT AD", icon, avt2extPanel, null);
tabPaneCenter.addTab("caGrid", icon, gridPanel, null);
tabPaneCenter.addTab("PACS", icon, dicomPanel, null);
tabPaneCenter.addTab("GlobalSearch", icon, globalSearchPanel, null);
tabPaneCenter.addTab("XDS", icon, xdsPanel, null);
tabPaneCenter.addTab("Worklist", icon, worklistPanel, null);
tabPaneCenter.setFont(font);
tabPaneCenter.setSelectedComponent(dicomPanel);
toolBar.btnHost.addActionListener(this);
toolBar.btnLocal.addActionListener(this);
toolBar.btnOptions.addActionListener(this);
toolBar.btnExit.addActionListener(this);
toolBar.btnSuspend.addActionListener(this);
toolBar.btnCancel.addActionListener(this);
toolBar.btnExitApp.addActionListener(this);
toolBar.lblAbout.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
new AboutDialog(new JFrame());
}
});
toolBar.lblHelp.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
new HelpManager(new JFrame());
}
});
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(0, 0, (int)screenSize.getWidth(), (int)screenSize.getHeight());
getContentPane().setBackground(xipColor);
setVisible(true);
setAlwaysOnTop(true);
setAlwaysOnTop(false);
}
void buildHostPanelLayout(){
GridBagLayout layout = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
hostPanel.setLayout(layout);
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.anchor = GridBagConstraints.CENTER;
layout.setConstraints(tabPaneCenter, constraints);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == toolBar.btnHost){
sideTabbedPane.setSelectedIndex(0);
toolBar.switchButtons(0);
setAlwaysOnTop(true);
setAlwaysOnTop(false);
}else if (e.getSource() == toolBar.btnLocal){
HostFileChooser fileChooser = new HostFileChooser(true, new File("./dicom-dataset-demo"));
fileChooser.setVisible(true);
File[] files = fileChooser.getSelectedItems();
if(files == null){
return;
}
FileManager fileMgr = FileManagerFactory.getInstance();
fileMgr.run(files);
}else if(e.getSource() == toolBar.btnOptions){
int x = (int)((JButton)e.getSource()).getLocationOnScreen().getX();
int y = (int)((JButton)e.getSource()).getLocationOnScreen().getY() + 45;
optionsDialog.display(x, y);
}else if (e.getSource() == toolBar.btnExit) {
HostConfigurator hostConfig = HostConfigurator.getHostConfigurator();
hostConfig.runHostShutdownSequence();
}else if(e.getSource() == toolBar.btnCancel){
Application app = getSelectedApplication();
if(!app.cancelProcessing()){
new ExceptionDialog("Selected application processing cannot be canceled.",
"Application state must be INPROGRESS or SUSPENDED.",
"Host Dialog");
}
}else if(e.getSource() == toolBar.btnSuspend){
Application app = getSelectedApplication();
if(!app.suspendProcessing()){
new ExceptionDialog("Selected application processing cannot be suspended.",
"Application state must be INPROGRESS but is " + app.getState().toString() + ".",
"Host Dialog");
}
}else if(e.getSource() == toolBar.btnExitApp){
Application app = getSelectedApplication();
boolean isShutDownAllowed = app.shutDown();
if(isShutDownAllowed == false){
new ExceptionDialog(app.getName() + " cannot be terminated by host.",
"Application current state: " + app.getState().toString() + ".",
"Host Dialog");
}
}
}
Application getSelectedApplication(){
int index = sideTabbedPane.getSelectedIndex();
//String appName = ((VerticalTextIcon)sideTabbedPane.getIconAt(index)).getTabTitle();
UUID uuid = ((VerticalTextIcon)sideTabbedPane.getIconAt(index)).getUUIDfromTab();
//Application app = ApplicationManagerFactory.getInstance().getApplication(appName);
Application app = ApplicationManagerFactory.getInstance().getApplication(uuid);
return app;
}
public static Rectangle getApplicationPreferredSize(){
int appXPosition;
int appYPosition;
int appWidth;
int appHeight;
if(HostConfigurator.OS.contains("Windows")){
appXPosition = (int) hostPanel.getLocationOnScreen().getX();
appYPosition = (int) hostPanel.getLocationOnScreen().getY();
appWidth = (int) hostPanel.getBounds().getWidth();
appHeight = (int) hostPanel.getBounds().getHeight();
}else{
appXPosition = 0;
appYPosition = 0;
appWidth = (int)screenSize.getWidth();
appHeight = (int)screenSize.getHeight();
}
appScreenSize.setBounds(appXPosition, appYPosition, appWidth, appHeight);
return appScreenSize;
}
public static void addTab(String appName, UUID appUUID){
VerticalTextIcon.addTab(sideTabbedPane, appName, appUUID, null);
int tabCount = sideTabbedPane.getTabCount();
sideTabbedPane.setSelectedIndex(tabCount - 1);
toolBar.switchButtons(1);
}
public static void removeTab(UUID appUUID){
int tabCount = sideTabbedPane.getTabCount();
for(int i = 0; i < tabCount; i++){
UUID selectedTabUUID = ((VerticalTextIcon)sideTabbedPane.getIconAt(i)).getUUIDfromTab();
if(appUUID.equals(selectedTabUUID)){
sideTabbedPane.remove(i);
sideTabbedPane.setSelectedIndex(0);
toolBar.switchButtons(0);
return;
}
}
}
class SideTabMouseAdapter extends MouseAdapter{
public void mousePressed(MouseEvent e) {
if(e.getButton() == 1){
if(e.getSource() == sideTabbedPane){
int i = (((JTabbedPane)e.getSource()).getSelectedIndex());
//String selectedTabTitle = ((VerticalTextIcon)sideTabbedPane.getIconAt(i)).getTabTitle();
UUID uuid = ((VerticalTextIcon)sideTabbedPane.getIconAt(i)).getUUIDfromTab();
//System.out.println("Title: " + (selectedTabTitle));
if (sideTabbedPane.getSelectedIndex() == 0){
toolBar.switchButtons(0);
setAlwaysOnTop(true);
setAlwaysOnTop(false);
} else if (sideTabbedPane.getSelectedIndex() != 0){
//Application app = ApplicationManager.getApplication(selectedTabTitle);
Application app = ApplicationManagerFactory.getInstance().getApplication(uuid);
if(HostConfigurator.OS.contains("Windows") == false){
iconify();
}
app.bringToFront();
toolBar.switchButtons(1);
}else {
setAlwaysOnTop(true);
setAlwaysOnTop(false);
}
}
}
}
public void mouseReleased(MouseEvent e){
//3 = right mouse click
if(e.getButton() == 3){
if(e.getSource() == sideTabbedPane){
int i = (((JTabbedPane)e.getSource()).getSelectedIndex());
//String selectedTabTitle = ((VerticalTextIcon)sideTabbedPane.getIconAt(i)).getTabTitle();
UUID uuid = ((VerticalTextIcon)sideTabbedPane.getIconAt(i)).getUUIDfromTab();
//System.out.println("Title: " + (selectedTabTitle));
if (sideTabbedPane.getSelectedIndex() == 0){
toolBar.switchButtons(0);
setAlwaysOnTop(true);
setAlwaysOnTop(false);
} else if (sideTabbedPane.getSelectedIndex() != 0){
//Application app = ApplicationManager.getApplication(selectedTabTitle);
Application app = ApplicationManagerFactory.getInstance().getApplication(uuid);
app.bringToFront();
toolBar.switchButtons(1);
}else {
setAlwaysOnTop(true);
setAlwaysOnTop(false);
}
}
}
}
}
public void setUserName(String userName){
this.userName = userName;
}
public static void main(String [] args){
HostMainWindow mainWindow = new HostMainWindow();
mainWindow.display();
}
/*public void deiconify() {
int state = getExtendedState();
state &= ~Frame.ICONIFIED;
setExtendedState(state);
}*/
public void iconify() {
int state = getExtendedState();
state |= Frame.ICONIFIED;
setExtendedState(state);
}
public static HostIconBar getHostIconBar(){
return toolBar;
}
public Component getSelectedSearchTab() {
return tabPaneCenter.getSelectedComponent();
}
InputDialog inputDialog;
public void setInputDialog(InputDialog inputDialog){
this.inputDialog = inputDialog;
}
public InputDialog getInputDialog(){
return inputDialog;
}
}
|
package org.genericsystem.cv.application;
import org.genericsystem.cv.AbstractApp;
import org.genericsystem.cv.Img;
import org.genericsystem.cv.utils.NativeLibraryLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Range;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javafx.application.Platform;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
public class RadonTransformDemo2 extends AbstractApp {
public static void main(String[] args) {
launch(args);
}
static {
NativeLibraryLoader.load();
}
private final double f = 6.053 / 0.009;
private GSCapture gsCapture = new GSVideoCapture(0, f, GSVideoCapture.HD, GSVideoCapture.VGA);
private SuperFrameImg superFrame = gsCapture.read();
private ScheduledExecutorService timer = new BoundedScheduledThreadPoolExecutor();
private Config config = new Config();
private final ImageView[][] imageViews = new ImageView[][] { new ImageView[3], new ImageView[3], new ImageView[3], new ImageView[3], new ImageView[3] };
private void startTimer() {
timer.scheduleAtFixedRate(() -> {
try {
Image[] images = doWork();
if (images != null)
Platform.runLater(() -> {
Iterator<Image> it = Arrays.asList(images).iterator();
for (int row = 0; row < imageViews.length; row++)
for (int col = 0; col < imageViews[row].length; col++)
if (it.hasNext())
imageViews[row][col].setImage(it.next());
});
} catch (Throwable e) {
e.printStackTrace();
}
}, 1000, 30, TimeUnit.MILLISECONDS);
}
@Override
protected void fillGrid(GridPane mainGrid) {
double displaySizeReduction = 1.5;
for (int col = 0; col < imageViews.length; col++)
for (int row = 0; row < imageViews[col].length; row++) {
ImageView imageView = new ImageView();
imageViews[col][row] = imageView;
mainGrid.add(imageViews[col][row], col, row);
imageView.setFitWidth(superFrame.width() / displaySizeReduction);
imageView.setFitHeight(superFrame.height() / displaySizeReduction);
}
startTimer();
}
private Image[] doWork() {
System.out.println("do work");
if (!config.stabilizedMode) {
superFrame = gsCapture.read();
}
Image[] images = new Image[20];
long ref = System.currentTimeMillis();
Img binarized = superFrame.getFrame().adaptativeGaussianInvThreshold(7, 5);
// Img binarized = new Img(Mat.zeros(360, 640, CvType.CV_8UC1), false);
double[] angles = { -10, -25, -5 };
int count = 0;
for (int y = 100; y <= 260; y += 80) {
double angle = angles[count] / 180 * Math.PI;
// Imgproc.line(binarized.getSrc(), new Point(320 - 40 * Math.cos(angle), y - 40 * Math.sin(angle)), new Point(320 + 40 * Math.cos(angle), y + 40 * Math.sin(angle)), new Scalar(255), 1);
// Imgproc.putText(binarized.getSrc(), "Hello boy", new Point(320 - 40 * Math.cos(angle), y - 40 * Math.sin(angle)), Core.FONT_HERSHEY_PLAIN, 2, new Scalar(255), 1);
count++;
}
images[0] = binarized.toJfxImage();
ref = trace("Binarization", ref);
int stripWidth = 100;
Mat vStrip = RadonTransform.extractStrip(binarized.getSrc(), binarized.width() / 2 - stripWidth / 2, stripWidth);
Mat vStripDisplay = Mat.zeros(binarized.size(), binarized.type());
Mat roi = new Mat(vStripDisplay, new Range(0, binarized.height()), new Range(binarized.width() / 2 - stripWidth / 2, binarized.width() / 2 + stripWidth / 2));
vStrip.copyTo(roi);
images[1] = new Img(vStripDisplay, false).toJfxImage();
ref = trace("Extract strip", ref);
Mat houghTransform = RadonTransform.fastHoughTransform(vStrip);
// houghTransform.row(0).setTo(new Scalar(0));
// houghTransform.row(houghTransform.rows() - 1).setTo(new Scalar(0));
Core.normalize(houghTransform, houghTransform, 0, 255, Core.NORM_MINMAX);
images[3] = new Img(houghTransform, false).toJfxImage();
ref = trace("FHT", ref);
Mat gradient = new Mat();
Mat blur = new Mat();
Imgproc.blur(houghTransform, blur, new Size(1, 11), new Point(-1, -1), Core.BORDER_ISOLATED);
Core.absdiff(houghTransform, blur, gradient);
images[2] = new Img(blur, false).toJfxImage();
// gradient.row(0).setTo(new Scalar(0));
// gradient.row(houghTransform.rows() - 1).setTo(new Scalar(0));
Core.pow(gradient, 2, gradient);
Core.normalize(gradient, gradient, 0, 255, Core.NORM_MINMAX);
images[4] = new Img(gradient, false).toJfxImage();
ref = trace("FHT Gradient", ref);
TrajectStep[] houghVtraj = RadonTransform.bestTrajectFHT(gradient, -50);
List<Double> magnitudes = new ArrayList<>();
for (int row = 0; row < houghVtraj.length; row++) {
double magnitude = houghTransform.get(row, houghVtraj[row].theta)[0];
magnitudes.add(magnitude);
}
for (int y = 0; y < houghVtraj.length; y++)
houghVtraj[y].theta = (int) Math.round(Math.atan((double) (houghVtraj[y].theta - (stripWidth - 1)) / (stripWidth - 1)) / Math.PI * 180 + 45);
for (int y = 0; y < houghVtraj.length; y++) {
if (houghVtraj[y].magnitude <= 1)
for (int end = y + 1; end < houghVtraj.length; end++) {
if (houghVtraj[end].magnitude > 1) {
for (int current = y; current < end; current++)
houghVtraj[current].theta = houghVtraj[y == 0 ? 0 : y - 1].theta + (houghVtraj[end].theta - houghVtraj[y == 0 ? 0 : y - 1].theta) * (current - y) / (end - y + 1);
y = end;
break;
}
}
}
Mat vHoughColor = Mat.zeros(houghTransform.height(), 91, CvType.CV_8UC3);
for (int y = 0; y < vHoughColor.height(); y++) {
vHoughColor.put(y, houghVtraj[y].theta, 0, 0, 255);
if (houghVtraj[y].magnitude >= 1)
vHoughColor.put(y, houghVtraj[y].theta, 255, 0, 0);
}
images[5] = new Img(vHoughColor, false).toJfxImage();
ref = trace("FHT traject", ref);
Mat comb = Mat.zeros(magnitudes.size(), 255, CvType.CV_8UC1);
for (TrajectStep trajectStep : houghVtraj)
Imgproc.line(comb, new Point(0, trajectStep.k), new Point(trajectStep.magnitude, trajectStep.k), new Scalar(255));
// for (int row = 0; row < comb.rows(); row++)
// Imgproc.line(comb, new Point(0, row), new Point(magnitudes.get(row), row), new Scalar(255));
// comb = new Img(comb, false).morphologyEx(Imgproc.MORPH_CLOSE, Imgproc.MORPH_RECT, new Size(1, 3)).getSrc();
ref = trace("Display comb", ref);
images[6] = new Img(comb, false).toJfxImage();
List<Double> magnitudesGradient = new ArrayList<>();
Mat gradientComb = Mat.zeros(houghVtraj.length, 255, CvType.CV_8UC3);
for (int row = 0; row < magnitudes.size() - 1; row++) {
double dMag = magnitudes.get(row + 1) - magnitudes.get(row);
magnitudesGradient.add(dMag);
if (Math.abs(dMag) > stripWidth / 5) {
Scalar color = dMag > 0 ? new Scalar(0, 255, 0) : new Scalar(0, 0, 255);
Imgproc.line(gradientComb, new Point(0, row), new Point(Math.abs(dMag), row), color);
}
}
images[7] = new Img(gradientComb, false).toJfxImage();
ref = trace("Display gradient comb", ref);
Mat vStripColor = new Mat();
Imgproc.cvtColor(vStrip, vStripColor, Imgproc.COLOR_GRAY2BGR);
// vStrip.convertTo(vStripColor, CvType.CV_8UC3);
for (TrajectStep trajectStep : Arrays.stream(houghVtraj).filter(ts -> Math.abs(ts.magnitude) > stripWidth / 5).collect(Collectors.toList())) {
double mag = stripWidth;
double theta = ((double) trajectStep.theta - 45) / 180 * Math.PI;
System.out.println("coucou " + theta + " " + trajectStep.k);
int row = trajectStep.k;
Scalar color = (magnitudes.get(row) - magnitudes.get(row < houghVtraj.length - 1 ? row + 1 : row) >= 0) ? new Scalar(0, 255, 0) : new Scalar(0, 0, 255);
Imgproc.line(vStripColor, new Point(vStripColor.width() / 2 - mag * Math.cos(theta), row - mag * Math.sin(theta)), new Point(vStripColor.width() / 2 + mag * Math.cos(theta), row + mag * Math.sin(theta)), color, 1);
}
Mat vStripColorDisplay = Mat.zeros(binarized.size(), vStripColor.type());
Mat stripRoi = new Mat(vStripColorDisplay, new Range(0, vStripColorDisplay.height()), new Range(vStripColorDisplay.width() / 2 - stripWidth / 2, vStripColorDisplay.width() / 2 + stripWidth / 2));
vStripColor.copyTo(stripRoi);
images[8] = new Img(vStripColorDisplay, false).toJfxImage();
ref = trace("Display underlined strip", ref);
// Mat gray = new Mat();
// houghTransform.convertTo(gray, CvType.CV_8UC1);
// Imgproc.threshold(gray, houghTransform, 0, 255, Imgproc.THRESH_BINARY_INV + Imgproc.THRESH_OTSU);
// Scalar mean = Core.mean(houghTransform);
// Core.absdiff(houghTransform, mean, houghTransform);
// Imgproc.Sobel(houghTransform, gradient, CvType.CV_64FC1, 0, 1);
// Imgproc.Sobel(houghTransform, gradient, CvType.CV_64FC1, 1, 0);
// Core.absdiff(gradient, new Scalar(0), gradient);
// wImgproc.adaptiveThreshold(gray, houghTransform, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY_INV, 7, 10);
// Core.pow(houghTransform, 4, houghTransform);
// gradient.row(0).setTo(new Scalar(0));
// gradient.row(houghTransform.rows() - 1).setTo(new Scalar(0));
// Core.normalize(houghTransform, houghTransform, 0, 255, Core.NORM_MINMAX);
// houghTransform = new Img(houghTransform, false).morphologyEx(Imgproc.MORPH_CLOSE, Imgproc.MORPH_ELLIPSE, new Size(1, 7)).getSrc();
// Imgproc.threshold(houghTransform, houghTransform, 0, 1, Imgproc.THRESH_TOZERO);
// Core.addWeighted(houghTransform, 0, gradient, 1, 0, houghTransform);
// Core.normalize(houghTransform, houghTransform, 0, 1, Core.NORM_MINMAX);
// Imgproc.threshold(houghTransform, houghTransform, 150, 255, Imgproc.THRESH_BINARY);
// Imgproc.morphologyEx(houghTransform, gradient, Imgproc.MORPH_GRADIENT, Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(1, 2)));
// Function<Double, Double> approxHoughVFunction = RadonTransform.approxTraject(houghVtraj);
// for (int y = 0; y < vHoughColor.height(); y++) {
// int x = (int) Math.round(approxHoughVFunction.apply((double) y));
// if (x < 0)
// x = 0;
// if (x >= vHoughColor.width())
// x = vHoughColor.width() - 1;
// vHoughColor.put(y, x, 0, 255, 0);
// ref = trace("Fht approx", ref);
// System.out.println(houghTransform);
// for (Pair pair : RadonTransform.getLocalExtr(houghTransform, 200)) {
// Imgproc.circle(vHoughColor, new Point((Math.atan((pair.point.x - stripWidth + 1) / (stripWidth - 1)) / Math.PI * 180) + 45, pair.point.y), 2, new Scalar(255, 0, 0), -1);
// System.out.println((Math.atan((pair.point.x - stripWidth + 1) / (stripWidth - 1)) / Math.PI * 180) + " " + pair.point.y + " " + pair.value);
Mat vTransform = RadonTransform.radonTransform(vStrip, -45, 45);
Mat vProjection = RadonTransform.radonRemap(vTransform, -45);
images[9] = new Img(vProjection, false).toJfxImage();
System.out.println(vProjection);
Imgproc.morphologyEx(vProjection, vProjection, Imgproc.MORPH_GRADIENT, Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(1, 2)));
Core.normalize(vProjection, vProjection, 0, 255, Core.NORM_MINMAX);
ref = trace("Radon + Projection", ref);
images[10] = new Img(vProjection, false).toJfxImage();
TrajectStep[] vtraj = RadonTransform.bestTrajectRadon(vProjection, -20);
for (int y = 0; y < vtraj.length; y++) {
if (vtraj[y].magnitude == 0)
for (int end = y + 1; end < vtraj.length; end++) {
if (vtraj[end].magnitude != 0) {
for (int current = y; current < end; current++)
vtraj[current].theta = vtraj[y == 0 ? 0 : y - 1].theta + (vtraj[end].theta - vtraj[y == 0 ? 0 : y - 1].theta) * (current - y) / (end - y + 1);
y = end;
break;
}
}
}
Mat vProjectionColor = Mat.zeros(vProjection.size(), CvType.CV_8UC3);
for (int y = 0; y < vProjectionColor.height(); y++) {
vProjectionColor.put(y, vtraj[y].theta, 0, 0, 255);
if (vtraj[y].magnitude != 0) {
vProjectionColor.put(y, vtraj[y].theta, 255, 0, 0);
}
}
ref = trace("Best traject radon", ref);
images[11] = new Img(vProjectionColor, false).toJfxImage();
// Function<Double, Double> approxRadonVFunction = RadonTransform.approxTraject(vtraj);
// for (int y = 0; y < vProjectionColor.height(); y++) {
// int x = (int) Math.round(approxRadonVFunction.apply((double) y));
// if (x < 0)
// x = 0;
// if (x >= vProjectionColor.width())
// x = vProjectionColor.width() - 1;
// vProjectionColor.put(y, x, 255, 0, 0);
// x = (int) Math.round(approxHoughVFunction.apply((double) y));
// if (x < 0)
// x = 0;
// if (x >= vProjectionColor.width())
// x = vProjectionColor.width() - 1;
// vProjectionColor.put(y, x, 0, 255, 0);
// ref = trace("Approx traject radon", ref);
double houghError = 0;
double houghApproxError = 0;
double radonError = 0;
double radonApproxError = 0;
count = 0;
for (int y = 100; y <= 260; y += 80) {
houghError += Math.pow((houghVtraj[y].theta - 45) - angles[count], 2);
// houghApproxError += Math.pow(approxHoughVFunction.apply((double) y) - 45 - angles[count], 2);
radonError += Math.pow((vtraj[y].theta - 45) - angles[count], 2);
// radonApproxError += Math.pow(approxRadonVFunction.apply((double) y) - 45 - angles[count], 2);
count++;
}
houghError = Math.sqrt(houghError);
houghApproxError = Math.sqrt(houghApproxError);
radonError = Math.sqrt(radonError);
radonApproxError = Math.sqrt(radonApproxError);
System.out.println("Hough : " + houghError);
System.out.println("Hough approx : " + houghApproxError);
System.out.println("Radon : " + radonError);
System.out.println("Radon approx : " + radonApproxError);
return images;
}
private long trace(String message, long ref) {
long last = System.currentTimeMillis();
System.out.println(message + " : " + (last - ref));
return last;
}
@Override
protected void onS() {
config.stabilizedMode = !config.stabilizedMode;
}
@Override
protected void onSpace() {
if (config.isOn) {
timer.shutdown();
// gsCapture.release();
} else {
timer = new BoundedScheduledThreadPoolExecutor();
// gsCapture = new GSVideoCapture(0, f, GSVideoCapture.HD, GSVideoCapture.VGA);
startTimer();
}
config.isOn = !config.isOn;
}
@Override
protected void onT() {
config.textsEnabledMode = !config.textsEnabledMode;
}
@Override
public void stop() throws Exception {
super.stop();
timer.shutdown();
timer.awaitTermination(5000, TimeUnit.MILLISECONDS);
gsCapture.release();
}
}
|
// NavigableImagePanel.java
package imagej.gui.swing.display;
import imagej.IntCoords;
import imagej.RealCoords;
import imagej.display.EventDispatcher;
import imagej.display.MouseCursor;
import imagej.display.NavigableImageCanvas;
import imagej.event.EventSubscriber;
import imagej.event.Events;
import imagej.tool.event.ToolActivatedEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class NavigableImagePanel extends JPanel implements
NavigableImageCanvas
{
// Rendering...
private static final double HIGH_QUALITY_RENDERING_SCALE_THRESHOLD = 1.0;
private static final Object INTERPOLATION_TYPE =
RenderingHints.VALUE_INTERPOLATION_BILINEAR;
private boolean highQualityRenderingEnabled = true;
private double zoomFactor = 1.0 + getZoomIncrement();
private BufferedImage image;
private double initialScale = 0.0;
private double scale = 0.0;
private int originX = 0;
private int originY = 0;
private Point mousePosition;
private Dimension previousPanelSize;
/**
* <p>
* Creates a new navigable image panel with no default image and the mouse
* scroll wheel as the zooming device.
* </p>
*/
public NavigableImagePanel() {
setOpaque(false);
addResizeListener();
addMouseListeners();
setZoomDevice(ZoomDevice.MOUSE_WHEEL);
// setZoomDevice(ZoomDevice.MOUSE_BUTTON);
}
/**
* <p>
* Creates a new navigable image panel with the specified image and the mouse
* scroll wheel as the zooming device.
* </p>
*/
public NavigableImagePanel(final BufferedImage image) {
this();
setImage(image);
}
private void addMouseListeners() {
addMouseListener(new MouseAdapter() {
@SuppressWarnings("synthetic-access")
@Override
public void mousePressed(final MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
if (isInNavigationImage(e.getPoint())) {
final Point p = e.getPoint();
displayImageAt(ptToCoords(p));
}
}
}
});
addMouseMotionListener(new MouseMotionListener() {
@SuppressWarnings("synthetic-access")
@Override
public void mouseDragged(final MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) &&
!isInNavigationImage(e.getPoint()))
{
// TODO - clean up this section, to fully remove pan support
// in favor of the pan tool way of doing things
// Point p = e.getPoint();
// moveImage(p);
}
}
@SuppressWarnings("synthetic-access")
@Override
public void mouseMoved(final MouseEvent e) {
// we need the mouse position so that after zooming
// that position of the image is maintained
mousePosition = e.getPoint();
// Coords coord = panelToImageCoords(mousePosition);
// // Display current pixel value in StatusBar
// //sampleImage.getRaster().getDataBuffer(). .getPixel(coord.getIntX(), coord.getIntY(), dArray)
// if (isInImage(mousePosition)) {
// int value = image.getRGB(coord.getIntX(), coord.getIntY());
// Events.publish(new StatusEvent("Pixel: (" + coord.getIntX() + "," + coord.getIntY() + ") "
// + pixelARGBtoString(value)));
}
});
}
public String pixelARGBtoString(final int pixel) {
final int alpha = (pixel >> 24) & 0xff;
final int red = (pixel >> 16) & 0xff;
final int green = (pixel >> 8) & 0xff;
final int blue = (pixel) & 0xff;
return "" + alpha + ", " + red + ", " + green + ", " + blue;
}
// Called from paintComponent() when a new image is set.
private void initializeParams() {
final double xScale = (double) getWidth() / image.getWidth();
final double yScale = (double) getHeight() / image.getHeight();
initialScale = Math.min(xScale, yScale);
scale = initialScale;
// An image is initially centered
centerImage();
if (isNavigationImageEnabled()) {
createNavigationImage();
}
// setSize(image.getWidth(), image.getHeight());
}
@Override
public int getImageWidth() {
return image.getWidth();
}
@Override
public int getImageHeight() {
return image.getHeight();
}
/**
* <p>
* Sets an image for display in the panel.
* </p>
*
* @param image an image to be set in the panel
*/
public void setImage(final BufferedImage image) {
final BufferedImage oldImage = this.image;
this.image = toCompatibleImage(image);
// Reset scale so that initializeParameters() is called in paintComponent()
// for the new image.
scale = 0.0;
firePropertyChange(IMAGE_CHANGED_PROPERTY, oldImage, image);
repaint();
}
public BufferedImage getImage() {
return image;
}
/**
* <p>
* Tests whether an image uses the standard RGB color space.
* </p>
*/
public static boolean isStandardRGBImage(final BufferedImage bImage) {
return bImage.getColorModel().getColorSpace().isCS_sRGB();
}
private static BufferedImage toCompatibleImage(final BufferedImage image) {
if (image.getColorModel().equals(CONFIGURATION.getColorModel())) {
return image;
}
final BufferedImage compatibleImage =
CONFIGURATION.createCompatibleImage(image.getWidth(), image.getHeight(),
image.getTransparency());
final Graphics g = compatibleImage.getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return compatibleImage;
}
private static final GraphicsConfiguration CONFIGURATION =
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
private int getScreenImageWidth() {
return (int) (scale * image.getWidth());
}
private int getScreenImageHeight() {
return (int) (scale * image.getHeight());
}
// <editor-fold defaultstate="collapsed" desc=" <<< Position / Panning >>> ">
/** Centers the current image in the panel. */
private void centerImage() {
originX = (getWidth() - getScreenImageWidth()) / 2;
originY = (getHeight() - getScreenImageHeight()) / 2;
}
/**
* <p>
* Gets the image origin.
* </p>
* <p>
* Image origin is defined as the upper, left corner of the image in the
* panel's coordinate system.
* </p>
*
* @return the point of the upper, left corner of the image in the panel's
* coordinates system.
*/
@Override
public IntCoords getImageOrigin() {
return new IntCoords(originX, originY);
}
/**
* <p>
* Sets the image origin.
* </p>
* <p>
* Image origin is defined as the upper, left corner of the image in the
* panel's coordinate system. After a new origin is set, the image is
* repainted. This method is used for programmatic image navigation.
* </p>
*
* @param x the x coordinate of the new image origin
* @param y the y coordinate of the new image origin
*/
@Override
public void setImageOrigin(final int x, final int y) {
setImageOrigin(new IntCoords(x, y));
}
/**
* <p>
* Sets the image origin.
* </p>
* <p>
* Image origin is defined as the upper, left corner of the image in the
* panel's coordinate system. After a new origin is set, the image is
* repainted. This method is used for programmatic image navigation.
* </p>
*
* @param newOrigin the value of a new image origin
*/
@Override
public void setImageOrigin(final IntCoords newOrigin) {
originX = newOrigin.x;
originY = newOrigin.y;
repaint();
}
/** Pans the image by the given (X, Y) amount. */
@Override
public void pan(final int xDelta, final int yDelta) {
originX += xDelta;
originY += yDelta;
repaint();
}
// </editor-fold>
@Override
public void updateImage() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void addEventDispatcher(final EventDispatcher dispatcher) {
addKeyListener((AWTEventDispatcher) dispatcher);
addMouseListener((AWTEventDispatcher) dispatcher);
addMouseMotionListener((AWTEventDispatcher) dispatcher);
addMouseWheelListener((AWTEventDispatcher) dispatcher);
}
/*
* Handles setting of the cursor depending on the activated tool
*/
@Override
public void subscribeToToolEvents() {
final EventSubscriber<ToolActivatedEvent> toolSubscriber =
new EventSubscriber<ToolActivatedEvent>() {
@Override
public void onEvent(final ToolActivatedEvent event) {
setCursor(event.getTool().getCursor());
}
};
Events.subscribe(ToolActivatedEvent.class, toolSubscriber);
}
@Override
public void setCursor(final MouseCursor cursor) {
final int cursorCode = AWTCursorManager.getAWTCursorCode(cursor);
setCursor(Cursor.getPredefinedCursor(cursorCode));
}
// <editor-fold defaultstate="collapsed" desc=" <<< Coordinate XForms, Origin >>> ">
// Converts this panel's coordinates into the original image coordinates
@Override
public RealCoords panelToImageCoords(final IntCoords p) {
return new RealCoords((p.x - originX) / scale, (p.y - originY) / scale);
}
// Converts the original image coordinates into this panel's coordinates
@Override
public RealCoords imageToPanelCoords(final RealCoords p) {
return new RealCoords((p.x * scale) + originX, (p.y * scale) + originY);
}
// Tests whether a given point in the panel falls within the image boundaries.
@Override
public boolean isInImage(final IntCoords p) {
final RealCoords coords = panelToImageCoords(p);
final int x = coords.getIntX();
final int y = coords.getIntY();
return (x >= 0 && x < image.getWidth() && y >= 0 && y < image.getHeight());
}
// Tests whether the image is displayed in its entirety in the panel.
private boolean isFullImageInPanel() {
return (originX >= 0 && (originX + getScreenImageWidth()) < getWidth() &&
originY >= 0 && (originY + getScreenImageHeight()) < getHeight());
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="<<< Rendering Quality >>>">
/**
* <p>
* Indicates whether the high quality rendering feature is enabled.
* </p>
*
* @return true if high quality rendering is enabled, false otherwise.
*/
@Override
public boolean isHighQualityRenderingEnabled() {
return highQualityRenderingEnabled;
}
/**
* <p>
* Enables/disables high quality rendering.
* </p>
*
* @param enabled enables/disables high quality rendering
*/
@Override
public void setHighQualityRenderingEnabled(final boolean enabled) {
highQualityRenderingEnabled = enabled;
}
// High quality rendering kicks in when when a scaled image is larger
// than the original image. In other words,
// when image decimation stops and interpolation starts.
private boolean isHighQualityRendering() {
return (highQualityRenderingEnabled && scale > HIGH_QUALITY_RENDERING_SCALE_THRESHOLD);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc=" <<< Paint >>> ">
/**
* Gets the bounds of the image area currently displayed in the panel (in
* image coordinates).
*/
private Rectangle getImageClipBounds() {
final RealCoords startCoords = panelToImageCoords(new IntCoords(0, 0));
final RealCoords endCoords =
panelToImageCoords(new IntCoords(getWidth() - 1, getHeight() - 1));
final int panelX1 = startCoords.getIntX();
final int panelY1 = startCoords.getIntY();
final int panelX2 = endCoords.getIntX();
final int panelY2 = endCoords.getIntY();
// No intersection?
if (panelX1 >= image.getWidth() || panelX2 < 0 ||
panelY1 >= image.getHeight() || panelY2 < 0)
{
return null;
}
final int x1 = (panelX1 < 0) ? 0 : panelX1;
final int y1 = (panelY1 < 0) ? 0 : panelY1;
final int x2 =
(panelX2 >= image.getWidth()) ? image.getWidth() - 1 : panelX2;
final int y2 =
(panelY2 >= image.getHeight()) ? image.getHeight() - 1 : panelY2;
return new Rectangle(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
}
/**
* Paints the panel and its image at the current zoom level, location, and
* interpolation method dependent on the image scale.</p>
*
* @param g the <code>Graphics</code> context for painting
*/
@Override
protected void paintComponent(final Graphics g) {
super.paintComponent(g); // Paints the background
if (image == null) {
return;
}
if (scale == 0.0) {
initializeParams();
}
if (isHighQualityRendering()) {
final Rectangle rect = getImageClipBounds();
if (rect == null || rect.width == 0 || rect.height == 0) { // no part of
// image is
// displayed
// in the
// panel
return;
}
final BufferedImage subimage =
image.getSubimage(rect.x, rect.y, rect.width, rect.height);
final Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, INTERPOLATION_TYPE);
g2.drawImage(subimage, Math.max(0, originX), Math.max(0, originY), Math
.min((int) (subimage.getWidth() * scale), getWidth()), Math.min(
(int) (subimage.getHeight() * scale), getHeight()), null);
}
else {
g.drawImage(image, originX, originY, getScreenImageWidth(),
getScreenImageHeight(), null);
}
drawNavigationImage(g);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc=" <<< Resizing >>> ">
private void addResizeListener() {
// Handle component resizing
addComponentListener(new ComponentAdapter() {
@SuppressWarnings("synthetic-access")
@Override
public void componentResized(final ComponentEvent e) {
if (scale > 0.0) {
if (isFullImageInPanel()) {
centerImage();
}
else if (isImageEdgeInPanel()) {
scaleOrigin();
}
if (isNavigationImageEnabled()) {
createNavigationImage();
}
repaint();
}
previousPanelSize = getSize();
}
});
}
// Used when the image is resized.
private boolean isImageEdgeInPanel() {
if (previousPanelSize == null) {
return false;
}
return (originX > 0 && originX < previousPanelSize.width || originY > 0 &&
originY < previousPanelSize.height);
}
// Used when the panel is resized
private void scaleOrigin() {
originX = originX * getWidth() / previousPanelSize.width;
originY = originY * getHeight() / previousPanelSize.height;
repaint();
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc=" <<< Zooming >>> ">
/** Converts the specified zoom level to scale. */
private double zoomToScale(final double zoom) {
return initialScale * zoom;
}
/**
* <p>
* Gets the current zoom level.
* </p>
*
* @return the current zoom level
*/
@Override
public double getZoom() {
return scale / initialScale;
}
/**
* <p>
* Sets the zoom level used to display the image.
* </p>
* <p>
* This method is used in programmatic zooming. The zooming center is the
* point of the image closest to the center of the panel. After a new zoom
* level is set the image is repainted.
* </p>
*
* @param newZoom the zoom level used to display this panel's image.
*/
@Override
public void setZoom(final double newZoom) {
final IntCoords zoomingCenter =
new IntCoords(getWidth() / 2, getHeight() / 2);
setZoom(newZoom, zoomingCenter);
}
/**
* <p>
* Sets the zoom level used to display the image, and the zooming center,
* around which zooming is done.
* </p>
* <p>
* This method is used in programmatic zooming. After a new zoom level is set
* the image is repainted.
* </p>
*
* @param newZoom the zoom level used to display this panel's image.
*/
@Override
public void setZoom(final double newZoom, final IntCoords zoomingCenter) {
final RealCoords imageP = panelToImageCoords(zoomingCenter);
if (imageP.x < 0.0) {
imageP.x = 0.0;
}
if (imageP.y < 0.0) {
imageP.y = 0.0;
}
if (imageP.x >= image.getWidth()) {
imageP.x = image.getWidth() - 1.0;
}
if (imageP.y >= image.getHeight()) {
imageP.y = image.getHeight() - 1.0;
}
final RealCoords correctedP = imageToPanelCoords(imageP);
final double oldZoom = getZoom();
scale = zoomToScale(newZoom);
final RealCoords panelP = imageToPanelCoords(imageP);
originX += (correctedP.getIntX() - (int) panelP.x);
originY += (correctedP.getIntY() - (int) panelP.y);
firePropertyChange(ZOOM_LEVEL_CHANGED_PROPERTY, new Double(oldZoom),
new Double(getZoom()));
repaint();
}
// TODO - allow the increment to be a function
private double zoomIncrement = 0.2;
/**
* <p>
* Gets the current zoom increment.
* </p>
*
* @return the current zoom increment
*/
@Override
public double getZoomIncrement() {
return calculateZoomIncrement();
}
private double calculateZoomIncrement() {
return this.zoomIncrement;
}
/**
* <p>
* Sets a new zoom increment value.
* </p>
*
* @param newZoomIncrement new zoom increment value
*/
@Override
public void setZoomIncrement(final double newZoomIncrement) {
final double oldZoomIncrement = zoomIncrement;
zoomIncrement = newZoomIncrement;
firePropertyChange(ZOOM_INCREMENT_CHANGED_PROPERTY, new Double(
oldZoomIncrement), new Double(zoomIncrement));
}
// Zooms an image in the panel by repainting it at the new zoom level.
// The current mouse position is the zooming center.
private void zoomImage() {
final RealCoords imageP = panelToImageCoords(ptToCoords(mousePosition));
// check if zoomed in too close
if ((zoomFactor > 1) && (scale > initialScale))
{
// TODO - do we want minDimension instead?
int maxDimension = Math.max(image.getWidth(), image.getHeight());
// if zooming the image would show less than one pixel of image data
if ((maxDimension / getZoom()) < 1)
return; // DO NOT ZOOM ANY FARTHER
}
// check if zoomed out too far
if ((zoomFactor < 1) && (scale < initialScale))
{
// get boundaries of image in panel coords
final RealCoords nearCorner = imageToPanelCoords(new RealCoords(0,0));
final RealCoords farCorner = imageToPanelCoords(new RealCoords(image.getWidth(),image.getHeight()));
// if boundaries take up less than 25 pixels in either dimension
if (((farCorner.x - nearCorner.x) < 25) || ((farCorner.y - nearCorner.y < 25)))
return; // DO NOT ZOOM ANY FARTHER
}
final double oldZoom = getZoom();
scale *= zoomFactor;
final RealCoords panelP = imageToPanelCoords(imageP);
originX += (mousePosition.x - (int) panelP.x);
originY += (mousePosition.y - (int) panelP.y);
firePropertyChange(ZOOM_LEVEL_CHANGED_PROPERTY, new Double(oldZoom),
new Double(getZoom()));
repaint();
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc=" <<< NavigationImage >>> ">
private static final double SCREEN_NAV_IMAGE_FACTOR = 0.15; // 15% of panel's
// width
private static final double NAV_IMAGE_FACTOR = 0.3; // 30% of panel's width
private double navZoomFactor = 1.0 + zoomIncrement;
private double navScale = 0.0;
private boolean navigationImageEnabled = true;
private BufferedImage navigationImage;
private int navImageWidth;
private int navImageHeight;
// Creates and renders the navigation image in the upper let corner of the
// panel.
private void createNavigationImage() {
// We keep the original navigation image larger than initially
// displayed to allow for zooming into it without pixellation effect.
navImageWidth = (int) (getWidth() * NAV_IMAGE_FACTOR);
navImageHeight = navImageWidth * image.getHeight() / image.getWidth();
final int scrNavImageWidth = (int) (getWidth() * SCREEN_NAV_IMAGE_FACTOR);
// int scrNavImageHeight = scrNavImageWidth * image.getHeight() /
// image.getWidth();
navScale = (double) scrNavImageWidth / navImageWidth;
final GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice gs = ge.getDefaultScreenDevice();
final GraphicsConfiguration gc = gs.getDefaultConfiguration();
navigationImage =
gc.createCompatibleImage(navImageWidth, navImageHeight,
Transparency.OPAQUE);
final Graphics g = navigationImage.getGraphics();
g.drawImage(image, 0, 0, navImageWidth, navImageHeight, null);
}
private int getScreenNavImageWidth() {
return (int) (navScale * navImageWidth);
}
private int getScreenNavImageHeight() {
return (int) (navScale * navImageHeight);
}
// Converts the navigation image coordinates into the zoomed image coordinates
private IntCoords navToZoomedImageCoords(final IntCoords p) {
final int x = p.x * getScreenImageWidth() / getScreenNavImageWidth();
final int y = p.y * getScreenImageHeight() / getScreenNavImageHeight();
return new IntCoords(x, y);
}
// The user clicked within the navigation image and this part of the image
// is displayed in the panel. The clicked point of the image is centered in
// the panel.
private void displayImageAt(final IntCoords p) {
final IntCoords scrImagePoint = navToZoomedImageCoords(p);
originX = -(scrImagePoint.x - getWidth() / 2);
originY = -(scrImagePoint.y - getHeight() / 2);
repaint();
}
private IntCoords ptToCoords(final Point p) {
return new IntCoords(p.x, p.y);
}
/**
* <p>
* Indicates whether navigation image is enabled.
* <p>
*
* @return true when navigation image is enabled, false otherwise.
*/
@Override
public boolean isNavigationImageEnabled() {
return navigationImageEnabled;
}
/**
* <p>
* Enables/disables navigation with the navigation image.
* </p>
* <p>
* Navigation image should be disabled when custom, programmatic navigation is
* implemented.
* </p>
*
* @param enabled true when navigation image is enabled, false otherwise.
*/
@Override
public void setNavigationImageEnabled(final boolean enabled) {
navigationImageEnabled = enabled;
repaint();
}
// Tests whether a given point in the panel falls within the navigation image
// boundaries.
private boolean isInNavigationImage(final Point p) {
return (isNavigationImageEnabled() && p.x < getScreenNavImageWidth() && p.y < getScreenNavImageHeight());
}
// Zooms the navigation image
private void zoomNavigationImage() {
navScale *= navZoomFactor;
repaint();
}
private void drawNavigationImage(final Graphics g) {
// Draw navigation image
if (isNavigationImageEnabled()) {
g.drawImage(navigationImage, 0, 0, getScreenNavImageWidth(),
getScreenNavImageHeight(), null);
g.setColor(Color.blue);
g.drawRect(0, 0, getScreenNavImageWidth(), getScreenNavImageHeight());
drawZoomAreaOutline(g);
}
}
// Paints a white outline over the navigation image indicating
// the area of the image currently displayed in the panel.
private void drawZoomAreaOutline(final Graphics g) {
if (isFullImageInPanel()) {
return;
}
final int x = -originX * getScreenNavImageWidth() / getScreenImageWidth();
final int y =
-originY * getScreenNavImageHeight() / getScreenImageHeight();
final int width =
getWidth() * getScreenNavImageWidth() / getScreenImageWidth();
final int height =
getHeight() * getScreenNavImageHeight() / getScreenImageHeight();
g.setColor(Color.white);
g.drawRect(x, y, width, height);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc=" <<< Zoom Device >>> ">
// -- Zooming --
private WheelZoomDevice wheelZoomDevice = null;
private ButtonZoomDevice buttonZoomDevice = null;
@SuppressWarnings("synthetic-access")
private void addWheelZoomDevice() {
if (wheelZoomDevice == null) {
wheelZoomDevice = new WheelZoomDevice();
addMouseWheelListener(wheelZoomDevice);
}
}
@SuppressWarnings("synthetic-access")
private void addButtonZoomDevice() {
if (buttonZoomDevice == null) {
buttonZoomDevice = new ButtonZoomDevice();
addMouseListener(buttonZoomDevice);
}
}
private void removeWheelZoomDevice() {
if (wheelZoomDevice != null) {
removeMouseWheelListener(wheelZoomDevice);
wheelZoomDevice = null;
}
}
private void removeButtonZoomDevice() {
if (buttonZoomDevice != null) {
removeMouseListener(buttonZoomDevice);
buttonZoomDevice = null;
}
}
/**
* <p>
* Sets a new zoom device.
* </p>
*
* @param newZoomDevice specifies the type of a new zoom device.
*/
public void setZoomDevice(final ZoomDevice newZoomDevice) {
if (newZoomDevice == ZoomDevice.NONE) {
removeWheelZoomDevice();
removeButtonZoomDevice();
}
else if (newZoomDevice == ZoomDevice.MOUSE_BUTTON) {
removeWheelZoomDevice();
addButtonZoomDevice();
}
else if (newZoomDevice == ZoomDevice.MOUSE_WHEEL) {
removeButtonZoomDevice();
addWheelZoomDevice();
}
}
/**
* <p>
* Gets the current zoom device.
* </p>
*/
public ZoomDevice getZoomDevice() {
if (buttonZoomDevice != null) {
return ZoomDevice.MOUSE_BUTTON;
}
else if (wheelZoomDevice != null) {
return ZoomDevice.MOUSE_WHEEL;
}
else {
return ZoomDevice.NONE;
}
}
/**
* <p>
* Defines zoom devices.
* </p>
*/
public static class ZoomDevice {
/**
* <p>
* Identifies that the panel does not implement zooming, but the component
* using the panel does (programmatic zooming method).
* </p>
*/
public static final ZoomDevice NONE = new ZoomDevice("none");
/**
* <p>
* Identifies the left and right mouse buttons as the zooming device.
* </p>
*/
public static final ZoomDevice MOUSE_BUTTON =
new ZoomDevice("mouseButton");
/**
* <p>
* Identifies the mouse scroll wheel as the zooming device.
* </p>
*/
public static final ZoomDevice MOUSE_WHEEL = new ZoomDevice("mouseWheel");
private final String zoomDevice;
private ZoomDevice(final String zoomDevice) {
this.zoomDevice = zoomDevice;
}
@Override
public String toString() {
return zoomDevice;
}
}
private class WheelZoomDevice implements MouseWheelListener {
@SuppressWarnings("synthetic-access")
@Override
public void mouseWheelMoved(final MouseWheelEvent e) {
final Point p = e.getPoint();
final boolean zoomIn = (e.getWheelRotation() < 0);
if (isInNavigationImage(p)) {
if (zoomIn) {
navZoomFactor = 1.0 + zoomIncrement;
}
else {
navZoomFactor = 1.0 - zoomIncrement;
}
zoomNavigationImage();
}
else if (isInImage(ptToCoords(p))) {
if (zoomIn) {
zoomFactor = 1.0 + zoomIncrement;
}
else {
zoomFactor = 1.0 - zoomIncrement;
}
zoomImage();
}
}
}
private class ButtonZoomDevice extends MouseAdapter {
@SuppressWarnings("synthetic-access")
@Override
public void mouseClicked(final MouseEvent e) {
final Point p = e.getPoint();
if (SwingUtilities.isRightMouseButton(e)) {
if (isInNavigationImage(p)) {
navZoomFactor = 1.0 - zoomIncrement;
zoomNavigationImage();
}
else if (isInImage(ptToCoords(p))) {
zoomFactor = 1.0 - zoomIncrement;
zoomImage();
}
}
else {
if (isInNavigationImage(p)) {
navZoomFactor = 1.0 + zoomIncrement;
zoomNavigationImage();
}
else if (isInImage(ptToCoords(p))) {
zoomFactor = 1.0 + zoomIncrement;
zoomImage();
}
}
}
}
// </editor-fold>
public static void main(final String[] args) {
// if (args.length == 0) {
// System.out.println("Usage: java NavigableImagePanel imageFilename");
// System.exit(1);
final String filename = // args[0];
"diatoms.jpg";
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final JFrame frame = new JFrame("Navigable Image Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final NavigableImagePanel panel = new NavigableImagePanel();
try {
final BufferedImage image = ImageIO.read(new File(filename));
panel.setImage(image);
}
catch (final IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "",
JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
panel.setNavigationImageEnabled(true);
frame.getContentPane().add(panel, BorderLayout.CENTER);
final GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
final Rectangle bounds = ge.getMaximumWindowBounds();
frame.setSize(new Dimension(bounds.width, bounds.height));
frame.setVisible(true);
}
});
}
}
|
package hex.deeplearning;
import java.util.*;
import org.junit.BeforeClass;
import org.junit.Test;
import water.*;
import water.fvec.Frame;
import water.fvec.NFSFileVec;
import water.parser.ParseDataset;
import water.util.Log;
import static hex.deeplearning.DeepLearningModel.DeepLearningParameters;
import static org.junit.Assert.assertTrue;
public class DeepLearningReproducibilityTest extends TestUtil {
@BeforeClass() public static void setup() { stall_till_cloudsize(1); }
@Test
public void run() {
long seed = new Random().nextLong();
DeepLearningModel mymodel = null;
Frame train = null;
Frame test = null;
Frame data = null;
Map<Integer,Float> repeatErrs = new TreeMap<>();
int N = 3;
StringBuilder sb = new StringBuilder();
float repro_error = 0;
for (boolean repro : new boolean[]{true, false}) {
Scope.enter();
Frame[] preds = new Frame[N];
for (int repeat = 0; repeat < N; ++repeat) {
try {
NFSFileVec file = NFSFileVec.make(find_test_file("smalldata/junit/weather.csv"));
data = ParseDataset.parse(Key.make("data.hex"), file._key);
// Create holdout test data on clean data (before adding missing values)
train = data;
test = data;
// Build a regularized DL model with polluted training data, score on clean validation set
DeepLearningParameters p = new DeepLearningParameters();
p._train = train._key;
p._valid = test._key;
p._convert_to_enum = true;
p._destination_key = Key.make();
p._response_column = train.names()[train.names().length-1];
p._ignored_columns = new String[]{"EvapMM", "RISK_MM"}; //for weather data
p._activation = DeepLearningParameters.Activation.RectifierWithDropout;
p._hidden = new int[]{32, 58};
p._l1 = 1e-5;
p._l2 = 3e-5;
p._seed = 0xbebe;
p._input_dropout_ratio = 0.2;
p._train_samples_per_iteration = 3;
p._hidden_dropout_ratios = new double[]{0.4, 0.1};
p._epochs = 1.32;
p._quiet_mode = true;
p._reproducible = repro;
DeepLearning dl = new DeepLearning(p);
try {
mymodel = dl.trainModel().get();
} catch (Throwable t) {
t.printStackTrace();
throw new RuntimeException(t);
} finally {
dl.remove();
}
// Extract the scoring on validation set from the model
mymodel = DKV.getGet(p._destination_key);
preds[repeat] = mymodel.score(test);
repeatErrs.put(repeat, mymodel.error());
} catch (Throwable t) {
t.printStackTrace();
throw new RuntimeException(t);
} finally {
// cleanup
if (mymodel != null) {
mymodel.delete_xval_models();
mymodel.delete();
}
if (train != null) train.delete();
if (test != null) test.delete();
if (data != null) data.delete();
}
}
sb.append("Reproducibility: ").append(repro ? "on" : "off").append("\n");
sb.append("Repeat # --> Validation Error\n");
for (String s : Arrays.toString(repeatErrs.entrySet().toArray()).split(","))
sb.append(s.replace("=", " --> ")).append("\n");
sb.append('\n');
Log.info(sb.toString());
try {
if (repro) {
// check reproducibility
for (Float error : repeatErrs.values())
assertTrue(error.equals(repeatErrs.get(0)));
// exposes bug: no work gets done on remote if frame has only 1 chunk and is homed remotely.
for (Frame f : preds) {
assertTrue(TestUtil.isBitIdentical(f, preds[0]));
}
repro_error = repeatErrs.get(0);
} else {
// check standard deviation of non-reproducible mode
double mean = 0;
for (Float error : repeatErrs.values()) {
mean += error;
}
mean /= N;
// check non-reproducibility (Hogwild! will never reproduce)
for (int i=1; i<N; ++i)
assertTrue(repeatErrs.get(i) != repeatErrs.get(0));
Log.info("mean error: " + mean);
double stddev = 0;
for (Float error : repeatErrs.values()) {
stddev += (error - mean) * (error - mean);
}
stddev /= N;
stddev = Math.sqrt(stddev);
Log.info("standard deviation: " + stddev);
// assertTrue(stddev < 0.3 / Math.sqrt(N));
Log.info("difference to reproducible mode: " + Math.abs(mean - repro_error) / stddev + " standard deviations");
}
} finally {
for (Frame f : preds) if (f != null) f.delete();
}
Scope.exit();
}
}
}
|
package net.runelite.http.service.feed;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import net.runelite.http.api.feed.FeedItem;
import net.runelite.http.api.feed.FeedResult;
import net.runelite.http.service.feed.blog.BlogService;
import net.runelite.http.service.feed.osrsnews.OSRSNewsService;
import net.runelite.http.service.feed.twitter.TwitterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/feed")
@Slf4j
public class FeedController
{
private final BlogService blogService;
private final TwitterService twitterService;
private final OSRSNewsService osrsNewsService;
private static class MemoizedFeed
{
final FeedResult feedResult;
final String hash;
MemoizedFeed(FeedResult feedResult)
{
this.feedResult = feedResult;
Hasher hasher = Hashing.sha256().newHasher();
for (FeedItem itemPrice : feedResult.getItems())
{
hasher.putBytes(itemPrice.getTitle().getBytes()).putBytes(itemPrice.getContent().getBytes());
}
HashCode code = hasher.hash();
hash = code.toString();
}
}
private MemoizedFeed memoizedFeed;
@Autowired
public FeedController(BlogService blogService, TwitterService twitterService, OSRSNewsService osrsNewsService)
{
this.blogService = blogService;
this.twitterService = twitterService;
this.osrsNewsService = osrsNewsService;
}
@Scheduled(fixedDelay = 10 * 60 * 1000)
public void updateFeed()
{
List<FeedItem> items = new ArrayList<>();
try
{
items.addAll(blogService.getBlogPosts());
}
catch (Exception e)
{
log.warn("unable to fetch blogs", e);
}
try
{
items.addAll(twitterService.getTweets());
}
catch (Exception e)
{
log.warn("unable to fetch tweets", e);
}
try
{
items.addAll(osrsNewsService.getNews());
}
catch (Exception e)
{
log.warn("unable to fetch news", e);
}
memoizedFeed = new MemoizedFeed(new FeedResult(items));
}
@GetMapping
public ResponseEntity<FeedResult> getFeed()
{
if (memoizedFeed == null)
{
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
.cacheControl(CacheControl.noCache())
.build();
}
return ResponseEntity.ok()
.eTag(memoizedFeed.hash)
.cacheControl(CacheControl.maxAge(10, TimeUnit.MINUTES).cachePublic())
.body(memoizedFeed.feedResult);
}
}
|
package org.innovateuk.ifs.form.resource;
import java.util.Optional;
/**
* This enum marks sections as a given type.
*/
public enum SectionType {
FINANCE(),
PROJECT_COST_FINANCES(FINANCE),
PROJECT_LOCATION(FINANCE),
ORGANISATION_FINANCES(FINANCE),
FUNDING_FINANCES(FINANCE),
OVERVIEW_FINANCES(),
GENERAL(),
TERMS_AND_CONDITIONS();
private final SectionType parent;
SectionType() {
this.parent = null;
}
SectionType(SectionType parent) {
this.parent = parent;
}
public Optional<SectionType> getParent() {
return Optional.ofNullable(parent);
}
public String getNameLower() {
return this.name().toLowerCase();
}
}
|
package org.intermine.modelproduction;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.metadata.AttributeDescriptor;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.CollectionDescriptor;
import org.intermine.metadata.FieldDescriptor;
import org.intermine.metadata.MetaDataException;
import org.intermine.metadata.Model;
import org.intermine.metadata.ReferenceDescriptor;
import org.intermine.util.StringUtil;
/**
* Merge model additions into a source model to produce a new larger model.
*
* @author Thomas Riley
*/
public class ModelMerger
{
private static final Logger LOG = Logger.getLogger(ModelMerger.class);
/**
* Creates a new instance of ModelMerger.
*/
private ModelMerger() {
// empty
}
/**
* 'Merges' the information from the set of ClassDescriptors <code>classes</code>
* into the model <code>target</code>. This method does not actually modify
* <code>target</code> but creates and returns a new model containing updated class
* descriptors. Merging may involve the following actions:
*
* <ul>
* <li>Adding fields.
* <li>Adding references.
* <li>Adding collections.
* <li>Adding a new class.
* <li>Modifying inheritance hierarchy.
* </ul>
*
* @param original the existing model (not modified)
* @param classes set of ClassDescriptors containing new information to add to the model
* @return the resulting merged model
* @throws ModelMergerException if an error occurs during model mergining
*/
public static Model mergeModel(Model original, Set<ClassDescriptor> classes)
throws ModelMergerException {
Map<String, ClassDescriptor> newClasses = new HashMap<String, ClassDescriptor>();
for (ClassDescriptor mergeClass : classes) {
ClassDescriptor oldClass = original.getClassDescriptorByName(mergeClass.getName());
ClassDescriptor newClass;
// record this old class (
if (oldClass != null) {
// Merge two classes
newClass = mergeClass(oldClass, mergeClass, original, classes);
} else {
// It is a new class
newClass = cloneClassDescriptor(mergeClass);
}
newClasses.put(newClass.getName(), newClass);
}
// Find the original classes that weren't mentioned classes
for (ClassDescriptor oldClass : original.getClassDescriptors()) {
if (!newClasses.containsKey(oldClass.getName())) {
// We haven't merged this class so we add the old one
newClasses.put(oldClass.getName(), cloneClassDescriptor(oldClass));
}
}
// Remove any reference or collection descriptors made redundant by additions
newClasses = removeRedundancy(newClasses);
try {
Model newModel = new Model(original.getName(), original.getNameSpace().toString(),
new HashSet<ClassDescriptor>(newClasses.values()));
return newModel;
} catch (URISyntaxException err) {
throw new ModelMergerException(err);
} catch (MetaDataException err) {
throw new ModelMergerException(err);
}
}
/**
* When changes are made to the inheritance hierarchy (especially the addition of
* superinterfaces), fields may be defined on superinterfaces making previous definitions
* further down the inheritance hierarchy redundant. This method removes those redundant
* fields.
*
* @param classes starting collection of ClassDescriptors
* @return a new mapping from class name to ClassDescriptors
* @throws ModelMergerException if an error occurs during model merging
*/
protected static Map<String, ClassDescriptor> removeRedundancy(Map<String,
ClassDescriptor> classes) throws ModelMergerException {
Map<String, ClassDescriptor> newSet = new HashMap<String, ClassDescriptor>();
for (ClassDescriptor cd : classes.values()) {
Set<CollectionDescriptor> cdescs = cloneCollectionDescriptors(
cd.getCollectionDescriptors());
Set<AttributeDescriptor> adescs = cloneAttributeDescriptors(
cd.getAttributeDescriptors());
Set<ReferenceDescriptor> rdescs = cloneReferenceDescriptors(
cd.getReferenceDescriptors());
Set<String> supers = new HashSet<String>();
findAllSuperclasses(cd, classes, supers);
// Now remove any attributes, references or collections that are now defined
// in a superclass/superinterface
for (String sup : supers) {
ClassDescriptor scd = classes.get(sup);
// Check attributes
for (Iterator<AttributeDescriptor> aiter = adescs.iterator(); aiter.hasNext();) {
AttributeDescriptor ad = aiter.next();
if (scd.getAttributeDescriptorByName(ad.getName()) != null) {
LOG.info("removing attribute " + ad.getName()
+ " redefinition in " + cd.getName() + " (is now defined in "
+ scd.getName() + ")");
aiter.remove();
}
}
// Check references
for (Iterator<ReferenceDescriptor> riter = rdescs.iterator(); riter.hasNext();) {
ReferenceDescriptor rd = riter.next();
if (scd.getReferenceDescriptorByName(rd.getName()) != null) {
LOG.info("removing reference " + rd.getName()
+ " redefinition in " + cd.getName() + " (is now defined in "
+ scd.getName() + ")");
riter.remove();
}
}
// Check collections
for (Iterator<CollectionDescriptor> citer = cdescs.iterator(); citer.hasNext();) {
CollectionDescriptor cold = citer.next();
if (scd.getCollectionDescriptorByName(cold.getName()) != null) {
LOG.info("removing collection " + cold.getName()
+ " redefinition in " + cd.getName() + " (is now defined in "
+ scd.getName() + ")");
citer.remove();
}
}
}
String supersStr = toSupersString(cd.getSuperclassNames());
newSet.put(cd.getName(), new ClassDescriptor(cd.getName(), supersStr, cd.isInterface(),
cloneAttributeDescriptors(adescs),
cloneReferenceDescriptors(rdescs),
cloneCollectionDescriptors(cdescs)));
}
return newSet;
}
private static String toSupersString(Set<String> supers) {
String supersStr = StringUtil.join(supers, " ");
if (supersStr != null && supersStr.equals("")) {
supersStr = null;
}
return supersStr;
}
private static void findAllSuperclasses(ClassDescriptor cd,
Map<String, ClassDescriptor> classes, Set<String> names) throws ModelMergerException {
Set<String> supers = cd.getSuperclassNames();
names.addAll(supers);
for (String superClassName : supers) {
if (!"java.lang.Object".equals(superClassName)) {
ClassDescriptor cld = classes.get(superClassName);
if (cld == null) {
throw new ModelMergerException("cannot find superclass \"" + superClassName
+ "\" of " + cd + " in the model");
}
findAllSuperclasses(cld, classes, names);
}
}
}
/**
* Merge the attributes, collections and references from ClassDescriptor <code>merge</code>
* into the ClassDescriptor <code>original</code>. The two are different in that inheritance
* settings on the merge class can override the inheritance present in the original class.
* This method will throw a ModelMergerException if the two class descriptors return different
* values from <code>isInterface</code>.<p>
*
* If the original class extends a superclass, and the <code>merge</code> also specifies
* a superclass then the merge superclass will override the old superclass.<p>
*
* This method requires <code>originalModel</code> and <code>mergeClasses</code> so it can
* determine whether the superclass names in <code>merge</code> represente classes or
* interfaces.
*
* @param original the original ClassDescriptor
* @param merge the ClassDescriptor to merge into the original
* @param originalModel the original Model we're merging into
* @param mergeClasses the set of ClassDescriptors being merged
* @return ClassDescriptor merge "merged" into ClassDescriptor original
* @throws ModelMergerException if an error occurs during model merging
*/
public static ClassDescriptor mergeClass(ClassDescriptor original, ClassDescriptor merge,
Model originalModel, Set<ClassDescriptor> mergeClasses) throws ModelMergerException {
if (merge.isInterface() != original.isInterface()) {
throw new ModelMergerException(original.getName() + ".isInterface/"
+ original.isInterface() + " != " + merge.getName() + ".isInterface/"
+ merge.isInterface());
}
Set<AttributeDescriptor> attrs = mergeAttributes(original, merge);
Set<CollectionDescriptor> cols = mergeCollections(original, merge);
Set<ReferenceDescriptor> refs = mergeReferences(original, merge);
Set<String> supers = new TreeSet<String>();
boolean replacingSuperclass = false;
// Figure out if we're replacing the superclass
if (original.getSuperclassDescriptor() != null) {
Set<String> superNames = merge.getSuperclassNames();
for (String clsName : superNames) {
ClassDescriptor cld = originalModel.getClassDescriptorByName(clsName);
if (cld != null && !cld.isInterface()) {
replacingSuperclass = true;
break;
}
cld = descriptorByName(mergeClasses, clsName);
if (cld != null && !cld.isInterface()) {
replacingSuperclass = true;
break;
}
}
}
supers.addAll(original.getSuperclassNames());
supers.addAll(merge.getSuperclassNames());
if (replacingSuperclass) {
supers.remove(original.getSuperclassDescriptor().getName());
}
// supers can't be an empty string
String supersStr = StringUtil.join(supers, " ");
if (supersStr != null && supersStr.equals("")) {
supersStr = null;
}
return new ClassDescriptor(original.getName(), supersStr,
merge.isInterface(), attrs, refs, cols);
}
/**
* Merge the attributes of a target model class descriptor <code>original</code> with
* the attributes present in class descriptor <code>merge</code>. Returns a new set of
* AttributeDescriptors.
*
* @param original the target model class descriptor
* @param merge the additions
* @return new set of AttributeDescriptors
* @throws ModelMergerException if an error occurs during model mergining
*/
public static Set<AttributeDescriptor> mergeAttributes(ClassDescriptor original,
ClassDescriptor merge) throws ModelMergerException {
for (AttributeDescriptor merg : merge.getAttributeDescriptors()) {
// nb: does not look for references in superclasses/superinterfaces
AttributeDescriptor orig = original.getAttributeDescriptorByName(merg.getName());
if (orig != null) {
if (!merg.getType().equals(orig.getType())) {
String fldName = original.getName() + "." + orig.getName();
throw new ModelMergerException("type mismatch between attributes: "
+ fldName + ":" + merg.getType() + " != "
+ fldName + ":" + orig.getType());
}
}
}
Set<AttributeDescriptor> newSet = new HashSet<AttributeDescriptor>();
newSet.addAll(cloneAttributeDescriptors(original.getAttributeDescriptors()));
newSet.addAll(cloneAttributeDescriptors(merge.getAttributeDescriptors()));
return newSet;
}
/**
* Merge the collections of a target model class descriptor <code>original</code> with
* the collections present in class descriptor <code>merge</code>. Returns a new set of
* CollectionDescriptors.
*
* @param original the target model class descriptor
* @param merge the additions
* @return new set of CollectionDescriptors
* @throws ModelMergerException if an error occurs during model mergining
*/
public static Set<CollectionDescriptor> mergeCollections(ClassDescriptor original,
ClassDescriptor merge) throws ModelMergerException {
Set<CollectionDescriptor> newSet = new HashSet<CollectionDescriptor>();
newSet.addAll(cloneCollectionDescriptors(original.getCollectionDescriptors()));
for (CollectionDescriptor merg : merge.getCollectionDescriptors()) {
// nb: does not look for references in superclasses/superinterfaces
CollectionDescriptor orig = original.getCollectionDescriptorByName(merg.getName());
if (orig != null) {
// New descriptor may add a reverse reference field name
if (merg.getReverseReferenceFieldName() != null
&& orig.getReverseReferenceFieldName() == null) {
// This is a valid change - remove original descriptor and replace with new
removeFieldDescriptor(newSet, orig.getName());
newSet.add(cloneCollectionDescriptor(merg));
continue;
}
// Check for inconsistencies and throw exceptions if inconsistencies are found
if (!StringUtils.equals(merg.getReverseReferenceFieldName(),
orig.getReverseReferenceFieldName())) {
String fldName = original.getName() + "." + orig.getName();
throw new ModelMergerException("mismatch between reverse reference field name: "
+ fldName + "<-" + merg.getReverseReferenceFieldName() + " != "
+ fldName + "<-" + orig.getReverseReferenceFieldName());
}
if (!merg.getReferencedClassName().equals(orig.getReferencedClassName())) {
String fldName = original.getName() + "." + orig.getName();
throw new ModelMergerException("type mismatch between collection types: "
+ fldName + ":" + merg.getReferencedClassName() + " != "
+ fldName + ":" + orig.getReferencedClassName());
}
}
// New descriptor of no differences, so add merg to newSet
newSet.add(cloneCollectionDescriptor(merg));
}
return newSet;
}
/**
* Merge the references of a target model class descriptor <code>original</code> with
* the references present in class descriptor <code>merge</code>. Returns a new set of
* ReferenceDescriptors.
*
* @param original the target model class descriptor
* @param merge the additions
* @return new set of CollectionDescriptors
* @throws ModelMergerException if an error occurs during model mergining
*/
public static Set<ReferenceDescriptor> mergeReferences(ClassDescriptor original,
ClassDescriptor merge) throws ModelMergerException {
Set<ReferenceDescriptor> newSet = new HashSet<ReferenceDescriptor>();
newSet.addAll(cloneReferenceDescriptors(original.getReferenceDescriptors()));
for (ReferenceDescriptor merg : merge.getReferenceDescriptors()) {
// nb: does not look for references in superclasses/superinterfaces
ReferenceDescriptor orig = original.getReferenceDescriptorByName(merg.getName());
if (orig != null) {
// New descriptor may add a reverse reference field name
if (merg.getReverseReferenceFieldName() != null
&& orig.getReverseReferenceFieldName() == null) {
// This is a valid change - remove original descriptor and replace with new
removeFieldDescriptor(newSet, orig.getName());
newSet.add(cloneReferenceDescriptor(merg));
continue;
}
if (!merg.getReferencedClassName().equals(orig.getReferencedClassName())) {
String fldName = original.getName() + "." + orig.getName();
throw new ModelMergerException("type mismatch between reference types: "
+ fldName + ":" + merg.getReferencedClassName() + " != "
+ fldName + ":" + orig.getReferencedClassName());
}
if (!StringUtils.equals(merg.getReverseReferenceFieldName(),
orig.getReverseReferenceFieldName())) {
String fldName = original.getName() + "." + orig.getName();
throw new ModelMergerException("mismatch between reverse reference field name: "
+ fldName + "<-" + merg.getReverseReferenceFieldName() + " != "
+ fldName + "<-" + orig.getReverseReferenceFieldName());
}
}
// New descriptor of no differences, so add merg to newSet
newSet.add(cloneReferenceDescriptor(merg));
}
return newSet;
}
/**
* Clone a set of ReferenceDescriptors.
*
* @param refs a set of ReferenceDescriptors
* @return cloned set of ReferenceDescriptors
*/
protected static Set<ReferenceDescriptor> cloneReferenceDescriptors(
Set<ReferenceDescriptor> refs) {
Set<ReferenceDescriptor> copy = new HashSet<ReferenceDescriptor>();
for (ReferenceDescriptor ref : refs) {
copy.add(cloneReferenceDescriptor(ref));
}
return copy;
}
private static ReferenceDescriptor cloneReferenceDescriptor(ReferenceDescriptor ref) {
return new ReferenceDescriptor(ref.getName(), ref.getReferencedClassName(),
ref.getReverseReferenceFieldName());
}
/**
* Clone a set of CollectionDescriptors.
*
* @param refs a set of CollectionDescriptors
* @return cloned set of CollectionDescriptors
*/
protected static Set<CollectionDescriptor> cloneCollectionDescriptors(
Set<CollectionDescriptor> refs) {
Set<CollectionDescriptor> copy = new LinkedHashSet<CollectionDescriptor>();
for (CollectionDescriptor ref : refs) {
copy.add(cloneCollectionDescriptor(ref));
}
return copy;
}
private static CollectionDescriptor cloneCollectionDescriptor(CollectionDescriptor ref) {
return new CollectionDescriptor(ref.getName(), ref.getReferencedClassName(),
ref.getReverseReferenceFieldName());
}
/**
* Remove a FieldDescriptor from a Set of FieldDescriptors by name.
*
* @param fields set of FieldDescriptors
* @param name the field name
*/
protected static void removeFieldDescriptor(Set<? extends FieldDescriptor> fields,
String name) {
for (Iterator<? extends FieldDescriptor> iter = fields.iterator(); iter.hasNext();) {
FieldDescriptor desc = iter.next();
if (desc.getName().equals(name)) {
iter.remove();
return;
}
}
}
/**
* Clone a set of AttributeDescriptors.
*
* @param refs a set of AttributeDescriptors
* @return cloned set of AttributeDescriptors
*/
protected static Set<AttributeDescriptor> cloneAttributeDescriptors(
Set<AttributeDescriptor> refs) {
Set<AttributeDescriptor> copy = new HashSet<AttributeDescriptor>();
for (AttributeDescriptor ref : refs) {
copy.add(new AttributeDescriptor(ref.getName(), ref.getType()));
}
return copy;
}
/**
* Construct a ClassDescriptor that takes on all the properties of <code>cld</code>
* without attaching to a particular Model.
*
* @param cld the ClassDescriptor to clone
* @return cloned ClassDescriptor
*/
protected static ClassDescriptor cloneClassDescriptor(ClassDescriptor cld) {
// supers can't be an empty string
String supers = StringUtil.join(cld.getSuperclassNames(), " ");
if (supers != null && supers.equals("")) {
supers = null;
}
return new ClassDescriptor(cld.getName(), supers, cld.isInterface(),
cloneAttributeDescriptors(cld.getAttributeDescriptors()),
cloneReferenceDescriptors(cld.getReferenceDescriptors()),
cloneCollectionDescriptors(cld.getCollectionDescriptors()));
}
/**
* Find ClassDescriptor in set with given name.
*/
private static ClassDescriptor descriptorByName(Set<ClassDescriptor> clds, String name) {
for (ClassDescriptor cld : clds) {
if (cld.getName().equals(name)) {
return cld;
}
}
return null;
}
}
|
package autoChirp;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import autoChirp.tweetCreation.Tweet;
import autoChirp.tweetCreation.TweetGroup;
/**
* A class for database input/output. Includes methods to write in and read from
* the database
*
* @author Alena Geduldig
*
*/
public class DBConnector {
private static Connection connection;
/**
* connects to a database
*
* @param dbFilePath
* file to database
* @return connection
*
*/
public static Connection connect(String dbFilePath) {
// register the driver
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
System.out.print("DBConnector.connect: ");
e.printStackTrace();
}
try {
connection = DriverManager.getConnection("jdbc:sqlite:" + dbFilePath);
} catch (SQLException e) {
System.out.print("DBConnector.connect: ");
e.printStackTrace();
}
System.out.println("Database '" + dbFilePath + "' successfully opened");
return connection;
}
/**
* creates (or overrides) output-tables defined in dbCreationFileName
*
* @param dbCreationFileName
* file to the db-specification
*
*/
public static void createOutputTables(String dbCreationFileName) {
// read creationFile
StringBuffer sql = new StringBuffer();
BufferedReader in;
try {
in = new BufferedReader(new FileReader(dbCreationFileName));
String line = in.readLine();
while (line != null) {
sql.append(line + "\n");
line = in.readLine();
}
in.close();
} catch (IOException e) {
System.out.print("DBConnector.createOututTables: couldnt create outputtables");
e.printStackTrace();
}
try {
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
stmt.executeUpdate(sql.toString());
stmt.close();
connection.commit();
System.out.println("Initialized new output-database.");
} catch (SQLException e) {
System.out.print("DBConnector.createOututTables: couldnt create outputtable");
e.printStackTrace();
}
}
/**
* checks if the user with the given twitterID is already registered.
*
* @param twitter_id
* the global TwitterID
* @return returns the local userID if user already exists in the database,
* or -1 if not.
*/
public static int checkForUser(long twitter_id) {
int toReturn;
try {
connection.setAutoCommit(false);
String sql = "SELECT twitter_id, user_id FROM users WHERE (twitter_id = '" + twitter_id + "')";
Statement stmt = connection.createStatement();
ResultSet result = stmt.executeQuery(sql);
if (!result.next()) {
toReturn = -1;
} else {
toReturn = result.getInt(2);
}
stmt.close();
connection.commit();
return toReturn;
} catch (SQLException e) {
System.out.print("DBConnector: checkForUser: ");
e.printStackTrace();
return -1;
}
}
/**
* creates a new user in the table 'users' and returns its local userID
*
* @param twitterID
* the users global twitterID
* @param oauthToken
* the users twitter oauthToken
* @param oauthTokenSecret
* the users twitter oauthTokenSecret
* @return the local userID of the new user or -1 if insertion was not
* successful
*/
public static int insertNewUser(long twitterID, String oauthToken, String oauthTokenSecret) {
int toReturn;
try {
// insert user
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
String sql = "INSERT INTO users (twitter_id, oauth_token, oauth_token_secret) VALUES ('" + twitterID + "', "
+ "'" + oauthToken + "', " + "'" + oauthTokenSecret + "' )";
stmt.executeUpdate(sql);
stmt.close();
connection.commit();
// get userID
stmt = connection.createStatement();
sql = "SELECT last_insert_rowid();";
ResultSet result = stmt.executeQuery(sql);
toReturn = result.getInt(1);
stmt.close();
connection.commit();
} catch (SQLException e) {
System.out.println("DBConnector.insertNewUser: couldnt insert the new user " + twitterID);
e.printStackTrace();
toReturn = -1;
}
return toReturn;
}
/**
* returns the config.-attributes for the given userID as a string-array of
* lenth 3. config[0]: the users global twitterID config[1]: the users
* oauthToken config[2]: the users oauthTokenSecret
*
* @param userID
* userID
* @return string-array with twitterID (0), oauthToken (1) and
* oauthTokenSecret (2)
*/
public static String[] getUserConfig(int userID) {
String[] toReturn = null;
try {
connection.setAutoCommit(false);
String sql = "SELECT twitter_id, oauth_token, oauth_token_secret FROM users WHERE user_id = '" + userID
+ "';";
Statement stmt = connection.createStatement();
ResultSet result = stmt.executeQuery(sql);
if (!result.next()) {
return toReturn;
}
toReturn = new String[3];
toReturn[0] = Integer.toString(result.getInt(1));
toReturn[1] = result.getString(2);
toReturn[2] = result.getString(3);
stmt.close();
connection.commit();
} catch (Exception e) {
System.out.println("DBConnector: couldnt read config for user_id " + userID);
e.printStackTrace();
}
return toReturn;
}
/**
* writes a TweetGroup into the database and returns its new groupID.
* updates the tables 'groups' and 'tweets'.
*
* @param tweetGroup
* a TweetGroup-Object consisting of title, description and a
* list of tweets
* @param userID
* the users local userID
* @return the groupID of the inserted tweetGroup, or -1 if insertion failed
*
*/
public static int insertTweetGroup(TweetGroup tweetGroup, int userID) {
int toReturn;
try {
connection.setAutoCommit(false);
PreparedStatement prepUsers = connection
.prepareStatement("INSERT INTO groups(user_id, group_name, description, enabled) VALUES(?,?,?,?)");
PreparedStatement prepTweets = connection.prepareStatement(
"INSERT INTO tweets(user_id, group_id, scheduled_date, tweet, scheduled, tweeted, img_url, longitude, latitude) VALUES(?,?,?,?,?,?,?,?,?)");
// update table users
prepUsers.setInt(1, userID);
prepUsers.setString(2, tweetGroup.title);
prepUsers.setString(3, tweetGroup.description);
prepUsers.setBoolean(4, false);
prepUsers.executeUpdate();
// get groupID
Statement stmt = connection.createStatement();
String sql = "SELECT last_insert_rowid();";
ResultSet result = stmt.executeQuery(sql);
int group_id = result.getInt(1);
toReturn = group_id;
// update table 'tweets'
for (Tweet tweet : tweetGroup.tweets) {
prepTweets.setInt(1, userID);
prepTweets.setInt(2, group_id);
prepTweets.setString(3, tweet.tweetDate);
prepTweets.setString(4, tweet.content);
prepTweets.setBoolean(5, false);
prepTweets.setBoolean(6, false);
prepTweets.setString(7, tweet.imageUrl);
prepTweets.setFloat(8, tweet.longitude);
prepTweets.setFloat(9, tweet.latitude);
prepTweets.executeUpdate();
}
prepUsers.close();
prepTweets.close();
stmt.close();
connection.commit();
} catch (Exception e) {
System.out.print("DBConnector.insertTweets: Couldnt insert tweets ");
e.printStackTrace();
toReturn = -1;
}
return toReturn;
}
/**
* enables/disables (activates/deactivates) the given TweetGroup for
* tweeting (if userID fits to groupID) and updates the field 'enabled' in
* table 'groups'
*
* @param groupID
* groupID
* @param enabled
* to update
* @param userID
* userID
* @return returns true if update was successful
*/
public static boolean updateGroupStatus(int groupID, boolean enabled, int userID) {
try {
int boolint = (enabled) ? 1 : 0;
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
String sql = "UPDATE groups SET enabled = '" + boolint + "' WHERE (group_id = '" + groupID
+ "' AND user_id = '" + userID + "')";
stmt.executeUpdate(sql);
stmt.close();
connection.commit();
} catch (SQLException e) {
System.out.println("DBConnector.updateGroupStatus: couldnt update group-status");
e.printStackTrace();
return false;
}
return true;
}
/**
* flags the given tweet as scheduled (if userID fits to tweetID )
*
* @param tweetID
* tweetID
* @param userID
* userID
* @return returns true if update was successful
*/
public static boolean flagAsScheduled(int tweetID, int userID) {
try {
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
String sql = "UPDATE tweets SET scheduled = '1' WHERE (tweet_id = '" + tweetID + "' AND user_id = '"
+ userID + "')";
stmt.executeUpdate(sql);
stmt.close();
connection.commit();
} catch (SQLException e) {
System.out.print("DBConnector.flagAsScheduled: failed");
e.printStackTrace();
return false;
}
return true;
}
/**
* flags the given tweet as tweeted (if userID fits to tweetID )
*
* @param tweetID
* tweetID
* @param userID
* userID
* @return returns true if update was successful
*/
public static boolean flagAsTweeted(int tweetID, int userID) {
try {
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
String sql = "UPDATE tweets SET tweeted = '1' WHERE (tweet_id = '" + tweetID + "' AND user_id = '" + userID
+ "')";
stmt.executeUpdate(sql);
stmt.close();
connection.commit();
} catch (SQLException e) {
System.out.print("DBConnector.flagAsTweeted: failed");
e.printStackTrace();
return false;
}
return true;
}
/**
* deletes the TweetGroup with the given groupID in table 'groups' and all
* tweets in table 'tweets' related to this group
*
* @param groupID
* to delete
* @param userID
* userID
*/
public static void deleteGroup(int groupID, int userID) {
try {
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
String sql = "DELETE FROM groups WHERE group_id = '" + groupID + "' AND user_id = '" + userID + "'";
stmt.executeUpdate(sql);
stmt.close();
connection.commit();
sql = "DELETE FROM tweets WHERE group_id='" + groupID + "'";
stmt = connection.createStatement();
stmt.executeUpdate(sql);
stmt.close();
connection.commit();
} catch (SQLException e) {
System.out.println("DBConnector.deleteGroup:");
e.printStackTrace();
}
}
/**
* deletes a single tweet in table 'tweets'
*
* @param tweetID
* to delete
* @param userID
* userID
*/
public static void deleteTweet(int tweetID, int userID) {
try {
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
String sql = "DELETE FROM tweets WHERE tweet_id = '" + tweetID + "' AND user_id = '" + userID + "'";
stmt.executeUpdate(sql);
stmt.close();
connection.commit();
} catch (SQLException e) {
System.out.println("DBConnector.deleteTweet:");
e.printStackTrace();
}
}
/**
* returns a list of all tweets from the specified tweetGroup with the given
* scheduled- and tweeted-status
*
* @param userID
* userID
* @param scheduled
* selected scheduled status
* @param tweeted
* selected tweeted status
* @param groupID
* goupID
* @return a list of all tweets which satisfy the given status-combination
*/
public static List<Tweet> getTweetsForUser(int userID, boolean scheduled, boolean tweeted, int groupID) {
int scheduledInt = (scheduled) ? 1 : 0;
int tweetedInt = (tweeted) ? 1 : 0;
String query = "SELECT * FROM tweets WHERE(user_id = '" + userID + "' AND group_id = '" + groupID
+ "' AND scheduled = '" + scheduledInt + "' AND tweeted = '" + tweetedInt
+ "') ORDER BY scheduled_date ASC";
return getTweets(query, userID);
}
/**
* @param userID
* @param groupID
* @return all tweets with the given groupID
*/
private static List<Tweet> getTweetsForUser(int userID, int groupID) {
String query = "SELECT * FROM tweets WHERE(user_id = '" + userID + "' AND group_id = '" + groupID
+ "') ORDER BY scheduled_date ASC";
return getTweets(query, userID);
}
/**
* returns a list of all tweets of a user with the given scheduled- and
* tweeted-status
*
* @param userID
* iserID
* @param scheduled
* selected scheduled status
* @param tweeted
* selected tweeted status
* @return all tweets which satisfy the given status-combination
*/
public static List<Tweet> getTweetsForUser(int userID, boolean scheduled, boolean tweeted) {
int scheduledInt = (scheduled) ? 1 : 0;
int tweetedInt = (tweeted) ? 1 : 0;
String query = "SELECT * FROM tweets WHERE(user_id = '" + userID + "' AND scheduled = '" + scheduledInt
+ "' AND tweeted = '" + tweetedInt + "') ORDER BY scheduled_date ASC";
return getTweets(query, userID);
}
/**
* returns a list of all tweets from a user
*
* @param userID
* userID
* @return all tweets from the user
*/
public static List<Tweet> getTweetsForUser(int userID) {
String query = "SELECT * FROM tweets WHERE(user_id = '" + userID + "') ORDER BY scheduled_date ASC";
return getTweets(query, userID);
}
/**
*
* @param query
* @param userID
* @return list of tweets selected with the query
*/
private static List<Tweet> getTweets(String query, int userID) {
List<Tweet> toReturn = new ArrayList<Tweet>();
try {
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
Tweet tweet = new Tweet(result.getString(4), result.getString(5), result.getInt(1), result.getInt(3),
result.getBoolean(6), result.getBoolean(7), userID, result.getString(8), result.getFloat(9),
result.getFloat(10));
toReturn.add(tweet);
}
stmt.close();
connection.commit();
} catch (SQLException e) {
System.out.print("DBConnector.getTweets: ");
e.printStackTrace();
}
return toReturn;
}
/**
* returns the tweetGroup with the given groupID (if userID fits to groupID)
*
* @param userID
* userID
* @param groupID
* groupID
* @return tweetGroup with groupID
*/
public static TweetGroup getTweetGroupForUser(int userID, int groupID) {
try {
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
String sql = "SELECT group_name, description, enabled, group_id FROM groups WHERE (user_id = '" + userID
+ "' AND group_id = '" + groupID + "')";
ResultSet result = stmt.executeQuery(sql);
if (!result.next())
return null;
TweetGroup group = new TweetGroup(result.getInt(4), result.getString(1), result.getString(2),
result.getBoolean(3));
stmt.close();
connection.commit();
List<Tweet> tweets = getTweetsForUser(userID, groupID);
group.setTweets(tweets);
return group;
} catch (SQLException e) {
System.out.print("DBConnector.getTweetGroupForUser: ");
e.printStackTrace();
return null;
}
}
/**
* returns a list with all groupIDs for the given user
*
* @param userID
* userID
* @return groupIDs of the users group
*/
public static List<Integer> getGroupIDsForUser(int userID) {
List<Integer> toReturn = new ArrayList<Integer>();
try {
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
String sql = "SELECT group_id FROM groups WHERE (user_id = '" + userID + "')";
ResultSet result = stmt.executeQuery(sql);
while (result.next()) {
toReturn.add(result.getInt(1));
}
} catch (SQLException e) {
System.out.print("DBConnector.getGroupIDsForUser: ");
e.printStackTrace();
}
return toReturn;
}
/**
* reads a single tweet from the database specified by tweetID (if userID
* fits to tweetID)
*
* @param tweetID
* tweetID
* @param userID
* userID
* @return tweet with tweetID
*/
public static Tweet getTweetByID(int tweetID, int userID) {
Tweet toReturn = null;
try {
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
String sql = "SELECT * FROM tweets WHERE (tweet_id = '" + tweetID + "' AND user_id = '" + userID + "')";
ResultSet result = stmt.executeQuery(sql);
if (!result.next()) {
return null;
}
toReturn = new Tweet(result.getString(4), result.getString(5), result.getInt(1), result.getInt(3),
result.getBoolean(6), result.getBoolean(7), userID, result.getString(8), result.getFloat(9),
result.getFloat(10));
} catch (SQLException e) {
System.out.print("DBConnector.getGroupIDsForUser: ");
e.printStackTrace();
}
return toReturn;
}
/**
* returns the groupTitle of the given group (if userID fits to groupID)
*
* @param groupID
* groupID
* @param userID
* userID
* @return groupTitle of the given group
*/
public static String getGroupTitle(int groupID, int userID) {
String toReturn = null;
try {
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
String sql = "SELECT group_name FROM groups WHERE (group_id = '" + groupID + "' AND user_id = '" + userID
+ "')";
ResultSet result = stmt.executeQuery(sql);
if (!result.next()) {
return null;
}
toReturn = result.getString(1);
} catch (SQLException e) {
System.out.print("DBConnector.getGroupIDsForUser: ");
e.printStackTrace();
}
return toReturn;
}
/**
* updates a groups description or title in the database (if userID fits to
* groupID)
*
* @param groupID
* groupID
* @param title
* new title
* @param description
* new description
* @param userID
* userID
*/
public static void editGroup(int groupID, String title, String description, int userID) {
try {
connection.setAutoCommit(false);
PreparedStatement stmt = connection.prepareStatement("UPDATE groups SET group_name = ?, description = ? WHERE (group_id = ? AND user_id = ?)");
// String sql = "UPDATE groups SET group_name = '" + title + "', description = '" + description
// + "' WHERE (group_id = '" + groupID + "' AND user_id = '" + userID + "')";
stmt.setString(1,title);
stmt.setString(2, description);
stmt.setInt(3, groupID);
stmt.setInt(4, userID);
stmt.executeUpdate();
stmt.close();
connection.commit();
} catch (SQLException e) {
System.out.print("DBConnector.editGroup: ");
e.printStackTrace();
}
}
/**
* updates the content, imageUrl and/or geo-location of a single tweet (if
* userID fits to tweetID)
*
* @param tweetID
* tweetID
* @param content
* new content
* @param userID
* userID
* @param imageUrl
* new imageUrl
* @param longitude
* new longitude
* @param latitude
* new latitude
*/
public static void editTweet(int tweetID, String content, int userID, String imageUrl, float longitude,
float latitude) {
try {
connection.setAutoCommit(false);
PreparedStatement stmt = connection.prepareStatement("UPDATE tweets SET tweet = ?, img_url = ?, longitude = ?, latitude = ? WHERE (tweet_id = ? AND user_id = ?)");
// String sql = "UPDATE tweets SET tweet = '" + content + "', img_url = '" + imageUrl + "', longitude = '"
// + longitude + "', latitude = '" + latitude + "' WHERE (tweet_id = '" + tweetID
// + "' AND user_id = '" + userID + "')";
stmt.setString(1, content);
stmt.setString(2, imageUrl);
stmt.setFloat(3, longitude);
stmt.setFloat(4, latitude);
stmt.setInt(5, tweetID);
stmt.setInt(6, userID);
stmt.executeUpdate();
stmt.close();
connection.commit();
} catch (SQLException e) {
System.out.print("DBConnector.editTweet: ");
e.printStackTrace();
}
}
/**
* adds a single tweet to an existing group and returns its tweetID
*
* @param userID
* userID
* @param tweet
* to add
* @param groupID
* groupID
* @return tweetID of the new tweet
*/
public static int addTweetToGroup(int userID, Tweet tweet, int groupID) {
try {
connection.setAutoCommit(false);
//Statement stmt = connection.createStatement();
PreparedStatement prepStmt = connection.prepareStatement("INSERT INTO tweets (user_id, group_id, scheduled_date, tweet, scheduled, tweeted, img_url, longitude, latitude) VALUES(?,?,?,?,?,?,?,?,?)");
// String sql = "INSERT INTO tweets (user_id, group_id, scheduled_date, tweet, scheduled, tweeted, img_url, longitude, latitude) VALUES ('"
// + userID + "', " + "'" + groupID + "', " + "'" + tweet.tweetDate + "', " + "'" + tweet.content
// + "', " + "'false', 'false', '" + tweet.imageUrl + "', '" + tweet.longitude + "', '"
// + tweet.latitude + "' )";
prepStmt.setInt(1, userID);
prepStmt.setInt(2, groupID);
prepStmt.setString(3, tweet.tweetDate);
prepStmt.setString(4, tweet.content);
prepStmt.setBoolean(5, false);
prepStmt.setBoolean(6, false);
prepStmt.setString(7,tweet.imageUrl);
prepStmt.setFloat(8, tweet.longitude);
prepStmt.setFloat(9, tweet.latitude);
prepStmt.executeUpdate();
prepStmt.close();
connection.commit();
Statement stmt = connection.createStatement();
String sql = "SELECT last_insert_rowid();";
ResultSet result = stmt.executeQuery(sql);
int toReturn = result.getInt(1);
stmt.close();
prepStmt.close();
connection.commit();
DBConnector.updateGroupStatus(groupID, false, userID);
return toReturn;
} catch (SQLException e) {
System.out.print("DBConnector.addTweetToGroup: ");
e.printStackTrace();
return -1;
}
}
/**
* returns the status (enabled/disabled) of the given group
*
* @param groupID
* groupID
* @param userID
* userID
* @return enabled enabled status
*/
public static boolean isEnabledGroup(int groupID, int userID) {
try {
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
String sql = "SELECT enabled FROM groups WHERE (group_id = '" + groupID + "' AND user_id = '" + userID
+ "')";
ResultSet result = stmt.executeQuery(sql);
boolean enabled = result.getBoolean(1);
stmt.close();
connection.commit();
return enabled;
} catch (SQLException e) {
System.out.print("DBConnector.editTweet: ");
e.printStackTrace();
return false;
}
}
/**
*
* returns a map of all enabled (active) groups from the database, sorted by
* its usersIDs. This method is called once at the start of the application,
* to schedule all active tweets.
*
* @return a map of all active TweetGroups sorted by its users
*/
public static Map<Integer, List<TweetGroup>> getAllEnabledGroups() {
Map<Integer, List<TweetGroup>> toReturn = new HashMap<Integer, List<TweetGroup>>();
try {
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
String sql = "SELECT user_id, group_id FROM groups WHERE (enabled = '1')";
ResultSet result = stmt.executeQuery(sql);
TweetGroup group;
while (result.next()) {
int userID = result.getInt(1);
int groupID = result.getInt(2);
group = DBConnector.getTweetGroupForUser(userID, groupID);
List<TweetGroup> groupList = toReturn.get(userID);
if (groupList == null) {
groupList = new ArrayList<TweetGroup>();
}
groupList.add(group);
toReturn.put(userID, groupList);
}
stmt.close();
connection.commit();
} catch (SQLException e) {
System.out.print("DBConnector.getAllEnabledGroupsByUser: ");
e.printStackTrace();
}
return toReturn;
}
/**
* deletes a user from the database - deletes user config. from table
* 'users' - deletes all tweetGroups in table 'groups' - deletes all tweets
* in table 'tweets'
*
* @param userID
* userID
*/
public static void deleteUser(int userID) {
try {
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
String sql = "DELETE FROM users WHERE user_id = '" + userID + "'";
stmt.executeUpdate(sql);
stmt.close();
stmt = connection.createStatement();
sql = "DELETE FROM groups WHERE user_id = '" + userID + "'";
stmt.executeUpdate(sql);
stmt.close();
stmt = connection.createStatement();
sql = "DELETE FROM tweets WHERE user_id = '" + userID + "'";
stmt.executeUpdate(sql);
stmt.close();
connection.commit();
} catch (SQLException e) {
System.out.print("DBConnector.deleteUser: ");
e.printStackTrace();
}
}
}
|
package meizhuo.org.lightmeeting.acty;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import butterknife.InjectView;
import butterknife.OnClick;
import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import meizhuo.org.lightmeeting.R;
import meizhuo.org.lightmeeting.api.UserAPI;
import meizhuo.org.lightmeeting.app.BaseActivity;
import meizhuo.org.lightmeeting.imple.JsonResponseHandler;
import meizhuo.org.lightmeeting.utils.L;
import meizhuo.org.lightmeeting.widget.LoadingDialog;
public class Update_userdata extends BaseActivity {
@InjectView(R.id.lm_usercard_nickname) EditText lm_usercard_nickname;
@InjectView(R.id.lm_usercard_birth) EditText lm_usercard_birth;
@InjectView(R.id.lm_usercard_sex) TextView lm_usercard_sex;
@InjectView(R.id.lm_usercard_company) EditText lm_usercard_company;
@InjectView(R.id.lm_usercard_position) EditText lm_usercard_position;
@InjectView(R.id.lm_usercard_contactphone) EditText lm_usercard_contactphone;
@InjectView(R.id.lm_usercard_contactemail) EditText lm_usercard_contactemail;
LoadingDialog dialog;
ActionBar mActionBar;
String nickname,birth,sex,company,position,phone,email;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState,R.layout.acty_usercard_edit);
initData();
initLayout();
}
/**
intent.putExtra("nickname", member.getNickname());
intent.putExtra("birth", member.getBirth());
intent.putExtra("sex", member.getSex());
intent.putExtra("company", member.getCompany());
intent.putExtra("position", member.getPosition());
intent.putExtra("phone", member.getPhone());
intent.putExtra("email", member.getEmail());
*/
@Override
protected void initData() {
// TODO Auto-generated method stub
nickname = getIntent().getStringExtra("nickname");
birth = getIntent().getStringExtra("birth");
sex = getIntent().getStringExtra("sex");
company = getIntent().getStringExtra("company");
position = getIntent().getStringExtra("position");
phone = getIntent().getStringExtra("phone");
email = getIntent().getStringExtra("email");
}
/**
@InjectView(R.id.lm_usercard_nickname) EditText lm_usercard_nickname;
@InjectView(R.id.lm_usercard_birth) EditText lm_usercard_birth;
@InjectView(R.id.lm_usercard_sex) TextView lm_usercard_sex;
@InjectView(R.id.lm_usercard_company) EditText lm_usercard_company;
@InjectView(R.id.lm_usercard_position) EditText lm_usercard_position;
@InjectView(R.id.lm_usercard_contactphone) EditText lm_usercard_contactphone;
@InjectView(R.id.lm_usercard_contactemail) EditText lm_usercard_contactemail;
*/
@Override
protected void initLayout() {
// TODO Auto-generated method stub
lm_usercard_nickname.setText(nickname);
lm_usercard_birth.setText(birth);
lm_usercard_sex.setText(sex);
lm_usercard_company.setText(company);
lm_usercard_position.setText(position);
lm_usercard_contactphone.setText(phone);
lm_usercard_contactemail.setText(email);
mActionBar = getActionBar();
mActionBar.setDisplayHomeAsUpEnabled(true);
}
@OnClick(R.id.lm_usercard_save) public void save_userinfo(){
nickname = lm_usercard_nickname.getText().toString();
birth = lm_usercard_birth.getText().toString();
sex = lm_usercard_sex.getText().toString();
company = lm_usercard_company.getText().toString();
position = lm_usercard_position.getText().toString();
phone = lm_usercard_contactphone.getText().toString();
email = lm_usercard_contactemail.getText().toString();
if(sex.equals("")){
sex ="m";
}else{
sex = "f";
}
UserAPI.update(nickname, sex, phone, email, company, position, birth, new JsonResponseHandler() {
@Override
public void onOK(Header[] headers, JSONObject obj) {
// TODO Auto-generated method stub
try {
if(obj.getString("code").equals("20000")){
toast("");
Intent it = new Intent(Update_userdata.this, BusinessCard.class);
String nickname1 = nickname;
String birth1 = birth;
String sex1 = sex;
String company1 = birth;
String position1 = position;
String phone1 = phone;
String email1 = email;
it.putExtra("nickname", nickname1);
it.putExtra("birth",birth1);
it.putExtra("sex", sex1);
it.putExtra("company",company1);
it.putExtra("position", position1);
it.putExtra("phone", phone1);
it.putExtra("email", email1);
Update_userdata.this.setResult(205, it);
Update_userdata.this.finish();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onFaild(int errorType, int errorCode) {
// TODO Auto-generated method stub
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
default:
break;
}
return true;
}
}
|
package org.intermine.web.struts;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.tiles.ComponentContext;
import org.apache.struts.tiles.actions.TilesAction;
import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.InterMineBag;
import org.intermine.api.profile.Profile;
import org.intermine.api.query.WebResultsExecutor;
import org.intermine.api.results.WebResults;
import org.intermine.api.template.TemplatePopulator;
import org.intermine.api.template.TemplatePopulatorException;
import org.intermine.api.template.TemplateQuery;
import org.intermine.model.InterMineObject;
import org.intermine.pathquery.OrderElement;
import org.intermine.pathquery.Path;
import org.intermine.pathquery.PathException;
import org.intermine.pathquery.PathQuery;
import org.intermine.web.logic.results.PagedTable;
import org.intermine.web.logic.results.ReportObject;
import org.intermine.web.logic.session.SessionMethods;
public class ReportTemplateController extends TilesAction
{
private static final Logger LOG = Logger.getLogger(ReportTemplateController.class);
/**
* {@inheritDoc}
*/
@SuppressWarnings("null")
@Override
public ActionForward execute(ComponentContext context,
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
ReportObject reportObject = (ReportObject) context.getAttribute("reportObject");
InterMineBag interMineBag = (InterMineBag) context.getAttribute("interMineIdBag");
TemplateQuery template = (TemplateQuery) context.getAttribute("templateQuery");
// this is either a report page for an InterMineObject or a list analysis page
TemplateQuery populatedTemplate;
try {
if (reportObject != null) {
InterMineObject obj = reportObject.getObject();
template = updateView(template);
populatedTemplate = TemplatePopulator.populateTemplateWithObject(template, obj);
} else if (interMineBag != null) {
populatedTemplate = TemplatePopulator.populateTemplateWithBag(template,
interMineBag);
} else {
// should only have been called with an object or a bag
return null;
}
} catch (TemplatePopulatorException e) {
LOG.error("Error setting up template '" + template.getName() + "' on report page for"
+ ((reportObject == null) ? " bag " + interMineBag.getName()
: " object " + reportObject.getId()) + ".", e);
throw new RuntimeException("Error setting up template '" + template.getName()
+ "' on report page for" + ((reportObject == null) ? " bag "
+ interMineBag.getName() : " object " + reportObject.getId()) + ".", e);
}
Profile profile = SessionMethods.getProfile(session);
WebResultsExecutor executor = im.getWebResultsExecutor(profile);
WebResults webResults = executor.execute(populatedTemplate);
// if there was a problem running query ignore and don't put up results
if (webResults != null) {
PagedTable pagedResults = new PagedTable(webResults, 30);
pagedResults.setTableid("itt." + populatedTemplate.getName());
context.putAttribute("resultsTable", pagedResults);
}
return null;
}
/*
* Removed from the view all the direct attributes that aren't editable constraints
*/
private TemplateQuery updateView(TemplateQuery template) {
TemplateQuery templateQuery = template.clone();
List<String> viewPaths = templateQuery.getView();
PathQuery pathQuery = templateQuery.getPathQuery();
String rootClass = null;
try {
rootClass = templateQuery.getRootClass();
for (String viewPath : viewPaths) {
Path path = pathQuery.makePath(viewPath);
if (path.getElementClassDescriptors().size() == 1
&& path.getLastClassDescriptor().getUnqualifiedName().equals(rootClass)) {
if (templateQuery.getEditableConstraints(viewPath).isEmpty()) {
templateQuery.removeView(viewPath);
for (OrderElement oe : templateQuery.getOrderBy()) {
if (oe.getOrderPath().equals(viewPath)) {
templateQuery.removeOrderBy(viewPath);
}
}
}
}
}
} catch (PathException pe) {
LOG.error("Error updating the template's view", pe);
}
return templateQuery;
}
}
|
package org.javarosa.demo.shell;
import java.util.Hashtable;
import javax.microedition.midlet.MIDlet;
import org.javarosa.activity.splashscreen.SplashScreenActivity;
import org.javarosa.communication.http.HttpTransportModule;
import org.javarosa.communication.http.HttpTransportProperties;
import org.javarosa.communication.ui.CommunicationUIModule;
import org.javarosa.core.Context;
import org.javarosa.core.JavaRosaServiceProvider;
import org.javarosa.core.api.Constants;
import org.javarosa.core.api.IActivity;
import org.javarosa.core.api.IShell;
import org.javarosa.core.api.IView;
import org.javarosa.core.model.CoreModelModule;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.instance.DataModelTree;
import org.javarosa.core.model.storage.FormDefRMSUtility;
import org.javarosa.core.services.properties.JavaRosaPropertyRules;
import org.javarosa.core.services.transport.TransportMethod;
import org.javarosa.core.util.PropertyUtils;
import org.javarosa.core.util.WorkflowStack;
import org.javarosa.demo.properties.DemoAppProperties;
import org.javarosa.formmanager.FormManagerModule;
import org.javarosa.formmanager.activity.FormEntryActivity;
import org.javarosa.formmanager.activity.FormEntryContext;
import org.javarosa.formmanager.activity.FormListActivity;
import org.javarosa.formmanager.activity.FormTransportActivity;
import org.javarosa.formmanager.activity.ModelListActivity;
import org.javarosa.formmanager.utility.FormDefSerializer;
import org.javarosa.formmanager.utility.TransportContext;
import org.javarosa.formmanager.view.Commands;
import org.javarosa.formmanager.view.chatterbox.widget.ExtendedWidgetsModule;
import org.javarosa.j2me.storage.rms.RMSStorageModule;
import org.javarosa.model.xform.XFormSerializingVisitor;
import org.javarosa.model.xform.XFormsModule;
import org.javarosa.referral.ReferralModule;
import org.javarosa.services.properties.activity.PropertyScreenActivity;
import org.javarosa.user.activity.AddUserActivity;
import org.javarosa.user.activity.LoginActivity;
import org.javarosa.user.model.User;
import org.javarosa.xform.util.XFormUtils;
/**
* This is the shell for the JavaRosa demo that handles switching all of the views
* @author Brian DeRenzi
*
*/
public class JavaRosaDemoShell implements IShell {
// List of views that are used by this shell
MIDlet midlet;
WorkflowStack stack;
Context context;
IActivity currentActivity;
IActivity mostRecentListActivity; //should never be accessed, only checked for type
public JavaRosaDemoShell() {
stack = new WorkflowStack();
context = new Context();
}
public void exitShell() {
midlet.notifyDestroyed();
}
public void run() {
init();
workflow(null, null, null);
}
private void init() {
loadModules();
loadProperties();
FormDefRMSUtility formDef = (FormDefRMSUtility)JavaRosaServiceProvider.instance().getStorageManager().getRMSStorageProvider().getUtility(FormDefRMSUtility.getUtilityName());
if (formDef.getNumberOfRecords() == 0) {
formDef.writeToRMS(XFormUtils.getFormFromResource("/hmis-a_draft.xhtml"));
formDef.writeToRMS(XFormUtils.getFormFromResource("/hmis-b_draft.xhtml"));
formDef.writeToRMS(XFormUtils.getFormFromResource("/shortform.xhtml"));
formDef.writeToRMS(XFormUtils.getFormFromResource("/tz-e-ctc.xhtml"));
formDef.writeToRMS(XFormUtils.getFormFromResource("/CHMTTL.xhtml"));
formDef.writeToRMS(XFormUtils.getFormFromResource("/condtest.xhtml"));
}
}
private void loadModules() {
new RMSStorageModule().registerModule(context);
new XFormsModule().registerModule(context);
new CoreModelModule().registerModule(context);
new HttpTransportModule().registerModule(context);
new FormManagerModule().registerModule(context);
new ExtendedWidgetsModule().registerModule(context);
new CommunicationUIModule().registerModule(context);
new ReferralModule().registerModule(context);
}
private void generateSerializedForms(String originalResource) {
FormDef a = XFormUtils.getFormFromResource(originalResource);
FormDefSerializer fds = new FormDefSerializer();
fds.setForm(a);
fds.setFname(originalResource+".serialized");
new Thread(fds).start();
}
private void workflow(IActivity lastActivity, String returnCode, Hashtable returnVals) {
if (returnVals == null)
returnVals = new Hashtable(); //for easier processing
if (lastActivity != currentActivity) {
System.out.println("Received 'return' event from activity other than the current activity" +
" (such as a background process). Can't handle this yet. Saw: " +
lastActivity + " but expecting: " + currentActivity);
return;
}
if (returnCode == Constants.ACTIVITY_SUSPEND || returnCode == Constants.ACTIVITY_NEEDS_RESOLUTION) {
stack.push(lastActivity);
workflowLaunch(lastActivity, returnCode, returnVals);
} else {
if (stack.size() > 0) {
workflowResume(stack.pop(), lastActivity, returnCode, returnVals);
} else {
workflowLaunch(lastActivity, returnCode, returnVals);
if (lastActivity != null)
lastActivity.destroy();
}
}
}
private void workflowLaunch (IActivity returningActivity, String returnCode, Hashtable returnVals) {
if (returningActivity == null) {
launchActivity(new SplashScreenActivity(this, "/splash.gif"), context);
} else if (returningActivity instanceof SplashScreenActivity) {
//#if javarosa.dev.shortcuts
launchActivity(new FormListActivity(this, "Forms List"), context);
//#else
String passwordVAR = midlet.getAppProperty("username");
String usernameVAR = midlet.getAppProperty("password");
if ((usernameVAR == null) || (passwordVAR == null))
{
context.setElement("username","admin");
context.setElement("password","p");
}
else{
context.setElement("username",usernameVAR);
context.setElement("password",passwordVAR);
}
context.setElement("authorization", "admin");
launchActivity(new LoginActivity(this, "Login"), context);
//#endif
} else if (returningActivity instanceof LoginActivity) {
Object returnVal = returnVals.get(LoginActivity.COMMAND_KEY);
if (returnVal == "USER_VALIDATED") {
User user = (User)returnVals.get(LoginActivity.USER);
if (user != null){
context.setCurrentUser(user.getUsername());
context.setElement("USER", user);
}
launchActivity(new FormListActivity(this, "Forms List"), context);
} else if (returnVal == "USER_CANCELLED") {
exitShell();
}
} else if (returningActivity instanceof FormListActivity) {
String returnVal = (String)returnVals.get(FormListActivity.COMMAND_KEY);
if (returnVal == Commands.CMD_SETTINGS) {
launchActivity(new PropertyScreenActivity(this), context);
} else if (returnVal == Commands.CMD_VIEW_DATA) {
launchActivity(new ModelListActivity(this), context);
} else if (returnVal == Commands.CMD_SELECT_XFORM) {
launchFormEntryActivity(context, ((Integer)returnVals.get(FormListActivity.FORM_ID_KEY)).intValue(), -1);
} else if (returnVal == Commands.CMD_EXIT)
exitShell();
else if (returnVal == Commands.CMD_ADD_USER)
launchActivity( new AddUserActivity(this),context);
} else if (returningActivity instanceof ModelListActivity) {
Object returnVal = returnVals.get(ModelListActivity.returnKey);
if (returnVal == ModelListActivity.CMD_MSGS) {
launchFormTransportActivity(context, TransportContext.MESSAGE_VIEW, null);
} else if (returnVal == ModelListActivity.CMD_EDIT) {
launchFormEntryActivity(context, ((FormDef)returnVals.get("form")).getID(),
((DataModelTree)returnVals.get("data")).getId());
} else if (returnVal == ModelListActivity.CMD_SEND) {
launchFormTransportActivity(context, TransportContext.SEND_DATA, (DataModelTree)returnVals.get("data"));
} else if (returnVal == ModelListActivity.CMD_BACK) {
launchActivity(new FormListActivity(this, "Forms List"), context);
}
} else if (returningActivity instanceof FormEntryActivity) {
if (((Boolean)returnVals.get("FORM_COMPLETE")).booleanValue()) {
launchFormTransportActivity(context, TransportContext.SEND_DATA, (DataModelTree)returnVals.get("DATA_MODEL"));
} else {
relaunchListActivity();
}
} else if (returningActivity instanceof FormTransportActivity) {
if(returnVals.get(FormTransportActivity.RETURN_KEY ) == FormTransportActivity.NEW_DESTINATION) {
TransportMethod transport = JavaRosaServiceProvider.instance().getTransportManager().getTransportMethod(JavaRosaServiceProvider.instance().getTransportManager().getCurrentTransportMethod());
IActivity activity = transport.getDestinationRetrievalActivity();
activity.setShell(this);
this.launchActivity(activity, context);
} else {
relaunchListActivity();
}
//what is this for?
/*if (returnCode == Constants.ACTIVITY_NEEDS_RESOLUTION) {
String returnVal = (String)returnVals.get(FormTransportActivity.RETURN_KEY);
if(returnVal == FormTransportActivity.VIEW_MODELS) {
currentActivity = this.modelActivity;
this.modelActivity.start(context);
}
}*/
}
else if (returningActivity instanceof AddUserActivity)
launchActivity(new FormListActivity(this, "Forms List"), context);
}
private void workflowResume (IActivity suspendedActivity, IActivity completingActivity,
String returnCode, Hashtable returnVals) {
//default action
Context newContext = new Context(context);
newContext.addAllValues(returnVals);
resumeActivity(suspendedActivity, newContext);
}
private void launchActivity (IActivity activity, Context context) {
if (activity instanceof FormListActivity || activity instanceof ModelListActivity)
mostRecentListActivity = activity;
currentActivity = activity;
activity.start(context);
}
private void resumeActivity (IActivity activity, Context context) {
currentActivity = activity;
activity.resume(context);
}
private void launchFormEntryActivity (Context context, int formID, int instanceID) {
FormEntryActivity entryActivity = new FormEntryActivity(this, new FormEntryViewFactory());
FormEntryContext formEntryContext = new FormEntryContext(context);
formEntryContext.setFormID(formID);
if (instanceID != -1)
formEntryContext.setInstanceID(instanceID);
launchActivity(entryActivity, formEntryContext);
}
private void launchFormTransportActivity (Context context, String task, DataModelTree data) {
FormTransportActivity formTransport = new FormTransportActivity(this);
formTransport.setDataModelSerializer(new XFormSerializingVisitor());
formTransport.setData(data); //why isn't this going in the context?
TransportContext msgContext = new TransportContext(context);
msgContext.setRequestedTask(task);
launchActivity(formTransport, msgContext);
}
private void relaunchListActivity () {
if (mostRecentListActivity instanceof FormListActivity) {
launchActivity(new FormListActivity(this, "Forms List"), context);
} else if (mostRecentListActivity instanceof ModelListActivity) {
launchActivity(new ModelListActivity(this), context);
} else {
throw new IllegalStateException("Trying to resume list activity when no most recent set");
}
}
/* (non-Javadoc)
* @see org.javarosa.shell.IShell#activityCompeleted(org.javarosa.activity.IActivity)
*/
public void returnFromActivity(IActivity activity, String returnCode, Hashtable returnVals) {
//activity.halt(); //i don't think this belongs here? the contract reserves halt for unexpected halts;
//an activity calling returnFromActivity isn't halting unexpectedly
workflow(activity, returnCode, returnVals);
}
public boolean setDisplay(IActivity callingActivity, IView display) {
if(callingActivity == currentActivity) {
JavaRosaServiceProvider.instance().getDisplay().setView(display);
return true;
}
else {
//#if debug.output==verbose
System.out.println("Activity: " + callingActivity + " attempted, but failed, to set the display");
//#endif
return false;
}
}
public void setMIDlet(MIDlet midlet) {
this.midlet = midlet;
}
private void loadProperties() {
JavaRosaServiceProvider.instance().getPropertyManager().addRules(new JavaRosaPropertyRules());
JavaRosaServiceProvider.instance().getPropertyManager().addRules(new DemoAppProperties());
PropertyUtils.initializeProperty("DeviceID", PropertyUtils.genGUID(25));
PropertyUtils.initializeProperty(HttpTransportProperties.POST_URL_LIST_PROPERTY, "http://dev.cell-life.org/javarosa/web/limesurvey/admin/post2lime.php");
PropertyUtils.initializeProperty(HttpTransportProperties.POST_URL_PROPERTY, "http://dev.cell-life.org/javarosa/web/limesurvey/admin/post2lime.php");
}
}
|
package org.eclipse.jetty.server;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.ssl.SslConnection;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.IO;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.matchers.JUnitMatchers.containsString;
public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
{
protected static final int MAX_IDLE_TIME=500;
private int sleepTime = MAX_IDLE_TIME + MAX_IDLE_TIME/5;
private int minimumTestRuntime = MAX_IDLE_TIME-MAX_IDLE_TIME/5;
private int maximumTestRuntime = MAX_IDLE_TIME*10;
static
{
System.setProperty("org.eclipse.jetty.io.nio.IDLE_TICK","100");
}
@Test
public void testMaxIdleWithRequest10() throws Exception
{
configureServer(new HelloWorldHandler());
Socket client=newSocket(HOST,_connector.getLocalPort());
client.setSoTimeout(10000);
assertFalse(client.isClosed());
OutputStream os=client.getOutputStream();
InputStream is=client.getInputStream();
os.write((
"GET / HTTP/1.0\r\n"+
"host: "+HOST+":"+_connector.getLocalPort()+"\r\n"+
"connection: keep-alive\r\n"+
"\r\n").getBytes("utf-8"));
os.flush();
long start = System.currentTimeMillis();
IO.toString(is);
Thread.sleep(sleepTime);
assertEquals(-1, is.read());
Assert.assertTrue(System.currentTimeMillis()-start>minimumTestRuntime);
Assert.assertTrue(System.currentTimeMillis()-start<maximumTestRuntime);
}
@Test
public void testMaxIdleWithRequest11() throws Exception
{
configureServer(new EchoHandler());
Socket client=newSocket(HOST,_connector.getLocalPort());
client.setSoTimeout(10000);
assertFalse(client.isClosed());
OutputStream os=client.getOutputStream();
InputStream is=client.getInputStream();
String content="Wibble";
byte[] contentB=content.getBytes("utf-8");
os.write((
"POST /echo HTTP/1.1\r\n"+
"host: "+HOST+":"+_connector.getLocalPort()+"\r\n"+
"content-type: text/plain; charset=utf-8\r\n"+
"content-length: "+contentB.length+"\r\n"+
"\r\n").getBytes("utf-8"));
os.write(contentB);
os.flush();
long start = System.currentTimeMillis();
IO.toString(is);
Thread.sleep(sleepTime);
assertEquals(-1, is.read());
Assert.assertTrue(System.currentTimeMillis()-start>minimumTestRuntime);
Assert.assertTrue(System.currentTimeMillis()-start<maximumTestRuntime);
}
@Test
public void testMaxIdleWithRequest10NoClientClose() throws Exception
{
final Exchanger<EndPoint> exchanger = new Exchanger<>();
configureServer(new HelloWorldHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException,
ServletException
{
try
{
exchanger.exchange(baseRequest.getHttpChannel().getEndPoint());
}
catch (Exception e)
{
e.printStackTrace();
}
super.handle(target, baseRequest, request, response);
}
});
Socket client=newSocket(HOST,_connector.getLocalPort());
client.setSoTimeout(10000);
assertFalse(client.isClosed());
OutputStream os=client.getOutputStream();
InputStream is=client.getInputStream();
os.write((
"GET / HTTP/1.0\r\n"+
"host: "+HOST+":"+_connector.getLocalPort()+"\r\n"+
"connection: close\r\n"+
"\r\n").getBytes("utf-8"));
os.flush();
// Get the server side endpoint
EndPoint endPoint = exchanger.exchange(null,10,TimeUnit.SECONDS);
if (endPoint instanceof SslConnection.DecryptedEndPoint)
endPoint=endPoint.getConnection().getEndPoint();
// read the response
String result=IO.toString(is);
Assert.assertThat("OK",result,containsString("200 OK"));
// check client reads EOF
assertEquals(-1, is.read());
// wait for idle timeout
TimeUnit.MILLISECONDS.sleep(3 * MAX_IDLE_TIME);
// further writes will get broken pipe or similar
try
{
for (int i=0;i<1000;i++)
{
os.write((
"GET / HTTP/1.0\r\n"+
"host: "+HOST+":"+_connector.getLocalPort()+"\r\n"+
"connection: keep-alive\r\n"+
"\r\n").getBytes("utf-8"));
os.flush();
}
Assert.fail("half close should have timed out");
}
catch(SocketException e)
{
// expected
}
// check the server side is closed
Assert.assertFalse(endPoint.isOpen());
}
@Test
public void testMaxIdleWithRequest10ClientIgnoresClose() throws Exception
{
final Exchanger<EndPoint> exchanger = new Exchanger<>();
configureServer(new HelloWorldHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException,
ServletException
{
try
{
exchanger.exchange(baseRequest.getHttpChannel().getEndPoint());
}
catch (Exception e)
{
e.printStackTrace();
}
super.handle(target, baseRequest, request, response);
}
});
Socket client=newSocket(HOST,_connector.getLocalPort());
client.setSoTimeout(10000);
assertFalse(client.isClosed());
OutputStream os=client.getOutputStream();
InputStream is=client.getInputStream();
os.write((
"GET / HTTP/1.0\r\n"+
"host: "+HOST+":"+_connector.getLocalPort()+"\r\n"+
"connection: close\r\n"+
"\r\n").getBytes("utf-8"));
os.flush();
// Get the server side endpoint
EndPoint endPoint = exchanger.exchange(null,10,TimeUnit.SECONDS);
if (endPoint instanceof SslConnection.DecryptedEndPoint)
endPoint=endPoint.getConnection().getEndPoint();
// read the response
String result=IO.toString(is);
Assert.assertThat("OK",result,containsString("200 OK"));
// check client reads EOF
assertEquals(-1, is.read());
// further writes will get broken pipe or similar
try
{
for (int i=0;i<1000;i++)
{
os.write((
"GET / HTTP/1.0\r\n"+
"host: "+HOST+":"+_connector.getLocalPort()+"\r\n"+
"connection: keep-alive\r\n"+
"\r\n").getBytes("utf-8"));
os.flush();
}
Assert.fail("half close should have timed out");
}
catch(SocketException e)
{
// expected
}
Thread.sleep(2 * MAX_IDLE_TIME);
// check the server side is closed
Assert.assertFalse(endPoint.isOpen());
}
@Test
public void testMaxIdleWithRequest11NoClientClose() throws Exception
{
final Exchanger<EndPoint> exchanger = new Exchanger<>();
configureServer(new EchoHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException,
ServletException
{
try
{
exchanger.exchange(baseRequest.getHttpChannel().getEndPoint());
}
catch (Exception e)
{
e.printStackTrace();
}
super.handle(target, baseRequest, request, response);
}
});
Socket client=newSocket(HOST,_connector.getLocalPort());
client.setSoTimeout(10000);
assertFalse(client.isClosed());
OutputStream os=client.getOutputStream();
InputStream is=client.getInputStream();
String content="Wibble";
byte[] contentB=content.getBytes("utf-8");
os.write((
"POST /echo HTTP/1.1\r\n" +
"host: " + HOST + ":" + _connector.getLocalPort() + "\r\n" +
"content-type: text/plain; charset=utf-8\r\n" +
"content-length: " + contentB.length + "\r\n" +
"connection: close\r\n" +
"\r\n").getBytes("utf-8"));
os.write(contentB);
os.flush();
// Get the server side endpoint
EndPoint endPoint = exchanger.exchange(null,10,TimeUnit.SECONDS);
// read the response
IO.toString(is);
// check client reads EOF
assertEquals(-1, is.read());
TimeUnit.MILLISECONDS.sleep(3*MAX_IDLE_TIME);
// further writes will get broken pipe or similar
try
{
for (int i=0;i<1000;i++)
{
os.write((
"GET / HTTP/1.0\r\n"+
"host: "+HOST+":"+_connector.getLocalPort()+"\r\n"+
"connection: keep-alive\r\n"+
"\r\n").getBytes("utf-8"));
os.flush();
}
Assert.fail("half close should have timed out");
}
catch(SocketException e)
{
// expected
}
// check the server side is closed
Assert.assertFalse(endPoint.isOpen());
}
@Test
public void testMaxIdleNoRequest() throws Exception
{
configureServer(new EchoHandler());
Socket client=newSocket(HOST,_connector.getLocalPort());
client.setSoTimeout(10000);
InputStream is=client.getInputStream();
assertFalse(client.isClosed());
Thread.sleep(sleepTime);
long start = System.currentTimeMillis();
try
{
IO.toString(is);
assertEquals(-1, is.read());
}
catch(SSLException e)
{
}
catch(Exception e)
{
e.printStackTrace();
}
Assert.assertTrue(System.currentTimeMillis()-start<maximumTestRuntime);
}
@Test
public void testMaxIdleWithSlowRequest() throws Exception
{
configureServer(new EchoHandler());
Socket client=newSocket(HOST,_connector.getLocalPort());
client.setSoTimeout(10000);
assertFalse(client.isClosed());
OutputStream os=client.getOutputStream();
InputStream is=client.getInputStream();
String content="Wibble\r\n";
byte[] contentB=content.getBytes("utf-8");
os.write((
"GET / HTTP/1.0\r\n"+
"host: "+HOST+":"+_connector.getLocalPort()+"\r\n"+
"connection: keep-alive\r\n"+
"Content-Length: "+(contentB.length*20)+"\r\n"+
"Content-Type: text/plain\r\n"+
"Connection: close\r\n"+
"\r\n").getBytes("utf-8"));
os.flush();
for (int i =0;i<20;i++)
{
Thread.sleep(50);
os.write(contentB);
os.flush();
}
String in = IO.toString(is);
int offset=0;
for (int i =0;i<20;i++)
{
offset=in.indexOf("Wibble",offset+1);
Assert.assertTrue(""+i,offset>0);
}
}
@Test
public void testMaxIdleWithSlowResponse() throws Exception
{
configureServer(new SlowResponseHandler());
Socket client=newSocket(HOST,_connector.getLocalPort());
client.setSoTimeout(10000);
assertFalse(client.isClosed());
OutputStream os=client.getOutputStream();
InputStream is=client.getInputStream();
os.write((
"GET / HTTP/1.0\r\n"+
"host: "+HOST+":"+_connector.getLocalPort()+"\r\n"+
"connection: keep-alive\r\n"+
"Connection: close\r\n"+
"\r\n").getBytes("utf-8"));
os.flush();
String in = IO.toString(is);
int offset=0;
for (int i =0;i<20;i++)
{
offset=in.indexOf("Hello World",offset+1);
Assert.assertTrue(""+i,offset>0);
}
}
@Test
public void testMaxIdleWithWait() throws Exception
{
configureServer(new WaitHandler());
Socket client=newSocket(HOST,_connector.getLocalPort());
client.setSoTimeout(10000);
assertFalse(client.isClosed());
OutputStream os=client.getOutputStream();
InputStream is=client.getInputStream();
os.write((
"GET / HTTP/1.0\r\n"+
"host: "+HOST+":"+_connector.getLocalPort()+"\r\n"+
"connection: keep-alive\r\n"+
"Connection: close\r\n"+
"\r\n").getBytes("utf-8"));
os.flush();
String in = IO.toString(is);
int offset=in.indexOf("Hello World");
Assert.assertTrue(offset>0);
}
protected static class SlowResponseHandler extends AbstractHandler
{
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
response.setStatus(200);
OutputStream out = response.getOutputStream();
for (int i=0;i<20;i++)
{
out.write("Hello World\r\n".getBytes());
out.flush();
try{Thread.sleep(50);}catch(Exception e){e.printStackTrace();}
}
out.close();
}
}
protected static class WaitHandler extends AbstractHandler
{
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
baseRequest.setHandled(true);
response.setStatus(200);
OutputStream out = response.getOutputStream();
try{Thread.sleep(2000);}catch(Exception e){e.printStackTrace();}
out.write("Hello World\r\n".getBytes());
out.flush();
}
}
}
|
package net.viperfish.journal.secureProvider;
import java.io.File;
import java.security.SecureRandom;
import net.viperfish.journal.framework.Configuration;
import net.viperfish.journal.secureAlgs.MacDigester;
import net.viperfish.journal.secureAlgs.Macs;
import net.viperfish.journal.streamCipher.StreamCipherEncryptor;
import net.viperfish.journal.streamCipher.StreamCipherEncryptors;
final class StreamCipherTransformer extends CompressMacTransformer {
public static final String ALG_NAME = "net.viperfish.secure.streamCipher";
private byte[] masterKey;
private MacDigester macGen;
private SecureRandom rand;
private String algName;
StreamCipherTransformer(File salt) {
super(salt);
rand = new SecureRandom();
algName = Configuration.getString(ALG_NAME);
if (algName == null) {
algName = "ChaCha";
}
macGen = Macs.getMac("HMAC");
macGen.setMode("SHA512");
}
private byte[] generateSubKey(byte[] feed, int length) {
byte[] subKey = new byte[length];
macGen.setKey(masterKey);
int currentLength = 0;
while (currentLength != length) {
byte[] temp = macGen.calculateMac(feed);
int willAdd = (length - currentLength) > temp.length ? temp.length : length - currentLength;
System.arraycopy(temp, 0, subKey, currentLength, willAdd);
currentLength += willAdd;
feed = temp;
}
return subKey;
}
@Override
public void setPassword(String pass) {
masterKey = this.generateKey(pass);
byte[] macKey = generateSubKey("Mac Key".getBytes(), getMacKeySize() / 8);
this.initMac(macKey);
}
@Override
protected String encryptData(byte[] bytes) {
byte[] randomSource = new byte[16];
rand.nextBytes(randomSource);
int keysize = StreamCipherEncryptors.INSTANCE.getKeySize(algName) / 8;
int ivsize = StreamCipherEncryptors.INSTANCE.getIVSize(algName) / 8;
byte[] keyCombo = generateSubKey(randomSource, keysize + ivsize);
byte[] key = new byte[keysize];
byte[] iv = new byte[ivsize];
System.arraycopy(keyCombo, 0, key, 0, keysize);
System.arraycopy(keyCombo, keysize, iv, 0, ivsize);
StreamCipherEncryptor enc = StreamCipherEncryptors.INSTANCE.getEncryptor(algName);
byte[] ecrypted = enc.encrypt(bytes, key, iv);
ByteParameterPair pair = new ByteParameterPair(randomSource, ecrypted);
return pair.toString();
}
@Override
protected byte[] decryptData(String cData) {
ByteParameterPair pair = ByteParameterPair.valueOf(cData);
int keysize = StreamCipherEncryptors.INSTANCE.getKeySize(algName) / 8;
int ivsize = StreamCipherEncryptors.INSTANCE.getIVSize(algName) / 8;
byte[] keyCombo = generateSubKey(pair.getFirst(), keysize + ivsize);
byte[] key = new byte[keysize];
byte[] iv = new byte[ivsize];
System.arraycopy(keyCombo, 0, key, 0, keysize);
System.arraycopy(keyCombo, keysize, iv, 0, ivsize);
StreamCipherEncryptor enc = StreamCipherEncryptors.INSTANCE.getEncryptor(algName);
return enc.decrypt(pair.getSecond(), key, iv);
}
}
|
package apps;
import fos.drv.blk.Floppy;
import fos.drv.chr.Tty;
import java.io.IOException;
/**
*
* @author igel
*/
public class hello {
protected static String about = "falseOS ia a true operating system based on java\n\t[writted by Vakhurin Sergey aka igel]\n";
protected static String uc = "Unknown command: ";
protected static String help = "\tone of these command expected:\n\t\tclear - clear the screen\n\t\tfree - show memory usage\n\t\tfloppy- testing floppy controller\n\t\treboot - rebooting computer\n\t\tabout - show greeting\n";
protected static String promt = "[fos]$ ";
protected static String s = new String();
protected static void printm( int m ) {
if ( m > 5 * 1024 )
if ( m > 5 * 1024 * 1024 ) {
System.out.print( m / (1024 * 1024) );
System.out.print( 'M' );
} else {
System.out.print( m / 1024 );
System.out.print( 'K' );
}
else
System.out.print( m );
}
public static void main( String[] args ) throws IOException {
Tty.print( promt );
int c;
while ( (c = System.in.read()) >= 0 ) {
System.out.print( (char) c );
if ( c == '\b' )
s.remove( 1 );
else if ( c == '\n' ) {
if ( s.length() > 0 ) {
if ( s.equals( "about" ) )
Tty.print( about );
else if (s.equals("reboot"))
reboot();
else if ( s.equals( "clear" ) )
Tty.clear();
else if ( s.equals( "floppy" ) )
Floppy.init();
else if ( s.equals( "free" ) ) {
Runtime rt = Runtime.getRuntime();
long free = rt.freeMemory();
long used = rt.maxMemory() - free;
printm( (int) used );
Tty.print( '/' );
printm( (int) free );
Tty.print( " used/free\n" );
} else {
Tty.print( uc );
Tty.print( s );
Tty.print( '\n' );
Tty.print( help );
}
s.clear();
}
Tty.print( promt );
} else
s.append( (char) c );
}
}
private static void reboot() {
int good = 0x02;
while ((good & 0x02) != 0)
good = fos.sys.IOPorts.in(0x64);
fos.sys.IOPorts.out(0x64, 0xFE);
fos.sys.Interrupts.halt();
}
}
|
package com.intellij.codeInspection.ex;
import com.intellij.analysis.AnalysisScope;
import com.intellij.analysis.AnalysisUIOptions;
import com.intellij.analysis.PerformAnalysisInBackgroundOption;
import com.intellij.codeInsight.daemon.impl.LocalInspectionsPass;
import com.intellij.codeInspection.*;
import com.intellij.codeInspection.lang.GlobalInspectionContextExtension;
import com.intellij.codeInspection.lang.InspectionExtensionsFactory;
import com.intellij.codeInspection.reference.*;
import com.intellij.codeInspection.ui.InspectionResultsView;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PathMacroManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.progress.impl.ProgressManagerImpl;
import com.intellij.openapi.progress.util.ProgressWrapper;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectUtil;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.profile.Profile;
import com.intellij.profile.codeInspection.InspectionProfileManager;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.*;
import com.intellij.psi.search.scope.packageSet.NamedScope;
import com.intellij.ui.content.*;
import com.intellij.util.containers.HashMap;
import gnu.trove.THashMap;
import org.jdom.Document;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class GlobalInspectionContextImpl implements GlobalInspectionContext {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.ex.GlobalInspectionContextImpl");
private RefManager myRefManager;
private final NotNullLazyValue<ContentManager> myContentManager;
private AnalysisScope myCurrentScope;
private final Project myProject;
private List<JobDescriptor> myJobDescriptors;
private InspectionResultsView myView = null;
private Content myContent = null;
private ProgressIndicator myProgressIndicator;
public static final JobDescriptor BUILD_GRAPH = new JobDescriptor(InspectionsBundle.message("inspection.processing.job.descriptor"));
public static final JobDescriptor FIND_EXTERNAL_USAGES =
new JobDescriptor(InspectionsBundle.message("inspection.processing.job.descriptor1"));
private static final JobDescriptor LOCAL_ANALYSIS = new JobDescriptor(InspectionsBundle.message("inspection.processing.job.descriptor2"));
private InspectionProfile myExternalProfile = null;
private final Map<Key, GlobalInspectionContextExtension> myExtensions = new HashMap<Key, GlobalInspectionContextExtension>();
private boolean RUN_GLOBAL_TOOLS_ONLY = false;
private final Map<String, Tools> myTools = new THashMap<String, Tools>();
private final AnalysisUIOptions myUIOptions;
public GlobalInspectionContextImpl(Project project, NotNullLazyValue<ContentManager> contentManager) {
myProject = project;
myUIOptions = AnalysisUIOptions.getInstance(myProject).copy();
myRefManager = null;
myCurrentScope = null;
myContentManager = contentManager;
for (InspectionExtensionsFactory factory : Extensions.getExtensions(InspectionExtensionsFactory.EP_NAME)) {
final GlobalInspectionContextExtension extension = factory.createGlobalInspectionContextExtension();
myExtensions.put(extension.getID(), extension);
}
}
@NotNull
public Project getProject() {
return myProject;
}
public <T> T getExtension(final Key<T> key) {
return (T)myExtensions.get(key);
}
public ContentManager getContentManager() {
return myContentManager.getValue();
}
public InspectionProfile getCurrentProfile() {
if (myExternalProfile != null) return myExternalProfile;
InspectionManagerEx managerEx = (InspectionManagerEx)InspectionManager.getInstance(myProject);
final InspectionProjectProfileManager inspectionProfileManager = InspectionProjectProfileManager.getInstance(myProject);
Profile profile = inspectionProfileManager.getProfile(managerEx.getCurrentProfile(), false);
if (profile == null) {
profile = InspectionProfileManager.getInstance().getProfile(managerEx.getCurrentProfile());
if (profile != null) return (InspectionProfile)profile;
final String[] avaliableProfileNames = inspectionProfileManager.getAvailableProfileNames();
if (avaliableProfileNames == null || avaliableProfileNames.length == 0) {
//can't be
return null;
}
profile = inspectionProfileManager.getProfile(avaliableProfileNames[0]);
}
return (InspectionProfile)profile;
}
public boolean isSuppressed(RefEntity entity, String id) {
return entity instanceof RefElementImpl && ((RefElementImpl)entity).isSuppressed(id);
}
public boolean shouldCheck(RefEntity entity, GlobalInspectionTool tool) {
if (entity instanceof RefElementImpl) {
final RefElementImpl refElement = (RefElementImpl)entity;
if (refElement.isSuppressed(tool.getShortName())) return false;
final PsiFile file = refElement.getContainingFile();
if (file == null) return false;
final Tools tools = myTools.get(tool.getShortName());
for (ScopeToolState state : tools.getTools()) {
final NamedScope namedScope = state.getScope();
if (namedScope == null || namedScope.getValue().contains(file, getCurrentProfile().getProfileManager().getScopesManager())) {
return state.isEnabled() && ((GlobalInspectionToolWrapper)state.getTool()).getTool() == tool;
}
}
return false;
}
return true;
}
public boolean isSuppressed(PsiElement element, String id) {
final RefManagerImpl refManager = (RefManagerImpl)getRefManager();
if (refManager.isDeclarationsFound()) {
final RefElement refElement = refManager.getReference(element);
return refElement instanceof RefElementImpl && ((RefElementImpl)refElement).isSuppressed(id);
}
return InspectionManagerEx.isSuppressed(element, id);
}
public void addView(InspectionResultsView view, String title) {
myContentManager.getValue().addContentManagerListener(new ContentManagerAdapter() {
public void contentRemoved(ContentManagerEvent event) {
if (event.getContent() == myContent){
if (myView != null) {
close(false);
}
myContent = null;
}
}
});
myView = view;
ContentManager contentManager = getContentManager();
myContent = ContentFactory.SERVICE.getInstance().createContent(view, title, false);
myContent.setDisposer(myView);
contentManager.addContent(myContent);
contentManager.setSelectedContent(myContent);
ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.INSPECTION).activate(null);
}
private void addView(InspectionResultsView view) {
addView(view, view.getCurrentProfileName() == null
? InspectionsBundle.message("inspection.results.title")
: InspectionsBundle.message("inspection.results.for.profile.toolwindow.title", view.getCurrentProfileName()));
}
private void cleanup() {
myProgressIndicator = null;
for (GlobalInspectionContextExtension extension : myExtensions.values()) {
extension.cleanup();
}
for (Tools tools : myTools.values()) {
for (ScopeToolState state : tools.getTools()) {
((InspectionTool)state.getTool()).cleanup();
}
}
myTools.clear();
//EntryPointsManager.getInstance(getProject()).cleanup();
if (myRefManager != null) {
((RefManagerImpl)myRefManager).cleanup();
myRefManager = null;
if (myCurrentScope != null){
myCurrentScope.invalidate();
myCurrentScope = null;
}
}
}
public void setCurrentScope(AnalysisScope currentScope) {
myCurrentScope = currentScope;
}
public void doInspections(final AnalysisScope scope, final InspectionManager manager) {
if (!InspectionManagerEx.canRunInspections(myProject, true)) return;
cleanup();
if (myContent != null) {
getContentManager().removeContent(myContent, true);
}
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
myCurrentScope = scope;
launchInspections(scope, manager);
}
});
}
@NotNull
public RefManager getRefManager() {
if (myRefManager == null) {
myRefManager = ApplicationManager.getApplication().runReadAction(new Computable<RefManagerImpl>() {
public RefManagerImpl compute() {
return new RefManagerImpl(myProject, myCurrentScope, GlobalInspectionContextImpl.this);
}
});
}
return myRefManager;
}
public void launchInspectionsOffline(final AnalysisScope scope,
final String outputPath,
final boolean runWithEditorSettings,
final boolean runGlobalToolsOnly,
final InspectionManager manager) {
cleanup();
myCurrentScope = scope;
InspectionTool.setOutputPath(outputPath);
final boolean oldToolsSettings = RUN_GLOBAL_TOOLS_ONLY;
RUN_GLOBAL_TOOLS_ONLY = runGlobalToolsOnly;
try {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
performInspectionsWithProgress(scope, manager);
@NonNls final String ext = ".xml";
for (Map.Entry<String,Tools> stringSetEntry : myTools.entrySet()) {
final Element root = new Element(InspectionsBundle.message("inspection.problems"));
final Document doc = new Document(root);
final Tools sameTools = stringSetEntry.getValue();
boolean hasProblems = false;
boolean isLocalTool = false;
String toolName = stringSetEntry.getKey();
if (sameTools != null) {
for (ScopeToolState toolDescr : sameTools.getTools()) {
final InspectionTool tool = (InspectionTool)toolDescr.getTool();
if (tool instanceof LocalInspectionToolWrapper) {
hasProblems = new File(outputPath, toolName + ext).exists();
isLocalTool = true;
}
else {
tool.updateContent();
if (tool.hasReportedProblems()) {
hasProblems = true;
tool.exportResults(root);
}
}
}
}
if (!hasProblems) continue;
@NonNls final String isLocalToolAttribute = "is_local_tool";
root.setAttribute(isLocalToolAttribute, String.valueOf(isLocalTool));
OutputStream outStream = null;
try {
new File(outputPath).mkdirs();
final File file = new File(outputPath, toolName + ext);
if (isLocalTool) {
outStream = new BufferedOutputStream(new FileOutputStream(file, true));
outStream.write(("</" + InspectionsBundle.message("inspection.problems") + ">").getBytes());
}
else {
PathMacroManager.getInstance(getProject()).collapsePaths(doc.getRootElement());
outStream = new BufferedOutputStream(new FileOutputStream(file));
JDOMUtil.writeDocument(doc, outStream, "\n");
}
}
catch (IOException e) {
LOG.error(e);
}
finally {
if (outStream != null) {
try {
outStream.close();
}
catch (IOException e) {
LOG.error(e);
}
}
}
}
}
});
}
finally {
InspectionTool.setOutputPath(null);
RUN_GLOBAL_TOOLS_ONLY = oldToolsSettings;
}
}
public boolean isToCheckMember(@NotNull RefElement owner, InspectionTool tool) {
final PsiElement element = owner.getElement();
return isToCheckMember(element, tool) && !((RefElementImpl)owner).isSuppressed(tool.getShortName());
}
public boolean isToCheckMember(final PsiElement element, final InspectionTool tool) {
if (true) {
final Tools tools = myTools.get(tool.getShortName());
for (ScopeToolState state : tools.getTools()) {
final NamedScope namedScope = state.getScope();
if (namedScope == null || namedScope.getValue().contains(element.getContainingFile(), getCurrentProfile().getProfileManager().getScopesManager())) {
return state.isEnabled() && state.getTool() == tool;
}
}
return false;
}
return true;
}
public void ignoreElement(final InspectionTool tool, final PsiElement element) {
final RefElement refElement = getRefManager().getReference(element);
final Tools tools = myTools.get(tool.getShortName());
if (tools != null){
for (ScopeToolState state : tools.getTools()) {
ignoreElementRecursively((InspectionTool)state.getTool(), refElement);
}
}
}
private static void ignoreElementRecursively(final InspectionTool tool, final RefEntity refElement) {
if (refElement != null) {
tool.ignoreCurrentElement(refElement);
final List<RefEntity> children = refElement.getChildren();
if (children != null) {
for (RefEntity child : children) {
ignoreElementRecursively(tool, child);
}
}
}
}
public AnalysisUIOptions getUIOptions() {
return myUIOptions;
}
public void setSplitterProportion(final float proportion) {
myUIOptions.SPLITTER_PROPORTION = proportion;
}
public ToggleAction createToggleAutoscrollAction() {
return myUIOptions.getAutoScrollToSourceHandler().createToggleAction();
}
private void launchInspections(final AnalysisScope scope, final InspectionManager manager) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
}
});
LOG.info("Code inspection started");
ProgressManager.getInstance().run(new Task.Backgroundable(getProject(), InspectionsBundle.message("inspection.progress.title"), true, new PerformAnalysisInBackgroundOption(myProject)) {
public void run(@NotNull ProgressIndicator indicator) {
performInspectionsWithProgress(scope, manager);
}
@Override
public void onSuccess() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
LOG.info("Code inspection finished");
final InspectionResultsView view = new InspectionResultsView(myProject, getCurrentProfile(),
scope, GlobalInspectionContextImpl.this,
new InspectionRVContentProviderImpl(myProject));
if (!view.update() && !getUIOptions().SHOW_ONLY_DIFF) {
Messages.showMessageDialog(myProject, InspectionsBundle.message("inspection.no.problems.message"),
InspectionsBundle.message("inspection.no.problems.dialog.title"), Messages.getInformationIcon());
close(true);
}
else {
addView(view);
}
}
});
}
});
}
private void performInspectionsWithProgress(final AnalysisScope scope, final InspectionManager manager) {
final PsiManager psiManager = PsiManager.getInstance(myProject);
myProgressIndicator = ProgressManager.getInstance().getProgressIndicator();
//init manager in read action
RefManagerImpl refManager = (RefManagerImpl)getRefManager();
try {
psiManager.startBatchFilesProcessingMode();
refManager.inspectionReadActionStarted();
BUILD_GRAPH.setTotalAmount(scope.getFileCount());
LOCAL_ANALYSIS.setTotalAmount(scope.getFileCount());
final List<InspectionProfileEntry> needRepeatSearchRequest = new ArrayList<InspectionProfileEntry>();
((ProgressManagerImpl)ProgressManager.getInstance())
.executeProcessUnderProgress(new Runnable() { //to override current progress in order to hide useless messages/%
public void run() {
runTools(needRepeatSearchRequest, scope, manager);
}
}, ProgressWrapper.wrap(myProgressIndicator));
}
catch (ProcessCanceledException e) {
cleanup((InspectionManagerEx)manager);
throw e;
}
catch (Exception e) {
LOG.error(e);
}
finally {
refManager.inspectionReadActionFinished();
psiManager.finishBatchFilesProcessingMode();
}
}
private void runTools(final List<InspectionProfileEntry> needRepeatSearchRequest, final AnalysisScope scope, final InspectionManager manager) {
final List<Tools> usedTools = new ArrayList<Tools>();
final List<Tools> localTools = new ArrayList<Tools>();
initializeTools(usedTools, localTools);
((RefManagerImpl)getRefManager()).initializeAnnotators();
for (Tools tools : usedTools) {
for (ScopeToolState state : tools.getTools()) {
final InspectionTool tool = (InspectionTool)state.getTool();
try {
if (tool.isGraphNeeded()) {
((RefManagerImpl)tool.getRefManager()).findAllDeclarations();
}
tool.runInspection(scope, manager);
if (tool.queryExternalUsagesRequests(manager)) {
needRepeatSearchRequest.add(tool);
}
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Exception e) {
LOG.error(e);
}
}
}
for (GlobalInspectionContextExtension extension : myExtensions.values()) {
try {
extension.performPostRunActivities(needRepeatSearchRequest, this);
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Exception e) {
LOG.error(e);
}
}
if (RUN_GLOBAL_TOOLS_ONLY) return;
final PsiManager psiManager = PsiManager.getInstance(myProject);
scope.accept(new PsiRecursiveElementVisitor() {
@Override
public void visitFile(PsiFile file) {
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile != null) {
incrementJobDoneAmount(LOCAL_ANALYSIS, ProjectUtil.calcRelativeToProjectPath(virtualFile, myProject));
}
final FileViewProvider viewProvider = psiManager.findViewProvider(virtualFile);
final com.intellij.openapi.editor.Document document = viewProvider != null ? viewProvider.getDocument() : null;
if (document == null) return; //do not inspect binary files
final LocalInspectionsPass pass = new LocalInspectionsPass(file, document, 0, file.getTextLength());
try {
final List<InspectionProfileEntry> lTools = new ArrayList<InspectionProfileEntry>();
for (Tools tool : localTools) {
final InspectionTool enabledTool = (InspectionTool)tool.getEnabledTool(file);
if (enabledTool != null) {
lTools.add(enabledTool);
}
}
pass.doInspectInBatch((InspectionManagerEx)manager, lTools.toArray(new InspectionProfileEntry[lTools.size()]), myProgressIndicator,true);
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Exception e) {
LOG.error(e);
}
}
});
}
public void initializeTools(List<Tools> tools, List<Tools> localTools) {
myJobDescriptors = new ArrayList<JobDescriptor>();
final InspectionProfile profile = getCurrentProfile();
InspectionProfileWrapper inspectionProfile = InspectionProjectProfileManager.getInstance(myProject).getProfileWrapper(profile.getName());
if (inspectionProfile == null){
inspectionProfile = new InspectionProfileWrapper(profile);
final InspectionProfileWrapper profileWrapper = inspectionProfile;
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
profileWrapper.init(getProject()); //offline inspections only
}
});
}
final List<ToolsImpl> usedTools = ((InspectionProfileImpl)inspectionProfile.getInspectionProfile()).getAllEnabledInspectionTools();
for (Tools currentTools : usedTools) {
final String shortName = currentTools.getShortName();
myTools.put(shortName, currentTools);
final InspectionTool tool = (InspectionTool)currentTools.getTool();
if (tool instanceof LocalInspectionToolWrapper) {
localTools.add(currentTools);
appendJobDescriptor(LOCAL_ANALYSIS);
}
else {
tools.add(currentTools);
JobDescriptor[] jobDescriptors = tool.getJobDescriptors();
for (JobDescriptor jobDescriptor : jobDescriptors) {
appendJobDescriptor(jobDescriptor);
}
}
for (ScopeToolState state : currentTools.getTools()) {
((InspectionTool)state.getTool()).initialize(this);
}
}
for (GlobalInspectionContextExtension extension : myExtensions.values()) {
extension.performPreRunActivities(tools, localTools, this);
}
}
public Map<String, Tools> getTools() {
return myTools;
}
private void appendJobDescriptor(JobDescriptor job) {
if (!myJobDescriptors.contains(job)) {
myJobDescriptors.add(job);
job.setDoneAmount(0);
}
}
public void close(boolean noSuspisiousCodeFound) {
if (!noSuspisiousCodeFound && (myView == null || myView.isRerun())) return;
final InspectionManagerEx managerEx = (InspectionManagerEx)InspectionManager.getInstance(myProject);
cleanup(managerEx);
AnalysisUIOptions.getInstance(myProject).save(myUIOptions);
if (myContent != null) {
final ContentManager contentManager = getContentManager();
if (contentManager != null) { //null for tests
contentManager.removeContent(myContent, true);
}
}
myView = null;
}
public void cleanup(final InspectionManagerEx managerEx) {
managerEx.closeRunningContext(this);
for (Tools tools : myTools.values()) {
for (ScopeToolState state : tools.getTools()) {
((InspectionTool)state.getTool()).finalCleanup();
}
}
cleanup();
}
public void refreshViews() {
if (myView != null) {
myView.updateView(false);
}
}
public void incrementJobDoneAmount(JobDescriptor job, String message) {
if (myProgressIndicator == null) return;
ProgressManager.getInstance().checkCanceled();
int old = job.getDoneAmount();
job.setDoneAmount(old + 1);
int jobCount = myJobDescriptors.size();
float totalProgress = 0;
for (JobDescriptor jobDescriptor : myJobDescriptors) {
totalProgress += jobDescriptor.getProgress();
}
totalProgress /= jobCount;
myProgressIndicator.setFraction(totalProgress);
myProgressIndicator.setText(job.getDisplayName() + " " + message);
}
public void setExternalProfile(InspectionProfile profile) {
myExternalProfile = profile;
}
}
|
/*
* Thibaut Colar Feb 5, 2010
*/
package net.colar.netbeans.fan.parboiled;
import org.parboiled.BaseParser;
import org.parboiled.Rule;
import org.parboiled.support.Cached;
import org.parboiled.support.Leaf;
@SuppressWarnings(
{
"InfiniteRecursion"
})
public class FantomParser extends BaseParser<Object>
{
public boolean inFieldInit = false; // to help with differentiation of field accesor & itBlock
public boolean inEnum = false; // so we know whether to allow enumDefs
public boolean noSimpleMap = false; // to disallow ambigous simpleMaps in certain situations (within another map, ternaryExpr)
public Rule compilationUnit()
{
return sequence(
OPT_LF(),
// Missing from grammar: Optional unix env line
optional(sequence("#!", zeroOrMore(sequence(testNot("\n"), any())), "\n")),
zeroOrMore(firstOf(using(), incUsing())),
zeroOrMore(typeDef()),
OPT_LF(),
zeroOrMore(doc()), // allow for extra docs at end of file (if last type commented out)
OPT_LF(),
eoi());
}
public Rule using()
{
return sequence(OPT_LF(), enforcedSequence(
KW_USING,
optional(ffi()),
id(),
zeroOrMore(enforcedSequence(DOT, id())),
optional(enforcedSequence(SP_COLCOL, id())),
optional(usingAs()),
eos()), OPT_LF());
}
// Inconplete using - to allow completion
public Rule incUsing()
{
return enforcedSequence(
KW_USING,
optional(ffi()),
optional(id()), // Not optional, but we want a valid ast for completion if missing
zeroOrMore(sequence(DOT, id())),// not enforced to allow completion
optional(sequence(SP_COLCOL, id())),// not enforced to allow completion
optional(usingAs()),
optional(eos()), OPT_LF());
}
public Rule ffi()
{
return enforcedSequence(SQ_BRACKET_L, id(), SQ_BRACKET_R);
}
public Rule usingAs()
{
return enforcedSequence(KW_AS, id());
}
public Rule staticBlock()
{
return sequence(KW_STATIC, OPT_LF(), enforcedSequence(BRACKET_L, zeroOrMore(stmt()), OPT_LF(), BRACKET_R));
}
public Rule typeDef()
{
// grouped together classdef, enumDef, mixinDef & facetDef as they are grammatically very similar (optimized)
return sequence(
setInEnum(false),
OPT_LF(),
optional(doc()),
zeroOrMore(facet()),
optional(protection()),
enforcedSequence(
firstOf(
sequence(zeroOrMore(firstOf(KW_ABSTRACT, KW_FINAL, KW_CONST)), KW_CLASS), // standard class
enforcedSequence(ENUM, KW_CLASS, setInEnum(true)), // enum class
enforcedSequence(FACET, KW_CLASS), // facet class
sequence(optional(KW_CONST), KW_MIXIN) // mixin
),
id(),
optional(inheritance()),
OPT_LF(),
BRACKET_L,
OPT_LF(),
optional(sequence(peekTest(inEnum),optional(enumValDefs()))), // only valid for enums, but simplifying
// Static block missing from Fan grammar
zeroOrMore(firstOf(staticBlock(), slotDef())),
BRACKET_R, OPT_LF()));
}
public Rule protection()
{
return firstOf(KW_PUBLIC, KW_PROTECTED, KW_INTERNAL, KW_PRIVATE);
}
public Rule inheritance()
{
return enforcedSequence(SP_COL, typeList());
}
public Rule facet()
{
return enforcedSequence(AT, simpleType(), optional(facetVals()), OPT_LF());
}
public Rule facetVals()
{
return enforcedSequence(
BRACKET_L,
facetVal(),
zeroOrMore(sequence(eos(), facetVal())),
BRACKET_R);
}
public Rule facetVal()
{
return enforcedSequence(id(), AS_EQUAL, expr());
}
public Rule enumValDefs()
{
return sequence(enumValDef(), zeroOrMore(sequence(SP_COMMA, enumValDef())), OPT_LF(), eos());
}
public Rule enumValDef()
{
// Fantom grammar is missing "doc"
return sequence(OPT_LF(), optional(doc()), id(), optional(enforcedSequence(PAR_L, optional(args()), PAR_R)));
}
public Rule slotDef()
{
// Rewrote this to "unify" slots common parts (for better performance)
return sequence(
OPT_LF(),
optional(doc()),// common to all slots
zeroOrMore(facet()),// common to all slots
optional(protection()),// common to all slots
firstOf(
ctorDef(), // look for 'new'
methodDef(), // look for params : '('
fieldDef()), // others
OPT_LF());
}
public Rule fieldDef()
{
return sequence(
zeroOrMore(firstOf(KW_ABSTRACT, KW_CONST, KW_FINAL, KW_STATIC,
KW_NATIVE, KW_OVERRIDE, KW_READONLY, KW_VIRTUAL)),
/*typeAndOrId(),*/ type(), id(), // Type required for fields(no infered) (Grammar does not say so)
setFieldInit(true),
optional(enforcedSequence(OP_ASSIGN, OPT_LF(), expr())),
optional(fieldAccessor()),
setFieldInit(false),
eos());
}
public Rule methodDef()
{
return enforcedSequence(
sequence(
// Fan grammar misses 'final'
zeroOrMore(firstOf(KW_ABSTRACT, KW_NATIVE, KW_ONCE, KW_STATIC,
KW_OVERRIDE, KW_VIRTUAL, KW_FINAL)),
type(),
id(),
PAR_L),
optional(params()),
PAR_R,
methodBody());
}
public Rule ctorDef()
{
return enforcedSequence(KW_NEW,
id(),
PAR_L,
optional(params()),
PAR_R,
optional( // ctorChain
// Fantom Grammar page is missing the ':'
enforcedSequence(sequence(OPT_LF(), SP_COL),
firstOf(
enforcedSequence(KW_THIS, DOT, id(), enforcedSequence(PAR_L, optional(args()), PAR_R)),
enforcedSequence(KW_SUPER, optional(enforcedSequence(DOT, id())), enforcedSequence(PAR_L, optional(args()), PAR_R))))),
methodBody());
}
public Rule methodBody()
{
return sequence(firstOf(
enforcedSequence(sequence(OPT_LF(), BRACKET_L), zeroOrMore(stmt()), OPT_LF(), BRACKET_R),
eos()), OPT_LF()); // method with no body
}
public Rule params()
{
return sequence(param(), zeroOrMore(enforcedSequence(SP_COMMA, params())));
}
public Rule param()
{
return sequence(OPT_LF(), type(), id(), optional(enforcedSequence(OP_ASSIGN, expr())), OPT_LF());
}
public Rule fieldAccessor()
{
return sequence(OPT_LF(),
enforcedSequence(
BRACKET_L,
optional(sequence(OPT_LF(), enforcedSequence(GET, firstOf(block(), eos())))),
optional(sequence(OPT_LF(), optional(protection()), enforcedSequence(SET, firstOf(block(), eos())))),
BRACKET_R), OPT_LF());
}
public Rule args()
{
return sequence(expr(), zeroOrMore(sequence(OPT_LF(), enforcedSequence(SP_COMMA, OPT_LF(), expr()))), OPT_LF());
}
public Rule block()
{
return sequence(OPT_LF(), firstOf(
enforcedSequence(BRACKET_L, zeroOrMore(stmt()), OPT_LF(), BRACKET_R), // block
stmt() // single statement
), OPT_LF());
}
public Rule stmt()
{
return sequence(testNot(BRACKET_R), OPT_LF(),
firstOf(
sequence(KW_BREAK, eos()),
sequence(KW_CONTINUE, eos()),
sequence(KW_RETURN, sequence(optional(expr()), eos())).label("MY_RT_STMT"),
sequence(KW_THROW, expr(), eos()),
if_(),
for_(),
switch_(),
while_(),
try_(),
// check local var definition as it's faster to parse ':='
localDef(),
// otherwise expression (optional Comma for itAdd expression)
// using firstOf, because "," in this case can be considered an end of statement
sequence(expr(), firstOf(sequence(SP_COMMA, optional(eos())), eos()))),
OPT_LF());
}
public Rule for_()
{
return enforcedSequence(KW_FOR, PAR_L,
// LocalDef consumes the SEMI as part of loking for EOS, so rewrote to deal with this
firstOf(SP_SEMI, firstOf(localDef(), sequence(expr(), SP_SEMI))),
firstOf(SP_SEMI, sequence(expr(), SP_SEMI)),
optional(expr()),
PAR_R,
block());
}
public Rule if_()
{
// using condExpr rather than expr
return enforcedSequence(KW_IF, PAR_L, condOrExpr()/*was expr*/, PAR_R, block(),
optional(enforcedSequence(KW_ELSE, block())));
}
public Rule while_()
{
// using condExpr rather than expr
return enforcedSequence(KW_WHILE, PAR_L, condOrExpr()/*was expr*/, PAR_R, block());
}
public Rule localDef()
{
// slight chnage from teh grammar to match either:
// 'Int j', 'j:=27', 'Int j:=27'
return sequence(
firstOf(
// fan parser says if it's start with "id :=" or "Type, id", then it gotta be a localDef (enforce)
enforcedSequence(sequence(type(), id(), OP_ASSIGN), OPT_LF(), expr()),
// same if it starts with "id :="
enforcedSequence(sequence(id(), OP_ASSIGN), OPT_LF(), expr()),
// var def with no value
sequence(type(), id())),
eos());
}
public Rule try_()
{
return enforcedSequence(KW_TRY, block(), zeroOrMore(catch_()),
optional(sequence(KW_FINALLY, block())));
}
public Rule catch_()
{
return enforcedSequence(KW_CATCH, optional(enforcedSequence(PAR_L, type(), id(), PAR_R)), block());
}
public Rule switch_()
{
return enforcedSequence(KW_SWITCH, PAR_L, expr(), PAR_R,
OPT_LF(), BRACKET_L, OPT_LF(),
zeroOrMore(enforcedSequence(KW_CASE, expr(), SP_COL, zeroOrMore(firstOf(stmt(), LF())))),
optional(enforcedSequence(KW_DEFAULT, SP_COL, zeroOrMore(firstOf(stmt(), LF())))),
OPT_LF(), BRACKET_R);
}
public Rule expr()
{
return assignExpr();
}
public Rule assignExpr()
{
// check '=' first as is most common
// moved localDef to statement since it can't be on the right hand side
return sequence(ifExpr(), optional(enforcedSequence(firstOf(AS_EQUAL, AS_ASSIGN_OPS), OPT_LF(), assignExpr())));
}
public Rule ifExpr()
{
// rewritten (together with ternaryTail, elvisTail) such as we check condOrExpr only once
// this makes a gigantic difference in parser speed form original grammar
return sequence(condOrExpr(),
optional(firstOf(elvisTail(), ternaryTail())));
}
public Rule ternaryTail()
{
return enforcedSequence(SP_QMARK, OPT_LF(), setNoSimpleMap(true), ifExprBody(), setNoSimpleMap(false), SP_COL, OPT_LF(), ifExprBody());
}
public Rule elvisTail()
{
return enforcedSequence(OP_ELVIS, OPT_LF(), ifExprBody());
}
public Rule ifExprBody()
{
return firstOf(enforcedSequence(KW_THROW, expr()), condOrExpr());
}
public Rule condOrExpr()
{
return sequence(condAndExpr(), zeroOrMore(enforcedSequence(OP_OR, OPT_LF(), condAndExpr())));
}
public Rule condAndExpr()
{
return sequence(equalityExpr(), zeroOrMore(enforcedSequence(OP_AND, OPT_LF(), equalityExpr())));
}
public Rule equalityExpr()
{
return sequence(relationalExpr(), zeroOrMore(enforcedSequence(CP_EQUALITY, OPT_LF(), relationalExpr())));
}
public Rule relationalExpr()
{
// Changed (with typeCheckTail, compareTail) to check for rangeExpr only once (way faster)
return sequence(rangeExpr(), optional(firstOf(typeCheckTail(), compareTail())));
}
public Rule typeCheckTail()
{
// changed to required, otherwise consumes all rangeExpr and compare never gets evaled
return enforcedSequence(firstOf(KW_IS, KW_ISNOT, KW_AS), type());
}
public Rule compareTail()
{
// changed to not be zeroOrMore as there can be only one comparaison check in an expression (no 3< x <5)
return /*zeroOrMore(*/enforcedSequence(CP_COMPARATORS, OPT_LF(), rangeExpr())/*)*/;
}
public Rule rangeExpr()
{
// changed to not be zeroOrMore(opt instead) as there can be only one range in an expression (no [1..3..5])
return sequence(addExpr(),
optional(enforcedSequence(firstOf(OP_RANGE_EXCL, OP_RANGE), OPT_LF(), addExpr())));
}
public Rule addExpr()
{
return sequence(multExpr(),
// checking it's not '+=' or '-=', so we can let assignExpr happen
zeroOrMore(enforcedSequence(sequence(firstOf(OP_PLUS, OP_MINUS), testNot(AS_EQUAL)), OPT_LF(), multExpr())));
}
public Rule multExpr()
{
return sequence(parExpr(),
// checking it's not '*=', '/=' or '%=', so we can let assignExpr happen
zeroOrMore(enforcedSequence(sequence(firstOf(OP_MULT, OP_DIV, OP_MODULO), testNot(AS_EQUAL)), OPT_LF(), parExpr())));
}
public Rule parExpr()
{
return firstOf(castExpr(), groupedExpr(), unaryExpr());
}
public Rule castExpr()
{
return sequence(PAR_L, type(), PAR_R, parExpr());
}
public Rule groupedExpr()
{
return sequence(PAR_L, OPT_LF(), expr(), OPT_LF(), PAR_R, zeroOrMore(termChain()));
}
public Rule unaryExpr()
{
// grouped with postfixEpr to avoid looking for termExpr twice (very slow parsing !)
return firstOf(prefixExpr(), sequence(termExpr(), optional(firstOf(OP_2MINUS, OP_2PLUS))));
}
public Rule prefixExpr()
{
return sequence(
firstOf(OP_CURRY, OP_BANG, OP_2PLUS, OP_2MINUS, OP_PLUS, OP_MINUS),
parExpr());
}
public Rule termExpr()
{
return sequence(termBase(), zeroOrMore(termChain()));
}
public Rule termBase()
{
// check for ID alone last (and not as part of idExpr) otherwise it would never check literal & typebase !
return firstOf(idExprReq(), litteral(), typeBase(), id());
}
public Rule typeBase()
{
return firstOf(
enforcedSequence(OP_POUND, id()), // slot litteral (without type)
closure(),
dsl(), // DSL
// Optimized by grouping all the items that start with "type" (since looking for type if resource intensive)
sequence(type(), firstOf(
sequence(OP_POUND, optional(id())), // type/slot litteral
sequence(DOT, KW_SUPER), // named super
sequence(DOT, /*OPT_LF(),*/ idExpr()), // static call
sequence(PAR_L, expr(), PAR_R), // "simple"
itBlock() // ctor block
)));
}
public Rule dsl()
{
//TODO: unclosed DSL ?
return sequence(simpleType(),
enforcedSequence(DSL_OPEN, OPT_LF(), zeroOrMore(sequence(testNot(DSL_CLOSE), any())), OPT_LF(), DSL_CLOSE));
}
public Rule closure()
{
return sequence(funcType(), OPT_LF(), enforcedSequence(BRACKET_L, zeroOrMore(stmt()), BRACKET_R));
}
public Rule itBlock()
{
return sequence(
OPT_LF(),
enforcedSequence(sequence(BRACKET_L,
// Note, don't allow field accesors to be parsed as itBlock
peekTestNot(sequence(inFieldInit, OPT_LF(), firstOf(protection(), KW_STATIC, KW_READONLY, GET, SET, GET, SET)/*, echo("Skipping itBlock")*/))),
zeroOrMore(stmt()), BRACKET_R));
}
public Rule termChain()
{
return sequence(OPT_LF(),
firstOf(safeDotCall(), safeDynCall(), dotCall(), dynCall(), indexExpr(),
callOp(), itBlock()/*, incDotCall()*/));
}
public Rule dotCall()
{
// test not "..", as this would be a range
return enforcedSequence(sequence(DOT, testNot(DOT)), idExpr());
}
public Rule dynCall()
{
return enforcedSequence(OP_ARROW, idExpr());
}
public Rule safeDotCall()
{
return enforcedSequence(OP_SAFE_CALL, idExpr());
}
public Rule safeDynCall()
{
return enforcedSequence(OP_SAFE_DYN_CALL, idExpr());
}
// incomplete dot call, make valid to allow for completion
public Rule incDotCall()
{
return DOT;
}
public Rule idExpr()
{
// this can be either a local def(toto.value) or a call(toto.getValue or toto.getValue(<params>)) + opt. closure
return firstOf(idExprReq(), id());
}
public Rule idExprReq()
{
// Same but without matching ID by itself (this would prevent termbase from checking literals).
return firstOf(field(), call());
}
// require '*' otherwise it's just and ID (this would prevent termbase from checking literals)
public Rule field()
{
return sequence(OP_MULT, id());
}
// require params or/and closure, otherwise it's just and ID (this would prevent termbase from checking literals)
public Rule call()
{
return sequence(id(),
firstOf(
sequence(enforcedSequence(PAR_L, OPT_LF(), optional(args()), PAR_R), optional(closure())), //params & opt. closure
closure())); // closure only
}
public Rule indexExpr()
{
return sequence(SQ_BRACKET_L, expr(), SQ_BRACKET_R);
}
public Rule callOp()
{
return enforcedSequence(PAR_L, optional(args()), PAR_R, optional(closure()));
}
public Rule litteral()
{
return firstOf(litteralBase(), list(), map());
}
public Rule litteralBase()
{
return firstOf(KW_NULL, KW_THIS, KW_SUPER, KW_IT, KW_TRUE, KW_FALSE,
strs(), uri(), number(), char_());
}
public Rule list()
{
return sequence(
optional(type()), OPT_LF(),
SQ_BRACKET_L, OPT_LF(), listItems(), OPT_LF(), SQ_BRACKET_R);
}
public Rule listItems()
{
return firstOf(
SP_COMMA,
// allow extra comma
sequence(expr(), zeroOrMore(sequence(SP_COMMA, OPT_LF(), expr())), optional(SP_COMMA)));
}
public Rule map()
{
return sequence(
optional(firstOf(mapType(), simpleMapType())),
// Not enforced to allow resolving list of typed maps like [Str:Int][]
sequence(SQ_BRACKET_L, OPT_LF(), mapItems(), OPT_LF(), SQ_BRACKET_R));
}
public Rule mapItems()
{
return firstOf(SP_COL,//empty map
// allow extra comma
sequence(mapPair(), zeroOrMore(sequence(SP_COMMA, OPT_LF(), mapPair())), optional(SP_COMMA)));
}
public Rule mapPair()
{
// allowing all expressions is probably more than really needed
return sequence(expr(), enforcedSequence(SP_COL, expr()));
}
public Rule mapItem()
{
return expr();
}
public Rule strs()
{
return firstOf(
enforcedSequence("\"\"\"", // triple quoted string, // (not using 3QUOTE terminal, since it could eat empty space inside the string)
zeroOrMore(firstOf(
unicodeChar(),
escapedChar(),
sequence(testNot(QUOTES3), any()))), QUOTES3),
enforcedSequence("\"", // simple string, (not using QUOTE terminal, since it could eat empty space inside the string)
zeroOrMore(firstOf(
unicodeChar(),
escapedChar(),
sequence(testNot(QUOTE), any()))), QUOTE));
}
public Rule uri()
{
return enforcedSequence("`",// (not using TICK terminal, since it could eat empty space inside the string)
zeroOrMore(firstOf(
unicodeChar(),
escapedChar(),
sequence(testNot(TICK), any()))),
TICK);
}
public Rule char_()
{
return firstOf(
"' '",
enforcedSequence('\'',// (not using SINGLE_Q terminal, since it could eat empty space inside the char)
firstOf(
unicodeChar(),
escapedChar(),
any()), //all else
SINGLE_Q));
}
public Rule escapedChar()
{
return enforcedSequence('\\', firstOf('b', 'f', 'n', 'r', 't', '"', '\'', '`', '$', '\\'));
}
public Rule unicodeChar()
{
return enforcedSequence("\\u", hexDigit(), hexDigit(), hexDigit(), hexDigit());
}
public Rule hexDigit()
{
return firstOf(digit(),
charRange('a', 'f'),
charRange('A', 'F'));
}
public Rule digit()
{
return charRange('0', '9');
}
public Rule number()
{
return sequence(
optional(OP_MINUS),
firstOf(
// hex number
enforcedSequence(firstOf("0x", "0X"), oneOrMore(firstOf("_", hexDigit()))),
// decimal
// fractional
enforcedSequence(fraction(), optional(exponent())),
enforcedSequence(digit(),
zeroOrMore(sequence(zeroOrMore("_"), digit())),
optional(fraction()),
optional(exponent()))),
optional(nbType()),
OPT_SP);
}
public Rule fraction()
{
// not enfored to allow: "3.times ||" constructs as well as ranges 3..5
return sequence(DOT, digit(), zeroOrMore(sequence(zeroOrMore("_"), digit())));
}
public Rule exponent()
{
return enforcedSequence(charSet("eE"),
optional(firstOf(OP_PLUS, OP_MINUS)),
digit(),
zeroOrMore(sequence(zeroOrMore("_"), digit())));
}
public Rule nbType()
{
return firstOf(
"day", "hr", "min", "sec", "ms", "ns", //durations
"f", "F", "D", "d" // float / decimal
);
}
/** Rewrote more like Fantom Parser (simpler & faster) - lokffor type base then listOfs, mapOfs notations
* Added check so that the "?" (nullable type indicator) cannot be separated from it's type (noSpace)
* @return
*/
public Rule type()
{
return sequence(
firstOf(
mapType(),
funcType(),
sequence(id(), optional(sequence(noSpace(), SP_COLCOL, noSpace(), id())))
),
// Look for optional map/list/nullable items
optional(sequence(noSpace(), SP_QMARK)), //nullable
zeroOrMore(sequence(noSpace(),SQ_BRACKET_L, SQ_BRACKET_R)),//list(s)
// Do not allow simple maps within left side of expressions ... this causes issues with ":"
optional(sequence(peekTestNot(noSimpleMap), SP_COL, type())),//simple map Int:Str
optional(sequence(noSpace(), SP_QMARK)) // nullable list/map
);
}
public Rule simpleMapType()
{
// It has to be other nonSimpleMapTypes, otherwise it's left recursive (loops forever)
return sequence(nonSimpleMapTypes(), SP_COL, nonSimpleMapTypes(),
optional(
// Not enforcing [] because of problems with maps like this Str:int["":5]
sequence(optional(SP_QMARK), SQ_BRACKET_L, SQ_BRACKET_R)), // list of '?[]'
optional(SP_QMARK)); // nullable
}
// all types except simple map
public Rule nonSimpleMapTypes()
{
return sequence(
firstOf(funcType(), mapType(), simpleType()),
optional(
// Not enforcing [] because of problems with maps like this Str:int["":5]
sequence(optional(SP_QMARK), SQ_BRACKET_L, SQ_BRACKET_R)), // list of '?[]'
optional(SP_QMARK)); // nullable
}
public Rule simpleType()
{
return sequence(
id(),
optional(enforcedSequence(SP_COLCOL, id())));
}
public Rule mapType()
{
// We use nonSimpleMapTypes here as well, because [Str:Int:Str] would be confusing
// not enforced to allow map rule to work ([Int:Str][5,""])
return sequence(SQ_BRACKET_L, nonSimpleMapTypes(), SP_COL, nonSimpleMapTypes(), SQ_BRACKET_R);
}
public Rule funcType()
{
return sequence(
testNot(OP_OR), // '||' that's a logical OR not a function type
// '|' could be the closing pipe so we can't enforce
sequence(SP_PIPE,
firstOf(
// First we check for one with no formals |->| or |->Str|
enforcedSequence(OP_ARROW, optional(type())),
// Then we check for one with formals |Int i| or maybe full: |Int i -> Str|
sequence(formals(), optional(enforcedSequence(OP_ARROW, optional(type()))))),
SP_PIPE));
}
public Rule formals()
{
// Allowing funcType within formals | |Int-Str a| -> Str|
return sequence(
typeAndOrId(),
zeroOrMore(enforcedSequence(SP_COMMA, typeAndOrId())));
}
public Rule typeList()
{
return sequence(type(), zeroOrMore(enforcedSequence(SP_COMMA, type())));
}
public Rule typeAndOrId()
{
// Note it can be "type id", "type" or "id"
// but parser can't know if it's "type" or "id" so always recognize as type
// so would never actually hit id()
return firstOf(sequence(type(), id()), type());
}
public Rule id()
{
return sequence(testNot(keyword()),
firstOf(charRange('A', 'Z'), charRange('a', 'z'), "_"),
zeroOrMore(firstOf(charRange('A', 'Z'), charRange('a', 'z'), '_', charRange('0', '9'))),
OPT_SP);
}
public Rule doc()
{
// In theory there are no empty lines betwen doc and type ... but thta does happen so alowing it
return oneOrMore(sequence(OPT_SP, "**", zeroOrMore(sequence(testNot("\n"), any())), OPT_LF()));
}
@Leaf
public Rule spacing()
{
return oneOrMore(firstOf(
// whitespace (Do NOT eat \n since it can be meaningful)
oneOrMore(charSet(" \t\u000c")),
// multiline comment
sequence("/*", zeroOrMore(sequence(testNot("*/"), any())), "*/"), // normal comment
// if incomplete multiline comment, then end at end of line
sequence("/*", zeroOrMore(sequence(testNot(charSet("\r\n")), any()))/*, charSet("\r\n")*/),
// single line comment
sequence("//", zeroOrMore(sequence(testNot(charSet("\r\n")), any()))/*, charSet("\r\n")*/)));
}
public Rule LF()
{
return sequence(oneOrMore(sequence(OPT_SP, charSet("\n\r"))), OPT_SP);
}
public Rule OPT_LF()
{
return optional(LF());
}
@Leaf
public Rule keyword(String string)
{
// Makes sure not to match things that START with a keyword like "thisisatest"
return sequence(string,
testNot(firstOf(digit(), charRange('A', 'Z'), charRange('a', 'z'), "_")),
optional(spacing())).label(string);
}
@Leaf
public Rule terminal(String string)
{
return sequence(string, optional(spacing())).label(string);
}
@Leaf
public Rule terminal(String string, Rule mustNotFollow)
{
return sequence(string, testNot(mustNotFollow), optional(spacing())).label(string);
}
public Rule keyword()
{
return sequence(
// don't bother unless it starts with 'a'-'z'
test(charRange('a', 'z')),
firstOf(KW_ABSTRACT, KW_AS, KW_ASSERT, KW_BREAK, KW_CATCH, KW_CASE, KW_CLASS,
KW_CONST, KW_CONTINUE, KW_DEFAULT, KW_DO, KW_ELSE, KW_FALSE, KW_FINAL,
KW_FINALLY, KW_FOR, KW_FOREACH, KW_IF, KW_INTERNAL, KW_IS, KW_ISNOT, KW_IT,
KW_MIXIN, KW_NATIVE, KW_NEW, KW_NULL, KW_ONCE, KW_OVERRIDE, KW_PRIVATE,
KW_PROTECTED, KW_PUBLIC, KW_READONLY, KW_RETURN, KW_STATIC, KW_SUPER, KW_SWITCH,
KW_THIS, KW_THROW, KW_TRUE, KW_TRY, KW_USING, KW_VIRTUAL, KW_VOID, KW_VOLATILE,
KW_WHILE));
}
// -- Keywords --
public final Rule KW_ABSTRACT = keyword("abstract");
public final Rule KW_AS = keyword("as");
public final Rule KW_ASSERT = keyword("assert"); // not a grammar kw
public final Rule KW_BREAK = keyword("break");
public final Rule KW_CATCH = keyword("catch");
public final Rule KW_CASE = keyword("case");
public final Rule KW_CLASS = keyword("class");
public final Rule KW_CONST = keyword("const");
public final Rule KW_CONTINUE = keyword("continue");
public final Rule KW_DEFAULT = keyword("default");
public final Rule KW_DO = keyword("do"); // unused, reserved
public final Rule KW_ELSE = keyword("else");
public final Rule KW_FALSE = keyword("false");
public final Rule KW_FINAL = keyword("final");
public final Rule KW_FINALLY = keyword("finally");
public final Rule KW_FOR = keyword("for");
public final Rule KW_FOREACH = keyword("foreach"); // unused, reserved
public final Rule KW_IF = keyword("if");
public final Rule KW_INTERNAL = keyword("internal");
public final Rule KW_IS = keyword("is");
public final Rule KW_IT = keyword("ii");
public final Rule KW_ISNOT = keyword("isnot");
public final Rule KW_MIXIN = keyword("mixin");
public final Rule KW_NATIVE = keyword("native");
public final Rule KW_NEW = keyword("new");
public final Rule KW_NULL = keyword("null");
public final Rule KW_ONCE = keyword("once");
public final Rule KW_OVERRIDE = keyword("override");
public final Rule KW_PRIVATE = keyword("private");
public final Rule KW_PUBLIC = keyword("public");
public final Rule KW_PROTECTED = keyword("protected");
public final Rule KW_READONLY = keyword("readonly");
public final Rule KW_RETURN = keyword("return");
public final Rule KW_STATIC = keyword("static");
public final Rule KW_SUPER = keyword("super");
public final Rule KW_SWITCH = keyword("switch");
public final Rule KW_THIS = keyword("this");
public final Rule KW_THROW = keyword("throw");
public final Rule KW_TRUE = keyword("true");
public final Rule KW_TRY = keyword("try");
public final Rule KW_USING = keyword("using");
public final Rule KW_VIRTUAL = keyword("virtual");
public final Rule KW_VOID = keyword("void"); // unused, reserved
public final Rule KW_VOLATILE = keyword("volatile"); // unused, reserved
public final Rule KW_WHILE = keyword("while");
// Non keyword meningful items
public final Rule ENUM = keyword("enum");
public final Rule FACET = keyword("facet");
public final Rule GET = keyword("get");
public final Rule SET = keyword("set");
// operators
public final Rule OP_SAFE_CALL = terminal("?.");
public final Rule OP_SAFE_DYN_CALL = terminal("?->");
public final Rule OP_ARROW = terminal("->");
public final Rule OP_ASSIGN = terminal(":=");
public final Rule OP_ELVIS = terminal("?:");
public final Rule OP_OR = terminal("||");
public final Rule OP_AND = terminal("&&");
public final Rule OP_RANGE = terminal("..");
public final Rule OP_RANGE_EXCL = terminal("..<");
public final Rule OP_CURRY = terminal("&");
public final Rule OP_BANG = terminal("!");
public final Rule OP_2PLUS = terminal("++");
public final Rule OP_2MINUS = terminal("
public final Rule OP_PLUS = terminal("+");
public final Rule OP_MINUS = terminal("-");
public final Rule OP_MULT = terminal("*");
public final Rule OP_DIV = terminal("/");
public final Rule OP_MODULO = terminal("%");
public final Rule OP_POUND = terminal("
// comparators
public final Rule CP_EQUALITY = firstOf(terminal("==="), terminal("!=="),
terminal("=="), terminal("!="));
public final Rule CP_COMPARATORS = firstOf(terminal("<=>"), terminal("<="),
terminal(">="), terminal("<"), terminal(">"));
// separators
public final Rule SP_PIPE = terminal("|");
public final Rule SP_QMARK = terminal("?");
public final Rule SP_COLCOL = terminal("::");
public final Rule SP_COL = terminal(":");
public final Rule SP_COMMA = terminal(",");
public final Rule SP_SEMI = terminal(";");
// assignment
public final Rule AS_EQUAL = terminal("=");
public final Rule AS_ASSIGN_OPS = firstOf(terminal("*="), terminal("/="),
terminal("%="), terminal("+="), terminal("-="));
// others
public final Rule QUOTES3 = terminal("\"\"\"");
public final Rule QUOTE = terminal("\"");
public final Rule TICK = terminal("`");
public final Rule SINGLE_Q = terminal("'");
public final Rule DOT = terminal(".");
public final Rule AT = terminal("@");
public final Rule DSL_OPEN = terminal("<|");
public final Rule DSL_CLOSE = terminal("|>");
public final Rule SQ_BRACKET_L = terminal("[");
public final Rule SQ_BRACKET_R = terminal("]");
public final Rule BRACKET_L = terminal("{");
public final Rule BRACKET_R = terminal("}");
public final Rule PAR_L = terminal("(");
public final Rule PAR_R = terminal(")");
// shortcut for optional spacing
public final Rule OPT_SP = optional(spacing());
/**
* Override because sandard firstOf() complains about empty matches
* and we allow empty matches in peekTest
* @param rules
* @return
*/
@Override
@Cached
public Rule firstOf(Object[] rules)
{
return new PeekFirstOfMatcher(toRules(rules));
}
/**
* Custom test matchers which allow result without matching any data (boolean check)
* @param rule
* @return
*/
@Cached
public Rule peekTestNot(Object rule)
{
return new PeekTestMatcher(toRule(rule), true);
}
@Cached
public Rule peekTest(Object rule)
{
return new PeekTestMatcher(toRule(rule), false);
}
/**
* Custom action to find an end of statement
* @return
*/
public Rule eos()
{
return sequence(OPT_SP, firstOf(
SP_SEMI,
LF(),
peekTest(BRACKET_R), // '}' is end of statement too, but do NOT consume it !
peekTest(eoi()))); // EOI is end of statement too, but do NOT consume it !
}
/**Pass if not following some whitespace*/
public Rule noSpace()
{
return peekTestNot(afterSpace());
}
public boolean afterSpace()
{
char c = getContext().getCurrentLocation().lookAhead(getContext().getInputBuffer(), -1);
return Character.isWhitespace(c);
}
public boolean setFieldInit(boolean val)
{
inFieldInit = val;
return true;
}
public boolean setNoSimpleMap(boolean val)
{
noSimpleMap = val;
return true;
}
public boolean setInEnum(boolean val)
{
inEnum = val;
return true;
}
// Debugging utils
/** System.out - eval to true*/
public boolean echo(String str)
{
System.out.println(str);
return true;
}
/** System.out - eval to false*/
public boolean echof(String str)
{
System.out.println(str);
return false;
}
/** System.out current node path - eval to true*/
public boolean printPath()
{
System.out.println(getContext().getPath());
return true;
}
}
|
package net.maizegenetics.pipeline;
import java.awt.Frame;
import java.io.BufferedReader;
import java.io.File;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import net.maizegenetics.baseplugins.AbstractDisplayPlugin;
import net.maizegenetics.baseplugins.CombineDataSetsPlugin;
import net.maizegenetics.baseplugins.ConvertAlignmentCoordinatesPlugin;
import net.maizegenetics.baseplugins.ExportMultiplePlugin;
import net.maizegenetics.baseplugins.FileLoadPlugin;
import net.maizegenetics.baseplugins.FilterAlignmentPlugin;
import net.maizegenetics.baseplugins.FilterSiteNamePlugin;
import net.maizegenetics.baseplugins.FilterTaxaAlignmentPlugin;
import net.maizegenetics.baseplugins.FilterTraitsPlugin;
import net.maizegenetics.baseplugins.FixedEffectLMPlugin;
import net.maizegenetics.baseplugins.FlapjackLoadPlugin;
import net.maizegenetics.baseplugins.GenotypeImputationPlugin;
import net.maizegenetics.baseplugins.IntersectionAlignmentPlugin;
import net.maizegenetics.baseplugins.KinshipPlugin;
import net.maizegenetics.baseplugins.LinkageDiseqDisplayPlugin;
import net.maizegenetics.baseplugins.LinkageDisequilibriumPlugin;
import net.maizegenetics.baseplugins.MLMPlugin;
import net.maizegenetics.baseplugins.NumericalGenotypePlugin;
import net.maizegenetics.baseplugins.PlinkLoadPlugin;
import net.maizegenetics.baseplugins.TableDisplayPlugin;
import net.maizegenetics.baseplugins.UnionAlignmentPlugin;
import net.maizegenetics.baseplugins.genomicselection.RidgeRegressionEmmaPlugin;
import net.maizegenetics.pal.gui.LinkageDisequilibriumComponent;
import net.maizegenetics.pal.popgen.LinkageDisequilibrium.testDesign;
import net.maizegenetics.pal.ids.Identifier;
import net.maizegenetics.pal.ids.SimpleIdGroup;
import net.maizegenetics.plugindef.AbstractPlugin;
import net.maizegenetics.plugindef.DataSet;
import net.maizegenetics.plugindef.Datum;
import net.maizegenetics.plugindef.Plugin;
import net.maizegenetics.plugindef.PluginEvent;
import net.maizegenetics.plugindef.PluginListener;
import net.maizegenetics.plugindef.ThreadedPluginListener;
import net.maizegenetics.prefs.TasselPrefs;
import net.maizegenetics.progress.ProgressPanel;
import net.maizegenetics.tassel.DataTreePanel;
import net.maizegenetics.tassel.TASSELMainFrame;
import net.maizegenetics.util.ExceptionUtils;
import net.maizegenetics.util.Utils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
*
* @author terryc
*/
public class TasselPipeline implements PluginListener {
private static final Logger myLogger = Logger.getLogger(TasselPipeline.class);
private final TASSELMainFrame myMainFrame;
private final Map<String, List> myForks = new LinkedHashMap<String, List>();
private String myCurrentFork = null;
private List<Plugin> myCurrentPipe = null;
private Plugin myFirstPlugin = null;
private final List<ThreadedPluginListener> myThreads = new ArrayList();
private final Map<Plugin, Integer> myProgressValues = new HashMap<Plugin, Integer>();
/** Creates a new instance of TasselPipeline */
public TasselPipeline(String args[], TASSELMainFrame frame) {
myMainFrame = frame;
java.util.Properties props = new java.util.Properties();
props.setProperty("log4j.logger.net.maizegenetics", "INFO, stdout");
props.setProperty("log4j.appender.stdout",
"org.apache.log4j.ConsoleAppender");
props.setProperty("log4j.appender.stdout.layout",
"org.apache.log4j.TTCCLayout");
PropertyConfigurator.configure(props);
try {
parseArgs(args);
if (myMainFrame != null) {
ProgressPanel progressPanel = myMainFrame.getProgressPanel();
if (progressPanel != null) {
Iterator itr = myForks.keySet().iterator();
while (itr.hasNext()) {
String key = (String) itr.next();
List<Plugin> current = myForks.get(key);
progressPanel.addPipelineSegment(current);
}
}
}
for (int i = 0; i < myThreads.size(); i++) {
ThreadedPluginListener current = (ThreadedPluginListener) myThreads.get(i);
current.start();
}
} catch (Exception e) {
System.exit(1);
}
}
public static void main(String args[]) {
if ((args.length >= 2) && (args[0].equalsIgnoreCase("-createXML"))) {
String xmlFilename = args[1].trim();
String[] temp = new String[args.length - 2];
System.arraycopy(args, 2, temp, 0, temp.length);
TasselPipelineXMLUtil.writeArgsAsXML(xmlFilename, temp);
} else if ((args.length >= 2) && (args[0].equalsIgnoreCase("-translateXML"))) {
String xmlFilename = args[1].trim();
String[] result = TasselPipelineXMLUtil.readXMLAsArgs(xmlFilename);
for (int i = 0; i < result.length; i++) {
System.out.print(result[i]);
System.out.print(" ");
}
System.out.println("");
} else {
new TasselPipeline(args, null);
}
}
public void parseArgs(String[] args) {
if ((args.length >= 2) && (args[0].equalsIgnoreCase("-configFile"))) {
String xmlFilename = args[1].trim();
args = TasselPipelineXMLUtil.readXMLAsArgs(xmlFilename);
}
int index = 0;
while (index < args.length) {
try {
String current = args[index++];
if (!current.startsWith("-")) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: expecting argument beginning with dash: " + current);
}
if (current.startsWith("-runfork")) {
String key = current.replaceFirst("-runfork", "-fork");
List specifiedPipe = (List) myForks.get(key);
if (specifiedPipe == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: unknown fork: " + current);
} else if (specifiedPipe.size() == 0) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: empty fork: " + current);
} else {
PluginEvent event = new PluginEvent(new DataSet((Datum) null, null));
ThreadedPluginListener thread = new ThreadedPluginListener((Plugin) specifiedPipe.get(0), event);
myThreads.add(thread);
}
} else if (current.startsWith("-fork")) {
if ((myCurrentPipe != null) && (myCurrentPipe.size() != 0)) {
myCurrentPipe.get(myCurrentPipe.size() - 1).setThreaded(true);
}
myCurrentFork = current;
myCurrentPipe = new ArrayList<Plugin>();
myForks.put(myCurrentFork, myCurrentPipe);
} else if (current.startsWith("-input")) {
String key = current.replaceFirst("-input", "-fork");
List specifiedPipe = (List) myForks.get(key);
if (specifiedPipe == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: unknown input: " + current);
} else {
Plugin lastCurrentPipe = null;
try {
lastCurrentPipe = (Plugin) myCurrentPipe.get(myCurrentPipe.size() - 1);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: -input must come after plugin in current fork.");
}
Plugin endSpecifiedPipe = (Plugin) specifiedPipe.get(specifiedPipe.size() - 1);
lastCurrentPipe.receiveInput(endSpecifiedPipe);
}
} else if (current.startsWith("-inputOnce")) {
String key = current.replaceFirst("-input", "-fork");
List specifiedPipe = (List) myForks.get(key);
if (specifiedPipe == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: unknown input: " + current);
} else {
CombineDataSetsPlugin combinePlugin = null;
try {
combinePlugin = (CombineDataSetsPlugin) myCurrentPipe.get(myCurrentPipe.size() - 1);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: -inputOnce must follow -combine flag.");
}
Plugin endSpecifiedPipe = (Plugin) specifiedPipe.get(specifiedPipe.size() - 1);
combinePlugin.receiveDataSetOnceFrom(endSpecifiedPipe);
}
} else if (current.startsWith("-combine")) {
current = current.replaceFirst("-combine", "-fork");
if ((myCurrentPipe != null) && (myCurrentPipe.size() != 0)) {
myCurrentPipe.get(myCurrentPipe.size() - 1).setThreaded(true);
}
myCurrentFork = current;
myCurrentPipe = new ArrayList<Plugin>();
myForks.put(myCurrentFork, myCurrentPipe);
integratePlugin(new CombineDataSetsPlugin(), false);
} else if (current.equalsIgnoreCase("-t")) {
String traitFile = args[index++].trim();
loadFile(traitFile, FileLoadPlugin.TasselFileType.Numerical);
} else if (current.equalsIgnoreCase("-s")) {
String inputFile = args[index++].trim();
loadFile(inputFile, FileLoadPlugin.TasselFileType.Sequence);
} else if (current.equalsIgnoreCase("-p")) {
String inputFile = args[index++].trim();
loadFile(inputFile, FileLoadPlugin.TasselFileType.Polymorphism);
} else if (current.equalsIgnoreCase("-a")) {
String inputFile = args[index++].trim();
loadFile(inputFile, FileLoadPlugin.TasselFileType.Annotated);
} else if (current.equalsIgnoreCase("-k")) {
String kinshipFile = args[index++].trim();
loadFile(kinshipFile, FileLoadPlugin.TasselFileType.SqrMatrix);
} else if (current.equalsIgnoreCase("-q")) {
String populationFile = args[index++].trim();
loadFile(populationFile, FileLoadPlugin.TasselFileType.Phenotype);
} else if (current.equalsIgnoreCase("-h")) {
String hapFile = args[index++].trim();
loadFile(hapFile, FileLoadPlugin.TasselFileType.Hapmap);
} else if (current.equalsIgnoreCase("-r")) {
String phenotypeFile = args[index++].trim();
loadFile(phenotypeFile, FileLoadPlugin.TasselFileType.Phenotype);
} else if (current.equalsIgnoreCase("-plink")) {
String pedFile = null;
String mapFile = null;
for (int i = 0; i < 2; i++) {
String fileType = args[index++].trim();
String filename = args[index++].trim();
if (fileType.equalsIgnoreCase("-ped")) {
pedFile = filename;
} else if (fileType.equalsIgnoreCase("-map")) {
mapFile = filename;
} else {
throw new IllegalArgumentException("TasselPipeline: parseArgs: -plink: unknown file type: " + fileType);
}
}
if ((pedFile == null) || (mapFile == null)) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: -plink must specify both ped and map files.");
}
PlinkLoadPlugin plugin = new PlinkLoadPlugin(myMainFrame, false);
plugin.setPedFile(pedFile);
plugin.setMapFile(mapFile);
integratePlugin(plugin, true);
} else if (current.equalsIgnoreCase("-flapjack")) {
String genoFile = null;
String mapFile = null;
for (int i = 0; i < 2; i++) {
String fileType = args[index++].trim();
String filename = args[index++].trim();
if (fileType.equalsIgnoreCase("-geno")) {
genoFile = filename;
} else if (fileType.equalsIgnoreCase("-map")) {
mapFile = filename;
} else {
throw new IllegalArgumentException("TasselPipeline: parseArgs: -flapjack: unknown file type: " + fileType);
}
}
if ((genoFile == null) || (mapFile == null)) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: -flapjack must specify both ped and map files.");
}
FlapjackLoadPlugin plugin = new FlapjackLoadPlugin(myMainFrame, false);
plugin.setGenoFile(genoFile);
plugin.setMapFile(mapFile);
integratePlugin(plugin, true);
} else if (current.equalsIgnoreCase("-fasta")) {
String fastaFile = args[index++].trim();
loadFile(fastaFile, FileLoadPlugin.TasselFileType.Fasta);
} else if (current.equalsIgnoreCase("-geneticMap")) {
String geneticMapFile = args[index++].trim();
loadFile(geneticMapFile, FileLoadPlugin.TasselFileType.GeneticMap);
} else if (current.equalsIgnoreCase("-taxaJoinStrict")) {
String temp = args[index++].trim();
boolean strict = true;
if (temp.equalsIgnoreCase("false")) {
strict = false;
} else if (temp.equalsIgnoreCase("true")) {
strict = true;
} else {
throw new IllegalArgumentException("TasselPipeline: parseArgs: -taxaJoinStrict parameter must be true or false.");
}
TasselPrefs.putIDJoinStrict(strict);
} else if (current.equalsIgnoreCase("-union")) {
UnionAlignmentPlugin plugin = new UnionAlignmentPlugin(myMainFrame, false);
integratePlugin(plugin, true);
} else if (current.equalsIgnoreCase("-intersect")) {
IntersectionAlignmentPlugin plugin = new IntersectionAlignmentPlugin(myMainFrame, false);
integratePlugin(plugin, true);
} else if (current.equalsIgnoreCase("-excludeLastTrait")) {
FilterTraitsPlugin plugin = new FilterTraitsPlugin(myMainFrame, false);
ArrayList input = new ArrayList();
int[] excludeLast = new int[]{-1};
input.add(excludeLast);
plugin.setIncludeList(input);
integratePlugin(plugin, true);
} else if (current.equalsIgnoreCase("-mlm")) {
MLMPlugin plugin = new MLMPlugin(myMainFrame, false);
integratePlugin(plugin, true);
} else if (current.equalsIgnoreCase("-mlmVarCompEst")) {
MLMPlugin plugin = (MLMPlugin) findLastPluginFromCurrentPipe(new Class[]{MLMPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No MLM step defined: " + current);
}
String method = args[index++].trim();
plugin.setVarCompEst(method);
} else if (current.equalsIgnoreCase("-mlmCompressionLevel")) {
MLMPlugin plugin = (MLMPlugin) findLastPluginFromCurrentPipe(new Class[]{MLMPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No MLM step defined: " + current);
}
String type = args[index++].trim();
if (type.equalsIgnoreCase("Optimum")) {
plugin.setCompressionType(MLMPlugin.CompressionType.Optimum);
} else if (type.equalsIgnoreCase("Custom")) {
plugin.setCompressionType(MLMPlugin.CompressionType.Custom);
} else if (type.equalsIgnoreCase("None")) {
plugin.setCompressionType(MLMPlugin.CompressionType.None);
} else {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Unknown compression type: " + type);
}
} else if (current.equalsIgnoreCase("-mlmCustomCompression")) {
MLMPlugin plugin = (MLMPlugin) findLastPluginFromCurrentPipe(new Class[]{MLMPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No MLM step defined: " + current);
}
String temp = args[index++].trim();
double value = 0;
try {
value = Double.parseDouble(temp);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing custom compression: " + temp);
}
plugin.setCustomCompression(value);
} else if (current.equalsIgnoreCase("-mlmOutputFile")) {
MLMPlugin plugin = (MLMPlugin) findLastPluginFromCurrentPipe(new Class[]{MLMPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No MLM step defined: " + current);
}
String filename = args[index++].trim();
plugin.setOutputName(filename);
} else if (current.equalsIgnoreCase("-mlmMaxP")) {
MLMPlugin plugin = (MLMPlugin) findLastPluginFromCurrentPipe(new Class[]{MLMPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No MLM step defined: " + current);
}
String temp = args[index++].trim();
double maxP = 0;
try {
maxP = Double.parseDouble(temp);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing max P: " + temp);
}
plugin.setMaxp(maxP);
} else if (current.equalsIgnoreCase("-glm")) {
FixedEffectLMPlugin plugin = new FixedEffectLMPlugin(myMainFrame, false);
integratePlugin(plugin, true);
} else if (current.equalsIgnoreCase("-glmOutputFile")) {
FixedEffectLMPlugin plugin = (FixedEffectLMPlugin) findLastPluginFromCurrentPipe(new Class[]{FixedEffectLMPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No GLM step defined: " + current);
}
String filename = args[index++].trim();
plugin.setOutputFile(filename);
} else if (current.equalsIgnoreCase("-glmMaxP")) {
FixedEffectLMPlugin plugin = (FixedEffectLMPlugin) findLastPluginFromCurrentPipe(new Class[]{FixedEffectLMPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No GLM step defined: " + current);
}
String temp = args[index++].trim();
double maxP = 0;
try {
maxP = Double.parseDouble(temp);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing max P: " + temp);
}
plugin.setMaxP(maxP);
} else if (current.equalsIgnoreCase("-glmPermutations")) {
FixedEffectLMPlugin plugin = (FixedEffectLMPlugin) findLastPluginFromCurrentPipe(new Class[]{FixedEffectLMPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No GLM step defined: " + current);
}
String temp = args[index++].trim();
int permutations = 0;
try {
permutations = Integer.parseInt(temp);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing number of permutations: " + temp);
}
plugin.setPermute(true);
plugin.setNumberOfPermutations(permutations);
} else if (current.equalsIgnoreCase("-td_csv")) {
String csvFile = args[index++].trim();
getTableDisplayPlugin(csvFile, current);
} else if (current.equalsIgnoreCase("-td_tab")) {
String tabFile = args[index++].trim();
getTableDisplayPlugin(tabFile, current);
} else if (current.equalsIgnoreCase("-td_gui")) {
getTableDisplayPlugin(null, current);
} else if (current.equalsIgnoreCase("-ld")) {
getLinkageDisequilibriumPlugin();
} else if (current.equalsIgnoreCase("-ldPermNum")) {
LinkageDisequilibriumPlugin plugin = null;
try {
plugin = (LinkageDisequilibriumPlugin) myCurrentPipe.get(myCurrentPipe.size() - 1);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No LinkageDisequilibriumPlugin step defined: " + current);
}
String str = args[index++].trim();
int permNum = -1;
try {
permNum = Integer.parseInt(str);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem with LD Permutation number: " + str);
}
if (permNum < 1) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: LD Permutation size can't be less than 1.");
}
plugin.setPermutationNumber(permNum);
} else if (current.equalsIgnoreCase("-ldTestSite")) {
LinkageDisequilibriumPlugin plugin = null;
try {
plugin = (LinkageDisequilibriumPlugin) myCurrentPipe.get(myCurrentPipe.size() - 1);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No LinkageDisequilibriumPlugin step defined: " + current);
}
String str = args[index++].trim();
int testSite = -1;
try {
testSite = Integer.parseInt(str);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem with LD Test Site number: " + str);
}
if (testSite < 1) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: LD Test Site can't be less than 1.");
}
plugin.setTestSite(testSite);
} else if (current.equalsIgnoreCase("-ldWinSize")) {
LinkageDisequilibriumPlugin plugin = null;
try {
plugin = (LinkageDisequilibriumPlugin) myCurrentPipe.get(myCurrentPipe.size() - 1);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No LinkageDisequilibriumPlugin step defined: " + current);
}
String str = args[index++].trim();
int winSize = -1;
try {
winSize = Integer.parseInt(str);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem with LD Window Size: " + str);
}
if (winSize < 1) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: LD Window Size can't be less than 1.");
}
plugin.setWinSize(winSize);
} else if (current.equalsIgnoreCase("-ldRapidAnalysis")) {
LinkageDisequilibriumPlugin plugin = null;
try {
plugin = (LinkageDisequilibriumPlugin) myCurrentPipe.get(myCurrentPipe.size() - 1);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No LinkageDisequilibriumPlugin step defined: " + current);
}
String temp = args[index++].trim();
boolean rapid = true;
if (temp.equalsIgnoreCase("false")) {
rapid = false;
} else if (temp.equalsIgnoreCase("true")) {
rapid = true;
} else {
throw new IllegalArgumentException("TasselPipeline: parseArgs: LD Rapid Analysis parameter must be true or false.");
}
plugin.setRapidAnalysis(rapid);
} else if (current.equalsIgnoreCase("-ldType")) {
LinkageDisequilibriumPlugin plugin = null;
try {
plugin = (LinkageDisequilibriumPlugin) myCurrentPipe.get(myCurrentPipe.size() - 1);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No LinkageDisequilibriumPlugin step defined: " + current);
}
String temp = args[index++].trim();
if (temp.equalsIgnoreCase("All")) {
plugin.setLDType(testDesign.All);
} else if (temp.equalsIgnoreCase("SlidingWindow")) {
plugin.setLDType(testDesign.SlidingWindow);
} else if (temp.equalsIgnoreCase("SiteByAll")) {
plugin.setLDType(testDesign.SiteByAll);
} else {
throw new IllegalArgumentException("TasselPipeline: parseArgs: LD Type parameter must be All, SlidingWindow, or SiteByAll.");
}
} else if (current.equalsIgnoreCase("-ldd")) {
String outputType = args[index++].trim();
getLinkageDiseqDisplayPlugin(outputType);
} else if (current.equalsIgnoreCase("-ldplotsize")) {
LinkageDiseqDisplayPlugin plugin = null;
try {
plugin = (LinkageDiseqDisplayPlugin) myCurrentPipe.get(myCurrentPipe.size() - 1);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No LinkageDiseqDisplay step defined: " + current);
}
String str = args[index++].trim();
int plotSize = -1;
try {
plotSize = Integer.parseInt(str);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem with LD Plot size number: " + str);
}
if (plotSize < 1) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: LD Plot size can't be less than 1.");
}
plugin.setImageSize(plotSize, plotSize);
} else if (current.equalsIgnoreCase("-ldplotlabels")) {
LinkageDiseqDisplayPlugin plugin = null;
try {
plugin = (LinkageDiseqDisplayPlugin) myCurrentPipe.get(myCurrentPipe.size() - 1);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No LinkageDiseqDisplay step defined: " + current);
}
String temp = args[index++].trim();
boolean ldPlotLabels = true;
if (temp.equalsIgnoreCase("false")) {
ldPlotLabels = false;
} else if (temp.equalsIgnoreCase("true")) {
ldPlotLabels = true;
} else {
throw new IllegalArgumentException("TasselPipeline: parseArgs: LD Plot labels parameter must be true or false.");
}
plugin.setShowLabels(ldPlotLabels);
} else if (current.equalsIgnoreCase("-o")) {
Plugin plugin = findLastPluginFromCurrentPipe(new Class[]{LinkageDiseqDisplayPlugin.class});
String temp = args[index++].trim();
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No LinkageDiseqDisplay step defined: " + current + " " + temp);
} else if (plugin instanceof LinkageDiseqDisplayPlugin) {
((LinkageDiseqDisplayPlugin) plugin).setSaveFile(new File(temp));
}
} else if (current.equalsIgnoreCase("-ck")) {
KinshipPlugin plugin = new KinshipPlugin(myMainFrame, false);
integratePlugin(plugin, true);
} else if (current.equalsIgnoreCase("-ckModelHets")) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: -ckModelHets not needed in Tassel 4.0. It is designed to handle heterzygotes.");
} else if (current.equalsIgnoreCase("-ckRescale")) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: -ckRescale not needed in Tassel 4.0. It is designed to handle heterzygotes.");
} else if (current.equalsIgnoreCase("-gs")) {
RidgeRegressionEmmaPlugin plugin = new RidgeRegressionEmmaPlugin(myMainFrame, false);
integratePlugin(plugin, true);
} else if (current.equalsIgnoreCase("-export")) {
String[] filenames = args[index++].trim().split(",");
ExportMultiplePlugin plugin = new ExportMultiplePlugin(myMainFrame);
plugin.setSaveFiles(filenames);
integratePlugin(plugin, false);
} else if (current.equalsIgnoreCase("-exportType")) {
ExportMultiplePlugin plugin = (ExportMultiplePlugin) findLastPluginFromCurrentPipe(new Class[]{ExportMultiplePlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No Export step defined: " + current);
}
String type = args[index++].trim();
if (type.equalsIgnoreCase(FileLoadPlugin.TasselFileType.Flapjack.toString())) {
plugin.setAlignmentFileType(FileLoadPlugin.TasselFileType.Flapjack);
} else if (type.equalsIgnoreCase(FileLoadPlugin.TasselFileType.Hapmap.toString())) {
plugin.setAlignmentFileType(FileLoadPlugin.TasselFileType.Hapmap);
} else if (type.equalsIgnoreCase(FileLoadPlugin.TasselFileType.Phylip_Inter.toString())) {
plugin.setAlignmentFileType(FileLoadPlugin.TasselFileType.Phylip_Inter);
} else if (type.equalsIgnoreCase(FileLoadPlugin.TasselFileType.Phylip_Seq.toString())) {
plugin.setAlignmentFileType(FileLoadPlugin.TasselFileType.Phylip_Seq);
} else if (type.equalsIgnoreCase(FileLoadPlugin.TasselFileType.Plink.toString())) {
plugin.setAlignmentFileType(FileLoadPlugin.TasselFileType.Plink);
}
} else if (current.equalsIgnoreCase("-impute")) {
GenotypeImputationPlugin plugin = new GenotypeImputationPlugin(myMainFrame, false);
integratePlugin(plugin, true);
} else if (current.equalsIgnoreCase("-imputeMethod")) {
GenotypeImputationPlugin plugin = (GenotypeImputationPlugin) findLastPluginFromCurrentPipe(new Class[]{GenotypeImputationPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No Impute step defined: " + current);
}
String temp = args[index++].trim();
if (temp.equalsIgnoreCase(GenotypeImputationPlugin.ImpMethod.Length.toString())) {
plugin.setMethod(GenotypeImputationPlugin.ImpMethod.Length);
} else if (temp.equalsIgnoreCase(GenotypeImputationPlugin.ImpMethod.MajorAllele.toString())) {
plugin.setMethod(GenotypeImputationPlugin.ImpMethod.MajorAllele);
} else if (temp.equalsIgnoreCase(GenotypeImputationPlugin.ImpMethod.IBDProb.toString())) {
plugin.setMethod(GenotypeImputationPlugin.ImpMethod.IBDProb);
} else if (temp.equalsIgnoreCase(GenotypeImputationPlugin.ImpMethod.SimilarWindow.toString())) {
plugin.setMethod(GenotypeImputationPlugin.ImpMethod.SimilarWindow);
} else {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Not defined impute method: " + temp);
}
} else if (current.equalsIgnoreCase("-imputeMinLength")) {
GenotypeImputationPlugin plugin = (GenotypeImputationPlugin) findLastPluginFromCurrentPipe(new Class[]{GenotypeImputationPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No Impute step defined: " + current);
}
String temp = args[index++].trim();
int minLength = 0;
try {
minLength = Integer.parseInt(temp);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing impute min length: " + temp);
}
plugin.setMinLength(minLength);
} else if (current.equalsIgnoreCase("-imputeMaxMismatch")) {
GenotypeImputationPlugin plugin = (GenotypeImputationPlugin) findLastPluginFromCurrentPipe(new Class[]{GenotypeImputationPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No Impute step defined: " + current);
}
String temp = args[index++].trim();
int maxMismatch = 0;
try {
maxMismatch = Integer.parseInt(temp);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing impute max mismatch: " + temp);
}
plugin.setMaxMisMatch(maxMismatch);
} else if (current.equalsIgnoreCase("-imputeMinProb")) {
GenotypeImputationPlugin plugin = (GenotypeImputationPlugin) findLastPluginFromCurrentPipe(new Class[]{GenotypeImputationPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No Impute step defined: " + current);
}
String temp = args[index++].trim();
double minProb = 0;
try {
minProb = Double.parseDouble(temp);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing impute min probability: " + temp);
}
plugin.setMinProb(minProb);
} else if (current.equalsIgnoreCase("-filterAlign")) {
FilterAlignmentPlugin plugin = new FilterAlignmentPlugin(myMainFrame, false);
integratePlugin(plugin, true);
} else if (current.equalsIgnoreCase("-filterAlignMinCount")) {
FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current);
}
String temp = args[index++].trim();
int minCount = 0;
try {
minCount = Integer.parseInt(temp);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing filter alignment min count: " + temp);
}
plugin.setMinCount(minCount);
} else if (current.equalsIgnoreCase("-filterAlignMinFreq")) {
FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current);
}
String temp = args[index++].trim();
double minFreq = 0;
try {
minFreq = Double.parseDouble(temp);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing filter alignment min frequency: " + temp);
}
plugin.setMinFreq(minFreq);
} else if (current.equalsIgnoreCase("-filterAlignMaxFreq")) {
FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current);
}
String temp = args[index++].trim();
double maxFreq = 0;
try {
maxFreq = Double.parseDouble(temp);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing filter alignment max frequency: " + temp);
}
plugin.setMaxFreq(maxFreq);
} else if (current.equalsIgnoreCase("-filterAlignStart")) {
FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current);
}
String temp = args[index++].trim();
int start = 0;
try {
start = Integer.parseInt(temp);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing filter alignment start: " + temp);
}
plugin.setStart(start);
} else if (current.equalsIgnoreCase("-filterAlignEnd")) {
FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current);
}
String temp = args[index++].trim();
int end = 0;
try {
end = Integer.parseInt(temp);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing filter alignment end: " + temp);
}
plugin.setEnd(end);
} else if (current.equalsIgnoreCase("-filterAlignExtInd")) {
FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current);
}
plugin.setExtractIndels(true);
} else if (current.equalsIgnoreCase("-filterAlignRemMinor")) {
FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current);
}
plugin.setFilterMinorSNPs(true);
} else if (current.equalsIgnoreCase("-filterAlignSliding")) {
FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current);
}
plugin.setDoSlidingHaps(true);
} else if (current.equalsIgnoreCase("-filterAlignHapLen")) {
FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current);
}
String temp = args[index++].trim();
int hapLen = 0;
try {
hapLen = Integer.parseInt(temp);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing filter alignment haplotype length: " + temp);
}
plugin.setWinSize(hapLen);
} else if (current.equalsIgnoreCase("-filterAlignStepLen")) {
FilterAlignmentPlugin plugin = (FilterAlignmentPlugin) findLastPluginFromCurrentPipe(new Class[]{FilterAlignmentPlugin.class});
if (plugin == null) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No Filter Alignment step defined: " + current);
}
String temp = args[index++].trim();
int stepLen = 0;
try {
stepLen = Integer.parseInt(temp);
} catch (Exception e) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Problem parsing filter alignment step length: " + temp);
}
plugin.setStepSize(stepLen);
} else if (current.equalsIgnoreCase("-numericalGenoTransform")) {
NumericalGenotypePlugin plugin = new NumericalGenotypePlugin();
String temp = args[index++].trim();
if (temp.equalsIgnoreCase(NumericalGenotypePlugin.TRANSFORM_TYPE.colapse.toString())) {
plugin.setTransformType(NumericalGenotypePlugin.TRANSFORM_TYPE.colapse);
} else if (temp.equalsIgnoreCase(NumericalGenotypePlugin.TRANSFORM_TYPE.separated.toString())) {
plugin.setTransformType(NumericalGenotypePlugin.TRANSFORM_TYPE.separated);
} else {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Not defined genotype transform type: " + temp);
}
integratePlugin(plugin, true);
} else if (current.equalsIgnoreCase("-includeTaxa")) {
FilterTaxaAlignmentPlugin plugin = new FilterTaxaAlignmentPlugin(myMainFrame, false);
String[] taxa = args[index++].trim().split(",");
Identifier[] ids = new Identifier[taxa.length];
for (int i = 0; i < taxa.length; i++) {
ids[i] = new Identifier(taxa[i]);
}
plugin.setIdsToKeep(new SimpleIdGroup(ids));
integratePlugin(plugin, true);
} else if (current.equalsIgnoreCase("-includeTaxaInFile")) {
FilterTaxaAlignmentPlugin plugin = new FilterTaxaAlignmentPlugin(myMainFrame, false);
String taxaListFile = args[index++].trim();
List taxa = new ArrayList();
BufferedReader br = null;
try {
br = Utils.getBufferedReader(taxaListFile);
String inputline = br.readLine();
Pattern sep = Pattern.compile("\\s+");
while (inputline != null) {
inputline = inputline.trim();
String[] parsedline = sep.split(inputline);
for (int i = 0; i < parsedline.length; i++) {
if ((parsedline[i] != null) || (parsedline[i].length() != 0)) {
taxa.add(parsedline[i]);
}
}
inputline = br.readLine();
}
} finally {
br.close();
}
Identifier[] ids = new Identifier[taxa.size()];
for (int i = 0; i < taxa.size(); i++) {
ids[i] = new Identifier((String) taxa.get(i));
}
plugin.setIdsToKeep(new SimpleIdGroup(ids));
integratePlugin(plugin, true);
} else if (current.equalsIgnoreCase("-excludeTaxa")) {
FilterTaxaAlignmentPlugin plugin = new FilterTaxaAlignmentPlugin(myMainFrame, false);
String[] taxa = args[index++].trim().split(",");
Identifier[] ids = new Identifier[taxa.length];
for (int i = 0; i < taxa.length; i++) {
ids[i] = new Identifier(taxa[i]);
}
plugin.setIdsToRemove(new SimpleIdGroup(ids));
integratePlugin(plugin, true);
} else if (current.equalsIgnoreCase("-includeSiteNames")) {
FilterSiteNamePlugin plugin = new FilterSiteNamePlugin(myMainFrame, false);
String[] names = args[index++].trim().split(",");
plugin.setSiteNamesToKeep(names);
integratePlugin(plugin, true);
} else if (current.equalsIgnoreCase("-includeSiteNamesInFile")) {
FilterSiteNamePlugin plugin = new FilterSiteNamePlugin(myMainFrame, false);
String siteNameListFile = args[index++].trim();
List siteNames = new ArrayList();
BufferedReader br = null;
try {
br = Utils.getBufferedReader(siteNameListFile);
String inputline = br.readLine();
Pattern sep = Pattern.compile("\\s+");
while (inputline != null) {
inputline = inputline.trim();
String[] parsedline = sep.split(inputline);
for (int i = 0; i < parsedline.length; i++) {
if ((parsedline[i] != null) || (parsedline[i].length() != 0)) {
siteNames.add(parsedline[i]);
}
}
inputline = br.readLine();
}
} finally {
br.close();
}
String[] siteNameArray = new String[siteNames.size()];
siteNameArray = (String[]) siteNames.toArray(siteNameArray);
plugin.setSiteNamesToKeep(siteNameArray);
integratePlugin(plugin, true);
} else if (current.equalsIgnoreCase("-newCoordinates")) {
ConvertAlignmentCoordinatesPlugin plugin = new ConvertAlignmentCoordinatesPlugin(myMainFrame);
String mapFile = args[index++].trim();
plugin.setMapFilename(mapFile);
integratePlugin(plugin, true);
} else {
try {
Plugin plugin = null;
String possibleClassName = current.substring(1);
List<String> matches = Utils.getFullyQualifiedClassNames(possibleClassName);
for (String match : matches) {
try {
Class currentMatch = Class.forName(match);
Constructor constructor = currentMatch.getConstructor(Frame.class);
plugin = (Plugin) constructor.newInstance(myMainFrame);
break;
} catch (NoSuchMethodException nsme) {
myLogger.warn("Self-describing Plugins should implement this constructor: " + current);
myLogger.warn("public Plugin(Frame parentFrame) {");
myLogger.warn(" super(parentFrame, false);");
myLogger.warn("}");
} catch (Exception e) {
// do nothing
}
}
if (plugin == null) {
try {
Class possibleClass = Class.forName(possibleClassName);
Constructor constructor = possibleClass.getConstructor(Frame.class);
plugin = (Plugin) constructor.newInstance(myMainFrame);
} catch (NoSuchMethodException nsme) {
myLogger.warn("Self-describing Plugins should implement this constructor: " + current);
myLogger.warn("public Plugin(Frame parentFrame) {");
myLogger.warn(" super(parentFrame, false);");
myLogger.warn("}");
} catch (Exception e) {
// do nothing
}
}
if (plugin != null) {
List pluginArgs = new ArrayList();
if (index == args.length) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No -endPlugin flag specified.");
}
String temp = args[index++].trim();
while (!temp.equalsIgnoreCase("-endPlugin")) {
pluginArgs.add(temp);
if (index == args.length) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: No -endPlugin flag specified.");
}
temp = args[index++].trim();
}
String[] result = new String[pluginArgs.size()];
result = (String[]) pluginArgs.toArray(result);
plugin.setParameters(result);
integratePlugin(plugin, true);
} else {
throw new IllegalArgumentException("TasselPipeline: parseArgs: Unknown parameter: " + current);
}
} catch (UnsupportedOperationException usoe) {
throw new IllegalArgumentException("TasselPipeline: parseArgs: this plugin is not self-described: " + current);
} catch (Exception e) {
ExceptionUtils.logExceptionCauses(e, myLogger, Level.ERROR);
throw new IllegalArgumentException("TasselPipeline: parseArgs: Unknown parameter: " + current);
}
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
if (myFirstPlugin != null) {
//((AbstractPlugin) myFirstPlugin).trace(0);
tracePipeline();
} else {
myLogger.warn("parseArgs: no arguments specified.");
}
}
private void tracePipeline() {
for (int i = 0; i < myThreads.size(); i++) {
Plugin current = (Plugin) ((ThreadedPluginListener) myThreads.get(i)).getPluginListener();
((AbstractPlugin) current).trace(0);
}
}
public FileLoadPlugin loadFile(String filename, FileLoadPlugin.TasselFileType fileType) {
myLogger.info("loadFile: " + filename);
FileLoadPlugin plugin = new FileLoadPlugin(myMainFrame, false);
if (fileType == null) {
plugin.setTheFileType(FileLoadPlugin.TasselFileType.Unknown);
} else {
plugin.setTheFileType(fileType);
}
plugin.setOpenFiles(new String[]{filename});
integratePlugin(plugin, true);
return plugin;
}
public TableDisplayPlugin getTableDisplayPlugin(String filename, String flag) {
TableDisplayPlugin plugin = null;
if (flag.equalsIgnoreCase("-td_gui")) {
plugin = new TableDisplayPlugin(myMainFrame, true);
integratePlugin(plugin, false);
} else if (flag.equalsIgnoreCase("-td_tab")) {
myLogger.info("getTableDisplayPlugin: " + filename);
plugin = new TableDisplayPlugin(myMainFrame, false);
plugin.setDelimiter("\t");
plugin.setSaveFile(new File(filename));
integratePlugin(plugin, false);
} else if (flag.equalsIgnoreCase("-td_csv")) {
myLogger.info("getTableDisplayPlugin: " + filename);
plugin = new TableDisplayPlugin(myMainFrame, false);
plugin.setDelimiter(",");
plugin.setSaveFile(new File(filename));
integratePlugin(plugin, false);
}
return plugin;
}
public LinkageDisequilibriumPlugin getLinkageDisequilibriumPlugin() {
LinkageDisequilibriumPlugin plugin = new LinkageDisequilibriumPlugin(myMainFrame, false);
integratePlugin(plugin, true);
return plugin;
}
public LinkageDiseqDisplayPlugin getLinkageDiseqDisplayPlugin(String type) {
LinkageDiseqDisplayPlugin plugin = new LinkageDiseqDisplayPlugin(myMainFrame, true);
if (type.equalsIgnoreCase("gui")) {
plugin = new LinkageDiseqDisplayPlugin(null, true);
plugin.setBlockSchematic(false);
plugin.setLowerCorner(LinkageDisequilibriumComponent.P_VALUE);
plugin.setUpperCorner(LinkageDisequilibriumComponent.RSQUARE);
} else {
plugin = new LinkageDiseqDisplayPlugin(null, false);
plugin.setBlockSchematic(false);
plugin.setLowerCorner(LinkageDisequilibriumComponent.P_VALUE);
plugin.setUpperCorner(LinkageDisequilibriumComponent.RSQUARE);
if (type.equalsIgnoreCase("png")) {
plugin.setOutformat(AbstractDisplayPlugin.Outformat.png);
} else if (type.equalsIgnoreCase("gif")) {
plugin.setOutformat(AbstractDisplayPlugin.Outformat.gif);
} else if (type.equalsIgnoreCase("bmp")) {
plugin.setOutformat(AbstractDisplayPlugin.Outformat.bmp);
} else if (type.equalsIgnoreCase("jpg")) {
plugin.setOutformat(AbstractDisplayPlugin.Outformat.jpg);
} else if (type.equalsIgnoreCase("svg")) {
plugin.setOutformat(AbstractDisplayPlugin.Outformat.svg);
} else {
throw new IllegalArgumentException("TasselPipeline: getLinkageDiseqDisplayPlugin: unknown output type: " + type);
}
}
integratePlugin(plugin, false);
return plugin;
}
private void integratePlugin(Plugin plugin, boolean displayDataTree) {
if (myFirstPlugin == null) {
myFirstPlugin = plugin;
}
if (displayDataTree) {
plugin.addListener(this);
}
if (myCurrentPipe == null) {
myCurrentPipe = new ArrayList();
}
if (myCurrentPipe.size() == 0) {
myCurrentPipe.add(plugin);
} else {
plugin.receiveInput(((Plugin) myCurrentPipe.get(myCurrentPipe.size() - 1)));
myCurrentPipe.add(plugin);
}
}
private Plugin findLastPluginFromAll(Class[] types) {
if ((myCurrentPipe != null) && (myCurrentPipe.size() != 0)) {
for (int i = myCurrentPipe.size() - 1; i >= 0; i
Plugin current = (Plugin) myCurrentPipe.get(i);
if (matchType(types, current)) {
return current;
}
}
}
List keys = new ArrayList(myForks.keySet());
for (int i = keys.size() - 1; i >= 0; i
List currentPipe = (List) myForks.get(keys.get(i));
for (int j = currentPipe.size() - 1; j >= 0; j
Plugin current = (Plugin) currentPipe.get(j);
if (matchType(types, current)) {
return current;
}
}
}
return null;
}
private Plugin findLastPluginFromCurrentPipe(Class[] types) {
if ((myCurrentPipe != null) && (myCurrentPipe.size() != 0)) {
for (int i = myCurrentPipe.size() - 1; i >= 0; i
Plugin current = (Plugin) myCurrentPipe.get(i);
if (matchType(types, current)) {
return current;
}
}
}
return null;
}
private boolean matchType(Class[] types, Object test) {
for (int i = 0; i < types.length; i++) {
if (types[i].isInstance(test)) {
return true;
}
}
return false;
}
/**
* Returns Tassel data set after complete.
*
* @param event event
*/
public void dataSetReturned(PluginEvent event) {
DataSet tds = (DataSet) event.getSource();
if ((tds != null) && (tds.getSize() != 0) && (myMainFrame != null)) {
myMainFrame.getDataTreePanel().addDataSet(tds, DataTreePanel.NODE_TYPE_DEFAULT);
}
}
/**
* Returns progress of execution.
*
* @param event event
*/
public void progress(PluginEvent event) {
if (myMainFrame == null) {
DataSet ds = (DataSet) event.getSource();
if (ds != null) {
List percentage = ds.getDataOfType(Integer.class);
Plugin plugin = ds.getCreator();
Integer lastValue = (Integer) myProgressValues.get(plugin);
if (lastValue == null) {
lastValue = new Integer(0);
}
if (percentage.size() > 0) {
Datum datum = (Datum) percentage.get(0);
Integer percent = (Integer) datum.getData();
if (percent >= lastValue) {
myLogger.info(ds.getCreator().getClass().getName() + ": progress: " + percent.intValue() + "%");
lastValue = lastValue + 10;
myProgressValues.put(plugin, lastValue);
}
}
}
}
}
}
|
package net.p316.news.newscat.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import net.p316.news.newscat.data.NcTitle;
public class MySQLConnector
{
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://news.p316.net/news_crawler";
static final String USER = "crawler";
static final String PASS = "4X\"Zd@JaTs\\Yk<c]";
private DriverManager driverManager;
private Connection conn = null;
public MySQLConnector()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL
+ "?characterEncoding=utf8"
+ "&user=" + USER
+ "&password=" + PASS);
}
catch(Exception ex)
{
System.out.println("SQLException: " + ex.getMessage());
}
}
public void close(){
if (conn != null) try { conn.close(); } catch(SQLException ex) {}
}
public int get_Recordcnt()
{
int rowcnt = 0;
Statement stmt = null;
ResultSet rs = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
String sql = "SELECT COUNT(*) FROM `nc_title`";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if(rs.next())
{
rowcnt = rs.getInt(1);
}
}
catch (SQLException ex)
{
System.out.println("SQLException: " + ex.getMessage());
}
catch (Exception ex)
{
} finally {
if (rs != null) try { rs.close(); } catch(SQLException ex) {}
if (stmt != null) try { stmt.close(); } catch(SQLException ex) {}
}
return rowcnt;
}
public ArrayList<NcTitle> get_Values(int crtpage)
{
ArrayList<NcTitle> data = new ArrayList<NcTitle>();
Statement stmt = null;
ResultSet rs = null;
crtpage
try
{
Class.forName("com.mysql.jdbc.Driver");
String sql = "SELECT * FROM `nc_title` LIMIT " + crtpage * 25 + ", 25";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next())
{
NcTitle temp = new NcTitle();
temp.set_idx(rs.getInt("idx"));
temp.set_idx_category(rs.getInt("idx_category"));
temp.set_url(rs.getString("url"));
temp.set_title(rs.getString("title"));
temp.set_company(rs.getString("company"));
temp.set_date(rs.getDate("date"));
data.add(temp);
}
}
catch (SQLException ex)
{
System.out.println("SQLException: " + ex.getMessage());
}
catch (Exception ex)
{
System.out.println("Exception: " + ex.getMessage());
} finally {
if (rs != null) try { rs.close(); } catch(SQLException ex) {}
if (stmt != null) try { stmt.close(); } catch(SQLException ex) {}
}
return data;
}
}
|
package net.wimpi.modbus.io;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;
import net.wimpi.modbus.Modbus;
import net.wimpi.modbus.ModbusIOException;
import net.wimpi.modbus.msg.ModbusMessage;
import net.wimpi.modbus.msg.ModbusRequest;
import net.wimpi.modbus.msg.ModbusResponse;
import net.wimpi.modbus.util.ModbusUtil;
/**
* @author bonino
*
*/
public class ModbusRTUTCPTransport implements ModbusTransport
{
public static final String logId = "[ModbusRTUTCPTransport]: ";
// The input stream from which reading the Modbus frames
private DataInputStream inputStream;
// The output stream to which writing the Modbus frames
private DataOutputStream outputStream;
// The Bytes output stream to use as output buffer for Modbus frames
private BytesOutputStream outputBuffer;
// The BytesInputStream wrapper for the transport input stream
private BytesInputStream inputBuffer;
// The last request sent over the transport ?? useful ??
private byte[] lastRequest = null;
// the socket used by this transport
private Socket socket;
// the read timeout timer
private Timer readTimeoutTimer;
// the read timout
private int readTimeout = 5000;
// the timeou flag
private boolean isTimedOut;
/**
* @param socket
* @throws IOException
*
*/
public ModbusRTUTCPTransport(Socket socket) throws IOException
{
// prepare the input and output streams...
if (socket != null)
this.setSocket(socket);
// set the timed out flag at false
this.isTimedOut = false;
}
/**
* Stores the given {@link Socket} instance and prepares the related streams
* to use them for Modbus RTU over TCP communication.
*
* @param socket
* @throws IOException
*/
public void setSocket(Socket socket) throws IOException
{
if (this.socket != null)
{
// TODO: handle clean closure of the streams
this.outputBuffer.close();
this.inputBuffer.close();
this.inputStream.close();
this.outputStream.close();
}
// store the socket used by this transport
this.socket = socket;
// get the input and output streams
this.inputStream = new DataInputStream(socket.getInputStream());
this.outputStream = new DataOutputStream(this.socket.getOutputStream());
// prepare the buffers
this.outputBuffer = new BytesOutputStream(Modbus.MAX_MESSAGE_LENGTH);
this.inputBuffer = new BytesInputStream(Modbus.MAX_MESSAGE_LENGTH);
}
/**
* writes the given ModbusMessage over the physical transport handled by
* this object.
*
* @param msg
* the {@link ModbusMessage} to be written on the transport.
*/
@Override
public synchronized void writeMessage(ModbusMessage msg) throws ModbusIOException
{
try
{
// atomic access to the output buffer
synchronized (this.outputBuffer)
{
// reset the output buffer
this.outputBuffer.reset();
// prepare the message for "virtual" serial transport
msg.setHeadless();
// write the message to the output buffer
msg.writeTo(this.outputBuffer);
// compute the CRC
int[] crc = ModbusUtil.calculateCRC(this.outputBuffer.getBuffer(), 0, this.outputBuffer.size());
// write the CRC on the output buffer
this.outputBuffer.writeByte(crc[0]);
this.outputBuffer.writeByte(crc[1]);
// store the buffer length
int bufferLength = this.outputBuffer.size();
// store the raw output buffer reference
byte rawBuffer[] = this.outputBuffer.getBuffer();
// write the buffer on the socket
this.outputStream.write(rawBuffer, 0, bufferLength); // PDU +
// CRC
this.outputStream.flush();
// debug
if (Modbus.debug)
System.out.println("Sent: " + ModbusUtil.toHex(rawBuffer, 0, bufferLength));
// store the written buffer as the last request
this.lastRequest = new byte[bufferLength];
System.arraycopy(rawBuffer, 0, this.lastRequest, 0, bufferLength);
// sleep for the time needed to receive the request at the other
// point of the connection
Thread.sleep(bufferLength);
}
}
catch (Exception ex)
{
throw new ModbusIOException("I/O failed to write");
}
}// writeMessage
// This is required for the slave that is not supported
@Override
public synchronized ModbusRequest readRequest() throws ModbusIOException
{
throw new RuntimeException("Operation not supported.");
} // readRequest
@Override
/**
* Lazy implementation: avoid CRC validation...
*/
public synchronized ModbusResponse readResponse() throws ModbusIOException
{
// the received response
ModbusResponse response = null;
// reset the timed out flag
this.isTimedOut = false;
// init and start the timeout timer
this.readTimeoutTimer = new Timer();
this.readTimeoutTimer.schedule(new TimerTask() {
@Override
public void run()
{
isTimedOut = true;
}
}, this.readTimeout);
try
{
// atomic access to the input buffer
synchronized (inputBuffer)
{
// clean the input buffer
inputBuffer.reset(new byte[Modbus.MAX_MESSAGE_LENGTH]);
// sleep for the time needed to receive the first part of the
// response
int available = this.inputStream.available();
while ((available < 4) && (!this.isTimedOut))
{
Thread.yield(); // 1ms * #bytes (4bytes in the worst case)
available = this.inputStream.available();
if (Modbus.debug)
System.out.println("Available bytes: " + available);
}
// check if timedOut
if (this.isTimedOut)
throw new ModbusIOException("I/O exception - read timeout.\n");
// get a reference to the inner byte buffer
byte inBuffer[] = this.inputBuffer.getBuffer();
// read the first 2 bytes from the input stream
this.inputStream.read(inBuffer, 0, 2);
// this.inputStream.readFully(inBuffer);
// read the progressive id
int packetId = inputBuffer.readUnsignedByte();
// debug
if (Modbus.debug)
System.out.println(ModbusRTUTCPTransport.logId + "Read packet with progressive id: " + packetId);
// read the function code
int functionCode = inputBuffer.readUnsignedByte();
// debug
if (Modbus.debug)
System.out.println(" uid: " + packetId + ", function code: " + functionCode);
// compute the number of bytes composing the message (including
// the CRC = 2bytes)
int packetLength = this.computePacketLength(functionCode);
// sleep for the time needed to receive the first part of the
// response
while ((this.inputStream.available() < (packetLength - 3)) && (!this.isTimedOut))
{
try
{
Thread.sleep(10);
}
catch (InterruptedException ie)
{
// do nothing
System.err.println("Sleep interrupted while waiting for response body...\n"+ie);
}
}
// check if timedOut
if (this.isTimedOut)
throw new ModbusIOException("I/O exception - read timeout.\n");
// read the remaining bytes
this.inputStream.read(inBuffer, 3, packetLength);
// debug
if (Modbus.debug)
System.out.println(" bytes: " + ModbusUtil.toHex(inBuffer, 0, packetLength) + ", desired length: "
+ packetLength);
// compute the CRC
int crc[] = ModbusUtil.calculateCRC(inBuffer, 0, packetLength - 2);
// check the CRC against the received one...
if (ModbusUtil.unsignedByteToInt(inBuffer[packetLength - 2]) != crc[0]
|| ModbusUtil.unsignedByteToInt(inBuffer[packetLength - 1]) != crc[1])
{
throw new IOException("CRC Error in received frame: " + packetLength + " bytes: "
+ ModbusUtil.toHex(inBuffer, 0, packetLength));
}
// reset the input buffer to the given packet length (excluding
// the CRC)
this.inputBuffer.reset(inBuffer, packetLength - 2);
// create the response
response = ModbusResponse.createModbusResponse(functionCode);
response.setHeadless();
// read the response
response.readFrom(inputBuffer);
}
}
catch (IOException e)
{
// debug
System.err.println(ModbusRTUTCPTransport.logId + "Error while reading from socket: " + e);
// clean the input stream
try
{
while (this.inputStream.read() != -1)
;
}
catch (IOException e1)
{
// debug
System.err.println(ModbusRTUTCPTransport.logId + "Error while emptying input buffer from socket: " + e);
}
// wrap and re-throw
throw new ModbusIOException("I/O exception - failed to read.\n" + e);
}
// reset the timeout timer
this.readTimeoutTimer.cancel();
// return the response read from the socket stream
return response;
}// readResponse
private int computePacketLength(int functionCode) throws IOException
{
// packet length by function code:
int length = 0;
switch (functionCode)
{
case 0x01:
case 0x02:
case 0x03:
case 0x04:
case 0x0C:
case 0x11: // report slave ID version and run/stop state
case 0x14: // read log entry (60000 memory reference)
case 0x15: // write log entry (60000 memory reference)
case 0x17:
{
// get a reference to the inner byte buffer
byte inBuffer[] = this.inputBuffer.getBuffer();
this.inputStream.read(inBuffer, 2, 1);
int dataLength = this.inputBuffer.readUnsignedByte();
length = dataLength + 5; // UID+FC+CRC(2bytes)
break;
}
case 0x05:
case 0x06:
case 0x0B:
case 0x0F:
case 0x10:
{
// read status: only the CRC remains after address and
// function code
length = 6;
break;
}
case 0x07:
case 0x08:
{
length = 3;
break;
}
case 0x16:
{
length = 8;
break;
}
case 0x18:
{
// get a reference to the inner byte buffer
byte inBuffer[] = this.inputBuffer.getBuffer();
this.inputStream.read(inBuffer, 2, 2);
length = this.inputBuffer.readUnsignedShort() + 6;// UID+FC+CRC(2bytes)
break;
}
case 0x83:
{
// error code
length = 5;
break;
}
}
return length;
}
@Override
public void close() throws IOException
{
inputStream.close();
outputStream.close();
}// close
/*
* private void getResponse(int fn, BytesOutputStream out) throws
* IOException { int bc = -1, bc2 = -1, bcw = -1; int inpBytes = 0; byte
* inpBuf[] = new byte[256];
*
* try { switch (fn) { case 0x01: case 0x02: case 0x03: case 0x04: case
* 0x0C: case 0x11: // report slave ID version and run/stop state case 0x14:
* // read log entry (60000 memory reference) case 0x15: // write log entry
* (60000 memory reference) case 0x17: // read the byte count; bc =
* inputStream.read(); out.write(bc); // now get the specified number of
* bytes and the 2 CRC bytes setReceiveThreshold(bc + 2); inpBytes =
* inputStream.read(inpBuf, 0, bc + 2); out.write(inpBuf, 0, inpBytes);
* m_CommPort.disableReceiveThreshold(); if (inpBytes != bc + 2) {
* System.out.println("Error: looking for " + (bc + 2) + " bytes, received "
* + inpBytes); } break; case 0x05: case 0x06: case 0x0B: case 0x0F: case
* 0x10: // read status: only the CRC remains after address and // function
* code setReceiveThreshold(6); inpBytes = inputStream.read(inpBuf, 0, 6);
* out.write(inpBuf, 0, inpBytes); m_CommPort.disableReceiveThreshold();
* break; case 0x07: case 0x08: // read status: only the CRC remains after
* address and // function code setReceiveThreshold(3); inpBytes =
* inputStream.read(inpBuf, 0, 3); out.write(inpBuf, 0, inpBytes);
* m_CommPort.disableReceiveThreshold(); break; case 0x16: // eight bytes in
* addition to the address and function codes setReceiveThreshold(8);
* inpBytes = inputStream.read(inpBuf, 0, 8); out.write(inpBuf, 0,
* inpBytes); m_CommPort.disableReceiveThreshold(); break; case 0x18: //
* read the byte count word bc = inputStream.read(); out.write(bc); bc2 =
* inputStream.read(); out.write(bc2); bcw = ModbusUtil.makeWord(bc, bc2);
* // now get the specified number of bytes and the 2 CRC bytes
* setReceiveThreshold(bcw + 2); inpBytes = inputStream.read(inpBuf, 0, bcw
* + 2); out.write(inpBuf, 0, inpBytes);
* m_CommPort.disableReceiveThreshold(); break; } } catch (IOException e) {
* m_CommPort.disableReceiveThreshold(); throw new
* IOException("getResponse serial port exception"); } }// getResponse
*/
}
|
package org.apache.xerces.impl.v2.identity;
/**
* Schema key reference identity constraint.
*
* @author Andy Clark, IBM
* @version $Id$
*/
public class KeyRef
extends IdentityConstraint {
// Data
/** The index of the key (or unique) being referred to. */
protected IdentityConstraint fKey;
// the uri of the grammar from which the key is taken.
protected String fKeyUri;
// Constructors
/** Constructs a keyref with the specified name. */
public KeyRef(String identityConstraintName, IdentityConstraint key, String keyUri) {
super(identityConstraintName);
fKey = key;
fKeyUri = keyUri;
type = KEYREF;
} // <init>(String,String,String)
// Public methods
/** Returns the key being referred to. */
public IdentityConstraint getKey() {
return fKey;
} // getKey(): int
// get grammar string
public String getKeyUri() {
return fKeyUri;
} // getKeyUri(): String
} // class KeyRef
|
package org.appwork.storage.jackson;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import org.appwork.storage.JSONMapper;
import org.appwork.storage.JSonMapperException;
import org.appwork.storage.JsonSerializer;
import org.appwork.storage.TypeRef;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.module.SimpleModule;
import org.codehaus.jackson.type.TypeReference;
/**
* @author thomas
*
*/
public class JacksonMapper implements JSONMapper {
private final ObjectMapper mapper;
public JacksonMapper() {
mapper = new ObjectMapper(new ExtJsonFactory());
mapper.getDeserializationConfig().set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
private List<JsonSerializer> serializer = new ArrayList<JsonSerializer>();
/**
* @param <T>
* @param class1
* @param jsonSerializer
*/
public <T> void addSerializer(final Class<T> clazz, final JsonSerializer<T> jsonSerializer) {
final SimpleModule mod = new SimpleModule("MyModule", new Version(1, 0, 0, null));
mod.addSerializer(clazz, new org.codehaus.jackson.map.JsonSerializer<T>() {
@Override
public void serialize(final T arg0, final JsonGenerator jgen, final SerializerProvider arg2) throws IOException, JsonProcessingException {
// jgen.writeRaw();
jgen.writeRawValue(jsonSerializer.toJSonString(arg0));
}
}
);
mapper.registerModule(mod);
}
/*
* (non-Javadoc)
*
* @see org.appwork.storage.JSONMapper#objectToString(java.lang.Object)
*/
@Override
public String objectToString(final Object o) throws JSonMapperException {
try {
return mapper.writeValueAsString(o);
} catch (final JsonGenerationException e) {
throw new JSonMapperException(e);
} catch (final JsonMappingException e) {
throw new JSonMapperException(e);
} catch (final IOException e) {
throw new JSonMapperException(e);
}
}
@Override
public <T> T stringToObject(final String jsonString, final Class<T> clazz) throws JSonMapperException {
try {
return mapper.readValue(jsonString, clazz);
} catch (final JsonParseException e) {
throw new JSonMapperException(e);
} catch (final JsonMappingException e) {
throw new JSonMapperException(e);
} catch (final IOException e) {
throw new JSonMapperException(e);
}
}
/*
* (non-Javadoc)
*
* @see org.appwork.storage.JSONMapper#stringToObject(java.lang.String,
* org.appwork.storage.TypeRef)
*/
@SuppressWarnings("unchecked")
@Override
public <T> T stringToObject(final String jsonString, final TypeRef<T> type) throws JSonMapperException {
try {
final TypeReference<T> tr = new TypeReference<T>() {
@Override
public Type getType() {
return type.getType();
}
};
// this (T) is required because of java bug
// (compiles in eclipse, but not with javac)
return (T) mapper.readValue(jsonString, tr);
} catch (final JsonParseException e) {
throw new JSonMapperException(e);
} catch (final JsonMappingException e) {
throw new JSonMapperException(e);
} catch (final IOException e) {
throw new JSonMapperException(e);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.