answer
stringlengths 17
10.2M
|
|---|
package org.sagebionetworks.repo.manager.principal;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.sagebionetworks.StackConfiguration;
import org.sagebionetworks.repo.manager.AuthenticationManager;
import org.sagebionetworks.repo.manager.EmailUtils;
import org.sagebionetworks.repo.manager.SendRawEmailRequestBuilder;
import org.sagebionetworks.repo.manager.UserManager;
import org.sagebionetworks.repo.manager.SendRawEmailRequestBuilder.BodyType;
import org.sagebionetworks.repo.model.AuthorizationUtils;
import org.sagebionetworks.repo.model.DatastoreException;
import org.sagebionetworks.repo.model.NameConflictException;
import org.sagebionetworks.repo.model.UnauthorizedException;
import org.sagebionetworks.repo.model.UserInfo;
import org.sagebionetworks.repo.model.UserProfile;
import org.sagebionetworks.repo.model.UserProfileDAO;
import org.sagebionetworks.repo.model.auth.NewUser;
import org.sagebionetworks.repo.model.auth.Session;
import org.sagebionetworks.repo.model.auth.Username;
import org.sagebionetworks.repo.model.dao.NotificationEmailDAO;
import org.sagebionetworks.repo.model.principal.*;
import org.sagebionetworks.repo.transactions.WriteTransaction;
import org.sagebionetworks.repo.util.SignedTokenUtil;
import org.sagebionetworks.repo.web.NotFoundException;
import org.sagebionetworks.securitytools.HMACUtils;
import org.sagebionetworks.util.SerializationUtils;
import org.sagebionetworks.util.ValidateArgument;
import org.springframework.beans.factory.annotation.Autowired;
import com.amazonaws.services.simpleemail.model.SendRawEmailRequest;
/**
* Basic implementation of the PrincipalManager.
* @author John
*
*/
public class PrincipalManagerImpl implements PrincipalManager {
@Autowired
private PrincipalAliasDAO principalAliasDAO;
@Autowired
private NotificationEmailDAO notificationEmailDao;
@Autowired
private UserManager userManager;
@Autowired
private AuthenticationManager authManager;
@Autowired
private SynapseEmailService sesClient;
@Autowired
private UserProfileDAO userProfileDAO;
public static final String PARAMETER_CHARSET = Charset.forName("utf-8").name();
public static final String EMAIL_VALIDATION_FIRST_NAME_PARAM = "firstname";
public static final String EMAIL_VALIDATION_DOMAIN_PARAM = "domain";
public static final String EMAIL_VALIDATION_LAST_NAME_PARAM = "lastname";
public static final String EMAIL_VALIDATION_USER_ID_PARAM = "userid";
public static final String EMAIL_VALIDATION_EMAIL_PARAM = "email";
public static final String EMAIL_VALIDATION_TIME_STAMP_PARAM = "timestamp";
public static final String EMAIL_VALIDATION_SIGNATURE_PARAM = "mac";
public static final String DATE_FORMAT_ISO8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
public static final String AMPERSAND = "&";
public static final String EQUALS = "=";
public static final long EMAIL_VALIDATION_TIME_LIMIT_MILLIS = 24*3600*1000L; // 24 hours as milliseconds
@Override
public boolean isAliasAvailable(String alias) {
if(alias == null) throw new IllegalArgumentException("Alias cannot be null");
return this.principalAliasDAO.isAliasAvailable(alias);
}
@Override
public boolean isAliasValid(String alias, AliasType type) {
if(alias == null) throw new IllegalArgumentException("Alias cannot be null");
if(type == null) throw new IllegalArgumentException("AliasType cannot be null");
// Check the value
try {
AliasEnum.valueOf(type.name()).validateAlias(alias);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
@Deprecated
public static String generateSignature(String payload) {
try {
byte[] secretKey = StackConfiguration.getEncryptionKey().getBytes(PARAMETER_CHARSET);
byte[] signatureAsBytes = HMACUtils.generateHMACSHA1SignatureFromRawKey(payload, secretKey);
return new String(signatureAsBytes, PARAMETER_CHARSET);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
@Deprecated
public static String generateSignatureForNewAccount(String firstName, String lastName,
String email, String timestamp, String domain) {
return generateSignature(firstName+lastName+email+timestamp+domain);
}
@Deprecated
// note, this assumes that first name, last name and email are valid in 'user'
public static String createTokenForNewAccount(NewUser user, Date now) {
try {
StringBuilder sb = new StringBuilder();
String urlEncodedFirstName = URLEncoder.encode(user.getFirstName(), PARAMETER_CHARSET);
sb.append(EMAIL_VALIDATION_FIRST_NAME_PARAM+EQUALS+urlEncodedFirstName);
String urlEncodedLastName = URLEncoder.encode(user.getLastName(), PARAMETER_CHARSET);
sb.append(AMPERSAND+EMAIL_VALIDATION_LAST_NAME_PARAM+EQUALS+urlEncodedLastName);
String urlEncodedEmail = URLEncoder.encode(user.getEmail(), PARAMETER_CHARSET);
sb.append(AMPERSAND+EMAIL_VALIDATION_EMAIL_PARAM+EQUALS+urlEncodedEmail);
DateFormat df = new SimpleDateFormat(DATE_FORMAT_ISO8601);
String timestampString = df.format(now);
String urlEncodedTimeStampString = URLEncoder.encode(timestampString, PARAMETER_CHARSET);
sb.append(AMPERSAND+EMAIL_VALIDATION_TIME_STAMP_PARAM+EQUALS+urlEncodedTimeStampString);
String urlEncodedDomain = URLEncoder.encode("Synapse", PARAMETER_CHARSET);
sb.append(AMPERSAND+EMAIL_VALIDATION_DOMAIN_PARAM+EQUALS+urlEncodedDomain);
String mac = generateSignatureForNewAccount(
urlEncodedFirstName, urlEncodedLastName, urlEncodedEmail,
urlEncodedTimeStampString, urlEncodedDomain);
sb.append(AMPERSAND+EMAIL_VALIDATION_SIGNATURE_PARAM+EQUALS+URLEncoder.encode(mac, PARAMETER_CHARSET));
return sb.toString();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
private String createAccountCreationToken(NewUser user, Date now) {
AccountCreationToken accountCreationToken = new AccountCreationToken();
accountCreationToken.setMembershipInvtnSignedToken(user.getMembershipInvtnSignedToken());
EmailValidationSignedToken emailValidationSignedToken = new EmailValidationSignedToken();
emailValidationSignedToken.setEmail(user.getEmail());
emailValidationSignedToken.setCreatedOn(now);
SignedTokenUtil.signToken(emailValidationSignedToken);
accountCreationToken.setEmailValidationSignedToken(emailValidationSignedToken);
return SerializationUtils.serializeAndHexEncode(accountCreationToken);
}
public static String validateAccountSetupInfo(AccountSetupInfo accountSetupInfo, Date now) {
// Find out which kind of token is being used
String token = accountSetupInfo.getEmailValidationToken();
EmailValidationSignedToken signedToken = accountSetupInfo.getEmailValidationSignedToken();
if (signedToken != null && token == null) {
return validateEmailSignedToken(signedToken, new Date());
} else if (token != null && signedToken == null) {
return validateEmailToken(token, new Date());
} else {
throw new IllegalArgumentException("One and only one type of email validation token must be provided.");
}
}
@Deprecated
// returns the validated email address
// note, we pass the current time as a parameter to facilitate testing
public static String validateEmailToken(String token, Date now) {
String urlEncodedFirstName = null;
String urlEncodedLastName = null;
String urlEncodedEmail = null;
String urlEncodedTokenTimestampString = null;
String urlEncodedDomain = null;
String urlEncodedMac = null;
String[] requestParams = token.split(AMPERSAND);
for (String param : requestParams) {
if (param.startsWith(EMAIL_VALIDATION_FIRST_NAME_PARAM+EQUALS)) {
urlEncodedFirstName = param.substring((EMAIL_VALIDATION_FIRST_NAME_PARAM+EQUALS).length());
} else if (param.startsWith(EMAIL_VALIDATION_LAST_NAME_PARAM+EQUALS)) {
urlEncodedLastName = param.substring((EMAIL_VALIDATION_LAST_NAME_PARAM+EQUALS).length());
} else if (param.startsWith(EMAIL_VALIDATION_EMAIL_PARAM+EQUALS)) {
urlEncodedEmail = param.substring((EMAIL_VALIDATION_EMAIL_PARAM+EQUALS).length());
} else if (param.startsWith(EMAIL_VALIDATION_TIME_STAMP_PARAM+EQUALS)) {
urlEncodedTokenTimestampString = param.substring((EMAIL_VALIDATION_TIME_STAMP_PARAM+EQUALS).length());
} else if (param.startsWith(EMAIL_VALIDATION_DOMAIN_PARAM+EQUALS)) {
urlEncodedDomain = param.substring((EMAIL_VALIDATION_DOMAIN_PARAM+EQUALS).length());
} else if (param.startsWith(EMAIL_VALIDATION_SIGNATURE_PARAM+EQUALS)) {
urlEncodedMac = param.substring((EMAIL_VALIDATION_SIGNATURE_PARAM+EQUALS).length());
}
}
if (urlEncodedFirstName==null) throw new IllegalArgumentException("first name is missing.");
if (urlEncodedLastName==null) throw new IllegalArgumentException("last name is missing.");
if (urlEncodedEmail==null) throw new IllegalArgumentException("email is missing.");
if (urlEncodedTokenTimestampString==null) throw new IllegalArgumentException("time stamp is missing.");
if (urlEncodedDomain==null) throw new IllegalArgumentException("domain is missing.");
if (urlEncodedMac==null) throw new IllegalArgumentException("digital signature is missing.");
String email;
String tokenTimestampString;
try {
email = URLDecoder.decode(urlEncodedEmail, PARAMETER_CHARSET);
tokenTimestampString = URLDecoder.decode(urlEncodedTokenTimestampString, PARAMETER_CHARSET);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
Date tokenTimestamp;
DateFormat df = new SimpleDateFormat(DATE_FORMAT_ISO8601);
try {
tokenTimestamp = df.parse(tokenTimestampString);
} catch (ParseException e) {
throw new IllegalArgumentException(tokenTimestampString+" is not a properly formatted time stamp", e);
}
if (now.getTime()-tokenTimestamp.getTime()>EMAIL_VALIDATION_TIME_LIMIT_MILLIS)
throw new IllegalArgumentException("Email validation link is out of date.");
String mac = generateSignatureForNewAccount(
urlEncodedFirstName, urlEncodedLastName,
urlEncodedEmail, urlEncodedTokenTimestampString, urlEncodedDomain);
String newUrlEncodedMac;
try {
newUrlEncodedMac = URLEncoder.encode(mac, PARAMETER_CHARSET);
} catch(UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
if (!urlEncodedMac.equals(newUrlEncodedMac))
throw new IllegalArgumentException("Invalid digital signature.");
return email;
}
public static String validateEmailSignedToken(EmailValidationSignedToken token, Date now) {
if (token.getUserId() != null)
throw new IllegalArgumentException("EmailValidationSignedToken.token must be null");
String email = token.getEmail();
ValidateArgument.required(email, "EmailValidationSignedToken.email");
Date createdOn = token.getCreatedOn();
ValidateArgument.required(createdOn, "EmailValidationSignedToken.createdOn");
if (now.getTime() - createdOn.getTime() > EMAIL_VALIDATION_TIME_LIMIT_MILLIS)
throw new IllegalArgumentException("Email validation link is out of date.");
SignedTokenUtil.validateToken(token);
return email;
}
// will throw exception for invalid email, invalid endpoint, or an email which is already taken
@Override
public void newAccountEmailValidation(NewUser user, String portalEndpoint) {
AliasEnum.USER_EMAIL.validateAlias(user.getEmail());
// is the email taken?
if (!principalAliasDAO.isAliasAvailable(user.getEmail())) {
throw new NameConflictException("The email address provided is already used.");
}
String token = createAccountCreationToken(user, new Date());
String url = portalEndpoint+token;
EmailUtils.validateSynapsePortalHost(url);
String subject = "Welcome to Synapse!";
Map<String,String> fieldValues = new HashMap<>();
fieldValues.put(EmailUtils.TEMPLATE_KEY_ORIGIN_CLIENT, "Synapse");
fieldValues.put(EmailUtils.TEMPLATE_KEY_WEB_LINK, url);
String messageBody = EmailUtils.readMailTemplate("message/CreateAccountTemplate.html", fieldValues);
SendRawEmailRequest sendEmailRequest = new SendRawEmailRequestBuilder()
.withRecipientEmail(user.getEmail())
.withSubject(subject)
.withBody(messageBody, BodyType.HTML)
.withIsNotificationMessage(true)
.build();
sesClient.sendRawEmail(sendEmailRequest);
}
@WriteTransaction
@Override
public Session createNewAccount(AccountSetupInfo accountSetupInfo) throws NotFoundException {
String validatedEmail = validateAccountSetupInfo(accountSetupInfo, new Date());
NewUser newUser = new NewUser();
newUser.setEmail(validatedEmail);
newUser.setFirstName(accountSetupInfo.getFirstName());
newUser.setLastName(accountSetupInfo.getLastName());
newUser.setUserName(accountSetupInfo.getUsername());
long newPrincipalId = userManager.createUser(newUser);
authManager.changePassword(newPrincipalId, accountSetupInfo.getPassword());
return authManager.authenticate(newPrincipalId, accountSetupInfo.getPassword());
}
@Deprecated
public static String generateSignatureForAdditionalEmail(String userId, String email, String timestamp, String domain) {
return generateSignature(userId+email+timestamp+domain);
}
@Deprecated
public static String createTokenForAdditionalEmail(Long userId, String email, Date now) {
try {
StringBuilder sb = new StringBuilder();
String urlEncodedUserId = URLEncoder.encode(userId.toString(), PARAMETER_CHARSET);
sb.append(EMAIL_VALIDATION_USER_ID_PARAM+EQUALS+urlEncodedUserId);
String urlEncodedEmail = URLEncoder.encode(email, PARAMETER_CHARSET);
sb.append(AMPERSAND+EMAIL_VALIDATION_EMAIL_PARAM+EQUALS+urlEncodedEmail);
DateFormat df = new SimpleDateFormat(DATE_FORMAT_ISO8601);
String timestampString = df.format(now);
String urlEncodedTimeStampString = URLEncoder.encode(timestampString, PARAMETER_CHARSET);
sb.append(AMPERSAND+EMAIL_VALIDATION_TIME_STAMP_PARAM+EQUALS+urlEncodedTimeStampString);
String urlEncodedDomain = URLEncoder.encode("Synapse", PARAMETER_CHARSET);
sb.append(AMPERSAND+EMAIL_VALIDATION_DOMAIN_PARAM+EQUALS+urlEncodedDomain);
String mac = generateSignatureForAdditionalEmail(urlEncodedUserId, urlEncodedEmail,
urlEncodedTimeStampString, urlEncodedDomain);
sb.append(AMPERSAND+EMAIL_VALIDATION_SIGNATURE_PARAM+EQUALS+URLEncoder.encode(mac, PARAMETER_CHARSET));
return sb.toString();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
private String createEmailValidationInfo(Long userId, String email, Date now) {
AddEmailInfo addEmailInfoSignedToken = new AddEmailInfo();
EmailValidationSignedToken emailValidationSignedToken = new EmailValidationSignedToken();
emailValidationSignedToken.setUserId(userId + "");
emailValidationSignedToken.setEmail(email);
emailValidationSignedToken.setCreatedOn(now);
SignedTokenUtil.signToken(emailValidationSignedToken);
addEmailInfoSignedToken.setEmailValidationSignedToken(emailValidationSignedToken);
return SerializationUtils.serializeAndHexEncode(addEmailInfoSignedToken);
}
private static class ValidatedEmailInfo {
public String userId;
public String newEmail;
}
public static ValidatedEmailInfo validateAddEmailInfo(AddEmailInfo addEmailInfo, Date now) {
ValidatedEmailInfo result = new ValidatedEmailInfo();
// Find out which kind of token is being used
String token = addEmailInfo.getEmailValidationToken();
EmailValidationSignedToken signedToken = addEmailInfo.getEmailValidationSignedToken();
if (signedToken != null && token == null) {
validateAdditionalEmailSignedToken(signedToken, new Date());
result.newEmail = signedToken.getEmail();
result.userId = signedToken.getUserId();
} else if (token != null && signedToken == null) {
validateAdditionalEmailToken(token, new Date());
result.newEmail = getParameterValueFromToken(token, EMAIL_VALIDATION_EMAIL_PARAM);
result.userId = getParameterValueFromToken(token, EMAIL_VALIDATION_USER_ID_PARAM);
} else {
throw new IllegalArgumentException("One and only one type of email validation token must be provided.");
}
return result;
}
public static String validateAdditionalEmailSignedToken(EmailValidationSignedToken token, Date now) {
ValidateArgument.required(token.getUserId(), "EmailValidationSignedToken.userId");
String email = token.getEmail();
ValidateArgument.required(email, "EmailValidationSignedToken.email");
Date createdOn = token.getCreatedOn();
ValidateArgument.required(createdOn, "EmailValidationSignedToken.createdOn");
if (now.getTime() - createdOn.getTime() > EMAIL_VALIDATION_TIME_LIMIT_MILLIS)
throw new IllegalArgumentException("Email validation link is out of date.");
SignedTokenUtil.validateToken(token);
return email;
}
@Deprecated
// returns the validated email address
// note, we pass the current time as a parameter to facilitate testing
public static void validateAdditionalEmailToken(String token, Date now) {
String urlEncodedUserId = null;
String urlEncodedEmail = null;
String urlEncodedTimestampString = null;
String urlEncodedDomain = null;
String urlEncodedMac = null;
String[] requestParams = token.split(AMPERSAND);
for (String param : requestParams) {
if (param.startsWith(EMAIL_VALIDATION_USER_ID_PARAM+EQUALS)) {
urlEncodedUserId = param.substring((EMAIL_VALIDATION_USER_ID_PARAM+EQUALS).length());
} else if (param.startsWith(EMAIL_VALIDATION_EMAIL_PARAM+EQUALS)) {
urlEncodedEmail = param.substring((EMAIL_VALIDATION_EMAIL_PARAM+EQUALS).length());
} else if (param.startsWith(EMAIL_VALIDATION_TIME_STAMP_PARAM+EQUALS)) {
urlEncodedTimestampString = param.substring((EMAIL_VALIDATION_TIME_STAMP_PARAM+EQUALS).length());
} else if (param.startsWith(EMAIL_VALIDATION_DOMAIN_PARAM+EQUALS)) {
urlEncodedDomain = param.substring((EMAIL_VALIDATION_DOMAIN_PARAM+EQUALS).length());
} else if (param.startsWith(EMAIL_VALIDATION_SIGNATURE_PARAM+EQUALS)) {
urlEncodedMac = param.substring((EMAIL_VALIDATION_SIGNATURE_PARAM+EQUALS).length());
}
}
if (urlEncodedUserId==null) throw new IllegalArgumentException("userId is missing.");
if (urlEncodedEmail==null) throw new IllegalArgumentException("email is missing.");
if (urlEncodedTimestampString==null) throw new IllegalArgumentException("time stamp is missing.");
if (urlEncodedDomain==null) throw new IllegalArgumentException("domain is missing.");
if (urlEncodedMac==null) throw new IllegalArgumentException("digital signature is missing.");
String tokenTimestampString;
try {
tokenTimestampString = URLDecoder.decode(urlEncodedTimestampString, PARAMETER_CHARSET);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
Date tokenTimestamp;
DateFormat df = new SimpleDateFormat(DATE_FORMAT_ISO8601);
try {
tokenTimestamp = df.parse(tokenTimestampString);
} catch (ParseException e) {
throw new IllegalArgumentException(tokenTimestampString+" is not a properly formatted time stamp", e);
}
if (now.getTime()-tokenTimestamp.getTime()>EMAIL_VALIDATION_TIME_LIMIT_MILLIS)
throw new IllegalArgumentException("Email validation link is out of date.");
String mac = generateSignatureForAdditionalEmail(
urlEncodedUserId, urlEncodedEmail, urlEncodedTimestampString, urlEncodedDomain);
String newUrlEncodedMac;
try {
newUrlEncodedMac = URLEncoder.encode(mac, PARAMETER_CHARSET);
} catch(UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
if (!urlEncodedMac.equals(newUrlEncodedMac))
throw new IllegalArgumentException("Invalid digital signature.");
}
@Override
public void additionalEmailValidation(UserInfo userInfo, Username email,
String portalEndpoint) throws NotFoundException {
if (AuthorizationUtils.isUserAnonymous(userInfo.getId()))
throw new UnauthorizedException("Anonymous user may not add email address.");
AliasEnum.USER_EMAIL.validateAlias(email.getEmail());
// is the email taken?
if (!principalAliasDAO.isAliasAvailable(email.getEmail())) {
throw new NameConflictException("The email address provided is already used.");
}
String token = createEmailValidationInfo(userInfo.getId(), email.getEmail(), new Date());
String url = portalEndpoint+token;
EmailUtils.validateSynapsePortalHost(url);
// all requirements are met, so send the email
String subject = "Request to add or change new email";
Map<String,String> fieldValues = new HashMap<String,String>();
UserProfile userProfile = userProfileDAO.get(userInfo.getId().toString());
fieldValues.put(EmailUtils.TEMPLATE_KEY_DISPLAY_NAME, userProfile.getFirstName()+" "+userProfile.getLastName());
fieldValues.put(EmailUtils.TEMPLATE_KEY_WEB_LINK, url);
fieldValues.put(EmailUtils.TEMPLATE_KEY_EMAIL, email.getEmail());
fieldValues.put(EmailUtils.TEMPLATE_KEY_ORIGIN_CLIENT, "Synapse");
fieldValues.put(EmailUtils.TEMPLATE_KEY_USERNAME, principalAliasDAO.getUserName(userInfo.getId()));
String messageBody = EmailUtils.readMailTemplate("message/AdditionalEmailTemplate.html", fieldValues);
SendRawEmailRequest sendEmailRequest = new SendRawEmailRequestBuilder()
.withRecipientEmail(email.getEmail())
.withSubject(subject)
.withBody(messageBody, BodyType.HTML)
.withIsNotificationMessage(true)
.build();
sesClient.sendRawEmail(sendEmailRequest);
}
public static String getParameterValueFromToken(String token, String paramName) {
String[] requestParams = token.split(AMPERSAND);
for (String param : requestParams) {
if (param.startsWith(paramName+EQUALS)) {
String urlEncodedParamValue = param.substring((paramName+EQUALS).length());
try {
return URLDecoder.decode(urlEncodedParamValue, PARAMETER_CHARSET);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
throw new IllegalArgumentException("token does not contain parameter "+paramName);
}
@WriteTransaction
@Override
public void addEmail(UserInfo userInfo, AddEmailInfo addEmailInfo,
Boolean setAsNotificationEmail) throws NotFoundException {
ValidatedEmailInfo info = validateAddEmailInfo(addEmailInfo, new Date());
PrincipalAlias alias = new PrincipalAlias();
alias.setAlias(info.newEmail);
alias.setPrincipalId(userInfo.getId());
alias.setType(AliasType.USER_EMAIL);
alias = principalAliasDAO.bindAliasToPrincipal(alias);
if (setAsNotificationEmail!=null && setAsNotificationEmail==true) notificationEmailDao.update(alias);
}
@WriteTransaction
@Override
public void removeEmail(UserInfo userInfo, String email) throws NotFoundException {
if (email.equals(notificationEmailDao.getNotificationEmailForPrincipal(userInfo.getId())))
throw new IllegalArgumentException("To remove this email from your account, first establish a different notification address.");
PrincipalAlias emailAlias = findAliasForEmail(userInfo.getId(), email);
principalAliasDAO.removeAliasFromPrincipal(userInfo.getId(), emailAlias.getAliasId());
}
private PrincipalAlias findAliasForEmail(Long principalId, String email) throws NotFoundException {
List<PrincipalAlias> aliases = principalAliasDAO.listPrincipalAliases(principalId, AliasType.USER_EMAIL, email);
if (aliases.size()==0) {
throw new NotFoundException("Cannot find alias for "+principalId+" matching "+email);
} else if (aliases.size()==1) {
return aliases.get(0);
} else {
throw new DatastoreException("Expected 0-1 results but found "+aliases.size());
}
}
/**
* Set the email which is used for notification.
*
* @param userInfo
* @param email
* @throws NotFoundException
*/
@WriteTransaction
@Override
public void setNotificationEmail(UserInfo userInfo, String email) throws NotFoundException {
PrincipalAlias emailAlias = findAliasForEmail(userInfo.getId(), email);
notificationEmailDao.update(emailAlias);
}
/**
* Get the email which is used for notification.
*
* @param userInfo
* @return
* @throws NotFoundException
*/
@Override
public Username getNotificationEmail(UserInfo userInfo) throws NotFoundException {
String email= notificationEmailDao.getNotificationEmailForPrincipal(userInfo.getId());
Username dto = new Username();
dto.setEmail(email);
return dto;
}
@Override
public PrincipalAliasResponse lookupPrincipalId(PrincipalAliasRequest request) {
ValidateArgument.required(request, "request");
ValidateArgument.required(request.getAlias(), "PrincipalAliasRequest.alias");
ValidateArgument.required(request.getType(), "PrincipalAliasRequest.type");
ValidateArgument.requirement(request.getType() == AliasType.USER_NAME, "Unsupported alias type "+request.getType());
long principalId = principalAliasDAO.lookupPrincipalID(request.getAlias(), request.getType());
PrincipalAliasResponse response = new PrincipalAliasResponse();
response.setPrincipalId(principalId);
return response;
}
}
|
package io.vrap.rmf.raml.persistence.constructor;
import io.vrap.rmf.raml.model.modules.Api;
import io.vrap.rmf.raml.model.modules.Document;
import io.vrap.rmf.raml.model.modules.ModulesFactory;
import io.vrap.rmf.raml.model.resources.*;
import io.vrap.rmf.raml.persistence.antlr.RAMLParser;
import org.eclipse.emf.common.util.ECollections;
import org.eclipse.emf.ecore.EObject;
import java.util.List;
import java.util.stream.Collectors;
import static io.vrap.rmf.raml.model.modules.ModulesPackage.Literals.*;
import static io.vrap.rmf.raml.model.resources.ResourcesPackage.Literals.*;
public class ApiConstructor extends BaseConstructor {
private final UriTemplateConstructor uriTemplateConstructor = new UriTemplateConstructor();
@Override
public EObject construct(final RAMLParser parser, final Scope scope) {
final TypeDeclarationResolver typeDeclarationResolver = new TypeDeclarationResolver();
typeDeclarationResolver.resolve(parser.api(), scope);
parser.reset();
final Api api = (Api) withinScope(scope,
s -> visitApi(parser.api()));
return api;
}
@Override
public Object visitApi(final RAMLParser.ApiContext ctx) {
final EObject rootObject = scope.getResource().getContents().get(0);
return withinScope(scope.with(rootObject), rootScope -> {
ctx.documentationFacet().forEach(this::visitDocumentationFacet);
ctx.annotationFacet().forEach(this::visitAnnotationFacet);
ctx.attributeFacet().forEach(this::visitAttributeFacet);
ctx.traitsFacet().forEach(this::visitTraitsFacet);
ctx.typesFacet().forEach(this::visitTypesFacet);
ctx.baseUriFacet().forEach(this::visitBaseUriFacet);
ctx.baseUriParametersFacet().forEach(this::visitBaseUriParametersFacet);
// order is relevant:
// 1. construct security schemes
ctx.securitySchemesFacet().forEach(this::visitSecuritySchemesFacet); // TODO move to first construction phase
// 2. resolve secured by
ctx.securedByFacet().forEach(this::visitSecuredByFacet);
ctx.resourceFacet().forEach(this::visitResourceFacet);
withinScope(scope.with(TYPE_CONTAINER__RESOURCE_TYPES), resourceTypesScope ->
ctx.resourceTypesFacet().stream().map(this::visitResourceTypesFacet).collect(Collectors.toList()));
return rootObject;
});
}
@Override
public Object visitDocumentationFacet(RAMLParser.DocumentationFacetContext documentationFacet) {
return withinScope(scope.with(API__DOCUMENTATION), documentationScope ->
documentationFacet.document().stream().map(this::visitDocument).collect(Collectors.toList())
);
}
@Override
public Object visitDocument(RAMLParser.DocumentContext ctx) {
final Document document = ModulesFactory.eINSTANCE.createDocument();
scope.setValue(document, ctx.getStart());
return withinScope(scope.with(document), documentScope -> {
ctx.attributeFacet().forEach(this::visitAttributeFacet);
return document;
});
}
@Override
public Object visitBaseUriFacet(RAMLParser.BaseUriFacetContext ctx) {
final String baseUriText = ctx.baseUri.getText();
final UriTemplate uriTemplate = uriTemplateConstructor.parse(baseUriText, scope);
scope.with(API__BASE_URI).setValue(uriTemplate, ctx.getStart());
return uriTemplate;
}
@Override
public Object visitBaseUriParametersFacet(RAMLParser.BaseUriParametersFacetContext baseUriParametersFacet) {
return withinScope(scope.with(API__BASE_URI_PARAMETERS), baseUriParametersScope -> {
final List<Object> baseUriParameters = baseUriParametersFacet.uriParameterFacets.stream()
.map(this::visitTypedElementFacet)
.collect(Collectors.toList());
return baseUriParameters;
});
}
@Override
public Object visitResourceFacet(RAMLParser.ResourceFacetContext resourceFacet) {
return withinScope(scope.with(RESOURCE_CONTAINER__RESOURCES), resourcesScope -> {
final Resource resource = ResourcesFactory.eINSTANCE.createResource();
resourcesScope.setValue(resource, resourceFacet.getStart());
final UriTemplate relativeUri = uriTemplateConstructor.parse(resourceFacet.relativeUri.getText(), resourcesScope);
resource.setRelativeUri(relativeUri);
return withinScope(resourcesScope.with(resource), resourceScope -> {
resourceFacet.attributeFacet().forEach(this::visitAttributeFacet);
resourceFacet.annotationFacet().forEach(this::visitAnnotationFacet);
resourceFacet.securedByFacet().forEach(this::visitSecuredByFacet);
resourceFacet.methodFacet().forEach(this::visitMethodFacet);
resourceFacet.uriParametersFacet().forEach(this::visitUriParametersFacet);
resourceFacet.resourceFacet().forEach(this::visitResourceFacet);
resourceFacet.isFacet().forEach(this::visitIsFacet);
resourceFacet.resourceTypeFacet().forEach(this::visitResourceTypeFacet);
return resource;
});
});
}
@Override
public Object visitResourceTypeFacet(RAMLParser.ResourceTypeFacetContext ctx) {
return withinScope(scope.with(RESOURCE_BASE__TYPE), resourceTypeScope ->
visitResourceTypeApplication(ctx.resourceTypeApplication()));
}
@Override
public Object visitResourceTypeApplication(RAMLParser.ResourceTypeApplicationContext ctx) {
final ResourceTypeApplication resourceTypeApplication = ResourcesFactory.eINSTANCE.createResourceTypeApplication();
scope.setValue(resourceTypeApplication, ctx.getStart());
final ResourceType resourceType = (ResourceType) scope.with(RESOURCE_TYPE_APPLICATION__TYPE).getEObjectByName(ctx.type.getText());
resourceTypeApplication.setType(resourceType);
return withinScope(scope.with(resourceTypeApplication, RESOURCE_TYPE_APPLICATION__ARGUMENTS),
argumentsScope -> ctx.argument().stream()
.map(this::visitArgument)
.collect(Collectors.toList()));
}
@Override
public Object visitResourceTypeDeclarationFacet(RAMLParser.ResourceTypeDeclarationFacetContext resourceTypeDeclarationFacet) {
final String type = resourceTypeDeclarationFacet.name.getText();
final EObject resourceType = scope.getEObjectByName(type);
return withinScope(scope.with(resourceType), resourceTypeScope -> {
resourceTypeDeclarationFacet.attributeFacet().forEach(this::visitAttributeFacet);
resourceTypeDeclarationFacet.annotationFacet().forEach(this::visitAnnotationFacet);
resourceTypeDeclarationFacet.securedByFacet().forEach(this::visitSecuredByFacet);
resourceTypeDeclarationFacet.methodFacet().forEach(this::visitMethodFacet);
resourceTypeDeclarationFacet.uriParametersFacet().forEach(this::visitUriParametersFacet);
resourceTypeDeclarationFacet.resourceTypeFacet().forEach(this::visitResourceTypeFacet);
return resourceType;
});
}
@Override
public Object visitMethodFacet(RAMLParser.MethodFacetContext methodFacet) {
return withinScope(scope.with(RESOURCE_BASE__METHODS), methodsScope -> {
final Method method = ResourcesFactory.eINSTANCE.createMethod();
String httpMethodText = methodFacet.httpMethod().getText();
httpMethodText = httpMethodText.endsWith("?") ?
httpMethodText.substring(0, httpMethodText.length() - 1) :
httpMethodText;
final HttpMethod httpMethod = (HttpMethod) ResourcesFactory.eINSTANCE.createFromString(HTTP_METHOD, httpMethodText);
method.setMethod(httpMethod);
methodsScope.setValue(method, methodFacet.getStart());
withinScope(methodsScope.with(method), methodScope -> {
methodFacet.attributeFacet().forEach(this::visitAttributeFacet);
methodFacet.annotationFacet().forEach(this::visitAnnotationFacet);
methodFacet.securedByFacet().forEach(this::visitSecuredByFacet);
methodFacet.headersFacet().forEach(this::visitHeadersFacet);
methodFacet.queryParametersFacet().forEach(this::visitQueryParametersFacet);
withinScope(methodScope.with(METHOD__BODIES), bodiesScope -> {
methodFacet.bodyFacet().forEach(this::visitBodyFacet);
return null;
});
methodFacet.responsesFacet().forEach(this::visitResponsesFacet);
methodFacet.isFacet().forEach(this::visitIsFacet);
return methodScope.eObject();
});
return method;
});
}
@Override
public Object visitUriParametersFacet(RAMLParser.UriParametersFacetContext uriParametersFacet) {
return withinScope(scope.with(RESOURCE_BASE__URI_PARAMETERS), uriParametersScope -> {
final List<Object> uriParameters = ECollections.asEList(uriParametersFacet.uriParameterFacets.stream()
.map(this::visitTypedElementFacet)
.collect(Collectors.toList()));
scope.setValue(uriParameters, uriParametersFacet.getStart());
return uriParameters;
});
}
}
|
package org.requirementsascode.predicate;
import java.io.Serializable;
import java.util.Objects;
import java.util.function.Predicate;
import org.requirementsascode.Step;
import org.requirementsascode.UseCaseModelRunner;
public class ReactWhile implements Predicate<UseCaseModelRunner>, Serializable{
private static final long serialVersionUID = -3190093346311188647L;
private Predicate<UseCaseModelRunner> completeCondition;
private Predicate<UseCaseModelRunner> reactWhileCondition;
public ReactWhile(Step step, Predicate<UseCaseModelRunner> reactWhileCondition) {
Objects.requireNonNull(step);
Objects.requireNonNull(reactWhileCondition);
createReactWhileCondition(step, reactWhileCondition);
}
@Override
public boolean test(UseCaseModelRunner runner) {
return completeCondition.test(runner);
}
private void createReactWhileCondition(
Step step, Predicate<UseCaseModelRunner> reactWhileCondition) {
Predicate<UseCaseModelRunner> performIfConditionIsTrue = step.getPredicate().and(reactWhileCondition);
Predicate<UseCaseModelRunner> repeatIfConditionIsTrue =
new After(step).and(reactWhileCondition);
completeCondition = performIfConditionIsTrue.or(repeatIfConditionIsTrue);
this.reactWhileCondition = reactWhileCondition;
}
public Predicate<UseCaseModelRunner> getReactWhileCondition() {
return reactWhileCondition;
}
}
|
package solutions.deepfield.spark.itcase.annotations;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SparkSubmitTestWrapper {
private static final Logger logger = LoggerFactory.getLogger(SparkSubmitTestWrapper.class);
public static void main(String[] args) {
try {
// Examine arguments; there should be 1 being the test class.
if (args.length < 2) {
throw new Exception("Did not specify class to run or test method");
}
String classToRun = args[0];
logger.info("Test class is [" + classToRun + "]");
// Load the class to test.
Class testClass = SparkSubmitTestWrapper.class.getClassLoader().loadClass(classToRun);
logger.info("Loaded test class");
// Get the test method name from second argument.
String methodToTest = args[1];
Method method = testClass.getMethod(methodToTest);
if (method == null) {
throw new Exception("Unable to find test method [" + method + "] with zero arguments");
}
List<Method> befores = new ArrayList<Method>();
Class examineTarget = testClass;
// Look for before methods.
while (examineTarget != null) {
for (Method m : testClass.getMethods()) {
if (m.getAnnotation(SparkBefore.class) == null) {
continue;
}
if (m.getParameterTypes().length > 0) {
throw new Exception("Found @SparkBefore annotation on method with arguments");
}
befores.add(m);
}
examineTarget = examineTarget.getSuperclass();
}
// Look for after methods.
List<Method> afters = new ArrayList<Method>();
examineTarget = testClass;
while (examineTarget != null) {
for (Method m : testClass.getMethods()) {
if (m.getAnnotation(SparkAfter.class) == null) {
continue;
}
if (m.getParameterTypes().length > 0) {
throw new Exception("Found @SparkAfter annotation on method with arguments");
}
afters.add(m);
}
examineTarget = examineTarget.getSuperclass();
}
Object instance = testClass.newInstance();
// Invoke befores
for (Method before : befores) {
logger.info("Invoking before method [" + before.getDeclaringClass() + "#" + before.getName() + "]");
before.invoke(instance);
logger.info("Finished before method [" + before.getDeclaringClass() + "#" + before.getName() + "]");
}
// Execute the test method.
method.invoke(instance);
// Invoke afters
for (Method after : afters) {
logger.info("Invoking after method [" + after.getDeclaringClass() + "#" + after.getName() + "]");
after.invoke(instance);
logger.info("Finished after method [" + after.getDeclaringClass() + "#" + after.getName() + "]");
}
} catch (Exception e) {
logger.error("Error processing command: " + e.getMessage(), e);
System.exit(10);
}
}
}
|
package stroom.security.mock;
import stroom.security.api.ProcessingUserIdentityProvider;
import stroom.security.api.UserIdentity;
import java.util.Objects;
public class MockProcessingUserIdentityProvider implements ProcessingUserIdentityProvider {
private static final UserIdentity USER_IDENTITY = new MockUserIdentity();
@Override
public UserIdentity get() {
return USER_IDENTITY;
}
@Override
public boolean isProcessingUser(final UserIdentity userIdentity) {
return UserIdentity.IDENTITY_COMPARATOR.compare(USER_IDENTITY, userIdentity) == 0;
}
private static class MockUserIdentity implements UserIdentity {
@Override
public String getId() {
return "INTERNAL_PROCESSING_USER";
}
@Override
public String getJws() {
return null;
}
@Override
public String getSessionId() {
return null;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof UserIdentity)) return false;
final UserIdentity that = (UserIdentity) o;
return Objects.equals(getId(), that.getId()) &&
Objects.equals(getJws(), that.getJws());
}
@Override
public int hashCode() {
return Objects.hash(getId(), getJws());
}
@Override
public String toString() {
return getId();
}
}
}
|
package nl.esciencecenter.ncradar;
import static org.junit.Assert.assertEquals;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.junit.Before;
import org.junit.Test;
public class TestJNICalcTexture extends JNIMethodsVol2Bird {
private int[] texImage;
private int[] dbzImage;
private int[] vradImage;
private int nRangNeighborhood;
private int nAzimNeighborhood;
private int nCountMin;
private int texType;
private float texOffset;
private float texScale;
private float dbzOffset;
private float dbzScale;
private float vradOffset;
private float vradScale;
private int nRang;
private int nAzim;
private double calcMean(double[] array) {
int nSamples = array.length;
return calcSum(array) / nSamples;
}
private double calcStdDev(double[] array) {
int nSamples = array.length;
double[] squaredDevs = new double[nSamples];
double mean = calcMean(array);
for (int iSample = 0; iSample < nSamples; iSample++) {
squaredDevs[iSample] = Math.pow(array[iSample] - mean, 2);
}
double stdDev = Math.sqrt(calcMean(squaredDevs));
return stdDev;
}
private double calcSum(double[] array) {
int nSamples = array.length;
double sum = 0;
for (int iSample = 0; iSample < nSamples; iSample++) {
sum += array[iSample];
}
return sum;
}
private int[] readDataFromFile(String filename) throws IOException {
List<Integer> arrList = new ArrayList<Integer>();
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null) {
Scanner scanner = new Scanner(line);
while (scanner.hasNext()) {
int nextInt = scanner.nextInt();
arrList.add(nextInt);
}
}
reader.close();
int nElems = arrList.size();
int[] outputArray = new int[nElems];
for (int iElem = 0; iElem < nElems; iElem++) {
outputArray[iElem] = arrList.get(iElem).intValue();
}
return outputArray;
}
private int[][] reshapeTo2D(int[] inputArray, int nRows, int nCols) {
int[][] outputArray = new int[nRows][nCols];
int iGlobal = 0;
for (int iRow = 0; iRow < nRows; iRow++) {
for (int iCol = 0; iCol < nCols; iCol++) {
outputArray[iRow][iCol] = inputArray[iGlobal];
iGlobal += 1;
}
}
return outputArray;
}
@Before
public void setUp() throws Exception {
texImage = new int[] { 0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0 };
dbzImage = new int[] { 3, 46, 56, 7,
84, 6, 78, 72,
3, 5, 23, 56,
67, 23, 5, 67,
89, 7, 2, 5 };
vradImage = new int[] { 8, 94, 56, 65,
23, 2, 46, 73,
5, 6, 34, 53,
0, 89, 42, 3,
92, 5, 9, 79 };
nRangNeighborhood = 3;
nAzimNeighborhood = 3;
nCountMin = 0;
texType = 2; // 2 = STDDEV of VRAD
texOffset = 0.0f;
texScale = 1.0f;
dbzOffset = 2.0f;
dbzScale = -34.0f;
vradOffset = 0.0f;
vradScale = 1.0f;
nRang = 4;
nAzim = 5;
}
@Test
public void testNativeCalcTexture1() throws Exception {
// this test reproduces calculation of standard deviation as used
// in the C code (which is not obviously correct)
calcTexture(texImage,
dbzImage,
vradImage,
nRangNeighborhood,
nAzimNeighborhood,
nCountMin,
texType,
texOffset,
texScale,
dbzOffset,
dbzScale,
vradOffset,
vradScale,
nRang,
nAzim);
int[][] actual = reshapeTo2D(texImage.clone(), nAzim, nRang);
int[][] texImage2D = new int[nAzim][nRang];
int[][] vradImage2D = reshapeTo2D(vradImage, nAzim, nRang);
for (int iAzim = 0; iAzim < nAzim; iAzim++) {
for (int iRang = 0 + nRangNeighborhood / 2; iRang < nRang - nRangNeighborhood / 2; iRang++) {
double vmoment1 = 0;
double vmoment2 = 0;
float vRadDiff;
for (int iAzimNeighborhood = 0; iAzimNeighborhood < nAzimNeighborhood; iAzimNeighborhood++) {
for (int iRangNeighborhood = 0; iRangNeighborhood < nRangNeighborhood; iRangNeighborhood++) {
int iAzimDelta = iAzimNeighborhood - (nAzimNeighborhood / 2);
int iRangDelta = iRangNeighborhood - (nRangNeighborhood / 2);
int iAzimLocal = (nAzim + iAzim + iAzimDelta) % nAzim;
int iRangLocal = iRang + iRangDelta;
vRadDiff = vradOffset + vradScale *
(vradImage2D[iAzim][iRang] - vradImage2D[iAzimLocal][iRangLocal]);
vmoment1 += vRadDiff;
vmoment2 += Math.pow(vRadDiff, 2);
}
}
vmoment1 /= (nAzimNeighborhood * nRangNeighborhood);
vmoment2 /= (nAzimNeighborhood * nRangNeighborhood);
double tex = Math.sqrt(Math.abs(vmoment2 - Math.pow(vmoment1, 2)));
texImage2D[iAzim][iRang] = (byte) Math.round((tex - texOffset) / texScale);
}
}
int[][] expected = texImage2D.clone();
int differsByOne = 0;
for (int iAzim = 0; iAzim < nAzim; iAzim++) {
for (int iRang = 1; iRang < nRang - 1; iRang++) {
assertEquals(expected[iAzim][iRang], actual[iAzim][iRang], 1);
if (expected[iAzim][iRang] != actual[iAzim][iRang]) {
differsByOne += 1;
}
}
}
System.out.println("A total of " + differsByOne + " array entries differed by 1 from the C result.");
}
@Test
public void testNativeCalcTexture2() throws Exception {
// this test should reproduce calculation of standard deviation
calcTexture(texImage,
dbzImage,
vradImage,
nRangNeighborhood,
nAzimNeighborhood,
nCountMin,
texType,
texOffset,
texScale,
dbzOffset,
dbzScale,
vradOffset,
vradScale,
nRang,
nAzim);
int[][] actual = reshapeTo2D(texImage.clone(), nAzim, nRang);
int[][] texImage2D = new int[nAzim][nRang];
int[][] vradImage2D = reshapeTo2D(vradImage, nAzim, nRang);
for (int iAzim = 0; iAzim < nAzim; iAzim++) {
for (int iRang = 0 + nRangNeighborhood / 2; iRang < nRang - nRangNeighborhood / 2; iRang++) {
int iLocal = 0;
double[] neighborhoodData = new double[nAzimNeighborhood * nRangNeighborhood];
for (int iAzimNeighborhood = 0; iAzimNeighborhood < nAzimNeighborhood; iAzimNeighborhood++) {
for (int iRangNeighborhood = 0; iRangNeighborhood < nRangNeighborhood; iRangNeighborhood++) {
int iAzimDelta = iAzimNeighborhood - (nAzimNeighborhood / 2);
int iRangDelta = iRangNeighborhood - (nRangNeighborhood / 2);
int iAzimLocal = (nAzim + iAzim + iAzimDelta) % nAzim;
int iRangLocal = iRang + iRangDelta;
neighborhoodData[iLocal] = vradOffset + vradScale * vradImage2D[iAzimLocal][iRangLocal];
iLocal += 1;
}
}
double stdDev = calcStdDev(neighborhoodData);
texImage2D[iAzim][iRang] = (byte) Math.round(((stdDev - texOffset) / texScale));
}
}
int[][] expected = texImage2D.clone();
int differsByOne = 0;
for (int iAzim = 0; iAzim < nAzim; iAzim++) {
for (int iRang = 1; iRang < nRang - 1; iRang++) {
assertEquals(expected[iAzim][iRang], actual[iAzim][iRang], 1);
if (expected[iAzim][iRang] != actual[iAzim][iRang]) {
differsByOne += 1;
}
}
}
System.out.println("A total of " + differsByOne + " array entries differed by 1 from the C result.");
}
@Test
public void testNativeCalcTexture3() throws Exception {
// this test should reproduce calculation of standard deviation
int[] texImage = readDataFromFile("/home/wbouten/enram/ncradar/test/data/case1/testdata-12x11-pattern0.txt");
int[] dbzImage = readDataFromFile("/home/wbouten/enram/ncradar/test/data/case1/testdata-12x11-pattern-dbz.txt");
int[] vradImage = readDataFromFile("/home/wbouten/enram/ncradar/test/data/case1/testdata-12x11-pattern-vrad.txt");
int nAzim = 12;
int nRang = 11;
calcTexture(texImage,
dbzImage,
vradImage,
nRangNeighborhood,
nAzimNeighborhood,
nCountMin,
texType,
texOffset,
texScale,
dbzOffset,
dbzScale,
vradOffset,
vradScale,
nRang,
nAzim);
int[][] actual = reshapeTo2D(texImage.clone(), nAzim, nRang);
int[][] texImage2D = new int[nAzim][nRang];
int[][] vradImage2D = reshapeTo2D(vradImage, nAzim, nRang);
for (int iAzim = 0; iAzim < nAzim; iAzim++) {
for (int iRang = 0 + nRangNeighborhood / 2; iRang < nRang - nRangNeighborhood / 2; iRang++) {
int iLocal = 0;
double[] neighborhoodData = new double[nAzimNeighborhood * nRangNeighborhood];
for (int iAzimNeighborhood = 0; iAzimNeighborhood < nAzimNeighborhood; iAzimNeighborhood++) {
for (int iRangNeighborhood = 0; iRangNeighborhood < nRangNeighborhood; iRangNeighborhood++) {
int iAzimDelta = iAzimNeighborhood - (nAzimNeighborhood / 2);
int iRangDelta = iRangNeighborhood - (nRangNeighborhood / 2);
int iAzimLocal = (nAzim + iAzim + iAzimDelta) % nAzim;
int iRangLocal = iRang + iRangDelta;
neighborhoodData[iLocal] = vradOffset + vradScale * vradImage2D[iAzimLocal][iRangLocal];
iLocal += 1;
}
}
double stdDev = calcStdDev(neighborhoodData);
texImage2D[iAzim][iRang] = (byte) Math.round(((stdDev - texOffset) / texScale));
}
}
int[][] expected = texImage2D.clone();
int differsByOne = 0;
for (int iAzim = 0; iAzim < nAzim; iAzim++) {
for (int iRang = 1; iRang < nRang - 1; iRang++) {
assertEquals(expected[iAzim][iRang], actual[iAzim][iRang], 1);
if (expected[iAzim][iRang] != actual[iAzim][iRang]) {
differsByOne += 1;
}
}
}
System.out.println("A total of " + differsByOne + " array entries differed by 1 from the C result.");
}
}
|
package io.sniffy;
import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;
import io.sniffy.configuration.SniffyConfiguration;
import io.sniffy.socket.*;
import io.sniffy.sql.SqlStats;
import io.sniffy.sql.StatementMetaData;
import io.sniffy.util.ExceptionUtil;
import io.sniffy.util.StringUtil;
import java.io.Closeable;
import java.lang.ref.WeakReference;
import java.util.*;
import java.util.concurrent.Callable;
import static io.sniffy.util.ExceptionUtil.throwException;
/**
* Spy holds a number of queries which were executed at some point of time and uses it as a base for further assertions
*
* @see Sniffy#spy()
* @see Sniffy#expect(Expectation)
* @since 2.0
*/
public class Spy<C extends Spy<C>> extends LegacySpy<C> implements Closeable {
private final WeakReference<Spy> selfReference;
private boolean closed = false;
private StackTraceElement[] closeStackTrace;
private List<Expectation> expectations = new ArrayList<Expectation>();
/**
* @since 3.1
*/
@Override
public Map<StatementMetaData, SqlStats> getExecutedStatements(ThreadMatcher threadMatcher, boolean removeStackTraces) {
Map<StatementMetaData, SqlStats> executedStatements = new LinkedHashMap<StatementMetaData, SqlStats>();
for (Map.Entry<StatementMetaData, SqlStats> entry : this.executedStatements.ascendingMap().entrySet()) {
StatementMetaData statementMetaData = entry.getKey();
if (removeStackTraces) statementMetaData = new StatementMetaData(
statementMetaData.sql, statementMetaData.query, null, statementMetaData.getThreadMetaData()
);
if (threadMatcher.matches(statementMetaData.getThreadMetaData())) {
SqlStats existingSocketStats = executedStatements.get(statementMetaData);
if (null == existingSocketStats) {
executedStatements.put(statementMetaData, new SqlStats(entry.getValue()));
} else {
existingSocketStats.accumulate(entry.getValue());
}
}
}
return Collections.unmodifiableMap(executedStatements);
}
Spy() {
this(SpyConfiguration.builder().build());
}
Spy(SpyConfiguration spyConfiguration) {
super(spyConfiguration);
selfReference = Sniffy.registerSpy(this);
}
/**
* Wrapper for {@link Sniffy#spy()} method; useful for chaining
*
* @return a new {@link Spy} instance
* @since 2.0
*/
public C reset() {
checkOpened();
super.reset();
expectations.clear();
return self();
}
/**
* @since 3.1
*/
public Map<SocketMetaData, SocketStats> getSocketOperations(ThreadMatcher threadMatcher, String address, boolean removeStackTraces) {
return getSocketOperations(threadMatcher, AddressMatchers.exactAddressMatcher(address), removeStackTraces);
}
/**
* @since 3.1.10
*/
public Map<SocketMetaData, SocketStats> getSocketOperations(ThreadMatcher threadMatcher, boolean removeStackTraces) {
return getSocketOperations(threadMatcher, AddressMatchers.anyAddressMatcher(), removeStackTraces);
}
/**
* @since 3.1.10
*/
public Map<SocketMetaData, SocketStats> getSocketOperations(ThreadMatcher threadMatcher, AddressMatcher addressMatcher, boolean removeStackTraces) {
Map<SocketMetaData, SocketStats> socketOperations = new LinkedHashMap<SocketMetaData, SocketStats>();
for (Map.Entry<SocketMetaData, SocketStats> entry : this.socketOperations.ascendingMap().entrySet()) {
SocketMetaData socketMetaData = entry.getKey();
if (threadMatcher.matches(socketMetaData.getThreadMetaData()) && (null == addressMatcher || addressMatcher.matches(socketMetaData.getAddress()))) {
if (removeStackTraces) socketMetaData = new SocketMetaData(
socketMetaData.getProtocol(), socketMetaData.address, socketMetaData.connectionId, null, socketMetaData.getThreadMetaData()
);
SocketStats existingSocketStats = socketOperations.get(socketMetaData);
if (null == existingSocketStats) {
socketOperations.put(socketMetaData, new SocketStats(entry.getValue()));
} else {
existingSocketStats.accumulate(entry.getValue());
}
}
}
return Collections.unmodifiableMap(socketOperations);
}
/**
* @since 3.1.10
*/
public Map<SocketMetaData, List<NetworkPacket>> getNetworkTraffic() {
return getNetworkTraffic(Threads.ANY, AddressMatchers.anyAddressMatcher());
}
/**
* @since 3.1.10
*/
public Map<SocketMetaData, List<NetworkPacket>> getNetworkTraffic(ThreadMatcher threadMatcher, String address) {
return getNetworkTraffic(threadMatcher, AddressMatchers.exactAddressMatcher(address));
}
/**
* @since 3.1.10
*/
public Map<SocketMetaData, List<NetworkPacket>> getNetworkTraffic(ThreadMatcher threadMatcher, String address, GroupingOptions groupingOptions) {
return getNetworkTraffic(threadMatcher, AddressMatchers.exactAddressMatcher(address), groupingOptions);
}
/**
* @since 3.1.10
*/
public Map<SocketMetaData, List<NetworkPacket>> getNetworkTraffic(ThreadMatcher threadMatcher, AddressMatcher addressMatcher) {
return getNetworkTraffic(threadMatcher, addressMatcher, GroupingOptions.builder().build());
}
/**
* @since 3.1.10
*/
public Map<SocketMetaData, List<NetworkPacket>> getNetworkTraffic(ThreadMatcher threadMatcher, AddressMatcher addressMatcher, GroupingOptions groupingOptions) {
return filterTraffic(this.networkTraffic, threadMatcher, addressMatcher, groupingOptions);
}
/**
* @since 3.1.11
*/
public Map<SocketMetaData, List<NetworkPacket>> getDecryptedNetworkTraffic(ThreadMatcher threadMatcher, AddressMatcher addressMatcher, GroupingOptions groupingOptions) {
return filterTraffic(this.decryptedNetworkTraffic, threadMatcher, addressMatcher, groupingOptions);
}
private Map<SocketMetaData, List<NetworkPacket>> filterTraffic(ConcurrentLinkedHashMap<SocketMetaData, Deque<NetworkPacket>> originalTraffic, ThreadMatcher threadMatcher, AddressMatcher addressMatcher, GroupingOptions groupingOptions) {
Map<SocketMetaData, List<NetworkPacket>> reducedTraffic = new LinkedHashMap<SocketMetaData, List<NetworkPacket>>();
for (Map.Entry<SocketMetaData, Deque<NetworkPacket>> entry : originalTraffic.ascendingMap().entrySet()) {
SocketMetaData socketMetaData = entry.getKey();
Deque<NetworkPacket> networkPackets = entry.getValue();
if (addressMatcher.matches(socketMetaData.getAddress()) &&
(null == socketMetaData.getThreadMetaData() || threadMatcher.matches(socketMetaData.getThreadMetaData()))) {
for (NetworkPacket networkPacket : networkPackets) {
if (threadMatcher.matches(networkPacket.getThreadMetaData())) {
SocketMetaData reducedSocketMetaData = new SocketMetaData(
socketMetaData.getProtocol(),
socketMetaData.getAddress(),
groupingOptions.isGroupByConnection() ? socketMetaData.getConnectionId() : -1,
groupingOptions.isGroupByStackTrace() ? networkPacket.getStackTrace() : null,
groupingOptions.isGroupByThread() ? networkPacket.getThreadMetaData() : null
);
List<NetworkPacket> reducedNetworkPackets = reducedTraffic.get(reducedSocketMetaData);
//noinspection Java8MapApi
if (null == reducedNetworkPackets) {
reducedNetworkPackets = new ArrayList<NetworkPacket>();
reducedTraffic.put(reducedSocketMetaData, reducedNetworkPackets);
}
if ((getSpyConfiguration().isCaptureStackTraces() && !groupingOptions.isGroupByStackTrace())
|| !groupingOptions.isGroupByThread()) {
byte[] bytes = networkPacket.getBytes();
networkPacket = new NetworkPacket(
networkPacket.isSent(),
networkPacket.getTimestamp(),
groupingOptions.isGroupByStackTrace() ? networkPacket.getStackTrace() : null,
groupingOptions.isGroupByThread() ? networkPacket.getThreadMetaData() : null,
bytes, 0, bytes.length
);
}
if (reducedNetworkPackets.isEmpty()) {
reducedNetworkPackets.add(networkPacket);
} else {
NetworkPacket lastPacket = reducedNetworkPackets.get(reducedNetworkPackets.size() - 1);
if (!lastPacket.combine(networkPacket, SniffyConfiguration.INSTANCE.getPacketMergeThreshold())) {
reducedNetworkPackets.add(networkPacket);
}
}
}
}
}
}
return reducedTraffic;
}
// Expect and verify methods
/**
* @param expectation
* @return
* @since 3.1
*/
@Override
public C expect(Expectation expectation) {
checkOpened();
expectations.add(expectation);
return self();
}
/**
* @param expectation
* @return
* @since 3.1
*/
@Override
public C verify(Expectation expectation) {
checkOpened();
expectation.verify(this);
return self();
}
/**
* Verifies all expectations added previously using {@code expect} methods family
*
* @throws SniffyAssertionError if wrong number of queries was executed
* @since 2.0
*/
@Override
public void verify() throws SniffyAssertionError {
checkOpened();
SniffyAssertionError assertionError = getSniffyAssertionError();
if (null != assertionError) {
throw assertionError;
}
}
/**
* @return SniffyAssertionError or null if there are no errors
* @since 3.1
*/
@Override
public SniffyAssertionError getSniffyAssertionError() {
checkOpened();
SniffyAssertionError assertionError = null;
Throwable currentException = null;
for (Expectation expectation : expectations) {
try {
expectation.verify(this);
} catch (SniffyAssertionError e) {
if (null == assertionError) {
currentException = assertionError = e;
} else {
currentException.initCause(e);
currentException = e;
}
}
}
return assertionError;
}
/**
* Alias for {@link #verify()} method; it is useful for try-with-resource API:
* <pre>
* <code>
* {@literal @}Test
* public void testTryWithResourceApi() throws SQLException {
* final Connection connection = DriverManager.getConnection("sniffer:jdbc:h2:mem:", "sa", "sa");
* try (@SuppressWarnings("unused") Spy s = Sniffer.expectAtMostOnce();
* Statement statement = connection.createStatement()) {
* statement.execute("SELECT 1 FROM DUAL");
* }
* }
* }
* </code>
* </pre>
*
* @since 2.0
*/
public void close() {
try {
verify();
} finally {
Sniffy.removeSpyReference(selfReference);
closed = true;
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
closeStackTrace = new StackTraceElement[stackTrace.length - 1];
System.arraycopy(stackTrace, 1, closeStackTrace, 0, stackTrace.length - 1);
}
}
@Override
protected void checkOpened() {
if (closed) {
throw new SpyClosedException("Spy is closed", closeStackTrace);
}
}
/**
* Executes the {@link io.sniffy.Executable#execute()} method on provided argument and verifies the expectations
*
* @throws SniffyAssertionError if wrong number of queries was executed
* @since 3.1
*/
@Override
public C execute(io.sniffy.Executable executable) throws SniffyAssertionError {
checkOpened();
try {
executable.execute();
} catch (Throwable e) {
throw verifyAndAddToException(e);
}
verify();
return self();
}
/**
* Executes the {@link Runnable#run()} method on provided argument and verifies the expectations
*
* @throws SniffyAssertionError if wrong number of queries was executed
* @since 2.0
*/
public C run(Runnable runnable) throws SniffyAssertionError {
checkOpened();
try {
runnable.run();
} catch (Throwable e) {
throw verifyAndAddToException(e);
}
verify();
return self();
}
/**
* Executes the {@link Callable#call()} method on provided argument and verifies the expectations
*
* @throws SniffyAssertionError if wrong number of queries was executed
* @since 2.0
*/
public <V> SpyWithValue<V> call(Callable<V> callable) throws SniffyAssertionError {
checkOpened();
V result;
try {
result = callable.call();
} catch (Throwable e) {
throw verifyAndAddToException(e);
}
verify();
return new SpyWithValue<V>(result);
}
private RuntimeException verifyAndAddToException(Throwable e) {
try {
verify();
} catch (SniffyAssertionError ae) {
if (!ExceptionUtil.addSuppressed(e, ae)) {
ae.printStackTrace();
}
}
throwException(e);
return new RuntimeException(e);
}
/**
* @since 3.1
*/
public interface Expectation {
<T extends Spy<T>> Spy<T> verify(Spy<T> spy) throws SniffyAssertionError;
}
/**
* @since 3.1
*/
public static class SpyClosedException extends IllegalStateException {
private final StackTraceElement[] closeStackTrace;
public SpyClosedException(String s, StackTraceElement[] closeStackTrace) {
super(ExceptionUtil.generateMessage(s + StringUtil.LINE_SEPARATOR + "Close stack trace:", closeStackTrace));
this.closeStackTrace = closeStackTrace;
}
public StackTraceElement[] getCloseStackTrace() {
return null == closeStackTrace ? null : closeStackTrace.clone();
}
}
public static final class SpyWithValue<V> extends Spy<SpyWithValue<V>> {
private final V value;
SpyWithValue(V value) {
this.value = value;
}
public V getValue() {
return value;
}
}
}
|
package com.kumuluz.ee.maven.plugin.com.kumuluz.ee.maven.plugin.util;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.kumuluz.ee.maven.plugin.com.kumuluz.ee.maven.plugin.config.ApiSpecification;
import com.kumuluz.ee.maven.plugin.com.kumuluz.ee.maven.plugin.config.SpecificationConfig;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.logging.Logger;
/**
* ApiSpecsUtil class.
*
* @author Zvone Gazvoda
* @since 2.5.0
*/
public class ApiSpecsUtil {
private static final Logger LOG = Logger.getLogger(ApiSpecsUtil.class.getName());
public static List<ApiSpecURLs> getApiSpecs(MavenProject project, SpecificationConfig apiSpecificationConfig) throws
MojoExecutionException {
List<ApiSpecURLs> apiSpecs = new ArrayList<>();
List<File> openApiSpecsConfigsLocations = new ArrayList<>();
List<File> swaggerSpecsConfigsLocations = new ArrayList<>();
String apiSpecsPath = project.getBuild().getDirectory() + "/classes/api-specs";
File apiSpecFiles = new File(apiSpecsPath);
getApiSpecPaths(apiSpecFiles, openApiSpecsConfigsLocations, ApiSpecType.OPENAPI);
getApiSpecPaths(apiSpecFiles, swaggerSpecsConfigsLocations, ApiSpecType.SWAGGER);
ObjectMapper mapper = new ObjectMapper();
if (swaggerSpecsConfigsLocations.size() > 0) {
for (File swaggerConfig : swaggerSpecsConfigsLocations) {
try {
JsonNode root = mapper.readTree(swaggerConfig);
String apiName = root.path("swagger").path("info").path("title").asText() + " - " + root.path("swagger").path
("info").path("version").asText();
String basePath = root.path("swagger").path("basePath").asText();
basePath = StringUtils.strip(basePath, "/");
String apiUrl = "http://" + root.path("swagger").path("host").asText() + "/api-specs/" + basePath +
"/swagger.json";
ApiSpecURLs specUrl = new ApiSpecURLs();
specUrl.setName(apiName);
specUrl.setUrl(apiUrl);
apiSpecs.add(specUrl);
} catch (IOException e) {
throw new MojoExecutionException("Error processing API specification files", e);
}
}
} else if (openApiSpecsConfigsLocations.size() > 0) {
for (File openApiConfig : openApiSpecsConfigsLocations) {
try {
JsonNode root = mapper.readTree(openApiConfig);
String apiName = root.path("openAPI").path("info").path("title").asText() + " - " + root.path("openAPI").path
("info").path("version").asText();
URL url = null;
for (JsonNode node : root.path("openAPI").path("servers")) {
url = new URL(node.path("url").asText());
break;
}
if (url != null) {
String apiUrl = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort() + "/api-specs" + url.getPath() +
"/openapi.json";
ApiSpecURLs specUrl = new ApiSpecURLs();
specUrl.setName(apiName);
specUrl.setUrl(apiUrl);
apiSpecs.add(specUrl);
// Update resourcePackages
String applicationPathUrl = url.getPath();
Optional<ApiSpecification> config = apiSpecificationConfig.getApiSpecifications().stream().
filter(as -> applicationPathUrl
.equals(as.getApplicationPath())).findFirst();
if (config.isPresent()) {
ArrayNode array = mapper.valueToTree(config.get().getResourcePackages());
((ObjectNode) root).putArray("resourcePackages").addAll(array);
mapper.enable(SerializationFeature.INDENT_OUTPUT).writeValue(openApiConfig, root);
}
}
} catch (IOException e) {
throw new MojoExecutionException("Error processing API specification files", e);
}
}
}
return apiSpecs;
}
private static void getApiSpecPaths(File file, List<File> openApiConfigLocations, ApiSpecType type) {
File[] content = file.listFiles();
if (content != null) {
for (File f : content) {
if (f.isDirectory()) {
getApiSpecPaths(f, openApiConfigLocations, type);
} else if (f.getName().equals(type.toString())) {
openApiConfigLocations.add(f);
}
}
}
}
}
|
package expectj;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Date;
import java.util.concurrent.TimeoutException;
/**
* This class represents a spawned process. This will also interact with
* the process to read and write to it.
*
* @author Sachin Shekar Shetty
*/
public class SpawnedProcess implements TimerEventListener {
/** Default time out for expect commands */
private long m_lDefaultTimeOutSeconds = -1;
/**
* Buffered wrapper stream for slave's stdin.
*/
private BufferedWriter out = null;
// Debugger object
Debugger debug = new Debugger("SpawnedProcess", true);
/**
* This is what we're actually talking to.
*/
private SpawnableHelper slave = null;
private volatile boolean continueReading = true;
// Piper objects to pipe the process streams to standard streams
private StreamPiper interactIn = null;
private StreamPiper interactOut = null;
private StreamPiper interactErr = null;
/**
* Wait for data from spawn's stdout.
*/
private Selector stdoutSelector;
/**
* Wait for data from spawn's stderr.
*/
private Selector stderrSelector;
/**
* This object will be notified on timer timeout.
*/
private final Object timeoutNotification = new Object();
/**
* Constructor
*
* @param spawn This is what we'll control.
* @param lDefaultTimeOutSeconds Default timeout for expect commands
* @throws Exception on trouble launching the spawn
*/
SpawnedProcess(Spawnable spawn, long lDefaultTimeOutSeconds)
throws Exception
{
if (lDefaultTimeOutSeconds < -1) {
throw new IllegalArgumentException("Timeout must be >= -1, was "
+ lDefaultTimeOutSeconds);
}
m_lDefaultTimeOutSeconds = lDefaultTimeOutSeconds;
slave = new SpawnableHelper(spawn, lDefaultTimeOutSeconds);
slave.start();
debug.print("Spawned Process: " + spawn);
if (slave.getOutputStream() != null) {
out =
new BufferedWriter(new OutputStreamWriter(slave.getOutputStream()));
}
stdoutSelector = Selector.open();
slave.getSourceChannel().register(stdoutSelector, SelectionKey.OP_READ);
if (slave.getErrorSourceChannel() != null) {
stderrSelector = Selector.open();
slave.getErrorSourceChannel().register(stderrSelector, SelectionKey.OP_READ);
}
}
/**
* Timer callback method
* This method is invoked when the time-out occur
*/
public synchronized void timerTimedOut() {
continueReading = false;
stdoutSelector.wakeup();
if (stderrSelector != null) {
stderrSelector.wakeup();
}
synchronized (timeoutNotification) {
timeoutNotification.notify();
}
}
/**
* Timer callback method
* This method is invoked by the Timer, when the timer thread
* receives an interrupted exception
* @param reason Why we were interrupted
*/
public void timerInterrupted(InterruptedException reason) {
continueReading = false;
stdoutSelector.wakeup();
if (stderrSelector != null) {
stderrSelector.wakeup();
}
}
/**
* @return true if the last expect() or expectErr() method
* returned because of a time out rather then a match against
* the output of the process.
*/
public boolean isLastExpectTimeOut() {
return !continueReading;
}
/**
* This method functions exactly like the Unix expect command.
* It waits until a string is read from the standard output stream
* of the spawned process that matches the string pattern.
* SpawnedProcess does a cases insensitive substring match for pattern
* against the output of the spawned process.
* lDefaultTimeOut is the timeout in seconds that the expect command
* should wait for the pattern to match. This function returns
* when a match is found or after lTimOut seconds.
* You can use the SpawnedProcess.isLastExpectTimeOut() to identify
* the return path of the method. A timeout of -1 will make the expect
* method wait indefinitely until the supplied pattern matches
* with the Standard Out.
*
* @param pattern The case-insensitive substring to match against.
* @param lTimeOutSeconds The timeout in seconds before the match fails.
* @throws ExpectJException when some error occurs.
* @throws IOException on IO trouble waiting for pattern
* @throws TimeoutException on timeout waiting for pattern
*/
public void expect(String pattern, long lTimeOutSeconds)
throws ExpectJException, IOException, TimeoutException
{
expect(pattern, lTimeOutSeconds, stdoutSelector);
}
/**
* Wait for the spawned process to finish.
* @param lTimeOutSeconds The number of seconds to wait before giving up, or
* -1 to wait forever.
* @throws ExpectJException
* @throws TimeoutException
* @see #expectClose()
*/
public void expectClose(long lTimeOutSeconds)
throws ExpectJException, TimeoutException
{
if (lTimeOutSeconds < -1) {
throw new IllegalArgumentException("Timeout must be >= -1, was "
+ lTimeOutSeconds);
}
debug.print("SpawnedProcess.expectClose()");
Timer tm = null;
if (lTimeOutSeconds != -1 ) {
tm = new Timer(lTimeOutSeconds, this);
tm.startTimer();
}
continueReading = true;
boolean closed = false;
synchronized (timeoutNotification) {
while(continueReading) {
// Sleep if process is still running
if(slave.isClosed()) {
closed = true;
break;
} else {
try {
timeoutNotification.wait(500);
} catch (InterruptedException e) {
throw new ExpectJException("Interrupted waiting for spawn to finish",
e);
}
}
}
}
debug.print("expect Over");
debug.print("Found: " + closed);
debug.print("Continue Reading:" + continueReading );
if (tm != null) {
debug.print("Timer Status:" + tm.getStatus());
}
if (!continueReading) {
throw new TimeoutException("Timeout waiting for spawn to finish");
}
}
/**
* Wait the default timeout for the spawned process to finish.
* @throws ExpectJException If something fails.
* @throws TimeoutException
* @see #expectClose(long)
*/
public void expectClose()
throws ExpectJException, TimeoutException
{
expectClose(m_lDefaultTimeOutSeconds);
}
/**
* Workhorse of the expect() and expectErr() methods.
* @see #expect(String, long)
* @param pattern What to look for
* @param lTimeOutSeconds How long to look before giving up
* @param selector A selector covering only the channel we should read from
* @throws IOException on IO trouble waiting for pattern
* @throws TimeoutException on timeout waiting for pattern
*/
private void expect(String pattern, long lTimeOutSeconds, Selector selector)
throws IOException, TimeoutException
{
if (lTimeOutSeconds < -1) {
throw new IllegalArgumentException("Timeout must be >= -1, was "
+ lTimeOutSeconds);
}
if (selector.keys().size() != 1) {
throw new IllegalArgumentException("Selector key set size must be 1, was "
+ selector.keys().size());
}
// If this cast fails somebody gave us the wrong selector.
Pipe.SourceChannel readMe =
(Pipe.SourceChannel)selector.keys().iterator().next().channel();
debug.print("SpawnedProcess.expect(" + pattern + ")");
continueReading = true;
boolean found = false;
StringBuilder line = new StringBuilder();
Date runUntil = null;
if (lTimeOutSeconds > 0) {
runUntil = new Date(new Date().getTime() + lTimeOutSeconds * 1000);
}
ByteBuffer buffer = ByteBuffer.allocate(1024);
while(continueReading) {
if (runUntil == null) {
selector.select();
} else {
long msLeft = runUntil.getTime() - new Date().getTime();
if (msLeft > 0) {
selector.select(msLeft);
} else {
continueReading = false;
break;
}
}
if (selector.selectedKeys().size() == 0) {
// Woke up with nothing selected, try again
continue;
}
buffer.rewind();
if (readMe.read(buffer) == -1) {
// End of stream
break;
}
buffer.rewind();
for (int i = 0; i < buffer.limit(); i++) {
line.append((char)buffer.get(i));
}
if (line.toString().trim().toUpperCase().indexOf(pattern.toUpperCase()) != -1) {
debug.print("Matched for " + pattern + ":"
+ line);
found = true;
break;
}
while (line.indexOf("\n") != -1) {
line.delete(0, line.indexOf("\n") + 1);
}
}
debug.print("expect Over");
debug.print("Found: " + found);
debug.print("Continue Reading:" + continueReading );
if (!continueReading) {
throw new TimeoutException("Timeout trying to match \"" + pattern + "\"");
}
}
/**
* This method functions exactly like the corresponding expect
* function except for it tries to match the pattern with the
* output of standard error stream of the spawned process.
* @see #expect(String, long)
* @param pattern The case-insensitive substring to match against.
* @param lTimeOutSeconds The timeout in seconds before the match fails.
* @throws ExpectJException when some error occurs.
* @throws TimeoutException on timeout waiting for pattern
* @throws IOException on IO trouble waiting for pattern
*/
public void expectErr(String pattern, long lTimeOutSeconds)
throws ExpectJException, IOException, TimeoutException
{
expect(pattern, lTimeOutSeconds, stderrSelector);
}
/**
* This method functions exactly like expect described above,
* but uses the default timeout specified in the ExpectJ constructor.
* @param pattern The case-insensitive substring to match against.
* @throws ExpectJException when some error occurs.
* @throws TimeoutException on timeout waiting for pattern
* @throws IOException on IO trouble waiting for pattern
*/
public void expect(String pattern)
throws IOException, TimeoutException, ExpectJException
{
expect(pattern, m_lDefaultTimeOutSeconds);
}
/**
* This method functions exactly like the corresponding expect
* function except for it tries to match the pattern with the output
* of standard error stream of the spawned process.
* @param pattern The case-insensitive substring to match against.
* @throws ExpectJException when some error occurs.
* @throws TimeoutException on timeout waiting for pattern
* @throws IOException on IO trouble waiting for pattern
*/
public void expectErr(String pattern)
throws ExpectJException, IOException, TimeoutException
{
expectErr(pattern, m_lDefaultTimeOutSeconds);
}
/**
* This method should be use use to check the process status
* before invoking send()
* @return true if the process has already exited.
*/
public boolean isClosed() {
return slave.isClosed();
}
/**
* @return the exit code of the process if the process has
* already exited.
* @throws ExpectJException if the spawn is still running.
*/
public int getExitValue()
throws ExpectJException
{
return slave.getExitValue();
}
/**
* This method writes the string line to the standard input of the spawned process.
* @param string The string to send. Don't forget to terminate it with \n if you
* want it linefed.
* @throws IOException on IO trouble talking to spawn
*/
public void send(String string)
throws IOException {
debug.print("Sending " + string);
out.write(string);
out.flush();
}
/**
* This method functions like exactly the Unix interact command.
* It allows the user to interact with the spawned process.
* Known Issues: User input is echoed twice on the screen, need to
* fix this ;)
*
*/
public void interact() {
interactIn = new StreamPiper(null,
System.in, slave.getOutputStream());
interactIn.start();
interactOut = new StreamPiper(null,
Channels.newInputStream(slave.getSourceChannel()),
System.out);
interactOut.start();
interactErr = new StreamPiper(null,
Channels.newInputStream(slave.getErrorSourceChannel()),
System.err);
interactErr.start();
slave.stopPipingToStandardOut();
}
/**
* This method kills the process represented by SpawnedProcess object.
*/
public void stop() {
if (interactIn != null)
interactIn.stopProcessing();
if (interactOut != null)
interactOut.stopProcessing();
if (interactErr != null)
interactErr.stopProcessing();
slave.stop();
}
/**
* @return the available contents of Standard Out
*/
public String getCurrentStandardOutContents() {
return slave.getCurrentStandardOutContents();
}
/**
* @return the available contents of Standard Err
*/
public String getCurrentStandardErrContents() {
return slave.getCurrentStandardErrContents();
}
}
|
package org.xwiki.test.ui.po;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.LocaleUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.FindBys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.test.ui.po.editor.ClassEditPage;
import org.xwiki.test.ui.po.editor.EditPage;
import org.xwiki.test.ui.po.editor.ObjectEditPage;
import org.xwiki.test.ui.po.editor.RightsEditPage;
import org.xwiki.test.ui.po.editor.WYSIWYGEditPage;
import org.xwiki.test.ui.po.editor.WikiEditPage;
/**
* Represents the common actions possible on all Pages.
*
* @version $Id$
* @since 3.2M3
*/
public class BasePage extends BaseElement
{
private static final Logger LOGGER = LoggerFactory.getLogger(BasePage.class);
private static final By DRAWER_MATCHER = By.id("tmDrawer");
/**
* Used for sending keyboard shortcuts to.
*/
@FindBy(id = "xwikimaincontainer")
private WebElement mainContainerDiv;
/**
* The top floating content menu bar.
*/
@FindBy(id = "contentmenu")
private WebElement contentMenuBar;
@FindBy(xpath = "//div[@id='tmCreate']/a[contains(@role, 'button')]")
private WebElement tmCreate;
@FindBy(xpath = "//div[@id='tmMoreActions']/a[contains(@role, 'button')]")
private WebElement moreActionsMenu;
@FindBy(id = "tmDrawerActivator")
private WebElement drawerActivator;
@FindBy(xpath = "//input[@id='tmWatchDocument']/../span[contains(@class, 'bootstrap-switch-label')]")
private WebElement watchDocumentLink;
@FindBy(id = "tmPage")
private WebElement pageMenu;
@FindBys({ @FindBy(id = "tmRegister"), @FindBy(tagName = "a") })
private WebElement registerLink;
@FindBy(xpath = "//a[@id='tmLogin']")
private WebElement loginLink;
@FindBy(xpath = "//a[@id='tmUser']")
private WebElement userLink;
@FindBy(xpath = "//li[contains(@class, 'navbar-avatar')]//img[contains(@class, 'avatar')]")
private WebElement userAvatarImage;
@FindBy(id = "document-title")
private WebElement documentTitle;
@FindBy(xpath = "//input[@id='tmWatchSpace']/../span[contains(@class, 'bootstrap-switch-label')]")
private WebElement watchSpaceLink;
@FindBy(xpath = "//input[@id='tmWatchWiki']/../span[contains(@class, 'bootstrap-switch-label')]")
private WebElement watchWikiLink;
@FindBy(css = "#tmMoreActions a[title='Children']")
private WebElement childrenLink;
@FindBy(id = "tmNotifications")
private WebElement notificationsMenu;
/**
* Used to scroll the page to the top before accessing the floating menu.
*/
@FindBy(id = "companylogo")
protected WebElement logo;
/**
* Note: when reusing instances of BasePage, the constructor is not doing the work anymore and the
* waitUntilPageJSIsLoaded() method needs to be executed manually, when needed.
* <p>
* Note2: Never call the constructor before navigating to the page you need to test first.
*/
public BasePage()
{
super();
waitUntilPageJSIsLoaded();
}
public String getPageTitle()
{
return getDriver().getTitle();
}
// TODO I think this should be in the AbstractTest instead -cjdelisle
public String getPageURL()
{
return getDriver().getCurrentUrl();
}
/**
* @param metaName the name of the XWiki document metadata
* @return the value of the specified XWiki document metadata for the current XWiki document
* @see #getHTMLMetaDataValue(String)
*/
public String getMetaDataValue(String metaName)
{
return getDriver().findElement(By.xpath("/html")).getAttribute("data-xwiki-" + metaName);
}
/**
* @param metaName the name of the HTML meta field
* @return the value of the requested HTML meta field with from the current page
* @since 7.2RC1
*/
public String getHTMLMetaDataValue(String metaName)
{
return getDriver().findElement(By.xpath("//meta[@name='" + metaName + "']")).getAttribute("content");
}
/**
* @return true if we are currently logged in, false otherwise
*/
public boolean isAuthenticated()
{
return getDriver().hasElementWithoutWaiting(By.id("tmUser"));
}
/**
* Determine if the current page is a new document.
*
* @return true if the document is new, false otherwise
*/
public boolean isNewDocument()
{
return (Boolean) ((JavascriptExecutor) getDriver()).executeScript("return XWiki.docisnew");
}
/**
* Perform a click on a "edit menu" sub-menu entry.
*
* @param id The id of the entry to follow
*/
protected void clickEditSubMenuEntry(String id)
{
/**
* Performs a click on the "edit" button.
*/
public void edit()
{
WebElement editMenuButton =
getDriver().findElement(By.xpath("//div[@id='tmEdit']/a[contains(@role, 'button')]"));
editMenuButton.click();
}
/**
* Gets a string representation of the URL for editing the page.
*/
public String getEditURL()
{
return getDriver().findElement(By.xpath("//div[@id='tmEdit']//a")).getAttribute("href");
}
/**
* Performs a click on the "edit wiki" entry of the content menu.
*/
public WikiEditPage editWiki()
{
clickEditSubMenuEntry("tmEditWiki");
return new WikiEditPage();
}
/**
* Performs a click on the "edit wysiwyg" entry of the content menu.
*/
public WYSIWYGEditPage editWYSIWYG()
{
clickEditSubMenuEntry("tmEditWysiwyg");
return new WYSIWYGEditPage();
}
/**
* Performs a click on the "edit inline" entry of the content menu.
*/
public <T extends InlinePage> T editInline()
{
clickEditSubMenuEntry("tmEditInline");
return createInlinePage();
}
/**
* Can be overridden to return extended {@link InlinePage}.
*/
@SuppressWarnings("unchecked")
protected <T extends InlinePage> T createInlinePage()
{
return (T) new InlinePage();
}
/**
* Performs a click on the "edit acces rights" entry of the content menu.
*/
public RightsEditPage editRights()
{
clickEditSubMenuEntry("tmEditRights");
return new RightsEditPage();
}
/**
* Performs a click on the "edit objects" entry of the content menu.
*/
public ObjectEditPage editObjects()
{
clickEditSubMenuEntry("tmEditObject");
return new ObjectEditPage();
}
/**
* Performs a click on the "edit class" entry of the content menu.
*/
public ClassEditPage editClass()
{
clickEditSubMenuEntry("tmEditClass");
return new ClassEditPage();
}
/**
* @since 3.2M3
*/
public void sendKeys(CharSequence... keys)
{
this.mainContainerDiv.sendKeys(keys);
}
/**
* Waits until the page has loaded. Normally we don't need to call this method since a click in Selenium2 is a
* blocking call. However there are cases (such as when using a shortcut) when we asynchronously load a page.
*
* @return this page
* @since 3.2M3
*/
public BasePage waitUntilPageIsLoaded()
{
getDriver().waitUntilElementIsVisible(By.id("footerglobal"));
return this;
}
/**
* @since 7.2M3
*/
public void toggleDrawer()
{
if (isElementVisible(DRAWER_MATCHER)) {
// The drawer is visible, so we close it by clicking outside the drawer
this.mainContainerDiv.click();
getDriver().waitUntilElementDisappears(DRAWER_MATCHER);
} else {
// The drawer is not visible, so we open it
this.drawerActivator.click();
getDriver().waitUntilElementIsVisible(DRAWER_MATCHER);
}
}
/**
* @return true if the drawer used to be hidden
* @since 8.4.5
* @since 9.0RC1
*/
public boolean showDrawer()
{
if (!isElementVisible(DRAWER_MATCHER)) {
// The drawer is not visible, so we open it
this.drawerActivator.click();
getDriver().waitUntilElementIsVisible(DRAWER_MATCHER);
return true;
}
return false;
}
/**
* @return true if the drawer used to be displayed
* @since 8.4.5
* @since 9.0RC1
*/
public boolean hideDrawer()
{
if (isElementVisible(DRAWER_MATCHER)) {
// The drawer is visible, so we close it by clicking outside the drawer
// We don't perform directly a click since it could lead to a
// org.openqa.selenium.ElementClickInterceptedException because of a drawer-overlay-upper above it.
// The click through action is performed with a move and click, which is what we really want.
getDriver().createActions().click(this.mainContainerDiv).perform();
getDriver().waitUntilElementDisappears(DRAWER_MATCHER);
return true;
}
return false;
}
/**
* @since 8.4.5
* @since 9.0RC1
*/
public boolean isDrawerVisible()
{
return isElementVisible(DRAWER_MATCHER);
}
/**
* @since 7.2M3
*/
public void toggleActionMenu()
{
this.moreActionsMenu.click();
}
/**
* @since 7.0RC1
*/
public void clickMoreActionsSubMenuEntry(String id)
{
clickSubMenuEntryFromMenu(By.xpath("//div[@id='tmMoreActions']/a[contains(@role, 'button')]"), id);
}
/**
* @since 7.3M2
* @deprecated use {@link #clickMoreActionsSubMenuEntry(String)} instead which has a better name
*/
@Deprecated
public void clickAdminActionsSubMenuEntry(String id)
{
clickMoreActionsSubMenuEntry(id);
}
/**
* @since 7.0RC1
*/
private void clickSubMenuEntryFromMenu(By menuBy, String id)
{
// Open the parent Menu
getDriver().findElement(menuBy).click();
// Wait for the submenu entry to be visible
getDriver().waitUntilElementIsVisible(By.id(id));
// Click on the specified entry
getDriver().findElement(By.id(id)).click();
}
/**
* @since 4.5M1
*/
public CreatePagePage createPage()
{
this.tmCreate.click();
return new CreatePagePage();
}
/**
* @since 4.5M1
*/
public CopyPage copy()
{
clickMoreActionsSubMenuEntry("tmActionCopy");
return new CopyPage();
}
public RenamePage rename()
{
clickMoreActionsSubMenuEntry("tmActionRename");
return new RenamePage();
}
/**
* @since 4.5M1
*/
public ConfirmationPage delete()
{
clickMoreActionsSubMenuEntry("tmActionDelete");
return new ConfirmationPage();
}
/**
* Specific delete action when the delete action is performed on a page.
*
* @return a specialized confirmation page for page deletion
*
* @since 12.8RC1
*/
public DeletePageConfirmationPage deletePage()
{
clickMoreActionsSubMenuEntry("tmActionDelete");
return new DeletePageConfirmationPage();
}
/**
* @since 4.5M1
*/
public boolean canDelete()
{
toggleActionMenu();
// Don't wait here since test can use this method to verify that there's no Delete right on the current page
// and calling hasElement() would incurr the wait timeout.
boolean canDelete = getDriver().hasElementWithoutWaiting(By.id("tmActionDelete"));
toggleActionMenu();
return canDelete;
}
/**
* @since 4.5M1
*/
public void watchDocument()
{
toggleNotificationsMenu();
this.watchDocumentLink.click();
toggleActionMenu();
}
/**
* @since 4.5M1
*/
public boolean hasLoginLink()
{
// Note that we cannot test if the loginLink field is accessible since we're using an AjaxElementLocatorFactory
// and thus it would wait 15 seconds before considering it's not accessible.
return !getDriver().findElementsWithoutWaiting(By.id("tmLogin")).isEmpty();
}
/**
* @since 4.5M1
*/
public LoginPage login()
{
toggleDrawer();
this.loginLink.click();
return new LoginPage();
}
/**
* @since 4.5M1
*/
public String getCurrentUser()
{
// We need to show the drawer because #getText() does not allow getting hidden text (but allow finding the
// element and its attributes...)
boolean hide = showDrawer();
String user = this.userLink.getText();
if (hide) {
hideDrawer();
}
return user;
}
/**
* @since 9.0RC1
*/
public List<Locale> getLocales()
{
List<WebElement> elements =
getDriver().findElementsWithoutWaiting(By.xpath("//ul[@id='tmLanguages_menu']/li/a"));
List<Locale> locales = new ArrayList<>(elements.size());
for (WebElement element : elements) {
String href = element.getAttribute("href");
Matcher matcher = Pattern.compile(".*\\?.*language=([^=&]*)").matcher(href);
if (matcher.matches()) {
String locale = matcher.group(1);
locales.add(LocaleUtils.toLocale(locale));
}
}
return locales;
}
/**
* @since 9.0RC1
*/
public ViewPage clickLocale(Locale locale)
{
// Open drawer
toggleDrawer();
// Open Languages
WebElement languagesElement = getDriver().findElementWithoutWaiting(By.xpath("//a[@id='tmLanguages']"));
languagesElement.click();
// Wait for the languages submenu to be open
getDriver().waitUntilCondition(webDriver ->
getDriver().findElementWithoutWaiting(By.id("tmLanguages_menu")).getAttribute("class")
.contains("collapse in")
);
// Click passed locale
WebElement localeElement = getDriver().findElementWithoutWaiting(
By.xpath("//ul[@id='tmLanguages_menu']/li/a[contains(@href,'language=" + locale + "')]"));
localeElement.click();
return new ViewPage();
}
/**
* @since 4.5M1
*/
public void logout()
{
toggleDrawer();
getDriver().findElement(By.id("tmLogout")).click();
// Update the CSRF token because the context user has changed (it's guest user now). Otherwise, APIs like
// TestUtils#createUser*(), which expect the currently cached token to be valid, will fail because they would be
// using the token of the previously logged in user.
getUtil().recacheSecretToken();
}
/**
* @since 4.5M1
*/
public RegistrationPage register()
{
toggleDrawer();
this.registerLink.click();
return new RegistrationPage();
}
/**
* @since 4.5M1
*/
public String getDocumentTitle()
{
return this.documentTitle.getText();
}
/**
* @since 4.5M1
*/
public void watchSpace()
{
toggleNotificationsMenu();
this.watchSpaceLink.click();
toggleNotificationsMenu();
}
/**
* @since 6.0M1
*/
public void watchWiki()
{
toggleNotificationsMenu();
this.watchWikiLink.click();
toggleNotificationsMenu();
}
/**
* Opens the viewer that lists the children of the current page.
*
* @return the viewer that lists the child pages
* @since 7.3RC1
*/
public ChildrenViewer viewChildren()
{
toggleActionMenu();
this.childrenLink.click();
return new ChildrenViewer();
}
/**
* Says if the notifications menu is present (it is displayed only if it has some content).
*
* @return either or not the notifications menu is present
* @since 7.4M1
*/
public boolean hasNotificationsMenu()
{
return getDriver().hasElementWithoutWaiting(By.id("tmNotifications"));
}
/**
* Open/Close the notifications menu.
*
* @since 7.4M1
*/
public void toggleNotificationsMenu()
{
boolean hasMenu = isNotificationsMenuOpen();
this.notificationsMenu.click();
if (hasMenu) {
getDriver().waitUntilElementDisappears(this.notificationsMenu, By.className("dropdown-menu"));
} else {
getDriver().waitUntilElementIsVisible(this.notificationsMenu, By.className("dropdown-menu"));
}
}
/**
* @return true if the notifications menu is open
* @since 7.4M1
*/
public boolean isNotificationsMenuOpen()
{
return this.notificationsMenu.findElement(By.className("dropdown-menu")).isDisplayed();
}
/**
* @return the text of uncaught errors
* @since 8.0M1
*/
public String getErrorContent()
{
return getDriver()
.findElementWithoutWaiting(By.xpath("//div[@id = 'mainContentArea']/pre[contains(@class, 'xwikierror')]"))
.getText();
}
/**
* @param panelTitle the panel displayed title
* @return true if the panel is visible in the left panels or false otherwise
* @since 10.6RC1
*/
public boolean hasLeftPanel(String panelTitle)
{
return getDriver().hasElementWithoutWaiting(By.xpath(
"//div[@id = 'leftPanels']/div/h1[@class = 'xwikipaneltitle' and text() = '" + panelTitle +"']"));
}
public boolean isForbidden()
{
List<WebElement> messages = getDriver().findElementsWithoutWaiting(By.className("xwikimessage"));
for (WebElement message : messages) {
if (message.getText().contains("You are not allowed to view this page or perform this action.")) {
return true;
}
}
return false;
}
/**
* Use the following keyboard shortcut and wait for a new page to load.
* This should be only used for shortcuts that indeed loads a new page.
* @param shortcut the keyboard key combination to perform.
*/
private void useShortcutKeyAndLoads(CharSequence... shortcut)
{
getDriver().addPageNotYetReloadedMarker();
getDriver().createActions().sendKeys(shortcut).perform();
getDriver().waitUntilPageIsReloaded();
}
/**
* Use keyboard shortcuts to go to edit page.
* @return a new {@link EditPage}
* @since 11.9RC1
*/
public EditPage useShortcutKeyForEditing()
{
useShortcutKeyAndLoads("e");
return new EditPage();
}
/**
* Use keyboard shortcuts to go to wiki edit page.
* @return a new {@link WikiEditPage}
* @since 11.9RC1
*/
public WikiEditPage useShortcutKeyForWikiEditing()
{
useShortcutKeyAndLoads("k");
return new WikiEditPage();
}
/**
* Use keyboard shortcuts to go to WYSIWYG edit page.
* @return a new {@link WYSIWYGEditPage}
* @since 11.9RC1
*/
public WYSIWYGEditPage useShortcutKeyForWysiwygEditing()
{
useShortcutKeyAndLoads("g");
return new WYSIWYGEditPage();
}
/**
* Use keyboard shortcuts to go to Inline Form edit page.
* @return a new {@link InlinePage}
* @since 11.9RC1
*/
public InlinePage useShortcutKeyForInlineEditing()
{
useShortcutKeyAndLoads("f");
return new InlinePage();
}
/**
* Use keyboard shortcuts to go to rights edit page.
* @return a new {@link BasePage}: it can be actually either a {@link RightsEditPage} or an AdministrationPage
* depending if the page is terminal or not.
* @since 11.9RC1
*/
public BasePage useShortcutKeyForRightsEditing()
{
useShortcutKeyAndLoads("r");
return new BasePage();
}
/**
* Use keyboard shortcuts to go to object edit page.
* @return a new {@link ObjectEditPage}
* @since 11.9RC1
*/
public ObjectEditPage useShortcutKeyForObjectEditing()
{
useShortcutKeyAndLoads("o");
return new ObjectEditPage();
}
/**
* Use keyboard shortcuts to go to class edit page.
* @return a new {@link ClassEditPage}
* @since 11.9RC1
*/
public ClassEditPage useShortcutKeyForClassEditing()
{
useShortcutKeyAndLoads("s");
return new ClassEditPage();
}
/**
* Use keyboard shortcuts to go to delete page.
* @return a new {@link ConfirmationPage}
* @since 11.9RC1
*/
public ConfirmationPage useShortcutKeyForPageDeletion()
{
useShortcutKeyAndLoads(Keys.DELETE);
return new ConfirmationPage();
}
/**
* Use keyboard shortcuts to go to rename page.
* @return a new {@link RenamePage}
* @since 11.9RC1
*/
public RenamePage useShortcutKeyForPageRenaming()
{
useShortcutKeyAndLoads(Keys.F2);
return new RenamePage();
}
/**
* Use keyboard shortcuts to go to the source view of a page.
* @return a new {@link ViewPage}
* @since 11.9RC1
*/
public ViewPage useShortcutKeyForSourceViewer()
{
useShortcutKeyAndLoads("d");
return new ViewPage();
}
}
|
package org.xwiki.rendering.internal.configuration;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.phase.Initializable;
import org.xwiki.component.phase.InitializationException;
import org.xwiki.rendering.configuration.RenderingConfiguration;
import org.xwiki.rendering.transformation.Transformation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import javax.inject.Inject;
/**
* Basic default implementation to be used when using the XWiki Rendering system standalone.
*
* @version $Id$
* @since 2.0M1
*/
@Component
public class DefaultRenderingConfiguration implements RenderingConfiguration, Initializable
{
/**
* Holds the list of transformations to apply, sorted by priority in {@link #initialize()}.
*/
@Inject
private List<Transformation> transformations = new ArrayList<Transformation>();
/**
* @see #getLinkLabelFormat()
*/
private String linkLabelFormat = "%p";
/**
* @see #getInterWikiDefinitions()
*/
private Properties interWikiDefinitions = new Properties();
/**
* {@inheritDoc}
*
* @see Initializable#initialize()
*/
public void initialize() throws InitializationException
{
// Sort transformations by priority.
Collections.sort(this.transformations);
}
/**
* {@inheritDoc}
*
* @see org.xwiki.rendering.configuration.RenderingConfiguration#getLinkLabelFormat()
*/
public String getLinkLabelFormat()
{
return this.linkLabelFormat;
}
/**
* @param linkLabelFormat the format used to decide how to display links that have no label
*/
public void setLinkLabelFormat(String linkLabelFormat)
{
// This method is useful for those using the XWiki Rendering in standalone mode since it allows the rendering
// to work even without a configuration store.
this.linkLabelFormat = linkLabelFormat;
}
/**
* {@inheritDoc}
*
* @see org.xwiki.rendering.configuration.RenderingConfiguration#getInterWikiDefinitions()
*/
public Properties getInterWikiDefinitions()
{
return this.interWikiDefinitions;
}
/**
* @param interWikiAlias see {@link org.xwiki.rendering.listener.reference.InterWikiResourceReference}
* @param interWikiURL see {@link org.xwiki.rendering.listener.reference.InterWikiResourceReference}
*/
public void addInterWikiDefinition(String interWikiAlias, String interWikiURL)
{
// This method is useful for those using the XWiki Rendering in standalone mode since it allows the rendering
// to work even without a configuration store.
this.interWikiDefinitions.setProperty(interWikiAlias, interWikiURL);
}
/**
* @param transformations the explicit list of transformations to execute (overrides the default list)
*/
public void setTransformations(List<Transformation> transformations)
{
this.transformations = transformations;
}
/**
* {@inheritDoc}
*
* @see org.xwiki.rendering.configuration.RenderingConfiguration#getTransformations()
*/
public List<Transformation> getTransformations()
{
return this.transformations;
}
}
|
package eu.bcvsolutions.idm.core.service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import eu.bcvsolutions.idm.core.model.entity.IdmIdentity;
import eu.bcvsolutions.idm.core.model.entity.IdmIdentityContract;
import eu.bcvsolutions.idm.core.model.entity.IdmIdentityRole;
import eu.bcvsolutions.idm.core.model.entity.IdmTreeNode;
import eu.bcvsolutions.idm.core.model.entity.IdmTreeType;
import eu.bcvsolutions.idm.core.model.repository.IdmIdentityContractRepository;
import eu.bcvsolutions.idm.core.model.repository.IdmIdentityRepository;
import eu.bcvsolutions.idm.core.model.repository.IdmRoleRepository;
import eu.bcvsolutions.idm.core.model.service.IdmIdentityService;
import eu.bcvsolutions.idm.core.model.service.IdmTreeNodeService;
import eu.bcvsolutions.idm.core.model.service.IdmTreeTypeService;
import eu.bcvsolutions.idm.test.api.AbstractIntegrationTest;
/**
* Test for identity service find managers and role.
*
* @author Ondrej Kopr <kopr@xyxy.cz>
*
*/
public class IdentityFindPositionsTest extends AbstractIntegrationTest{
@Autowired
private IdmIdentityRepository identityRepository;
@Autowired
private IdmIdentityService identityService;
@Autowired
private IdmTreeNodeService treeNodeService;
@Autowired
private IdmTreeTypeService treeTypeService;
@Autowired
private IdmIdentityContractRepository identityContractRepository;
@PersistenceContext
private EntityManager entityManager;
@Before
public void init() {
loginAsAdmin("admin");
}
@After
public void deleteIdentity() {
logout();
}
@Test
public void findUser() {
IdmIdentity identity = createAndSaveIdentity("test_identity");
identity = identityRepository.save(identity);
IdmIdentity foundIdentity = this.identityService.get(identity.getId());
assertEquals(identity, foundIdentity);
}
@Test
@Transactional
public void findGuarantee() {
IdmIdentity user = createAndSaveIdentity("test_find_managers_user");
IdmIdentity quarantee1 = createAndSaveIdentity("test_find_managers_manager");
IdmIdentity quarantee2 = createAndSaveIdentity("test_find_managers_manager2");
createIdentityContract(user, quarantee1, null);
createIdentityContract(user, quarantee2, null);
List<IdmIdentity> result = identityService.findAllManagers(user, null);
assertEquals(2, result.size());
String resutlString = identityService.findAllManagersAsString(user.getId());
assertEquals(true, resutlString.contains(quarantee1.getUsername()));
assertEquals(true, resutlString.contains(quarantee2.getUsername()));
}
@Test
public void findManagers() {
IdmIdentity user = createAndSaveIdentity("test_position_01");
IdmIdentity user2 = createAndSaveIdentity("test_position_02");
IdmIdentity user3 = createAndSaveIdentity("test_position_03");
IdmIdentity user4 = createAndSaveIdentity("test_position_04");
IdmTreeType treeTypeFirst = new IdmTreeType();
treeTypeFirst.setCode("TEST_TYPE_CODE_FIRST");
treeTypeFirst.setName("TEST_TYPE_NAME_FIRST");
treeTypeService.save(treeTypeFirst);
IdmTreeType treeTypeSecond = new IdmTreeType();
treeTypeSecond.setCode("TEST_TYPE_CODE_SECOND");
treeTypeSecond.setName("TEST_TYPE_NAME_SECOND");
treeTypeService.save(treeTypeSecond);
// create root for second type
IdmTreeNode nodeRootSec = new IdmTreeNode();
nodeRootSec.setName("TEST_NODE_NAME_ROOT_SEC");
nodeRootSec.setCode("TEST_NODE_CODE_ROOT_SEC");
nodeRootSec.setTreeType(treeTypeSecond);
treeNodeService.save(nodeRootSec);
// create root for first type
IdmTreeNode nodeRoot = new IdmTreeNode();
nodeRoot.setName("TEST_NODE_NAME_ROOT");
nodeRoot.setCode("TEST_NODE_CODE_ROOT");
nodeRoot.setTreeType(treeTypeFirst);
treeNodeService.save(nodeRoot);
// create one for first type
IdmTreeNode nodeOne = new IdmTreeNode();
nodeOne.setName("TEST_NODE_NAME_ONE");
nodeOne.setCode("TEST_NODE_CODE_ONE");
nodeOne.setParent(nodeRoot);
nodeOne.setTreeType(treeTypeFirst);
treeNodeService.save(nodeOne);
// create two for first type
IdmTreeNode nodeTwo = new IdmTreeNode();
nodeTwo.setName("TEST_NODE_NAME_TWO");
nodeTwo.setCode("TEST_NODE_CODE_TWO");
nodeTwo.setParent(nodeOne);
nodeTwo.setTreeType(treeTypeFirst);
treeNodeService.save(nodeTwo);
createIdentityContract(user, null, nodeRoot);
createIdentityContract(user2, null, nodeOne);
createIdentityContract(user3, null, nodeOne);
createIdentityContract(user4, null, nodeTwo);
// createIdentityContract(user, manager3, null);
List<IdmIdentity> managersList = identityService.findAllManagers(user3, treeTypeFirst);
assertEquals(1, managersList.size());
IdmIdentity manager = managersList.get(0);
assertEquals(user.getId(), manager.getId());
managersList = identityService.findAllManagers(user4, treeTypeFirst);
assertEquals(2, managersList.size());
managersList = identityService.findAllManagers(user, treeTypeFirst);
assertEquals(1, managersList.size());
createIdentityContract(user, null, nodeTwo);
managersList = identityService.findAllManagers(user, treeTypeFirst);
assertEquals(2, managersList.size());
List<IdmIdentity> managersListSec = identityService.findAllManagers(user, treeTypeSecond);
// user with superAdminRole
assertEquals(1, managersListSec.size());
}
@Test
public void managerNotFound() {
IdmIdentity user = createAndSaveIdentity("test_2");
List<IdmIdentity> result = identityService.findAllManagers(user, null);
assertEquals(1, result.size());
IdmIdentity admin = result.get(0);
assertNotNull(admin);
}
@Transactional
private void deleteAllUser () {
for (IdmIdentity user : this.identityRepository.findAll()) {
identityRepository.delete(user);
}
}
private IdmIdentityContract createIdentityContract(IdmIdentity user, IdmIdentity quarantee, IdmTreeNode node) {
IdmIdentityContract position = new IdmIdentityContract();
position.setIdentity(user);
position.setGuarantee(quarantee);
position.setWorkingPosition(node);
return identityContractRepository.save(position);
}
private IdmIdentity createAndSaveIdentity(String userName) {
IdmIdentity user = constructTestIdentity();
user.setUsername(userName);
return identityRepository.save(user);
}
private IdmIdentity constructTestIdentity() {
IdmIdentity identity = new IdmIdentity();
identity.setUsername("service_test_user");
identity.setLastName("Service");
return identity;
}
}
|
package org.eclipse.birt.report.designer.internal.ui.util;
import org.eclipse.birt.report.designer.testutil.BaseTestCase;
import org.eclipse.birt.report.model.api.ListHandle;
import org.eclipse.birt.report.model.api.TableHandle;
import org.eclipse.swt.layout.GridLayout;
/**
* Non-UI tests for UIUtil
*/
public class UIUtilTest extends BaseTestCase
{
/*
* Class under test for GridLayout createGridLayoutWithoutMargin()
*/
public void testCreateGridLayoutWithoutMargin( )
{
GridLayout layout = UIUtil.createGridLayoutWithoutMargin( );
assertEquals( false, layout.makeColumnsEqualWidth );
assertEquals( 1, layout.numColumns );
assertEquals( 0, layout.marginHeight );
assertEquals( 0, layout.marginWidth );
}
/*
* Class under test for GridLayout createGridLayoutWithoutMargin(int,
* boolean)
*/
public void testCreateGridLayoutWithoutMarginintboolean( )
{
GridLayout layout = UIUtil.createGridLayoutWithoutMargin( 5, false );
assertEquals( false, layout.makeColumnsEqualWidth );
assertEquals( 5, layout.numColumns );
assertEquals( 0, layout.marginHeight );
assertEquals( 0, layout.marginWidth );
layout = UIUtil.createGridLayoutWithoutMargin( 3, true );
assertEquals( true, layout.makeColumnsEqualWidth );
assertEquals( 3, layout.numColumns );
assertEquals( 0, layout.marginHeight );
assertEquals( 0, layout.marginWidth );
}
public void testConvertToGUIString( )
{
assertEquals( "testString", UIUtil.convertToGUIString( "testString" ) );
assertEquals( " testString ",
UIUtil.convertToGUIString( " testString " ) );
assertEquals( "", UIUtil.convertToGUIString( "" ) );
assertEquals( "", UIUtil.convertToGUIString( null ) );
}
public void testConvertToModelString( )
{
assertEquals( " testString ",
UIUtil.convertToModelString( " testString ", false ) );
assertEquals( "testString",
UIUtil.convertToModelString( " testString ", true ) );
assertEquals( null, UIUtil.convertToModelString( "", false ) );
assertEquals( null, UIUtil.convertToModelString( null, true ) );
}
// public void testCreateGroup( )
// TableHandle table = getReportDesignHandle( ).getElementFactory( )
// .newTableItem( null, 3 );
// assertTrue( UIUtil.createGroup( table ) );
// assertTrue( UIUtil.createGroup( table ) );
// assertTrue( UIUtil.createGroup( table, 2 ) );
// assertEquals( 3, table.getGroups( ).getCount( ) );
// ListHandle list = getReportDesignHandle( ).getElementFactory( )
// .newList( null );
// assertTrue( UIUtil.createGroup( list ) );
// assertTrue( UIUtil.createGroup( list ) );
// assertTrue( UIUtil.createGroup( list, 1 ) );
// assertEquals( 3, list.getGroups( ).getCount( ) );
}
|
package org.eclipse.birt.report.designer.ui.wizards;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.ReportPlugin;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExecutableExtension;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
/**
* BIRT Project Wizard.
*
*/
public class NewLibraryWizard extends Wizard implements
INewWizard,
IExecutableExtension
{
// private static final String OPENING_FILE_FOR_EDITING =
// Messages.getString( "NewLibraryWizard.text.OpenFileForEditing" );
// //$NON-NLS-1$
// private static final String CREATING = Messages.getString(
// "NewLibraryWizard.text.Creating" ); //$NON-NLS-1$
private static final String NEW_REPORT_FILE_NAME_PREFIX = Messages.getString( "NewLibraryWizard.displayName.NewReportFileNamePrefix" ); //$NON-NLS-1$
private static final String NEW_REPORT_FILE_EXTENSION = Messages.getString( "NewLibraryWizard.displayName.NewReportFileExtension" ); //$NON-NLS-1$
private static final String NEW_REPORT_FILE_NAME = NEW_REPORT_FILE_NAME_PREFIX
+ NEW_REPORT_FILE_EXTENSION;
private static final String CREATE_A_NEW_REPORT = Messages.getString( "NewLibraryWizard.text.CreateReport" ); //$NON-NLS-1$
private static final String REPORT = Messages.getString( "NewLibraryWizard.title.Report" ); //$NON-NLS-1$
// private static final String WIZARDPAGE = Messages.getString(
// "NewLibraryWizard.title.WizardPage" ); //$NON-NLS-1$
private static final String NEW = Messages.getString( "NewLibraryWizard.title.New" ); //$NON-NLS-1$
// private static final String CHOOSE_FROM_TEMPLATE = Messages.getString(
// "NewReportWizard.title.Choose" ); //$NON-NLS-1$
/** Holds selected project resource for run method access */
private IStructuredSelection selection;
private INewLibraryCreationPage newLibraryFileWizardPage;
private int UNIQUE_COUNTER = 0;
// private WizardChoicePage choicePage;
// private WizardCustomTemplatePage customTemplatePage;
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.wizard.Wizard#performFinish()
*/
public boolean performFinish( )
{
return newLibraryFileWizardPage.performFinish( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench,
* org.eclipse.jface.viewers.IStructuredSelection)
*/
public void init( IWorkbench workbench, IStructuredSelection selection )
{
// check existing open project
// IWorkspaceRoot root = ResourcesPlugin.getWorkspace( ).getRoot( );
// IProject projects[] = root.getProjects( );
// boolean foundOpenProject = false;
// for ( int i = 0; i < projects.length; i++ )
// if ( projects[i].isOpen( ) )
// foundOpenProject = true;
// break;
// if ( !foundOpenProject )
// MessageDialog.openError( getShell( ),
// Messages.getString( "NewReportWizard.title.Error" ), //$NON-NLS-1$
// Messages.getString( "NewReportWizard.error.NoProject" ) );
// //$NON-NLS-1$
// // abort wizard. There is no clean way to do it.
// /**
// * Remove the exception here 'cause It's safe since the wizard won't
// * create any file without an open project.
// */
// // throw new RuntimeException( );
this.selection = selection;
setWindowTitle( NEW );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.wizard.IWizard#getDefaultPageImage()
*/
public Image getDefaultPageImage( )
{
return ReportPlugin.getImage( "/icons/wizban/create_report_wizard.gif" ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.wizard.IWizard#addPages()
*/
public void addPages( )
{
Object adapter = Platform.getAdapterManager( ).getAdapter( this,
INewLibraryCreationPage.class );
newLibraryFileWizardPage = (INewLibraryCreationPage) adapter;
addPage( newLibraryFileWizardPage );
// set titles
newLibraryFileWizardPage.setTitle( REPORT );
newLibraryFileWizardPage.setDescription( CREATE_A_NEW_REPORT );
resetUniqueCount( );
newLibraryFileWizardPage.setFileName( getUniqueReportName( ) );
newLibraryFileWizardPage.setContainerFullPath( getDefaultContainerPath( ) );
}
private void resetUniqueCount( )
{
UNIQUE_COUNTER = 0;
}
private IPath getDefaultContainerPath( )
{
IWorkbenchWindow benchWindow = PlatformUI.getWorkbench( )
.getActiveWorkbenchWindow( );
IWorkbenchPart part = benchWindow.getPartService( ).getActivePart( );
Object selection = null;
if ( part instanceof IEditorPart )
{
selection = ( (IEditorPart) part ).getEditorInput( );
}
else
{
ISelection sel = benchWindow.getSelectionService( ).getSelection( );
if ( ( sel != null ) && ( sel instanceof IStructuredSelection ) )
{
selection = ( (IStructuredSelection) sel ).getFirstElement( );
}
}
IContainer ct = getDefaultContainer( selection );
if ( ct == null )
{
IEditorPart editor = UIUtil.getActiveEditor( true );
if ( editor != null )
{
ct = getDefaultContainer( editor.getEditorInput( ) );
}
}
if ( ct != null )
{
return ct.getFullPath( );
}
return Platform.getLocation( );
}
private IContainer getDefaultContainer( Object selection )
{
IContainer ct = null;
if ( selection instanceof IAdaptable )
{
IResource resource = (IResource) ( (IAdaptable) selection ).getAdapter( IResource.class );
if ( resource instanceof IContainer && resource.isAccessible( ) )
{
ct = (IContainer) resource;
}
else if ( resource != null
&& resource.getParent( ) != null
&& resource.getParent( ).isAccessible( ) )
{
ct = resource.getParent( );
}
}
return ct;
}
private String getUniqueReportName( )
{
IProject[] pjs = ResourcesPlugin.getWorkspace( )
.getRoot( )
.getProjects( );
if ( pjs.length != 0 )
{
resetUniqueCount( );
boolean goon = true;
while ( goon )
{
goon = false;
for ( int i = 0; i < pjs.length; i++ )
{
if ( pjs[i].isAccessible( ) )
{
if ( !validDuplicate( NEW_REPORT_FILE_NAME_PREFIX,
NEW_REPORT_FILE_EXTENSION,
UNIQUE_COUNTER,
pjs[i] ) )
{
UNIQUE_COUNTER++;
goon = true;
break;
}
}
}
}
if ( UNIQUE_COUNTER == 0 )
{
return NEW_REPORT_FILE_NAME;
}
return NEW_REPORT_FILE_NAME_PREFIX + "_" //$NON-NLS-1$
+ UNIQUE_COUNTER + NEW_REPORT_FILE_EXTENSION; //$NON-NLS-1$
}
else
{
String extension = NEW_REPORT_FILE_EXTENSION;
String path = Platform.getLocation( ).toOSString();
String name = NEW_REPORT_FILE_NAME_PREFIX + NEW_REPORT_FILE_EXTENSION;
int count = 0;
File file;
file = new File( path, name );
while ( file.exists( ) )
{
count++;
name = NEW_REPORT_FILE_NAME_PREFIX + "_" + count + NEW_REPORT_FILE_EXTENSION; //$NON-NLS-1$
file = null;
file = new File( path, name );
}
file = null;
return name;
}
}
private static final List tmpList = new ArrayList( );
private IConfigurationElement configElement;
private boolean validDuplicate( String prefix, String ext, int count,
IResource res )
{
if ( res != null && res.isAccessible( ) )
{
final String name;
if ( count == 0 )
{
name = prefix + ext;
}
else
{
name = prefix + "_" + count + ext; //$NON-NLS-1$
}
try
{
tmpList.clear( );
res.accept( new IResourceVisitor( ) {
public boolean visit( IResource resource )
throws CoreException
{
if ( resource.getType( ) == IResource.FILE
&& name.equals( ( (IFile) resource ).getName( ) ) )
{
tmpList.add( Boolean.TRUE );
}
return true;
}
},
IResource.DEPTH_INFINITE,
true );
if ( tmpList.size( ) > 0 )
{
return false;
}
}
catch ( CoreException e )
{
ExceptionHandler.handle( e );
}
}
return true;
}
/**
* Creates a folder resource handle for the folder with the given workspace
* path. This method does not create the folder resource; this is the
* responsibility of <code>createFolder</code>.
*
* @param folderPath
* the path of the folder resource to create a handle for
* @return the new folder resource handle
*/
protected IFolder createFolderHandle( IPath folderPath )
{
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace( )
.getRoot( );
return workspaceRoot.getFolder( folderPath );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.IExecutableExtension#setInitializationData(org.eclipse.core.runtime.IConfigurationElement,
* java.lang.String, java.lang.Object)
*/
public void setInitializationData( IConfigurationElement config,
String propertyName, Object data ) throws CoreException
{
this.configElement = config;
}
public IConfigurationElement getConfigElement( )
{
return configElement;
}
public IStructuredSelection getSelection( )
{
return selection;
}
}
|
package org.springframework.roo.addon.web.mvc.controller;
import java.lang.reflect.Modifier;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.SortedSet;
import java.util.TreeSet;
import org.springframework.roo.addon.beaninfo.BeanInfoMetadata;
import org.springframework.roo.addon.entity.EntityMetadata;
import org.springframework.roo.addon.finder.FinderMetadata;
import org.springframework.roo.classpath.PhysicalTypeCategory;
import org.springframework.roo.classpath.PhysicalTypeDetails;
import org.springframework.roo.classpath.PhysicalTypeIdentifier;
import org.springframework.roo.classpath.PhysicalTypeIdentifierNamingUtils;
import org.springframework.roo.classpath.PhysicalTypeMetadata;
import org.springframework.roo.classpath.details.DefaultMethodMetadata;
import org.springframework.roo.classpath.details.FieldMetadata;
import org.springframework.roo.classpath.details.MethodMetadata;
import org.springframework.roo.classpath.details.annotations.AnnotatedJavaType;
import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue;
import org.springframework.roo.classpath.details.annotations.AnnotationMetadata;
import org.springframework.roo.classpath.details.annotations.DefaultAnnotationMetadata;
import org.springframework.roo.classpath.details.annotations.EnumAttributeValue;
import org.springframework.roo.classpath.details.annotations.StringAttributeValue;
import org.springframework.roo.classpath.itd.AbstractItdTypeDetailsProvidingMetadataItem;
import org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder;
import org.springframework.roo.classpath.itd.ItdSourceFileComposer;
import org.springframework.roo.metadata.MetadataIdentificationUtils;
import org.springframework.roo.metadata.MetadataService;
import org.springframework.roo.model.EnumDetails;
import org.springframework.roo.model.JavaSymbolName;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.project.Path;
import org.springframework.roo.support.style.ToStringCreator;
import org.springframework.roo.support.util.Assert;
/**
* Metadata for {@link RooWebScaffold}.
*
*
* @author Stefan Schmidt
* @since 1.0
*
*/
public class WebScaffoldMetadata extends AbstractItdTypeDetailsProvidingMetadataItem {
private static final String PROVIDES_TYPE_STRING = WebScaffoldMetadata.class.getName();
private static final String PROVIDES_TYPE = MetadataIdentificationUtils.create(PROVIDES_TYPE_STRING);
private WebScaffoldAnnotationValues annotationValues;
private BeanInfoMetadata beanInfoMetadata;
private EntityMetadata entityMetadata;
private MetadataService metadataService;
private SortedSet<JavaType> specialDomainTypes;
private String entityName;
private boolean typeExposesDateField = false;
public WebScaffoldMetadata(String identifier, JavaType aspectName, PhysicalTypeMetadata governorPhysicalTypeMetadata, MetadataService metadataService, WebScaffoldAnnotationValues annotationValues, BeanInfoMetadata beanInfoMetadata, EntityMetadata entityMetadata, FinderMetadata finderMetadata, ControllerOperations controllerOperations) {
super(identifier, aspectName, governorPhysicalTypeMetadata);
Assert.isTrue(isValid(identifier), "Metadata identification string '" + identifier + "' does not appear to be a valid");
Assert.notNull(annotationValues, "Annotation values required");
Assert.notNull(metadataService, "Metadata service required");
Assert.notNull(beanInfoMetadata, "Bean info metadata required");
Assert.notNull(entityMetadata, "Entity metadata required");
Assert.notNull(entityMetadata, "Finder metadata required");
Assert.notNull(controllerOperations, "Controller operations required");
if (!isValid()) {
return;
}
this.annotationValues = annotationValues;
this.beanInfoMetadata = beanInfoMetadata;
this.entityMetadata = entityMetadata;
this.entityName = beanInfoMetadata.getJavaBean().getSimpleTypeName().toLowerCase();
this.metadataService = metadataService;
//now figure out if we need to create any custom property editors
SortedSet<JavaType> editorsToBeCreated = getEditorToBeCreated();
if (editorsToBeCreated.size() > 0) {
controllerOperations.createPropertyEditors(editorsToBeCreated);
}
specialDomainTypes = getSpecialDomainTypes();
if (annotationValues.create) {
builder.addMethod(getCreateMethod());
builder.addMethod(getCreateFormMethod());
}
if (annotationValues.show) {
builder.addMethod(getShowMethod());
}
if (annotationValues.list) {
builder.addMethod(getListMethod());
}
if (annotationValues.update) {
builder.addMethod(getUpdateMethod());
builder.addMethod(getUpdateFormMethod());
}
if (annotationValues.delete) {
builder.addMethod(getDeleteMethod());
}
if (typeExposesDateField) {
builder.addMethod(getInitBinderMethod());
}
if (annotationValues.exposeFinders) {
for (String finderName : entityMetadata.getDynamicFinders()) {
builder.addMethod(getFinderFormMethod(finderMetadata.getDynamicFinderMethod(finderName)));
builder.addMethod(getFinderMethod(finderMetadata.getDynamicFinderMethod(finderName)));
}
}
itdTypeDetails = builder.build();
new ItdSourceFileComposer(itdTypeDetails);
}
public String getIdentifierForBeanInfoMetadata() {
return beanInfoMetadata.getId();
}
public String getIdentifierForEntityMetadata() {
return entityMetadata.getId();
}
public WebScaffoldAnnotationValues getAnnotationValues() {
return annotationValues;
}
private MethodMetadata getInitBinderMethod() {
JavaSymbolName methodName = new JavaSymbolName("initBinder");
for (MethodMetadata method : governorTypeDetails.getDeclaredMethods()) {
for (AnnotationMetadata annotation : method.getAnnotations()) {
if(annotation.getAnnotationType().equals(new JavaType("org.springframework.web.bind.annotation.InitBinder"))) {
//do nothing if the governor already has a custom init binder
return method;
}
}
}
List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>();
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.web.bind.WebDataBinder"), typeAnnotations));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("binder"));
List<AnnotationAttributeValue<?>> initBinderAttributes = new ArrayList<AnnotationAttributeValue<?>>();
AnnotationMetadata initBinder = new DefaultAnnotationMetadata(new JavaType("org.springframework.web.bind.annotation.InitBinder"), initBinderAttributes);
List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>();
annotations.add(initBinder);
SimpleDateFormat dateFormatLocalized = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.getDefault());
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("binder.registerCustomEditor(java.util.Date.class, new org.springframework.beans.propertyeditors.CustomDateEditor(new java.text.SimpleDateFormat(\"" + dateFormatLocalized.toPattern() + "\"), false));");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, JavaType.VOID_PRIMITIVE, paramTypes, paramNames, annotations, bodyBuilder.getOutput());
}
private MethodMetadata getDeleteMethod() {
JavaSymbolName methodName = new JavaSymbolName("delete");
MethodMetadata method = methodExists(methodName);
if (method != null) return method;
List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>();
List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>();
attributes.add(new StringAttributeValue(new JavaSymbolName("value"), "id"));
typeAnnotations.add(new DefaultAnnotationMetadata(new JavaType("org.springframework.web.bind.annotation.PathVariable"), attributes));
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(entityMetadata.getIdentifierField().getFieldType(), typeAnnotations));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("id"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/" + entityName + "/{id}"));
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("DELETE"))));
AnnotationMetadata requestMapping = new DefaultAnnotationMetadata(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>();
annotations.add(requestMapping);
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("if (id == null) throw new IllegalArgumentException(\"An Identifier is required\");");
bodyBuilder.appendFormalLine(beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + "." + entityMetadata.getFindMethod().getMethodName() + "(id)." + entityMetadata.getRemoveMethod().getMethodName() + "();");
bodyBuilder.appendFormalLine("return \"redirect:/" + entityName + "\";");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, new JavaType(String.class.getName()), paramTypes, paramNames, annotations, bodyBuilder.getOutput());
}
private MethodMetadata getListMethod() {
JavaSymbolName methodName = new JavaSymbolName("list");
MethodMetadata method = methodExists(methodName);
if (method != null) return method;
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.ModelMap"), null));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("modelMap"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/" + entityName));
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET"))));
AnnotationMetadata requestMapping = new DefaultAnnotationMetadata(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>();
annotations.add(requestMapping);
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("modelMap.addAttribute(\"" + entityMetadata.getPlural().toLowerCase() + "\", " + beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + "." + entityMetadata.getFindAllMethod().getMethodName() + "());");
bodyBuilder.appendFormalLine("return \"" + entityName + "/list\";");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, new JavaType(String.class.getName()), paramTypes, paramNames, annotations, bodyBuilder.getOutput());
}
private MethodMetadata getShowMethod() {
JavaSymbolName methodName = new JavaSymbolName("show");
MethodMetadata method = methodExists(methodName);
if (method != null) return method;
List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>();
List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>();
attributes.add(new StringAttributeValue(new JavaSymbolName("value"), "id"));
typeAnnotations.add(new DefaultAnnotationMetadata(new JavaType("org.springframework.web.bind.annotation.PathVariable"), attributes));
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(new JavaType("Long"), typeAnnotations));
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.ModelMap"), null));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("id"));
paramNames.add(new JavaSymbolName("modelMap"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/" + entityName + "/{id}"));
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET"))));
AnnotationMetadata requestMapping = new DefaultAnnotationMetadata(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>();
annotations.add(requestMapping);
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("if (id == null) throw new IllegalArgumentException(\"An Identifier is required\");");
bodyBuilder.appendFormalLine("modelMap.addAttribute(\"" + entityName + "\", " + beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + "." + entityMetadata.getFindMethod().getMethodName() + "(id));");
bodyBuilder.appendFormalLine("return \"" + entityName + "/show\";");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, new JavaType(String.class.getName()), paramTypes, paramNames, annotations, bodyBuilder.getOutput());
}
private MethodMetadata getCreateMethod() {
JavaSymbolName methodName = new JavaSymbolName("create");
MethodMetadata method = methodExists(methodName);
if (method != null) return method;
List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>();
List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>();
attributes.add(new StringAttributeValue(new JavaSymbolName("value"), entityName));
typeAnnotations.add(new DefaultAnnotationMetadata(new JavaType("org.springframework.web.bind.annotation.ModelAttribute"), attributes));
List<AnnotationMetadata> noAnnotations = new ArrayList<AnnotationMetadata>();
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(beanInfoMetadata.getJavaBean(), typeAnnotations));
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.validation.BindingResult"), noAnnotations));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName(entityName));
paramNames.add(new JavaSymbolName("result"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/" + entityName));
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("POST"))));
AnnotationMetadata requestMapping = new DefaultAnnotationMetadata(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>();
annotations.add(requestMapping);
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("if (" + entityName + " == null) throw new IllegalArgumentException(\"A " + entityName+ " is required\");");
bodyBuilder.appendFormalLine("for(javax.validation.ConstraintViolation<" + beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + "> constraint : javax.validation.Validation.buildDefaultValidatorFactory().getValidator().validate(" + entityName + ")) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("result.rejectValue(constraint.getPropertyPath(), null, constraint.getMessage());");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("if (result.hasErrors()) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("return \"" + entityName + "/create\";");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine(entityName + "." + entityMetadata.getPersistMethod().getMethodName() + "();");
bodyBuilder.appendFormalLine("return \"redirect:/" + entityName + "/\" + " + entityName + "." + entityMetadata.getIdentifierAccessor().getMethodName() + "();");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, new JavaType(String.class.getName()), paramTypes, paramNames, annotations, bodyBuilder.getOutput());
}
private MethodMetadata getCreateFormMethod() {
JavaSymbolName methodName = new JavaSymbolName("createForm");
MethodMetadata method = methodExists(methodName);
if (method != null) return method;
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.ModelMap"), null));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("modelMap"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/" + entityName + "/form"));
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET"))));
AnnotationMetadata requestMapping = new DefaultAnnotationMetadata(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>();
annotations.add(requestMapping);
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("modelMap.addAttribute(\"" + entityName + "\", new " + beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + "());");
if(specialDomainTypes.size() > 0) {
for (JavaType type: specialDomainTypes) {
EntityMetadata typeEntityMetadata = (EntityMetadata) metadataService.get(entityMetadata.createIdentifier(type, Path.SRC_MAIN_JAVA));
if (typeEntityMetadata != null) {
bodyBuilder.appendFormalLine("modelMap.addAttribute(\"" + typeEntityMetadata.getPlural().toLowerCase() + "\", " + type.getFullyQualifiedTypeName() + "." + typeEntityMetadata.getFindAllMethod().getMethodName() + "());");
} else if(isEnumType(type)){
bodyBuilder.appendFormalLine("modelMap.addAttribute(\"_" + type.getSimpleTypeName().toLowerCase() + "\", " + type.getFullyQualifiedTypeName() + ".class.getEnumConstants());");
}
}
}
bodyBuilder.appendFormalLine("return \"" + entityName + "/create\";");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, new JavaType(String.class.getName()), paramTypes, paramNames, annotations, bodyBuilder.getOutput());
}
private MethodMetadata getUpdateMethod() {
JavaSymbolName methodName = new JavaSymbolName("update");
MethodMetadata method = methodExists(methodName);
if (method != null) return method;
List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>();
List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>();
attributes.add(new StringAttributeValue(new JavaSymbolName("value"), entityName));
typeAnnotations.add(new DefaultAnnotationMetadata(new JavaType("org.springframework.web.bind.annotation.ModelAttribute"), attributes));
List<AnnotationMetadata> noAnnotations = new ArrayList<AnnotationMetadata>();
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(beanInfoMetadata.getJavaBean(), typeAnnotations));
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.validation.BindingResult"), noAnnotations));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName(entityName));
paramNames.add(new JavaSymbolName("result"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("PUT"))));
AnnotationMetadata requestMapping = new DefaultAnnotationMetadata(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>();
annotations.add(requestMapping);
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("if (" + entityName + " == null) throw new IllegalArgumentException(\"A " + entityName+ " is required\");");
bodyBuilder.appendFormalLine("for(javax.validation.ConstraintViolation<" + beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + "> constraint : javax.validation.Validation.buildDefaultValidatorFactory().getValidator().validate(" + entityName + ")) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("result.rejectValue(constraint.getPropertyPath(), null, constraint.getMessage());");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("if (result.hasErrors()) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("return \"" + entityName + "/update\";");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine(entityName + "." + entityMetadata.getMergeMethod().getMethodName() + "();");
bodyBuilder.appendFormalLine("return \"redirect:/" + entityName + "/\" + " + entityName + "." + entityMetadata.getIdentifierAccessor().getMethodName() + "();");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, new JavaType(String.class.getName()), paramTypes, paramNames, annotations, bodyBuilder.getOutput());
}
private MethodMetadata getUpdateFormMethod() {
JavaSymbolName methodName = new JavaSymbolName("updateForm");
MethodMetadata updateFormMethod = methodExists(methodName);
if (updateFormMethod != null) return updateFormMethod;
List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>();
List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>();
attributes.add(new StringAttributeValue(new JavaSymbolName("value"), "id"));
typeAnnotations.add(new DefaultAnnotationMetadata(new JavaType("org.springframework.web.bind.annotation.PathVariable"), attributes));
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(entityMetadata.getIdentifierField().getFieldType(), typeAnnotations));
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.ModelMap"), null));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("id"));
paramNames.add(new JavaSymbolName("modelMap"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/" + entityName + "/{id}/form"));
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET"))));
AnnotationMetadata requestMapping = new DefaultAnnotationMetadata(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>();
annotations.add(requestMapping);
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("if (id == null) throw new IllegalArgumentException(\"An Identifier is required\");");
bodyBuilder.appendFormalLine("modelMap.addAttribute(\"" + entityName + "\", " + beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + "." + entityMetadata.getFindMethod().getMethodName() + "(id));");
if(specialDomainTypes.size() > 0) {
for (JavaType type: specialDomainTypes) {
EntityMetadata typeEntityMetadata = (EntityMetadata) metadataService.get(entityMetadata.createIdentifier(type, Path.SRC_MAIN_JAVA));
if (typeEntityMetadata != null) {
bodyBuilder.appendFormalLine("modelMap.addAttribute(\"" + typeEntityMetadata.getPlural().toLowerCase() + "\", " + type.getFullyQualifiedTypeName() + "." + typeEntityMetadata.getFindAllMethod().getMethodName() + "());");
} else if (isEnumType(type)){
bodyBuilder.appendFormalLine("modelMap.addAttribute(\"_" + type.getSimpleTypeName().toLowerCase() + "\", " + type.getFullyQualifiedTypeName() + ".class.getEnumConstants());");
}
}
}
bodyBuilder.appendFormalLine("return \"" + entityName + "/update\";");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, methodName, new JavaType(String.class.getName()), paramTypes, paramNames, annotations, bodyBuilder.getOutput());
}
private MethodMetadata getFinderFormMethod(MethodMetadata methodMetadata) {
Assert.notNull(methodMetadata, "Method metadata required for finder");
JavaSymbolName finderFormMethodName = new JavaSymbolName(methodMetadata.getMethodName().getSymbolName() + "Form");
MethodMetadata finderFormMethod = methodExists(finderFormMethodName);
if (finderFormMethod != null) return finderFormMethod;
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
List<JavaType> types = AnnotatedJavaType.convertFromAnnotatedJavaTypes(methodMetadata.getParameterTypes());
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
boolean needModelMap = false;
for (JavaType javaType : types) {
if (isSpecialType(javaType)) {
EntityMetadata typeEntityMetadata = (EntityMetadata) metadataService.get(entityMetadata.createIdentifier(javaType, Path.SRC_MAIN_JAVA));
if (typeEntityMetadata != null) {
bodyBuilder.appendFormalLine("modelMap.addAttribute(\"" + typeEntityMetadata.getPlural().toLowerCase() + "\", " + javaType.getFullyQualifiedTypeName() + "." + typeEntityMetadata.getFindAllMethod().getMethodName() + "());");
}
needModelMap = true;
}
}
if (needModelMap) {
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.ModelMap"), null));
paramNames.add(new JavaSymbolName("modelMap"));
}
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "find/" + methodMetadata.getMethodName().getSymbolName().replaceFirst("find" + entityMetadata.getPlural(), "") + "/form"));
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET"))));
AnnotationMetadata requestMapping = new DefaultAnnotationMetadata(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>();
annotations.add(requestMapping);
bodyBuilder.appendFormalLine("return \"" + entityName + "/" + methodMetadata.getMethodName().getSymbolName() + "\";");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, finderFormMethodName, new JavaType(String.class.getName()), paramTypes, paramNames, annotations, bodyBuilder.getOutput());
}
private MethodMetadata getFinderMethod(MethodMetadata methodMetadata) {
Assert.notNull(methodMetadata, "Method metadata required for finder");
JavaSymbolName finderMethodName = new JavaSymbolName(methodMetadata.getMethodName().getSymbolName());
MethodMetadata finderMethod = methodExists(finderMethodName);
if (finderMethod != null) return finderMethod;
List<AnnotatedJavaType> annotatedParamTypes = new ArrayList<AnnotatedJavaType>();
List<JavaSymbolName> paramNames = methodMetadata.getParameterNames();
List<JavaType> paramTypes = AnnotatedJavaType.convertFromAnnotatedJavaTypes(methodMetadata.getParameterTypes());
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
StringBuilder methodParams = new StringBuilder();
for (int i = 0; i < paramTypes.size(); i++) {
List<AnnotationMetadata> pathVariable = new ArrayList<AnnotationMetadata>();
List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>();
attributes.add(new StringAttributeValue(new JavaSymbolName("value"), paramNames.get(i).getSymbolName().toLowerCase()));
pathVariable.add(new DefaultAnnotationMetadata(new JavaType("org.springframework.web.bind.annotation.RequestParam"), attributes));
annotatedParamTypes.add(new AnnotatedJavaType(paramTypes.get(i), pathVariable));
bodyBuilder.appendFormalLine("if(" + paramNames.get(i).getSymbolName() + " == null" + (paramTypes.get(i).equals(new JavaType(String.class.getName())) ? " || " + paramNames.get(i).getSymbolName() + ".length() == 0" : "") + ") throw new IllegalArgumentException(\"A " + paramNames.get(i).getSymbolNameCapitalisedFirstLetter() + " is required.\");");
methodParams.append(paramNames.get(i) + ", ");
}
if(methodParams.length() > 0) {
methodParams.delete(methodParams.length() - 2, methodParams.length());
}
annotatedParamTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.ModelMap"), new ArrayList<AnnotationMetadata>()));
List<JavaSymbolName> newParamNames = new ArrayList<JavaSymbolName>();
newParamNames.addAll(paramNames);
newParamNames.add(new JavaSymbolName("modelMap"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "find/" + methodMetadata.getMethodName().getSymbolName().replaceFirst("find" + entityMetadata.getPlural(), "")));
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET"))));
AnnotationMetadata requestMapping = new DefaultAnnotationMetadata(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>();
annotations.add(requestMapping);
bodyBuilder.appendFormalLine("modelMap.addAttribute(\"" + entityMetadata.getPlural().toLowerCase() + "\", " + beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + "." + methodMetadata.getMethodName().getSymbolName() + "(" + methodParams.toString() + ").getResultList());");
bodyBuilder.appendFormalLine("return \"" + entityName + "/list\";");
return new DefaultMethodMetadata(getId(), Modifier.PUBLIC, finderMethodName, new JavaType(String.class.getName()), annotatedParamTypes, newParamNames, annotations, bodyBuilder.getOutput());
}
private MethodMetadata methodExists(JavaSymbolName methodName) {
// We have no access to method parameter information, so we scan by name alone and treat any match as authoritative
// We do not scan the superclass, as the caller is expected to know we'll only scan the current class
for (MethodMetadata method : governorTypeDetails.getDeclaredMethods()) {
if (method.getMethodName().equals(methodName)) {
// Found a method of the expected name; we won't check method parameters though
return method;
}
}
return null;
}
private SortedSet<JavaType> getEditorToBeCreated() {
SortedSet<JavaType> editorTypes = new TreeSet<JavaType>();
for (MethodMetadata accessor : beanInfoMetadata.getPublicAccessors(false)) {
//not interested in identifiers and version fields
if (accessor.equals(entityMetadata.getIdentifierAccessor()) || accessor.equals(entityMetadata.getVersionAccessor())) {
continue;
}
//not interested in fields that are not exposed via a mutator
FieldMetadata fieldMetadata = beanInfoMetadata.getFieldForPropertyName(beanInfoMetadata.getPropertyNameForJavaBeanMethod(accessor));
if(fieldMetadata == null || !hasMutator(fieldMetadata)) {
continue;
}
JavaType type = accessor.getReturnType();
if(type.isCommonCollectionType()) {
for (JavaType genericType : type.getParameters()) {
if(isTypeElegibleForEditorCreation(genericType)) {
editorTypes.add(genericType);
} else if (genericType.equals(new JavaType(Date.class.getName()))) {
typeExposesDateField = true;
}
}
} else {
if(isTypeElegibleForEditorCreation(type)) {
editorTypes.add(type);
} else if (type.equals(new JavaType(Date.class.getName()))) {
typeExposesDateField = true;
}
}
}
return editorTypes;
}
private SortedSet<JavaType> getSpecialDomainTypes() {
SortedSet<JavaType> editorTypes = new TreeSet<JavaType>();
for (MethodMetadata accessor : beanInfoMetadata.getPublicAccessors(false)) {
//not interested in identifiers and version fields
if (accessor.equals(entityMetadata.getIdentifierAccessor()) || accessor.equals(entityMetadata.getVersionAccessor())) {
continue;
}
//not interested in fields that are not exposed via a mutator
FieldMetadata fieldMetadata = beanInfoMetadata.getFieldForPropertyName(beanInfoMetadata.getPropertyNameForJavaBeanMethod(accessor));
if(fieldMetadata == null || !hasMutator(fieldMetadata)) {
continue;
}
JavaType type = accessor.getReturnType();
if(type.isCommonCollectionType()) {
for (JavaType genericType : type.getParameters()) {
if(isSpecialType(genericType)) {
editorTypes.add(genericType);
} else if (genericType.equals(new JavaType(Date.class.getName()))) {
typeExposesDateField = true;
}
}
} else {
if(isSpecialType(type)) {
editorTypes.add(type);
} else if (type.equals(new JavaType(Date.class.getName()))) {
typeExposesDateField = true;
}
}
}
return editorTypes;
}
private boolean isEnumType(JavaType type) {
PhysicalTypeMetadata physicalTypeMetadata = (PhysicalTypeMetadata) metadataService.get(PhysicalTypeIdentifierNamingUtils.createIdentifier(PhysicalTypeIdentifier.class.getName(), type, Path.SRC_MAIN_JAVA));
if (physicalTypeMetadata != null) {
PhysicalTypeDetails details = physicalTypeMetadata.getPhysicalTypeDetails();
if (details != null) {
if (details.getPhysicalTypeCategory().equals(PhysicalTypeCategory.ENUMERATION)) {
return true;
}
}
}
return false;
}
private boolean hasMutator(FieldMetadata fieldMetadata) {
Assert.notNull(fieldMetadata, "Field metadata required");
for (MethodMetadata mutator : beanInfoMetadata.getPublicMutators()) {
if (fieldMetadata.equals(beanInfoMetadata.getFieldForPropertyName(beanInfoMetadata.getPropertyNameForJavaBeanMethod(mutator)))) return true;
}
return false;
}
private boolean isTypeElegibleForEditorCreation(JavaType javaType) {
String editorPhysicalTypeIdentifier = PhysicalTypeIdentifier.createIdentifier(new JavaType(javaType.getFullyQualifiedTypeName() + "Editor"), Path.SRC_MAIN_JAVA);
//we are only interested if the type is part of our application and if no editor exists for it already
if (isSpecialType(javaType) && metadataService.get(editorPhysicalTypeIdentifier) == null) {
return true;
}
return false;
}
private boolean isSpecialType(JavaType javaType) {
String physicalTypeIdentifier = PhysicalTypeIdentifier.createIdentifier(javaType, Path.SRC_MAIN_JAVA);
//we are only interested if the type is part of our application and if no editor exists for it already
if (metadataService.get(physicalTypeIdentifier) != null) {
return true;
}
return false;
}
public String toString() {
ToStringCreator tsc = new ToStringCreator(this);
tsc.append("identifier", getId());
tsc.append("valid", valid);
tsc.append("aspectName", aspectName);
tsc.append("destinationType", destination);
tsc.append("governor", governorPhysicalTypeMetadata.getId());
tsc.append("itdTypeDetails", itdTypeDetails);
return tsc.toString();
}
public static final String getMetadataIdentiferType() {
return PROVIDES_TYPE;
}
public static final String createIdentifier(JavaType javaType, Path path) {
return PhysicalTypeIdentifierNamingUtils.createIdentifier(PROVIDES_TYPE_STRING, javaType, path);
}
public static final JavaType getJavaType(String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.getJavaType(PROVIDES_TYPE_STRING, metadataIdentificationString);
}
public static final Path getPath(String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING, metadataIdentificationString);
}
public static boolean isValid(String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.isValid(PROVIDES_TYPE_STRING, metadataIdentificationString);
}
}
|
package org.springframework.roo.addon.web.mvc.controller;
import java.beans.Introspector;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Logger;
import org.springframework.roo.addon.beaninfo.BeanInfoMetadata;
import org.springframework.roo.addon.entity.EntityMetadata;
import org.springframework.roo.addon.entity.RooIdentifier;
import org.springframework.roo.addon.finder.FinderMetadata;
import org.springframework.roo.addon.json.JsonMetadata;
import org.springframework.roo.addon.plural.PluralMetadata;
import org.springframework.roo.classpath.PhysicalTypeCategory;
import org.springframework.roo.classpath.PhysicalTypeDetails;
import org.springframework.roo.classpath.PhysicalTypeIdentifier;
import org.springframework.roo.classpath.PhysicalTypeIdentifierNamingUtils;
import org.springframework.roo.classpath.PhysicalTypeMetadata;
import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails;
import org.springframework.roo.classpath.details.FieldMetadata;
import org.springframework.roo.classpath.details.FieldMetadataBuilder;
import org.springframework.roo.classpath.details.MemberFindingUtils;
import org.springframework.roo.classpath.details.MethodMetadata;
import org.springframework.roo.classpath.details.MethodMetadataBuilder;
import org.springframework.roo.classpath.details.annotations.AnnotatedJavaType;
import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue;
import org.springframework.roo.classpath.details.annotations.AnnotationMetadata;
import org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder;
import org.springframework.roo.classpath.details.annotations.ArrayAttributeValue;
import org.springframework.roo.classpath.details.annotations.BooleanAttributeValue;
import org.springframework.roo.classpath.details.annotations.EnumAttributeValue;
import org.springframework.roo.classpath.details.annotations.StringAttributeValue;
import org.springframework.roo.classpath.itd.AbstractItdTypeDetailsProvidingMetadataItem;
import org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder;
import org.springframework.roo.classpath.itd.ItdSourceFileComposer;
import org.springframework.roo.metadata.MetadataIdentificationUtils;
import org.springframework.roo.metadata.MetadataService;
import org.springframework.roo.model.DataType;
import org.springframework.roo.model.EnumDetails;
import org.springframework.roo.model.JavaSymbolName;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.model.ReservedWords;
import org.springframework.roo.project.Path;
import org.springframework.roo.support.style.ToStringCreator;
import org.springframework.roo.support.util.Assert;
import org.springframework.roo.support.util.StringUtils;
/**
* Metadata for {@link RooWebScaffold}.
*
* @author Stefan Schmidt
* @since 1.0
*/
public class WebScaffoldMetadata extends AbstractItdTypeDetailsProvidingMetadataItem {
private static final String PROVIDES_TYPE_STRING = WebScaffoldMetadata.class.getName();
private static final String PROVIDES_TYPE = MetadataIdentificationUtils.create(PROVIDES_TYPE_STRING);
private WebScaffoldAnnotationValues annotationValues;
private BeanInfoMetadata beanInfoMetadata;
private EntityMetadata entityMetadata;
private MetadataService metadataService;
private SortedSet<JavaType> specialDomainTypes;
private String controllerPath;
private String entityName;
private Map<JavaSymbolName, String> dateTypes;
private Map<JavaType, String> pluralCache;
private JsonMetadata jsonMetadata;
private Logger log = Logger.getLogger(getClass().getName());
public WebScaffoldMetadata(String identifier, JavaType aspectName, PhysicalTypeMetadata governorPhysicalTypeMetadata, MetadataService metadataService, WebScaffoldAnnotationValues annotationValues, BeanInfoMetadata beanInfoMetadata, EntityMetadata entityMetadata, FinderMetadata finderMetadata, ControllerOperations controllerOperations) {
super(identifier, aspectName, governorPhysicalTypeMetadata);
Assert.isTrue(isValid(identifier), "Metadata identification string '" + identifier + "' does not appear to be a valid");
Assert.notNull(annotationValues, "Annotation values required");
Assert.notNull(metadataService, "Metadata service required");
Assert.notNull(beanInfoMetadata, "Bean info metadata required");
Assert.notNull(entityMetadata, "Entity metadata required");
Assert.notNull(finderMetadata, "Finder metadata required");
Assert.notNull(controllerOperations, "Controller operations required");
if (!isValid()) {
return;
}
this.pluralCache = new HashMap<JavaType, String>();
this.annotationValues = annotationValues;
this.beanInfoMetadata = beanInfoMetadata;
this.entityMetadata = entityMetadata;
this.entityName = StringUtils.uncapitalize(beanInfoMetadata.getJavaBean().getSimpleTypeName());
if (ReservedWords.RESERVED_JAVA_KEYWORDS.contains(this.entityName)) {
this.entityName = "_" + entityName;
}
this.controllerPath = annotationValues.getPath();
this.metadataService = metadataService;
specialDomainTypes = getSpecialDomainTypes(beanInfoMetadata.getJavaBean());
dateTypes = getDatePatterns();
if (annotationValues.isRegisterConverters()) {
builder.addField(getConversionServiceField());
}
if (annotationValues.create) {
builder.addMethod(getCreateMethod());
builder.addMethod(getCreateFormMethod());
}
builder.addMethod(getShowMethod());
builder.addMethod(getListMethod());
if (annotationValues.update) {
builder.addMethod(getUpdateMethod());
builder.addMethod(getUpdateFormMethod());
}
if (annotationValues.delete) {
builder.addMethod(getDeleteMethod());
}
if (annotationValues.exposeFinders) { // No need for null check of entityMetadata.getDynamicFinders as it guarantees non-null (but maybe empty list)
for (String finderName : entityMetadata.getDynamicFinders()) {
builder.addMethod(getFinderFormMethod(finderMetadata.getDynamicFinderMethod(finderName, beanInfoMetadata.getJavaBean().getSimpleTypeName().toLowerCase())));
builder.addMethod(getFinderMethod(finderMetadata.getDynamicFinderMethod(finderName, beanInfoMetadata.getJavaBean().getSimpleTypeName().toLowerCase())));
}
}
if (specialDomainTypes.size() > 0) {
for (MethodMetadata method : getPopulateMethods()) {
builder.addMethod(method);
}
}
if (annotationValues.isRegisterConverters()) {
builder.addMethod(getRegisterConvertersMethod());
}
if (!dateTypes.isEmpty()) {
builder.addMethod(getDateTimeFormatHelperMethod());
}
if (annotationValues.isExposeJson()) {
// Decide if we want to build json support
this.jsonMetadata = (JsonMetadata) metadataService.get(JsonMetadata.createIdentifier(beanInfoMetadata.getJavaBean(), Path.SRC_MAIN_JAVA));
if (jsonMetadata != null) {
builder.addMethod(getJsonShowMethod());
builder.addMethod(getJsonCreateMethod());
builder.addMethod(getJsonListMethod());
builder.addMethod(getCreateFromJsonArrayMethod());
}
}
if (annotationValues.isCreate() || annotationValues.isUpdate()) {
builder.addMethod(getEncodeUrlPathSegmentMethod());
}
itdTypeDetails = builder.build();
new ItdSourceFileComposer(itdTypeDetails);
}
public String getIdentifierForBeanInfoMetadata() {
return beanInfoMetadata.getId();
}
public String getIdentifierForEntityMetadata() {
return entityMetadata.getId();
}
public WebScaffoldAnnotationValues getAnnotationValues() {
return annotationValues;
}
private FieldMetadataBuilder getConversionServiceField() {
FieldMetadataBuilder builder = new FieldMetadataBuilder(getId(), Modifier.PRIVATE, new JavaSymbolName("conversionService"), new JavaType("org.springframework.core.convert.support.GenericConversionService"), null);
builder.addAnnotation(new AnnotationMetadataBuilder(new JavaType("org.springframework.beans.factory.annotation.Autowired")));
return builder;
}
private MethodMetadata getDeleteMethod() {
if (entityMetadata.getFindMethod() == null || entityMetadata.getRemoveMethod() == null) {
// Mandatory input is missing (ROO-589)
return null;
}
JavaSymbolName methodName = new JavaSymbolName("delete");
MethodMetadata method = methodExists(methodName);
if (method != null) return method;
List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>();
List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>();
attributes.add(new StringAttributeValue(new JavaSymbolName("value"), entityMetadata.getIdentifierField().getFieldName().getSymbolName()));
AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.PathVariable"), attributes);
typeAnnotations.add(pathVariableAnnotation.build());
List<AnnotationAttributeValue<?>> firstResultAttributes = new ArrayList<AnnotationAttributeValue<?>>();
firstResultAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "page"));
firstResultAttributes.add(new BooleanAttributeValue(new JavaSymbolName("required"), false));
List<AnnotationMetadata> firstResultAnnotations = new ArrayList<AnnotationMetadata>();
AnnotationMetadataBuilder firstResultAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestParam"), firstResultAttributes);
firstResultAnnotations.add(firstResultAnnotation.build());
List<AnnotationAttributeValue<?>> maxResultsAttributes = new ArrayList<AnnotationAttributeValue<?>>();
maxResultsAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "size"));
maxResultsAttributes.add(new BooleanAttributeValue(new JavaSymbolName("required"), false));
List<AnnotationMetadata> maxResultsAnnotations = new ArrayList<AnnotationMetadata>();
AnnotationMetadataBuilder maxResultAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestParam"), maxResultsAttributes);
maxResultsAnnotations.add(maxResultAnnotation.build());
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(entityMetadata.getIdentifierField().getFieldType(), typeAnnotations));
paramTypes.add(new AnnotatedJavaType(new JavaType("Integer"), firstResultAnnotations));
paramTypes.add(new AnnotatedJavaType(new JavaType("Integer"), maxResultsAnnotations));
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName(entityMetadata.getIdentifierField().getFieldName().getSymbolName()));
paramNames.add(new JavaSymbolName("page"));
paramNames.add(new JavaSymbolName("size"));
paramNames.add(new JavaSymbolName("model"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/{" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "}"));
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("DELETE"))));
AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(requestMapping);
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine(beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getFindMethod().getMethodName() + "(" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + ")." + entityMetadata.getRemoveMethod().getMethodName() + "();");
bodyBuilder.appendFormalLine("model.addAttribute(\"page\", (page == null) ? \"1\" : page.toString());");
bodyBuilder.appendFormalLine("model.addAttribute(\"size\", (size == null) ? \"10\" : size.toString());");
bodyBuilder.appendFormalLine("return \"redirect:/" + controllerPath + "?page=\" + ((page == null) ? \"1\" : page.toString()) + \"&size=\" + ((size == null) ? \"10\" : size.toString());");
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder.build();
}
private MethodMetadata getListMethod() {
if (entityMetadata.getFindEntriesMethod() == null || entityMetadata.getCountMethod() == null || entityMetadata.getFindAllMethod() == null) {
// Mandatory input is missing (ROO-589)
return null;
}
JavaSymbolName methodName = new JavaSymbolName("list");
MethodMetadata method = methodExists(methodName);
if (method != null) return method;
List<AnnotationAttributeValue<?>> firstResultAttributes = new ArrayList<AnnotationAttributeValue<?>>();
firstResultAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "page"));
firstResultAttributes.add(new BooleanAttributeValue(new JavaSymbolName("required"), false));
List<AnnotationMetadata> firstResultAnnotations = new ArrayList<AnnotationMetadata>();
AnnotationMetadataBuilder firstResultAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestParam"), firstResultAttributes);
firstResultAnnotations.add(firstResultAnnotation.build());
List<AnnotationAttributeValue<?>> maxResultsAttributes = new ArrayList<AnnotationAttributeValue<?>>();
maxResultsAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "size"));
maxResultsAttributes.add(new BooleanAttributeValue(new JavaSymbolName("required"), false));
List<AnnotationMetadata> maxResultsAnnotations = new ArrayList<AnnotationMetadata>();
AnnotationMetadataBuilder maxResultAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestParam"), maxResultsAttributes);
maxResultsAnnotations.add(maxResultAnnotation.build());
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(new JavaType("Integer"), firstResultAnnotations));
paramTypes.add(new AnnotatedJavaType(new JavaType("Integer"), maxResultsAnnotations));
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("page"));
paramNames.add(new JavaSymbolName("size"));
paramNames.add(new JavaSymbolName("model"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET"))));
List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes));
String plural = getPlural(beanInfoMetadata.getJavaBean()).toLowerCase();
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("if (page != null || size != null) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("int sizeNo = size == null ? 10 : size.intValue();");
bodyBuilder.appendFormalLine("model.addAttribute(\"" + plural + "\", " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getFindEntriesMethod().getMethodName() + "(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));");
bodyBuilder.appendFormalLine("float nrOfPages = (float) " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getCountMethod().getMethodName() + "() / sizeNo;");
bodyBuilder.appendFormalLine("model.addAttribute(\"maxPages\", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("} else {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("model.addAttribute(\"" + plural + "\", " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getFindAllMethod().getMethodName() + "());");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
if (!dateTypes.isEmpty()) {
bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);");
}
bodyBuilder.appendFormalLine("return \"" + controllerPath + "/list\";");
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder.build();
}
private MethodMetadata getShowMethod() {
if (entityMetadata.getFindMethod() == null) {
// Mandatory input is missing (ROO-589)
return null;
}
JavaSymbolName methodName = new JavaSymbolName("show");
MethodMetadata method = methodExists(methodName);
if (method != null) return method;
List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>();
List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>();
attributes.add(new StringAttributeValue(new JavaSymbolName("value"), entityMetadata.getIdentifierField().getFieldName().getSymbolName()));
AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.PathVariable"), attributes);
typeAnnotations.add(pathVariableAnnotation.build());
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(entityMetadata.getIdentifierField().getFieldType(), typeAnnotations));
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName(entityMetadata.getIdentifierField().getFieldName().getSymbolName()));
paramNames.add(new JavaSymbolName("model"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/{" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "}"));
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET"))));
AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(requestMapping);
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
if (!dateTypes.isEmpty()) {
bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);");
}
bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName.toLowerCase() + "\", " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getFindMethod().getMethodName() + "(" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "));");
bodyBuilder.appendFormalLine("model.addAttribute(\"itemId\", " + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + ");");
bodyBuilder.appendFormalLine("return \"" + controllerPath + "/show\";");
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder.build();
}
private MethodMetadata getCreateMethod() {
if (entityMetadata.getPersistMethod() == null || entityMetadata.getFindAllMethod() == null) {
// Mandatory input is missing (ROO-589)
return null;
}
JavaSymbolName methodName = new JavaSymbolName("create");
MethodMetadata method = methodExists(methodName);
if (method != null) return method;
List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>();
AnnotationMetadataBuilder validAnnotation = new AnnotationMetadataBuilder(new JavaType("javax.validation.Valid"));
typeAnnotations.add(validAnnotation.build());
List<AnnotationMetadata> noAnnotations = new ArrayList<AnnotationMetadata>();
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(beanInfoMetadata.getJavaBean(), typeAnnotations));
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.validation.BindingResult"), noAnnotations));
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), noAnnotations));
paramTypes.add(new AnnotatedJavaType(new JavaType("javax.servlet.http.HttpServletRequest"), noAnnotations));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName(entityName));
paramNames.add(new JavaSymbolName("result"));
paramNames.add(new JavaSymbolName("model"));
paramNames.add(new JavaSymbolName("request"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("POST"))));
AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(requestMapping);
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("if (result.hasErrors()) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName + "\", " + entityName + ");");
if (!dateTypes.isEmpty()) {
bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);");
}
bodyBuilder.appendFormalLine("return \"" + controllerPath + "/create\";");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine(entityName + "." + entityMetadata.getPersistMethod().getMethodName() + "();");
bodyBuilder.appendFormalLine("return \"redirect:/" + controllerPath + "/\" + encodeUrlPathSegment(" + entityName + "." + entityMetadata.getIdentifierAccessor().getMethodName() + "().toString(), request);");
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder.build();
}
private MethodMetadata getCreateFormMethod() {
if (entityMetadata.getFindAllMethod() == null) {
// Mandatory input is missing (ROO-589)
return null;
}
JavaSymbolName methodName = new JavaSymbolName("createForm");
MethodMetadata method = methodExists(methodName);
if (method != null) return method;
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("model"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("params"), "form"));
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET"))));
AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(requestMapping);
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName + "\", new " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "());");
if (!dateTypes.isEmpty()) {
bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);");
}
boolean listAdded = false;
for (MethodMetadata accessorMethod : beanInfoMetadata.getPublicAccessors()) {
if (specialDomainTypes.contains(accessorMethod.getReturnType())) {
FieldMetadata field = beanInfoMetadata.getFieldForPropertyName(BeanInfoMetadata.getPropertyNameForJavaBeanMethod(accessorMethod));
if (null != field && null != MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.validation.constraints.NotNull"))) {
EntityMetadata entityMetadata = (EntityMetadata) metadataService.get(EntityMetadata.createIdentifier(accessorMethod.getReturnType(), Path.SRC_MAIN_JAVA));
if (entityMetadata != null) {
if (!listAdded) {
String listShort = new JavaType("java.util.List").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver());
String arrayListShort = new JavaType("java.util.ArrayList").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver());
bodyBuilder.appendFormalLine(listShort + " dependencies = new " + arrayListShort + "();");
listAdded = true;
}
bodyBuilder.appendFormalLine("if (" + accessorMethod.getReturnType().getSimpleTypeName() + "." + entityMetadata.getCountMethod().getMethodName().getSymbolName() + "() == 0) {");
bodyBuilder.indent();
// Adding string array which has the fieldName at position 0 and the path at position 1
bodyBuilder.appendFormalLine("dependencies.add(new String[]{\"" + field.getFieldName().getSymbolName() + "\", \"" + entityMetadata.getPlural().toLowerCase() + "\"});");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
}
}
}
}
if (listAdded) {
bodyBuilder.appendFormalLine("model.addAttribute(\"dependencies\", dependencies);");
}
bodyBuilder.appendFormalLine("return \"" + controllerPath + "/create\";");
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder.build();
}
private MethodMetadata getUpdateMethod() {
if (entityMetadata.getMergeMethod() == null || entityMetadata.getFindAllMethod() == null) {
// Mandatory input is missing (ROO-589)
return null;
}
JavaSymbolName methodName = new JavaSymbolName("update");
MethodMetadata method = methodExists(methodName);
if (method != null) return method;
List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>();
AnnotationMetadataBuilder validAnnotation = new AnnotationMetadataBuilder(new JavaType("javax.validation.Valid"));
typeAnnotations.add(validAnnotation.build());
List<AnnotationMetadata> noAnnotations = new ArrayList<AnnotationMetadata>();
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(beanInfoMetadata.getJavaBean(), typeAnnotations));
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.validation.BindingResult"), noAnnotations));
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), noAnnotations));
paramTypes.add(new AnnotatedJavaType(new JavaType("javax.servlet.http.HttpServletRequest"), noAnnotations));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName(entityName));
paramNames.add(new JavaSymbolName("result"));
paramNames.add(new JavaSymbolName("model"));
paramNames.add(new JavaSymbolName("request"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("PUT"))));
AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(requestMapping);
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("if (result.hasErrors()) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName + "\", " + entityName + ");");
if (!dateTypes.isEmpty()) {
bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);");
}
bodyBuilder.appendFormalLine("return \"" + controllerPath + "/update\";");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine(entityName + "." + entityMetadata.getMergeMethod().getMethodName() + "();");
bodyBuilder.appendFormalLine("return \"redirect:/" + controllerPath + "/\" + encodeUrlPathSegment(" + entityName + "." + entityMetadata.getIdentifierAccessor().getMethodName() + "().toString(), request);");
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder.build();
}
private MethodMetadata getUpdateFormMethod() {
if (entityMetadata.getFindMethod() == null || entityMetadata.getFindAllMethod() == null) {
// Mandatory input is missing (ROO-589)
return null;
}
JavaSymbolName methodName = new JavaSymbolName("updateForm");
MethodMetadata updateFormMethod = methodExists(methodName);
if (updateFormMethod != null) return updateFormMethod;
List<AnnotationMetadata> typeAnnotations = new ArrayList<AnnotationMetadata>();
List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>();
attributes.add(new StringAttributeValue(new JavaSymbolName("value"), entityMetadata.getIdentifierField().getFieldName().getSymbolName()));
AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.PathVariable"), attributes);
typeAnnotations.add(pathVariableAnnotation.build());
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(entityMetadata.getIdentifierField().getFieldType(), typeAnnotations));
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName(entityMetadata.getIdentifierField().getFieldName().getSymbolName()));
paramNames.add(new JavaSymbolName("model"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/{" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "}"));
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("params"), "form"));
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET"))));
AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(requestMapping);
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName + "\", " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + entityMetadata.getFindMethod().getMethodName() + "(" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "));");
if (!dateTypes.isEmpty()) {
bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);");
}
bodyBuilder.appendFormalLine("return \"" + controllerPath + "/update\";");
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder.build();
}
private MethodMetadata getJsonShowMethod() {
JavaSymbolName toJsonMethodName = jsonMetadata.getToJsonMethodName();
if (toJsonMethodName == null) {
return null;
}
JavaSymbolName methodName = new JavaSymbolName("showJson");
// See if the type itself declared the method
MethodMetadata result = MemberFindingUtils.getDeclaredMethod(governorTypeDetails, methodName, null);
if (result != null) {
return result;
}
List<AnnotationMetadata> parameters = new ArrayList<AnnotationMetadata>();
List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>();
attributes.add(new StringAttributeValue(new JavaSymbolName("value"), entityMetadata.getIdentifierField().getFieldName().getSymbolName()));
AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.PathVariable"), attributes);
parameters.add(pathVariableAnnotation.build());
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(entityMetadata.getIdentifierField().getFieldType(), parameters));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName(entityMetadata.getIdentifierField().getFieldName().getSymbolName()));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/{" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + "}"));
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET"))));
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json"));
AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(requestMapping);
annotations.add(new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.ResponseBody")));
String beanShortName = getShortName(beanInfoMetadata.getJavaBean());
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine(beanShortName + " " + beanShortName.toLowerCase() + " = " + beanShortName + "." + entityMetadata.getFindMethod().getMethodName() + "(" + entityMetadata.getIdentifierField().getFieldName().getSymbolName() + ");");
bodyBuilder.appendFormalLine("if (" + beanShortName.toLowerCase() + " == null) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("return new " + getShortName(new JavaType("org.springframework.http.ResponseEntity")) + "<String>(" + getShortName(new JavaType("org.springframework.http.HttpStatus")) + ".NOT_FOUND);");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("return " + beanShortName.toLowerCase() + "." + toJsonMethodName.getSymbolName() + "();");
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, new JavaType("java.lang.Object"), paramTypes, paramNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder.build();
}
private MethodMetadata getJsonCreateMethod() {
JavaSymbolName fromJsonMethodName = jsonMetadata.getFromJsonMethodName();
if (fromJsonMethodName == null) {
return null;
}
// See if the type itself declared the method
JavaSymbolName methodName = new JavaSymbolName("createFromJson");
MethodMetadata result = MemberFindingUtils.getDeclaredMethod(governorTypeDetails, methodName, null);
if (result != null) {
return result;
}
List<AnnotationMetadata> parameters = new ArrayList<AnnotationMetadata>();
AnnotationMetadataBuilder requestBodyAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestBody"));
parameters.add(requestBodyAnnotation.build());
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(JavaType.STRING_OBJECT, parameters));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("json"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("POST"))));
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json"));
AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(requestMapping);
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine(beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + fromJsonMethodName.getSymbolName() + "(json)." + entityMetadata.getPersistMethod().getMethodName().getSymbolName() + "();");
bodyBuilder.appendFormalLine("return new ResponseEntity<String>(\"" + beanInfoMetadata.getJavaBean().getSimpleTypeName() + " created\", " + new JavaType("org.springframework.http.HttpStatus").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".CREATED);");
List<JavaType> typeParams = new ArrayList<JavaType>();
typeParams.add(JavaType.STRING_OBJECT);
JavaType returnType = new JavaType("org.springframework.http.ResponseEntity", 0, DataType.TYPE, null, typeParams);
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, returnType, paramTypes, paramNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder.build();
}
private MethodMetadata getCreateFromJsonArrayMethod() {
JavaSymbolName fromJsonArrayMethodName = jsonMetadata.getFromJsonArrayMethodName();
if (fromJsonArrayMethodName == null) {
return null;
}
// See if the type itself declared the method
JavaSymbolName methodName = new JavaSymbolName("createFromJsonArray");
MethodMetadata result = MemberFindingUtils.getDeclaredMethod(governorTypeDetails, methodName, null);
if (result != null) {
return result;
}
List<AnnotationMetadata> parameters = new ArrayList<AnnotationMetadata>();
AnnotationMetadataBuilder requestBodyAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestBody"));
parameters.add(requestBodyAnnotation.build());
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(JavaType.STRING_OBJECT, parameters));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("json"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("value"), "/jsonArray"));
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("POST"))));
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json"));
AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(requestMapping);
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
String beanName = beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver());
List<JavaType> params = new ArrayList<JavaType>();
params.add(beanInfoMetadata.getJavaBean());
bodyBuilder.appendFormalLine("for (" + beanName + " " + entityName + ": " + beanName + "." + fromJsonArrayMethodName.getSymbolName() + "(json)) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine(entityName + "." + entityMetadata.getPersistMethod().getMethodName().getSymbolName() + "();");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("return new ResponseEntity<String>(\"" + beanInfoMetadata.getJavaBean().getSimpleTypeName() + " created\", " + new JavaType("org.springframework.http.HttpStatus").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".CREATED);");
List<JavaType> typeParams = new ArrayList<JavaType>();
typeParams.add(JavaType.STRING_OBJECT);
JavaType returnType = new JavaType("org.springframework.http.ResponseEntity", 0, DataType.TYPE, null, typeParams);
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, returnType, paramTypes, paramNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder.build();
}
private MethodMetadata getJsonListMethod() {
JavaSymbolName toJsonArrayMethodName = jsonMetadata.getToJsonArrayMethodName();
if (toJsonArrayMethodName == null) {
return null;
}
// See if the type itself declared the method
JavaSymbolName methodName = new JavaSymbolName("listJson");
MethodMetadata result = MemberFindingUtils.getDeclaredMethod(governorTypeDetails, methodName, null);
if (result != null) {
return result;
}
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("headers"), "Accept=application/json"));
AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(requestMapping);
annotations.add(new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.ResponseBody")));
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
String entityName = beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver());
bodyBuilder.appendFormalLine("return " + entityName + "." + toJsonArrayMethodName.getSymbolName() + "(" + entityName + "." + entityMetadata.getFindAllMethod().getMethodName() + "());");
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.STRING_OBJECT, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder.build();
}
private MethodMetadata getFinderFormMethod(MethodMetadata methodMetadata) {
if (entityMetadata.getFindAllMethod() == null) {
// Mandatory input is missing (ROO-589)
return null;
}
Assert.notNull(methodMetadata, "Method metadata required for finder");
JavaSymbolName finderFormMethodName = new JavaSymbolName(methodMetadata.getMethodName().getSymbolName() + "Form");
MethodMetadata finderFormMethod = methodExists(finderFormMethodName);
if (finderFormMethod != null) return finderFormMethod;
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
List<JavaType> types = AnnotatedJavaType.convertFromAnnotatedJavaTypes(methodMetadata.getParameterTypes());
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
boolean needmodel = false;
for (JavaType javaType : types) {
EntityMetadata typeEntityMetadata = null;
if (javaType.isCommonCollectionType() && isSpecialType(javaType.getParameters().get(0))) {
javaType = javaType.getParameters().get(0);
typeEntityMetadata = (EntityMetadata) metadataService.get(EntityMetadata.createIdentifier(javaType, Path.SRC_MAIN_JAVA));
} else if (isEnumType(javaType)) {
bodyBuilder.appendFormalLine("model.addAttribute(\"" + getPlural(javaType).toLowerCase() + "\", java.util.Arrays.asList(" + javaType.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".class.getEnumConstants()));");
} else if (isSpecialType(javaType)) {
typeEntityMetadata = (EntityMetadata) metadataService.get(EntityMetadata.createIdentifier(javaType, Path.SRC_MAIN_JAVA));
}
if (typeEntityMetadata != null) {
bodyBuilder.appendFormalLine("model.addAttribute(\"" + getPlural(javaType).toLowerCase() + "\", " + javaType.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + typeEntityMetadata.getFindAllMethod().getMethodName() + "());");
}
needmodel = true;
}
if (types.contains(new JavaType(Date.class.getName())) || types.contains(new JavaType(Calendar.class.getName()))) {
bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);");
}
bodyBuilder.appendFormalLine("return \"" + controllerPath + "/" + methodMetadata.getMethodName().getSymbolName() + "\";");
if (needmodel) {
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), null));
paramNames.add(new JavaSymbolName("model"));
}
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
List<StringAttributeValue> arrayValues = new ArrayList<StringAttributeValue>();
arrayValues.add(new StringAttributeValue(new JavaSymbolName("value"), "find=" + methodMetadata.getMethodName().getSymbolName().replaceFirst("find" + entityMetadata.getPlural(), "")));
arrayValues.add(new StringAttributeValue(new JavaSymbolName("value"), "form"));
requestMappingAttributes.add(new ArrayAttributeValue<StringAttributeValue>(new JavaSymbolName("params"), arrayValues));
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET"))));
AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(requestMapping);
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, finderFormMethodName, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder.build();
}
private MethodMetadata getFinderMethod(MethodMetadata methodMetadata) {
Assert.notNull(methodMetadata, "Method metadata required for finder");
JavaSymbolName finderMethodName = new JavaSymbolName(methodMetadata.getMethodName().getSymbolName());
MethodMetadata finderMethod = methodExists(finderMethodName);
if (finderMethod != null) return finderMethod;
List<AnnotatedJavaType> annotatedParamTypes = new ArrayList<AnnotatedJavaType>();
List<JavaSymbolName> paramNames = methodMetadata.getParameterNames();
List<JavaType> paramTypes = AnnotatedJavaType.convertFromAnnotatedJavaTypes(methodMetadata.getParameterTypes());
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
StringBuilder methodParams = new StringBuilder();
for (int i = 0; i < paramTypes.size(); i++) {
List<AnnotationMetadata> annotations = new ArrayList<AnnotationMetadata>();
List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>();
attributes.add(new StringAttributeValue(new JavaSymbolName("value"), StringUtils.uncapitalize(paramNames.get(i).getSymbolName())));
if (paramTypes.get(i).equals(JavaType.BOOLEAN_PRIMITIVE) || paramTypes.get(i).equals(JavaType.BOOLEAN_OBJECT)) {
attributes.add(new BooleanAttributeValue(new JavaSymbolName("required"), false));
}
AnnotationMetadataBuilder requestParamAnnotation = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestParam"), attributes);
annotations.add(requestParamAnnotation.build());
if (paramTypes.get(i).equals(new JavaType(Date.class.getName())) || paramTypes.get(i).equals(new JavaType(Calendar.class.getName()))) {
JavaSymbolName fieldName = null;
if (paramNames.get(i).getSymbolName().startsWith("max") || paramNames.get(i).getSymbolName().startsWith("min")) {
fieldName = new JavaSymbolName(StringUtils.uncapitalize(paramNames.get(i).getSymbolName().substring(3)));
} else {
fieldName = paramNames.get(i);
}
FieldMetadata field = beanInfoMetadata.getFieldForPropertyName(fieldName);
if (field != null) {
AnnotationMetadata annotation = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("org.springframework.format.annotation.DateTimeFormat"));
if (annotation != null) {
annotations.add(annotation);
}
}
}
annotatedParamTypes.add(new AnnotatedJavaType(paramTypes.get(i), annotations));
if (paramTypes.get(i).equals(JavaType.BOOLEAN_OBJECT)) {
methodParams.append(paramNames.get(i) + " == null ? new Boolean(false) : " + paramNames.get(i) + ", ");
} else {
methodParams.append(paramNames.get(i) + ", ");
}
}
if (methodParams.length() > 0) {
methodParams.delete(methodParams.length() - 2, methodParams.length());
}
annotatedParamTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), new ArrayList<AnnotationMetadata>()));
List<JavaSymbolName> newParamNames = new ArrayList<JavaSymbolName>();
newParamNames.addAll(paramNames);
newParamNames.add(new JavaSymbolName("model"));
List<AnnotationAttributeValue<?>> requestMappingAttributes = new ArrayList<AnnotationAttributeValue<?>>();
requestMappingAttributes.add(new StringAttributeValue(new JavaSymbolName("params"), "find=" + methodMetadata.getMethodName().getSymbolName().replaceFirst("find" + entityMetadata.getPlural(), "")));
requestMappingAttributes.add(new EnumAttributeValue(new JavaSymbolName("method"), new EnumDetails(new JavaType("org.springframework.web.bind.annotation.RequestMethod"), new JavaSymbolName("GET"))));
AnnotationMetadataBuilder requestMapping = new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.RequestMapping"), requestMappingAttributes);
List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
annotations.add(requestMapping);
bodyBuilder.appendFormalLine("model.addAttribute(\"" + getPlural(beanInfoMetadata.getJavaBean()).toLowerCase() + "\", " + beanInfoMetadata.getJavaBean().getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + methodMetadata.getMethodName().getSymbolName() + "(" + methodParams.toString() + ").getResultList());");
if (paramTypes.contains(new JavaType(Date.class.getName())) || paramTypes.contains(new JavaType(Calendar.class.getName()))) {
bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(model);");
}
bodyBuilder.appendFormalLine("return \"" + controllerPath + "/list\";");
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, finderMethodName, JavaType.STRING_OBJECT, annotatedParamTypes, newParamNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder.build();
}
private MethodMetadata getRegisterConvertersMethod() {
JavaSymbolName registerConvertersMethodName = new JavaSymbolName("registerConverters");
MethodMetadata registerConvertersMethod = methodExists(registerConvertersMethodName);
if (registerConvertersMethod != null) return registerConvertersMethod;
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
boolean converterPresent = false;
Set<JavaType> typesForConversion = specialDomainTypes;
typesForConversion.add(beanInfoMetadata.getJavaBean());
for (JavaType conversionType : typesForConversion) {
BeanInfoMetadata typeBeanInfoMetadata = (BeanInfoMetadata) metadataService.get(BeanInfoMetadata.createIdentifier(conversionType, Path.SRC_MAIN_JAVA));
EntityMetadata typeEntityMetadata = (EntityMetadata) metadataService.get(EntityMetadata.createIdentifier(conversionType, Path.SRC_MAIN_JAVA));
List<MethodMetadata> elegibleMethods = new ArrayList<MethodMetadata>();
int fieldCounter = 3;
if (typeBeanInfoMetadata != null) {
// Determine fields to be included in converter
for (MethodMetadata accessor : typeBeanInfoMetadata.getPublicAccessors(false)) {
if (fieldCounter == 0) {
break;
}
if (typeEntityMetadata != null) {
if (accessor.getMethodName().equals(typeEntityMetadata.getIdentifierAccessor().getMethodName()) || (typeEntityMetadata.getVersionAccessor() != null && accessor.getMethodName().equals(typeEntityMetadata.getVersionAccessor().getMethodName()))) {
continue;
}
}
FieldMetadata field = typeBeanInfoMetadata.getFieldForPropertyName(BeanInfoMetadata.getPropertyNameForJavaBeanMethod(accessor));
if (field != null // Should not happen
&& !field.getFieldType().isCommonCollectionType() && !field.getFieldType().isArray() // Exclude collections and arrays
&& !getSpecialDomainTypes(conversionType).contains(field.getFieldType()) // Exclude references to other domain objects as they are too verbose
&& !field.getFieldType().equals(JavaType.BOOLEAN_PRIMITIVE) && !field.getFieldType().equals(JavaType.BOOLEAN_OBJECT) /* Exclude boolean values as they would not be meaningful in this presentation */ ) {
elegibleMethods.add(accessor);
fieldCounter
}
}
if (elegibleMethods.size() > 0) {
JavaType converter = new JavaType("org.springframework.core.convert.converter.Converter");
String conversionTypeFieldName = Introspector.decapitalize(StringUtils.capitalize(conversionType.getSimpleTypeName()));
JavaSymbolName converterMethodName = new JavaSymbolName("get" + conversionType.getSimpleTypeName() + "Converter");
if (null == methodExists(converterMethodName)) {
bodyBuilder.appendFormalLine("conversionService.addConverter(" + converterMethodName.getSymbolName() + "());");
converterPresent = true;
// Register the converter method
InvocableMemberBodyBuilder converterBodyBuilder = new InvocableMemberBodyBuilder();
converterBodyBuilder.appendFormalLine("return new " + converter.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "<" + conversionType.getSimpleTypeName() + ", String>() {");
converterBodyBuilder.indent();
converterBodyBuilder.appendFormalLine("public String convert(" + conversionType.getSimpleTypeName() + " " + conversionTypeFieldName + ") {");
converterBodyBuilder.indent();
StringBuilder sb = new StringBuilder();
sb.append("return new StringBuilder().append(").append(conversionTypeFieldName).append(".").append(elegibleMethods.get(0).getMethodName().getSymbolName()).append("()");
if (isEnumType(elegibleMethods.get(0).getReturnType())) {
sb.append(".name()");
}
sb.append(")");
for (int i = 1; i < elegibleMethods.size(); i++) {
sb.append(".append(\" \").append(").append(conversionTypeFieldName).append(".").append(elegibleMethods.get(i).getMethodName().getSymbolName()).append("()");
if (isEnumType(elegibleMethods.get(i).getReturnType())) {
sb.append(".name()");
}
sb.append(")");
}
sb.append(".toString();");
converterBodyBuilder.appendFormalLine(sb.toString());
converterBodyBuilder.indentRemove();
converterBodyBuilder.appendFormalLine("}");
converterBodyBuilder.indentRemove();
converterBodyBuilder.appendFormalLine("};");
List<JavaType> params = new ArrayList<JavaType>();
params.add(conversionType);
params.add(JavaType.STRING_OBJECT);
JavaType parameterizedConverter = new JavaType("org.springframework.core.convert.converter.Converter", 0, DataType.TYPE, null, params);
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), 0, converterMethodName, parameterizedConverter, converterBodyBuilder);
builder.addMethod(methodBuilder.build());
}
}
}
}
if (converterPresent) {
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), 0, registerConvertersMethodName, JavaType.VOID_PRIMITIVE, bodyBuilder);
methodBuilder.addAnnotation(new AnnotationMetadataBuilder(new JavaType("javax.annotation.PostConstruct")));
return methodBuilder.build();
}
return null; //no converter to register
}
private MethodMetadata getDateTimeFormatHelperMethod() {
JavaSymbolName addDateTimeFormatPatterns = new JavaSymbolName("addDateTimeFormatPatterns");
MethodMetadata addDateTimeFormatPatternsMethod = methodExists(addDateTimeFormatPatterns);
if (addDateTimeFormatPatternsMethod != null) return addDateTimeFormatPatternsMethod;
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(new JavaType("org.springframework.ui.Model"), new ArrayList<AnnotationMetadata>()));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("model"));
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
Iterator<Map.Entry<JavaSymbolName, String>> it = dateTypes.entrySet().iterator();
while (it.hasNext()) {
Entry<JavaSymbolName, String> entry = it.next();
JavaType dateTimeFormat = new JavaType("org.joda.time.format.DateTimeFormat");
String dateTimeFormatSimple = dateTimeFormat.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver());
JavaType localeContextHolder = new JavaType("org.springframework.context.i18n.LocaleContextHolder");
String localeContextHolderSimple = localeContextHolder.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver());
bodyBuilder.appendFormalLine("model.addAttribute(\"" + entityName + "_" + entry.getKey().getSymbolName().toLowerCase() + "_date_format\", " + dateTimeFormatSimple + ".patternForStyle(\"" + entry.getValue() + "\", " + localeContextHolderSimple + ".getLocale()));");
}
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), 0, addDateTimeFormatPatterns, JavaType.VOID_PRIMITIVE, paramTypes, paramNames, bodyBuilder);
return methodBuilder.build();
}
private List<MethodMetadata> getPopulateMethods() {
List<MethodMetadata> methods = new ArrayList<MethodMetadata>();
for (JavaType type : specialDomainTypes) {
// There is a need to present a populator for self references (see ROO-1112)
// if (type.equals(beanInfoMetadata.getJavaBean())) {
// continue;
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
EntityMetadata typeEntityMetadata = (EntityMetadata) metadataService.get(EntityMetadata.createIdentifier(type, Path.SRC_MAIN_JAVA));
if (typeEntityMetadata != null) {
bodyBuilder.appendFormalLine("return " + type.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + "." + typeEntityMetadata.getFindAllMethod().getMethodName() + "();");
} else if (isEnumType(type)) {
JavaType arrays = new JavaType("java.util.Arrays");
bodyBuilder.appendFormalLine("return " + arrays.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".asList(" + type.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".class.getEnumConstants());");
} else if (isRooIdentifier(type)) {
continue;
} else {
throw new IllegalStateException("Could not scaffold controller for type " + beanInfoMetadata.getJavaBean().getFullyQualifiedTypeName() + ", the referenced type " + type.getFullyQualifiedTypeName() + " cannot be handled");
}
JavaSymbolName populateMethodName = new JavaSymbolName("populate" + getPlural(type));
MethodMetadata addReferenceDataMethod = methodExists(populateMethodName);
if (addReferenceDataMethod != null) continue;
List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>();
attributes.add(new StringAttributeValue(new JavaSymbolName("value"), getPlural(type).toLowerCase()));
annotations.add(new AnnotationMetadataBuilder(new JavaType("org.springframework.web.bind.annotation.ModelAttribute"), attributes));
List<JavaType> typeParams = new ArrayList<JavaType>();
typeParams.add(type);
JavaType returnType = new JavaType("java.util.Collection", 0, DataType.TYPE, null, typeParams);
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, populateMethodName, returnType, bodyBuilder);
methodBuilder.setAnnotations(annotations);
methods.add(methodBuilder.build());
}
return methods;
}
private MethodMetadata getEncodeUrlPathSegmentMethod() {
JavaSymbolName encodeUrlPathSegment = new JavaSymbolName("encodeUrlPathSegment");
MethodMetadata encodeUrlPathSegmentMethod = methodExists(encodeUrlPathSegment);
if (encodeUrlPathSegmentMethod != null) return encodeUrlPathSegmentMethod;
List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>();
paramTypes.add(new AnnotatedJavaType(JavaType.STRING_OBJECT, new ArrayList<AnnotationMetadata>()));
paramTypes.add(new AnnotatedJavaType(new JavaType("javax.servlet.http.HttpServletRequest"), new ArrayList<AnnotationMetadata>()));
List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>();
paramNames.add(new JavaSymbolName("pathSegment"));
paramNames.add(new JavaSymbolName("request"));
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("String enc = request.getCharacterEncoding();");
bodyBuilder.appendFormalLine("if (enc == null) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("enc = " + new JavaType("org.springframework.web.util.WebUtils").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".DEFAULT_CHARACTER_ENCODING;");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("try {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("pathSegment = " + new JavaType("org.springframework.web.util.UriUtils").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + ".encodePathSegment(pathSegment, enc);");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("catch (" + new JavaType("java.io.UnsupportedEncodingException").getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver()) + " uee) {}");
bodyBuilder.appendFormalLine("return pathSegment;");
return new MethodMetadataBuilder(getId(), Modifier.PRIVATE, encodeUrlPathSegment, JavaType.STRING_OBJECT, paramTypes, paramNames, bodyBuilder).build();
}
private MethodMetadata methodExists(JavaSymbolName methodName) {
// We have no access to method parameter information, so we scan by name alone and treat any match as authoritative
// We do not scan the superclass, as the caller is expected to know we'll only scan the current class
for (MethodMetadata method : governorTypeDetails.getDeclaredMethods()) {
if (method.getMethodName().equals(methodName)) {
// Found a method of the expected name; we won't check method parameters though
return method;
}
}
return null;
}
private SortedSet<JavaType> getSpecialDomainTypes(JavaType javaType) {
SortedSet<JavaType> specialTypes = new TreeSet<JavaType>();
BeanInfoMetadata bim = (BeanInfoMetadata) metadataService.get(BeanInfoMetadata.createIdentifier(javaType, Path.SRC_MAIN_JAVA));
if (bim == null) {
// Unable to get metadata so it is not a JavaType in our project anyway.
return specialTypes;
}
EntityMetadata em = (EntityMetadata) metadataService.get(EntityMetadata.createIdentifier(javaType, Path.SRC_MAIN_JAVA));
if (em == null) {
// Unable to get entity metadata so it is not a Entity in our project anyway.
return specialTypes;
}
for (MethodMetadata accessor : bim.getPublicAccessors(false)) {
// Not interested in identifiers and version fields
if (accessor.equals(em.getIdentifierAccessor()) || accessor.equals(em.getVersionAccessor())) {
continue;
}
// Not interested in fields that are not exposed via a mutator
FieldMetadata fieldMetadata = bim.getFieldForPropertyName(BeanInfoMetadata.getPropertyNameForJavaBeanMethod(accessor));
if (fieldMetadata == null || !hasMutator(fieldMetadata, bim)) {
continue;
}
JavaType type = accessor.getReturnType();
if (type.isCommonCollectionType()) {
for (JavaType genericType : type.getParameters()) {
if (isSpecialType(genericType)) {
specialTypes.add(genericType);
}
}
} else {
if (isSpecialType(type) && !isEmbeddedFieldType(fieldMetadata)) {
specialTypes.add(type);
}
}
}
return specialTypes;
}
private Map<JavaSymbolName, String> getDatePatterns() {
Map<JavaSymbolName, String> dates = new HashMap<JavaSymbolName, String>();
for (MethodMetadata accessor : beanInfoMetadata.getPublicAccessors(false)) {
// Not interested in identifiers and version fields
if (accessor.equals(entityMetadata.getIdentifierAccessor()) || accessor.equals(entityMetadata.getVersionAccessor())) {
continue;
}
// Not interested in fields that are not exposed via a mutator
FieldMetadata fieldMetadata = beanInfoMetadata.getFieldForPropertyName(BeanInfoMetadata.getPropertyNameForJavaBeanMethod(accessor));
if (fieldMetadata == null || !hasMutator(fieldMetadata, beanInfoMetadata)) {
continue;
}
JavaType type = accessor.getReturnType();
if (type.getFullyQualifiedTypeName().equals(Date.class.getName()) || type.getFullyQualifiedTypeName().equals(Calendar.class.getName())) {
AnnotationMetadata annotation = MemberFindingUtils.getAnnotationOfType(fieldMetadata.getAnnotations(), new JavaType("org.springframework.format.annotation.DateTimeFormat"));
if (annotation != null && annotation.getAttributeNames().contains(new JavaSymbolName("style"))) {
dates.put(fieldMetadata.getFieldName(), annotation.getAttribute(new JavaSymbolName("style")).getValue().toString());
for (String finder : entityMetadata.getDynamicFinders()) {
if (finder.contains(StringUtils.capitalize(fieldMetadata.getFieldName().getSymbolName()) + "Between")) {
dates.put(new JavaSymbolName("min" + StringUtils.capitalize(fieldMetadata.getFieldName().getSymbolName())), annotation.getAttribute(new JavaSymbolName("style")).getValue().toString());
dates.put(new JavaSymbolName("max" + StringUtils.capitalize(fieldMetadata.getFieldName().getSymbolName())), annotation.getAttribute(new JavaSymbolName("style")).getValue().toString());
}
}
} else {
log.warning("It is recommended to use @DateTimeFormat(style=\"S-\") on " + beanInfoMetadata.getJavaBean().getSimpleTypeName() + "." + fieldMetadata.getFieldName() + " to use automatic date conversion in Spring MVC");
}
}
}
return dates;
}
private String getShortName(JavaType type) {
return type.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver());
}
private boolean isEnumType(JavaType type) {
PhysicalTypeMetadata physicalTypeMetadata = (PhysicalTypeMetadata) metadataService.get(PhysicalTypeIdentifierNamingUtils.createIdentifier(PhysicalTypeIdentifier.class.getName(), type, Path.SRC_MAIN_JAVA));
if (physicalTypeMetadata != null) {
PhysicalTypeDetails details = physicalTypeMetadata.getPhysicalTypeDetails();
if (details != null) {
if (details.getPhysicalTypeCategory().equals(PhysicalTypeCategory.ENUMERATION)) {
return true;
}
}
}
return false;
}
private boolean isRooIdentifier(JavaType type) {
PhysicalTypeMetadata physicalTypeMetadata = (PhysicalTypeMetadata) metadataService.get(PhysicalTypeIdentifier.createIdentifier(type, Path.SRC_MAIN_JAVA));
if (physicalTypeMetadata == null) {
return false;
}
ClassOrInterfaceTypeDetails cid = (ClassOrInterfaceTypeDetails) physicalTypeMetadata.getPhysicalTypeDetails();
if (cid == null) {
return false;
}
return null != MemberFindingUtils.getAnnotationOfType(cid.getAnnotations(), new JavaType(RooIdentifier.class.getName()));
}
private boolean hasMutator(FieldMetadata fieldMetadata, BeanInfoMetadata bim) {
for (MethodMetadata mutator : bim.getPublicMutators()) {
if (fieldMetadata.equals(bim.getFieldForPropertyName(BeanInfoMetadata.getPropertyNameForJavaBeanMethod(mutator)))) return true;
}
return false;
}
private boolean isSpecialType(JavaType javaType) {
// We are only interested if the type is part of our application
if (metadataService.get(PhysicalTypeIdentifier.createIdentifier(javaType, Path.SRC_MAIN_JAVA)) != null) {
return true;
}
return false;
}
private boolean isEmbeddedFieldType(FieldMetadata field) {
return MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.Embedded")) != null;
}
private String getPlural(JavaType type) {
if (pluralCache.get(type) != null) {
return pluralCache.get(type);
}
PluralMetadata pluralMetadata = (PluralMetadata) metadataService.get(PluralMetadata.createIdentifier(type, Path.SRC_MAIN_JAVA));
Assert.notNull(pluralMetadata, "Could not determine the plural for the '" + type.getFullyQualifiedTypeName() + "' type");
if (!pluralMetadata.getPlural().equals(type.getSimpleTypeName())) {
pluralCache.put(type, pluralMetadata.getPlural());
return pluralMetadata.getPlural();
}
pluralCache.put(type, pluralMetadata.getPlural() + "Items");
return pluralMetadata.getPlural() + "Items";
}
public String toString() {
ToStringCreator tsc = new ToStringCreator(this);
tsc.append("identifier", getId());
tsc.append("valid", valid);
tsc.append("aspectName", aspectName);
tsc.append("destinationType", destination);
tsc.append("governor", governorPhysicalTypeMetadata.getId());
tsc.append("itdTypeDetails", itdTypeDetails);
return tsc.toString();
}
public static final String getMetadataIdentiferType() {
return PROVIDES_TYPE;
}
public static final String createIdentifier(JavaType javaType, Path path) {
return PhysicalTypeIdentifierNamingUtils.createIdentifier(PROVIDES_TYPE_STRING, javaType, path);
}
public static final JavaType getJavaType(String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.getJavaType(PROVIDES_TYPE_STRING, metadataIdentificationString);
}
public static final Path getPath(String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING, metadataIdentificationString);
}
public static boolean isValid(String metadataIdentificationString) {
return PhysicalTypeIdentifierNamingUtils.isValid(PROVIDES_TYPE_STRING, metadataIdentificationString);
}
}
|
package com.neverwinterdp.vm;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import com.mycila.guice.ext.closeable.CloseableInjector;
import com.neverwinterdp.module.AppContainer;
import com.neverwinterdp.module.AppModule;
import com.neverwinterdp.module.ServiceModuleContainer;
import com.neverwinterdp.module.VMModule;
import com.neverwinterdp.os.RuntimeEnv;
import com.neverwinterdp.registry.Registry;
import com.neverwinterdp.registry.RegistryConfig;
import com.neverwinterdp.registry.RegistryException;
import com.neverwinterdp.util.JSONSerializer;
import com.neverwinterdp.util.io.NetworkUtil;
import com.neverwinterdp.util.log.LoggerFactory;
import com.neverwinterdp.vm.VMApp.TerminateEvent;
import com.neverwinterdp.vm.command.VMCommandWatcher;
import com.neverwinterdp.vm.service.VMService;
public class VM {
static private Map<String, VM> vms = new ConcurrentHashMap<String, VM>() ;
private Logger logger ;
private VMDescriptor vmDescriptor;
private VMStatus vmStatus = VMStatus.INIT;
private AppContainer appContainer;
private ServiceModuleContainer vmModuleContainer;
private VMApplicationRunner vmApplicationRunner;
public VM(VMConfig vmConfig) throws Exception {
if(vmConfig.isSelfRegistration()) {
vmDescriptor = new VMDescriptor(vmConfig);
initContainer(vmDescriptor, vmConfig);
logger.info("Create VM with VMConfig:");
logger.info(JSONSerializer.INSTANCE.toString(vmConfig));
logger.info("Start self registration with the registry");
Registry registry = vmModuleContainer.getInstance(Registry.class);
VMService.register(registry, vmDescriptor);
logger.info("Finish self registration with the registry");
} else {
vmDescriptor = initContainer(null, vmConfig);
}
init();
}
public AppContainer getAppContainer() { return this.appContainer ; }
public ServiceModuleContainer getVMModuleServiceContainer() { return this.vmModuleContainer ; }
public LoggerFactory getLoggerFactory() { return appContainer.getLoggerFactory(); }
public RuntimeEnv getRuntimeEnv() { return appContainer.getRuntimeEnv(); }
private VMDescriptor initContainer(VMDescriptor vmDescriptor, final VMConfig vmConfig) throws Exception {
final String vmDescriptorPath = VMService.ALL_PATH + "/" + vmConfig.getName();
final RegistryConfig rConfig = vmConfig.getRegistryConfig();
final Registry registry = rConfig.newInstance().connect();
if(vmDescriptor == null) {
vmDescriptor = registry.getDataAs(vmDescriptorPath, VMDescriptor.class);
}
final VMDescriptor finalVMDescriptor = vmDescriptor;
Map<String, String> props = vmConfig.getProperties();
props.put("vm.registry.allocated.path", vmDescriptorPath);
String hostname = NetworkUtil.getHostname();
AppModule appModule = new AppModule(hostname, vmConfig.getName(), vmConfig.getAppHome(), vmConfig.getAppDataDir(), props) {
@Override
protected void configure(Map<String, String> properties) {
super.configure(properties);
try {
bindInstance(VMConfig.class, vmConfig);
bindInstance(VMDescriptor.class, finalVMDescriptor);
bindInstance(RegistryConfig.class, rConfig);
bindInstance(Registry.class, registry);
} catch(Exception e) {
e.printStackTrace();
}
}
};
appContainer = new AppContainer(appModule);
appContainer.onInit();
logger = appContainer.getLoggerFactory().getLogger(getClass());
appContainer.install(new HashMap<String, String>(), VMModule.NAME) ;
vmModuleContainer = appContainer.getModule("VMModule");
return finalVMDescriptor;
}
public VMStatus getVMStatus() { return this.vmStatus ; }
public VMDescriptor getDescriptor() { return vmDescriptor; }
public VMApp getVMApplication() {
if(vmApplicationRunner == null) return null;
return vmApplicationRunner.vmApplication;
}
public VMRegistry getVMRegistry() { return appContainer.getInstance(VMRegistry.class) ; }
public void setVMStatus(VMStatus status) throws RegistryException {
vmStatus = status;
getVMRegistry().updateStatus(status);
}
public void init() throws RegistryException {
logger.info("Start init(...)");
VMRegistry vmRegistry = getVMRegistry();
setVMStatus(VMStatus.INIT);
vmRegistry.addCommandWatcher(new VMCommandWatcher(this));
vmRegistry.createHeartbeat();
logger.info("Finish init(...)");
}
public void run() throws Exception {
logger.info("Start run()");
if(vmApplicationRunner != null) {
throw new Exception("VM Application is already started");
}
VMConfig vmConfig = vmDescriptor.getVmConfig();
Class<VMApp> vmAppType = (Class<VMApp>)Class.forName(vmConfig.getVmApplication()) ;
VMApp vmApp = vmAppType.newInstance();
vmApp.setVM(this);
setVMStatus(VMStatus.RUNNING);
vmApplicationRunner = new VMApplicationRunner(vmApp, vmConfig.getProperties()) ;
vmApplicationRunner.start();
logger.info("Finish run()");
}
public void shutdown() throws Exception {
terminate(TerminateEvent.Shutdown, 1000);
}
public void terminate(final TerminateEvent event, final long delay) throws Exception {
if(vmApplicationRunner == null || !vmApplicationRunner.isAlive()) return;
Thread thread = new Thread() {
public void run() {
try {
Thread.sleep(delay);
vmApplicationRunner.vmApplication.terminate(event);
if(!vmApplicationRunner.vmApplication.isWaittingForTerminate()) {
vmApplicationRunner.interrupt();
}
} catch (InterruptedException e) {
}
}
};
thread.start();
}
synchronized public void notifyComplete() {
notifyAll();
}
synchronized public void waitForComplete() throws InterruptedException {
long start = System.currentTimeMillis() ;
logger.info("Start waitForComplete()");
wait();
logger.info("Finish waitForComplete() in " + (System.currentTimeMillis() - start) + "ms");
}
public class VMApplicationRunner extends Thread {
VMApp vmApplication;
Map<String, String> properties;
public VMApplicationRunner(VMApp vmApplication, Map<String, String> props) {
setName("VM-" + vmApplication.getVM().getDescriptor().getId());
this.vmApplication = vmApplication;
this.properties = props;
}
public void run() {
try {
vmApplication.run();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
logger.error("Error in vm application", e);
} finally {
try {
setVMStatus(VMStatus.TERMINATED);
appContainer.onDestroy();
appContainer.getInstance(CloseableInjector.class).close();
} catch (RegistryException e) {
System.err.println("Set terminated vm status for " + vmDescriptor.getId() );
e.printStackTrace();
logger.error("Error in vm registry", e);
}
notifyComplete();
}
}
}
static public VM getVM(VMDescriptor descriptor) {
return vms.get(descriptor.getId());
}
static public void trackVM(VM vm) {
vms.put(vm.getDescriptor().getId(), vm);
}
static public VM run(VMConfig vmConfig) throws Exception {
VM vm = new VM(vmConfig);
vm.run();
return vm;
}
static public void main(String[] args) throws Exception {
long start = System.currentTimeMillis() ;
System.out.println("VM: main(..) start");
VMConfig vmConfig = new VMConfig(args);
vmConfig.getLoggerConfig().getConsoleAppender().setEnable(false);
String vmDir = "/opt/hadoop/vm/" + vmConfig.getName();
vmConfig.getLoggerConfig().getFileAppender().setFilePath(vmDir + "/logs/vm.log");
vmConfig.getLoggerConfig().getEsAppender().setBufferDir(vmDir + "/buffer/es/log4j");
vmConfig.getLoggerConfig().getKafkaAppender().setBufferDir(vmDir + "/buffer/kafka/log4j");
Map<String, String> log4jProps = vmConfig.getLoggerConfig().getLog4jConfiguration() ;
LoggerFactory.log4jConfigure(log4jProps);
VM vm = new VM(vmConfig);
vm.run();
vm.waitForComplete();
System.out.println("VM: main(..) finish in " + (System.currentTimeMillis() - start) + "ms");
}
}
|
package openfoodfacts.github.scrachx.openfood.test;
import openfoodfacts.github.scrachx.openfood.utils.LocaleHelper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public class ScreenshotParametersProvider {
public static ScreenshotParameter create(String countryTag, String languageCode, String... otherProductsCode) {
return create(countryTag, LocaleHelper.getLocale(languageCode), otherProductsCode);
}
private static ScreenshotParameter create(String countryTag, Locale locale, String... otherProductsCode) {
ScreenshotParameter parameter = new ScreenshotParameter(countryTag, locale);
parameter.setProductCodes(Arrays.asList(otherProductsCode));
return parameter;
}
public static List<ScreenshotParameter> createDefault() {
List<ScreenshotParameter> res = new ArrayList<>();
res.add(create("Albania", new Locale("sq", "AL"),"8076802795019","9006900014872","3250390003755","90087745","8600116000073","8003340069708","8600116000301","8600946862018","9120025838981","5060517885830","9006900014360","8002560070709","8000350004583"));
res.add(create("Algeria", new Locale("ar", "DZ"),"80177616","5449000000439","5449000000996","0065633071308","3450970006460","8000500037560","6191544100609","3564707098823","3564700759349","3564700676257","3564700555347","5410126716016","6130234002168","6133320000130","6130517000430","6130093056968","6130837001186","6130837001285","6130234000607","6130760005152"));
res.add(create("Andorra", new Locale("ca", "AD"),"3770002675113","8410100034027","3450970150828","8437000140481"));
res.add(create("Anguilla", new Locale("en", "AI"),"0041303014912"));
res.add(create("Argentina", new Locale("es", "AR"),"3017620429484","7792129002326","7792129002319","7791273000707","7791875005353","7796425000048","7792260000823"));
res.add(create("Australia", new Locale("en", "AU"),"26201142","26201542","9310881980140","9556092706166","9315070606634","9310036005988","9353712000037","9315896100316","9300462118437","9348360000003","8032595021407","9313107160265","9300682038911","22012401","9300639151328","26222035","9300601930203","9300796079947","9300645069013","9300601183395"));
res.add(create("Austria", new Locale("de", "AT"),"8000430900231","8712566328352","4000417702005","8076800195057","8076808060654","90162800","3083680073608","9015160102243","24045476","20763961","3838929513045","9100000051598","9100000716695","5449000000439","5760466920537","40144177","5449000000996","5900951028502","9100000733845","4008400191423"));
res.add(create("Bahrein", new Locale("ar", "BH"),"4025500183677"));
res.add(create("Belgium", new Locale("nl", "BE"),"8000430900231","8010721001509","80551072","5412929001092","5400101067554","5410483015036","5053990107339","5412038129083","5411021100047","20803902","3387390326574","8712566328352","5400601350835","4000417702005","20047214","20363253","5400112717127","20427986","87157239","5400141189841"));
res.add(create("Bosnia and Herzegovina", new Locale("bs", "BA"),"7622210642189","7622210642134","7622210642196","9006900014872","5900437005133","8606014409031","5941047829214","3850108020182","8600116000073","8600498176359","8600939212257","5204739612649","3831051008700","3875000050808","7622210397119","8600116000301","9120025838981","9006900014360","8600939212608","8607100510433"));
res.add(create("Brazil", new Locale("pt", "BR"),"5449000000996","8410770100022","7891000100448","3700123302360","7896984205004","7891000140307","7898941911065","7895000371303","7898176581187","7891991000826","5601045300022","3014680009175","7896336006624","3525","3760091729828","7896000530363","7896004002767","7894321722016","7896496940325","7891098000170"));
res.add(create("Bulgaria", new Locale("bg", "BG"),"7613036230506","4014051006092","8412779400103","4008400290126","3800055710063","4014400911039","7622210633354","7622210642189","5900259056207","4260012620276","7622210642134","7622210642196","8480017743398","2000228316639","9006900014872","5900437005133","8430807002297","8430807006240","5941000024700","4823077614767"));
res.add(create("Burkina Faso", new Locale("fr", "BF"),"9504000105013","8728200404009","3258561100104"));
res.add(create("Cambodia", new Locale("km", "KH"),"5410041332209","9310113532277","8851234310173"));
res.add(create("Cameroon", new Locale("fr", "CM"),"5449000000996","80177173","9501100001627","0853148003002","8425197712024","6174000001566","0853148003019","6001240100035"));
res.add(create("Canada", new Locale("en", "CA"),"0065633074712","0063667125080","26035277","0056800528022","0055220080059","26043357","26020457","0016000275270","0063348004949","26039886","26073835","26073347","26043579","26044439","26015057","26043081","26044064","3168930009993","5449000000996","0619893610557"));
res.add(create("Chile", new Locale("es", "CL"),"7801505000877","4003274001625","8410134013906","7502252481796","24500200","7801552000196","7804647172938","7802900365028","7802600133217","0832697000595"));
res.add(create("China", new Locale("zh-hans", "CN"),"8422174010029","3228021000084","3083680004671","4008400191423","4045317058593","3272770003148","5449000017932","3760150148607","80177173","0898999000022","8851978808158","6954767417684","8005709800984","6936571910018","6901939691601","4000417294005"));
res.add(create("Colombia", new Locale("es", "CO"),"7709335802602","3017620429484","1016001015256","3222471055113","3525","3248650098566","3350031544545","7702189109996","7702011012401","7707220540370","2147729071251","7702729934323","7702011281180"));
res.add(create("Cook Islands", new Locale("en", "CK"),"94155877"));
res.add(create("Costa Rica", new Locale("es", "CR"),"0658480001248","4008713702750","0747627005116","0873617002671","7000000143052"));
res.add(create("Côte d'Ivoire", new Locale("fr", "CI"),"3700311866292","8716200718585","6290090014559","3168930006725","3428271940066"));
res.add(create("Croatia", new Locale("hr", "HR"),"90426230","7622210642189","8076800376999","8023678162360","4260012620276","7622210642134","7622210642196","9006900014872","8714882001018","7622210982377","20641788","8606014409031","3859889622356","5941047829214","5997347555735","8600116000073","8600939212257","5204739612649","3831051008700","7622210254405"));
res.add(create("Cuba", new Locale("es", "CU"),"0037000184799","2000000044046","2000000044055","2000000044054","8500001030249"));
res.add(create("Cyprus", new Locale("el", "CY"),"5000168181578","5201168215649","8690504025207","8606003341137"));
res.add(create("Czech Republic", new Locale("cs", "CZ"),"4000417702005","90426230","5449000000439","20221133","5026489484785","5449000004864","4001686834022","8712566065011","8594001040018","8593893742840","5449000131843","20706852","5449000000286","4260012620276","7622210835338","4046234925906","8594002648008","85815483","4001954165513","8594001021499"));
res.add(create("Democratic Republic of the Congo (Congo-Kinshasa, former Zaire)", new Locale("fr", "CD"),"3258561410784"));
res.add(create("Denmark", new Locale("da", "DK"),"8000430900231","8712566328352","4000417702005","87157239","7622300336738","3046920028363","3228021000084","5000159407236","8410770100022","0024000011859","5000111018005","7613032625474","8010721998120","3395320066797","4000417214003","4014400400007","8410000810004","7622210477439","80177173","8713800132131"));
res.add(create("Djibouti", new Locale("fr", "DJ"),"3183280000902","3263852506411"));
res.add(create("Dominica", new Locale("en", "DM"),"0888670002919"));
res.add(create("Dominican Republic", new Locale("es", "DO"),"0065633438699","3451790886645"));
res.add(create("Ecuador", new Locale("es", "EC"),"7861006744045","7861077501592"));
res.add(create("Egypt", new Locale("ar", "EG"),"90162602","5000159031103","9557062321136","8714555000300","6221024991714","6223001360506"));
res.add(create("El Salvador", new Locale("es", "SV"),"7317731117352","2319374130793"));
res.add(create("Estonia", new Locale("et", "EE"),"2000228316639","80052760","3800020423578","5900437005133","40561073","8710908980459","7613035789197","4000415028701","4000607854606","6415717409000","4000415025304","6416453554719","7613033963391","90384103","90384066","5900020027689","9020200006917"));
res.add(create("Fiji", new Locale("en", "FJ"),"9403146721883"));
res.add(create("Finland", new Locale("fi", "FI"),"4000417289001","20036850","20022464","5900334007919","7310500094465","6430043013219","6408430011667","6411401028373","20425609","8713800132131","20366780","6415712002718","6415715930988","6417348171608","5410041001204","8008698007303","6430031984071","7622300571351","6415712508593","3770006832055"));
res.add(create("France", new Locale("fr", "FR"),"3760224570167","3180950004802","5053827101424","3180950006981","3240930313505","3180950001801","3154230010197","3073780977524","8000430900231","3449865293375","3073780516723","3181232180559","3180950007254","3180950007308","3073780515702","3245390181022","3180950008114","3235080008654","3273220086230","5055534325117"));
res.add(create("French Guiana", new Locale("fr", "GF"),"3256220258579","3256221653922","3256223010563","3256223022399","3256224234555","3017800132463","3308751000216","3229820780955","3263852557215","5741000002315","3487400000415","3019080031009","3435649826570","3760096960547","3256220659147","3244570054705","3256220280174","3256220280167","3368952621207","3256225721603"));
res.add(create("French Polynesia", new Locale("fr", "PF"),"0613008730734","0088009670721","3352271322211","9415262002104","3352271259227","80176800","15600703","3352271120060","9421903084576","3760251180094","0088009320633","3057640373183","3760150148607","3760150142933","9415102000857","3700279301491","3017760826174","3256225721603","3256225427239","3256222074573"));
res.add(create("Gabon", new Locale("fr", "GA"),"3052011006318","8435185100955","3410280024318"));
res.add(create("Georgia", new Locale("ka", "GE"),"5449000000996","54491472"));
res.add(create("Germany", new Locale("de", "DE"),"8000430900231","5055534325117","4008258143018","8010721001509","2000000095221","4008258100011","4032844250835","7610800005926","20490607","4388840213023","23625983","4002971453409","4000856007129","8712566328352","4000417289001","7622300479008","4000417702005","20001308","20095291","87157239"));
res.add(create("Greece", new Locale("el", "GR"),"4000417289001","5034525010119","5000159509831","3560070614202","8076800376999","3560070759927","7622300315269","8076808150072","20181529","5201004021328","3560070046478","9006900014872","20641788","59032823","8410376015515","5000159366229","5201024781288","4000339695027","5203937007721","7622300507121"));
res.add(create("Guadeloupe", new Locale("fr", "GP"),"3270190128519","7610036002676","80176800","3056440083193","3368850000036","3770000495010","3346438000104","3575650000207","15600703","3176571983008","3440950200476","3270190024972","3245411851149","3245412950872","3018930004903","7613034916891","3328382631320","3292090141221","3227061000023","3029330031987"));
res.add(create("Guatemala", new Locale("es", "GT"),"7501055352463","7441001606069"));
res.add(create("Guyana", new Locale("en", "GY"),"0024000163022"));
res.add(create("Hong Kong (SAR of China)", new Locale("zh-hant", "HK"),"3472860053057","4891028164456","5010029000023","4897042280424","80177609","5901414204679","3222475425363","4890008120307","00847049","00854252","3274080001005","7610400014571","3222472627630","4891028710660","4892214253527","3222472777526","8410973012115","3271820071557","0078895132908","4897005440056"));
res.add(create("Hungary", new Locale("hu", "HU"),"8712566328352","20280239","4008400290126","90426230","20002077","3046920028363","5904215138747","4001686834022","5998339749729","54491472","8714100581810","80176800","5000184321552","5900102013067","5997380351080","7622210145390","8714100637487","4006814001529","8076800376999","7622210835338"));
res.add(create("Iceland", new Locale("is", "IS"),"5411188110743","8410076481597","5690576271918","5690527673006","5010029222173"));
res.add(create("India", new Locale("hi", "IN"),"5449000000996","87157246","3256226759117","4060800001740","7610827760259","3124480184320","8901491208291","8901491990028","8901491990080","8904150502396","8902080011513","8901491365703","4000417224002","8901071706834","8901491102902","8901499008190","8904787201723","8901499008244","8901030691508","8904065212540"));
res.add(create("Indonesia", new Locale("id", "ID"),"8999999002503","13551128"));
res.add(create("Iran", new Locale("fa", "IR"),"22123572"));
res.add(create("Iraq", new Locale("ar", "IQ"),"5449000000439","5449000130389"));
res.add(create("Ireland", new Locale("en", "IE"),"5060088701690","8712566328352","90162800","5057753210823","7622210256225","20471613","4260334140148","20152543","5900951028502","3051800802735","5099874167020","5036829752207","5018374350930","5013683305800","5060072990017","80176800","5000159500371","5060088705988","5053526008291","25179750"));
res.add(create("Israel", new Locale("he", "IL"),"3525","5420066330234","0830296000404","8723400782100","7290002013839","0038527591053","7296073273424","8690777206051","3523230039437","7290106654945"));
res.add(create("Italy", new Locale("it", "IT"),"3560071005672","8712566328352","3560070709366","80019442","8076809575508","8013355000290","8002670500714","8076809521543","3560070470501","3046920029759","7622300336738","4000540003864","8076802085738","8034066307461","20590147","8013355999143","8001120895530","8019730075877","8019730075440","8010721996812"));
res.add(create("Japan", new Locale("ja", "JP"),"8076802085738","3019080067015","3263670033458","3165950108019","3368952992758","3263670297812","8076800195019","8712566432127","3038352877008","3019081236250","8076809570657","3271510000126","3165950210651","3263670237719","3019081239640","3263670014457","3083680996082","5010029000023","3263670123616","3165950217797"));
res.add(create("Jordan", new Locale("ar", "JO"),"6290400013425","6251079000901","3560070894550","8423352107036"));
res.add(create("Kuweit", new Locale("ar", "KW"),"0037466080864","5449000014535"));
res.add(create("Latvia", new Locale("lv", "LV"),"2000228316639","4750127300601","80052760","3800020423578","5900437005133","40561073","7613035789197","4000415028701","4000607854606","6415717409000","4000415025304","4750127300694","7613033963391","90384103","90384066","5902978008307","5900020027689"));
res.add(create("Lebanon", new Locale("ar", "LB"),"0735143083626","5410677110752","0735143009145","6291003203527","3596710081738","0735143003044"));
res.add(create("Liechtenstein", new Locale("de", "LI"),"7614200110211"));
res.add(create("Lithuania", new Locale("lt", "LT"),"1702881020007","2000228316639","80177609","80052760","3800020423578","5900437005133","40561073","20636838","5900278011058","7613035789197","4000415028701","4000607854606","6415717409000","4000415025304","7613033963391","90384103","90384066","4770959440962","5900020027689"));
res.add(create("Luxembourg", new Locale("lb", "LU"),"8076802085981","5450168551633","4006040329039","3229820167398","5449000000996","54491472","4104420209336","7622210995063","3165440007808","4260489091043","3254568020230","5400134350104","3274080005003","8003892007432","8008698002100","8003655122501","5410063004238","3228022150078","4011100005846","5449000265104"));
res.add(create("Macedonia (Former Yugoslav Republic of)", new Locale("mk", "MK"),"7622210642189","7622210642134","7622210642196","8606014409031","3850108020182","8600116000073","8600939212257","5204739612649","7622210397119","8600116000301","8600946862018","9120025838981","8600939212608","8600043001105","8600043022469","8606014409093"));
res.add(create("Madagascar", new Locale("mg", "MG"),"9501046019205","3700005003064","3700005002357","3263852669116","6901209197789","3760153580909"));
res.add(create("Malaysia", new Locale("ms", "MY"),"9315090202014","9316434288602","9556587102053","0024000163015","9555653100368","8888140030734","9557062321136","9316434288107","9556570312131"));
res.add(create("Mali", new Locale("fr", "ML"),"5449000000996","3268840001008","3274080005003","3017624047813","5775345138880","3057640229138"));
res.add(create("Malta", new Locale("mt", "MT"),"20471613","8000500310427","5000159451666","7622300632762","5359902778858"));
res.add(create("Martinique", new Locale("fr", "MQ"),"3182180012183","3368959945573","5010477348678","5449000000996","80176800","15600703","3274080005003","3256225042364","6111069000499","3263857004615","3329120001054","3017760826174","3256225721603","3256225428762","3256221664010","3256222254203","3330261040604","3392590810938","3533630086542","3415581319149"));
res.add(create("Mauritius", new Locale("mfe", "MU"),"3046920029759","5053990119004","05428212","4770149208129","3258561140292","8437011503077"));
res.add(create("Mexico", new Locale("es", "MX"),"7503018034058","7501000106301","7501055909582","7501295600621","7501020553154","7501020553147","7501055900077","04842293","7501055900060","7501058611857","7501024580217","7501020543032","7501295600713","7501791663663","7502252481789","7501032399238","8412224040175","8410069014276","8411555100152","0031200610355"));
res.add(create("Moldova", new Locale("ro", "MD"),"4008400290126","5900259056207","5941047814005","5941047829214","5942289000751","5941000024700","4840095009238","4840095001805","4841658000396","4841658000327","8000500119792"));
res.add(create("Monaco", new Locale("fr", "MC"),"8411317301285","3256225721603","8000643000384","3155250003312","3324498000746","3111902100051","3661405006973","3560070847945","3017760404396","3478220003519"));
res.add(create("Montenegro", new Locale("srp", "ME"),"8076800376999","8606014409048","8600102164802","40111216","9006900014872","54491069","8606014409031","8600116000073","8600498176359","5204739612649","9004380079602","7622210254405","5449000214775","8600116000301","8607100572691","8600939550076","8606018730469","8606104925991","4018077629334","8606107544144"));
res.add(create("Morocco", new Locale("fr", "MA"),"6111254878414","26035277","5449000000996","6111035000058","6111249941321","8411547001085","8410376036169","8000500037560","6111242923577","4017100263101","6111251420166","8410000810004","6111203002242","3017620401473","6111242101142","6111242104198","6111262580149","5410041001204","6111021090049","3229820794754"));
res.add(create("New Caledonia", new Locale("fr", "NC"),"5449000000996","9421903084293","3222473667215","9310055536623","3161911364531","3073780972703","3245414620131","87157246","9310072001777","3263851927019","3263859392017","3297760097143","3523230027946","3292590874094","3222471973530","3760020506698","3266191080994","3266191008035","3263850764417","3222474768430"));
res.add(create("New Zealand", new Locale("mi", "NZ"),"9300633340049","9300633443337","9300633919061","9300633905118","9300633953966","9400597019620","3760150148607","3760150142933","9310072001777","8076802085851","9400547007837","9556041780346","9415748021346","9311627010183","9310055536395","8714100897935","9310072021584","9556041611121","9415472101109","0637480010580"));
res.add(create("Niger", new Locale("fr", "NE"),"5290074003198"));
res.add(create("Norway", new Locale("nb", "NO"),"4000417702005","7622210477439","8713800132131","5021554989172","7041910057282","8008698007303","8076809545440","5021554989196","7040110642106","8714882001018","4000417269003","4251097402659","7622210626028","8410076481597","0200024009939","5712840020012","7035620024979","7039010016322","4001724017547","7312787740233"));
res.add(create("Oman", new Locale("ar", "OM"),"0032894010919"));
res.add(create("Pakistan", new Locale("en", "PK"),"5449000051981"));
res.add(create("Peru", new Locale("es", "PE"),"2644"));
res.add(create("Philippines", new Locale("en", "PH"),"0750515018402","0750515021228"));
res.add(create("Poland", new Locale("pl", "PL"),"8000430900231","5900531003202","5900531003400","90426230","5902581687593","5900354038221","5902180040102","5900977008779","20053963","5901588017938","5901588018409","5900500027796","5900500024337","5900334012869","5900334006363","5900334013316","5902581687609","5941021000639","5904215138747","5900102005550"));
res.add(create("Portugal", new Locale("pt", "PT"),"8000430900231","8076802085981","5601002009012","3046920028363","3596710354986","8410069014894","40052403","5449000000996","8410770100022","5600445608530","8436048414721","5601009160068","20177201","3250391997688","5601151543313","8722700462958","5601312047872","20413422","5601151213308","3250390221302"));
res.add(create("Puerto Rico", new Locale("es", "PR"),"7502270310320"));
res.add(create("Qatar", new Locale("ar", "QA"),"5000159031103"));
res.add(create("Republic of the Congo (Congo-Brazzaville)", new Locale("fr", "CG"),"6044000007250"));
res.add(create("Reunion", new Locale("fr", "RE"),"3017760314190","8000500227848","5449000000439","3560070309238","3412290057447","5449000000996","8710438110197","3350033118072","8410707110452","80176800","5449000050205","0653884020192","8888196172211","5202425000374","3368954300940","3286011100312","3061830001237","3222471092187","3222476078872","3308751000216"));
res.add(create("Romania", new Locale("ro", "RO"),"20280239","4008400290126","90426230","5900951247897","3046920028363","3038354199603","5941021001674","5941021000639","5904215138747","7622210836687","4311596435982","40052403","4009176454958","8601900001047","5449000240156","5941006101566","5941868200087","7622210633354","5949034000820","7613034955098"));
res.add(create("Russia", new Locale("ru", "RU"),"8000430900231","4000417702005","8076800195057","4600300075409","4000417933003","3596710309115","4810410062897","3046920028363","3256221111774","5900259056207","8023678162360","5000157024671","6411402976802","3076820002064","4600935000418","5901067455077","3017620429484","8008698007303","40084701","3256225042067"));
res.add(create("Saint Kitts and Nevis", new Locale("en", "KN"),"0041303014912"));
res.add(create("Saint Martin (French part)", new Locale("fr", "MF"),"3368954000147","3228020160093","3032222970264"));
res.add(create("Saint Pierre and Miquelon", new Locale("fr", "PM"),"3019080067015","0064100238220","3263851990419","3263851990518","3250390778851","0060410017982","3250390657330","06401612","3199240000752","3250390146063","3250390779087","3263851505118","3263850426018","3263851990310","3250390000518","3250390111054","3103220009413","3218930128009","3451791340399","3083013804"));
//res.add(create("San Marino", new Locale("it", "SM"),[]));
res.add(create("Saudi Arabia", new Locale("ar", "SA"),"5449000000996","40111445","5941192110335","3017620429484","8996001320839","5941047829214","4000415043100","4000415025304","9557062321136","9006900014360","0737666003167","8595229909286"));
res.add(create("Sénégal", new Locale("fr", "SN"),"5449000000996","3596710022694","3073780972703","8010817105319","8480017741349","3263820006004","3760091720207","3700328403114","3464130002759","3250547014115","3222471131626","3228024910366","8725000156992","6044000019024","5901882012493","8718226323071","6044000007250"));
res.add(create("Serbia", new Locale("sr", "RS"),"80177616","8076800195057","8000430386219","5000159459228","54491472","3800205875307","3800205875604","9011900139616","5203064007656","5906425121137","8076800376999","8606014409048","7622210642134","7622210642196","8600102164802","40111216","5400111050447","80761761","3046920028004","8606011898951"));
res.add(create("Seychelles", new Locale("fr", "SC"),"3174660032347"));
res.add(create("Singapore", new Locale("zh-hans", "SG"),"3760152700667","8888026870010","8888196451217","8885012290470","8888196456519","8888196454713","8888196185013","8888026432812","8850161160790","0016300168340","8888030019566","8888010102899","8881304288255","8850025060105","5000159461122","9310155100038","8888010101649","3222473958450","9315536220107","9556183960996"));
res.add(create("Slovakia", new Locale("sk", "SK"),"90426230","5449000000286","4260012620276","7622210835338","5900130015736","5902768862515","9006900014872","8714100659922","5902121000165","5902121024987","5900497330503","40561073","4030387755497","5900966009138","5900552029564","5902097251608","5997347543893","8586008109898","4335896444543","5900020000576"));
res.add(create("Slovenia", new Locale("sl", "SI"),"20906177","3838929513045","4001686834022","4099200130453","80176800","3830067210060","7610700946053","7622210642189","24140836","4014400400007","8076800376999","8023678162360","3838900946701","7622210642134","7622210642196","24060776","20906122","8008698007303","8004225047354","3830023481237"));
res.add(create("South Africa", new Locale("en", "ZA"),"8410076900418","6001052001018","3017620429484","6009188002213","5449000009067","6002870002164","6009198000452","6009188001216","6001704009614","6004923000516","6004052000463","6009880012381","6001299000270","6001032424646","6009900028224","6001068595808","6009900028200","6009510802542","6001068592401","5449000664761"));
//res.add(create("South Georgia and the South Sandwich Islands", new Locale("en", "GS"),[]));
res.add(create("South Korea", new Locale("ko", "KR"),"3222475310829","8801043020756","3178530412567","2000000021345"));
res.add(create("Spain", new Locale("ast", "ES"),"8480000561596","8413100612615","8480000826466","8410408050279","7613036230506","3560070696840","8422584314380","3000027364076","24087643","8429359002008","3700003781162","24021456","8480017142115","8410285114897","8422584315745","8480000109286","3770002675113","20095291","87157239","20452070"));
res.add(create("Swaziland", new Locale("en", "SZ"),"6009198001329","6009705211036","5449000006844"));
res.add(create("Sweden", new Locale("sv", "SE"),"8000430900231","8712566328352","4000417289001","4000417702005","20001308","87157239","5711953035104","6408432087868","7350011740680","3046920029759","20462369","8000430058666","20131968","8000430386219","5449000000439","7312080004025","20543075","9006900204099","20166083","3046920047302"));
res.add(create("Switzerland", new Locale("de", "CH"),"8000430900231","3073780516723","3181232180559","3073780515702","4008258143018","8010721001509","7610809035856","8886303210238","7616700100358","2112767004707","7613034700810","4008258100011","7610800005926","3095758863011","3261055420503","3387390326574","3228886043714","7610200248503","8712566328352","7610845376609"));
res.add(create("Syria", new Locale("ar", "SY"),"9557062321136"));
res.add(create("Taiwan", new Locale("zh-hant", "TW"),"5010029000023","4710060010180","4710060010012","8996001320839","3560070749027","4710783055116","4710018000102","3461820210371","4712929110178","4710209334115","4710018146305","4710018149108","1490274741355","4710126040595","4710128020106","4710209705113","4719859741397","4710176039136","4710143930510","4710063337710"));
res.add(create("Thailand", new Locale("th", "TH"),"8850045171959","8851351383548","8851028004073","8850123110115","8858684502585","8850125073807","8859501320085","8850188270106","8859473100050","8851013748494","8852021300001","8858893917491","8858998581115","8850088601901","8850511221140","8858702410311","8856742000028","8850329145867","8850511221843","8852052110501"));
res.add(create("The Netherlands", new Locale("nl", "NL"),"8000430900231","5412929001092","8712566328352","20799892","3263670041255","40097138","5411188094159","1101803","8714685902086","3428420053203","5053827167666","20622411","3380380072413","3760052232299","5034525010119","4012359113108","5411188123446","8714100873885","8008698003213","20195090"));
res.add(create("Tunisia", new Locale("ar", "TN"),"6194002510316","8000500037560","6191544100609","6194019605258","6194029100415","11940016","6191513501031","6194001800111","6194043001255","6194002510064","6191507249635","6194003801895","5000159031103","6194005446100","4025700001023","3046920023009","6191507249505","6194005413058","6194007510014","3760113766480"));
res.add(create("Turkey", new Locale("tr", "TR"),"8690575064310","4012625419910","4000415043100","8690574102457","4000415025304","8690504025207","8690565002988","8690787311059","8690777564007"));
res.add(create("Ukraine", new Locale("uk", "UA"),"7622210659156","5901367001240","5901367001172","4823077614767","4840095009238","4840095001805","90384103","90384066"));
res.add(create("United Arab Emirates", new Locale("ar", "AE"),"5941192110335","8410076800442","7613036438100","8410707000197","5000159031103","5900189004491","6290400013425","0863769000229","5000127049307","0050700559124"));
res.add(create("United Kingdom", new Locale("en", "GB"),"3760224570167","3180950004802","5053827101424","3180950006981","3240930313505","3180950001801","0011110807571","3154230010197","3073780977524","8000430900231","3449865293375","3073780516723","3181232180559","3180950007254","5050854766947","3180950007308","8480000561596","3073780515702","3245390181022","3180950008114"));
res.add(create("United States of America", new Locale("en", "US"),"0011110807571","0694990008506","0812475012293","0013800188076","0061954004452","0083737250122","0052603065061","0084253222143","0061954000539","0816979010250","0058449870241","0786162110008","5053990119004","0024463061163","0016000275270","0760712040014","0013409000335","36300416","0051000204721","0016229901141"));
res.add(create("Uruguay", new Locale("es", "UY"),"8076800376999","8019428000013","7730303009358"));
res.add(create("Vanuatu", new Locale("bi", "VU"),"3245390149701"));
res.add(create("Vietnam", new Locale("vi", "VN"),"8936079120276","8851978808158","8713600186211"));
res.add(create("Yemen", new Locale("ar", "YE"),"9501101320079"));
return res;
}
}
|
package org.chromium.chrome.browser.enhancedbookmarks;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.BookmarksBridge.BookmarkItem;
import org.chromium.chrome.browser.BookmarksBridge.BookmarkModelObserver;
import org.chromium.chrome.browser.enhanced_bookmarks.EnhancedBookmarksModel;
import org.chromium.chrome.browser.widget.EmptyAlertEditText;
import org.chromium.components.bookmarks.BookmarkId;
import java.util.ArrayList;
import java.util.List;
/**
* Activity that allows a user to add or edit a bookmark folder. This activity has two modes: adding
* mode and editing mode. Depending on different modes, it should be started via two static creator
* functions.
*/
public class EnhancedBookmarkAddEditFolderActivity extends EnhancedBookmarkActivityBase implements
View.OnClickListener {
static final String INTENT_IS_ADD_MODE = "EnhancedBookmarkAddEditFolderActivity.isAddMode";
static final String INTENT_BOOKMARK_ID = "EnhancedBookmarkAddEditFolderActivity.BookmarkId";
static final String
INTENT_CREATED_BOOKMARK = "EnhancedBookmarkAddEditFolderActivity.createdBookmark";
static final int PARENT_FOLDER_REQUEST_CODE = 10;
private boolean mIsAddMode;
private BookmarkId mParentId;
private EnhancedBookmarksModel mModel;
private TextView mParentTextView;
private EmptyAlertEditText mFolderTitle;
private ImageButton mBackButton;
private ImageButton mSaveButton;
// Add mode member variable
private List<BookmarkId> mBookmarksToMove;
// Edit mode member variables
private BookmarkId mFolderId;
private ImageButton mDeleteButton;
private BookmarkModelObserver mBookmarkModelObserver = new BookmarkModelObserver() {
@Override
public void bookmarkModelChanged() {
if (mIsAddMode) {
if (mModel.doesBookmarkExist(mParentId)) updateParent(mParentId);
else updateParent(mModel.getDefaultFolder());
} else {
assert mModel.doesBookmarkExist(mFolderId);
updateParent(mModel.getBookmarkById(mFolderId).getParentId());
}
}
@Override
public void bookmarkNodeMoved(BookmarkItem oldParent, int oldIndex, BookmarkItem newParent,
int newIndex) {
if (!oldParent.getId().equals(newParent.getId())
&& mModel.getChildAt(newParent.getId(), newIndex).equals(mFolderId)) {
updateParent(newParent.getId());
}
}
@Override
public void bookmarkNodeRemoved(BookmarkItem parent, int oldIndex, BookmarkItem node,
boolean isDoingExtensiveChanges) {
if (!node.getId().equals(mFolderId)) return;
finish();
}
};
/**
* Starts an edit folder activity. Require the context to fire an intent.
*/
public static void startEditFolderActivity(Context context, BookmarkId idToEdit) {
Intent intent = new Intent(context, EnhancedBookmarkAddEditFolderActivity.class);
intent.putExtra(INTENT_IS_ADD_MODE, false);
intent.putExtra(INTENT_BOOKMARK_ID, idToEdit.toString());
context.startActivity(intent);
}
/**
* Starts an add folder activity. This method should only be called by
* {@link EnhancedBookmarkFolderSelectActivity}.
*/
public static void startAddFolderActivity(EnhancedBookmarkFolderSelectActivity activity,
List<BookmarkId> bookmarksToMove) {
assert bookmarksToMove.size() > 0;
Intent intent = new Intent(activity, EnhancedBookmarkAddEditFolderActivity.class);
intent.putExtra(INTENT_IS_ADD_MODE, true);
ArrayList<String> bookmarkStrings = new ArrayList<>(bookmarksToMove.size());
for (BookmarkId id : bookmarksToMove) {
bookmarkStrings.add(id.toString());
}
intent.putStringArrayListExtra(
EnhancedBookmarkFolderSelectActivity.INTENT_BOOKMARKS_TO_MOVE, bookmarkStrings);
activity.startActivityForResult(intent,
EnhancedBookmarkFolderSelectActivity.CREATE_FOLDER_REQUEST_CODE);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EnhancedBookmarkUtils.setTaskDescriptionInDocumentMode(this,
getString(R.string.enhanced_bookmark_action_bar_edit_folder));
mModel = new EnhancedBookmarksModel();
mModel.addModelObserver(mBookmarkModelObserver);
mIsAddMode = getIntent().getBooleanExtra(INTENT_IS_ADD_MODE, false);
if (mIsAddMode) {
List<String> stringList = getIntent().getStringArrayListExtra(
EnhancedBookmarkFolderSelectActivity.INTENT_BOOKMARKS_TO_MOVE);
mBookmarksToMove = new ArrayList<>(stringList.size());
for (String string : stringList) {
mBookmarksToMove.add(BookmarkId.getBookmarkIdFromString(string));
}
} else {
mFolderId = BookmarkId.getBookmarkIdFromString(
getIntent().getStringExtra(INTENT_BOOKMARK_ID));
}
setContentView(R.layout.eb_add_edit_folder_activity);
TextView dialogTitle = (TextView) findViewById(R.id.dialog_title);
mParentTextView = (TextView) findViewById(R.id.parent_folder);
mFolderTitle = (EmptyAlertEditText) findViewById(R.id.folder_title);
mDeleteButton = (ImageButton) findViewById(R.id.delete);
mBackButton = (ImageButton) findViewById(R.id.back);
mSaveButton = (ImageButton) findViewById(R.id.save);
mBackButton.setOnClickListener(this);
mSaveButton.setOnClickListener(this);
mParentTextView.setOnClickListener(this);
mDeleteButton.setOnClickListener(this);
if (mIsAddMode) {
mDeleteButton.setVisibility(View.GONE);
dialogTitle.setText(R.string.add_folder);
updateParent(mModel.getDefaultFolder());
} else {
// Edit mode
mSaveButton.setVisibility(View.GONE);
dialogTitle.setText(R.string.edit_folder);
BookmarkItem bookmarkItem = mModel.getBookmarkById(mFolderId);
updateParent(bookmarkItem.getParentId());
mFolderTitle.setText(bookmarkItem.getTitle());
}
mParentTextView.setText(mModel.getBookmarkTitle(mParentId));
}
@Override
public void onClick(View v) {
if (v == mParentTextView) {
if (mIsAddMode) {
EnhancedBookmarkFolderSelectActivity.startNewFolderSelectActivity(this,
mBookmarksToMove);
} else {
EnhancedBookmarkFolderSelectActivity.startFolderSelectActivity(this, mFolderId);
}
} else if (v == mSaveButton) {
assert mIsAddMode;
if (save()) finish();
} else if (v == mBackButton) {
onBackPressed();
} else if (v == mDeleteButton) {
// When deleting, wait till the model has done its job and notify us via model observer,
// and then we finish this activity.
mModel.deleteBookmarks(mFolderId);
}
}
@Override
public void onBackPressed() {
if (!mIsAddMode) {
if (save()) finish();
} else {
super.onBackPressed();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
assert mIsAddMode;
if (requestCode == PARENT_FOLDER_REQUEST_CODE && resultCode == RESULT_OK) {
BookmarkId selectedBookmark = BookmarkId.getBookmarkIdFromString(data.getStringExtra(
EnhancedBookmarkFolderSelectActivity.INTENT_SELECTED_FOLDER));
updateParent(selectedBookmark);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mModel.removeModelObserver(mBookmarkModelObserver);
mModel.destroy();
mModel = null;
}
private boolean save() {
if (!mFolderTitle.validate()) {
mFolderTitle.requestFocus();
return false;
}
String folderTitle = mFolderTitle.getTrimmedText();
if (mIsAddMode) {
BookmarkId newFolder = mModel.addFolder(mParentId, 0, folderTitle);
Intent intent = new Intent();
intent.putExtra(INTENT_CREATED_BOOKMARK, newFolder.toString());
setResult(RESULT_OK, intent);
} else {
mModel.setBookmarkTitle(mFolderId, folderTitle);
}
return true;
}
private void updateParent(BookmarkId newParent) {
mParentId = newParent;
mParentTextView.setText(mModel.getBookmarkTitle(mParentId));
}
}
|
package com.archimatetool.editor.diagram.figures.connections;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.PolylineConnection;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.PointList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Rectangle;
import com.archimatetool.editor.diagram.figures.PolarPoint;
import com.archimatetool.editor.preferences.IPreferenceConstants;
import com.archimatetool.editor.preferences.Preferences;
public class RoundedPolylineConnection extends PolylineConnection {
// Maximum radius length from line-curves
final double CURVE_MAX_RADIUS = 14.0;
// Radius from line-jumps
final double JUMP_MAX_RADIUS = 5.0;
// Number of intermediate points for circle and ellipse approximation
final double MAX_ITER = 15.0;
// Constants
final double SQRT2 = Math.sqrt(2.0);
final double PI34 = Math.PI * 3.0 / 4.0;
final double PI2 = Math.PI * 2.0;
final double PI12 = Math.PI * 1.0 / 2.0;
@Override
public Rectangle getBounds() {
if (Preferences.STORE.getBoolean(IPreferenceConstants.USE_LINE_JUMPS))
return super.getBounds().getCopy().expand(10, 10);
else
return super.getBounds();
}
@Override
@SuppressWarnings("rawtypes")
protected void outlineShape(Graphics g) {
// Original list of bendpoints
PointList bendpoints = getPoints();
// List of bendpoints and points added to draw line-curves and line-jumps
PointList linepoints = new PointList();
// List of all connections on current diagram
ArrayList connections = getAllConnections();
if (bendpoints.size() == 0) {
return;
}
// Start point is the first "previous" point
Point prev = bendpoints.getPoint(0);
// Main loop: check all bendpoints and add curve is needed
for (int i = 1; i < bendpoints.size(); i++) {
// Current bendpoint
Point bp = bendpoints.getPoint(i);
// If last bendpoint, define points for line segment
// and then draw polyline
if (i == bendpoints.size() - 1) {
addSegment(g, prev, bp, connections, linepoints);
continue;
}
// Next bendpoint
Point next = bendpoints.getPoint(i + 1);
// If line-curves are enabled draw bendpoints using ellipse approximation
if(Preferences.STORE.getBoolean(IPreferenceConstants.USE_LINE_CURVES)) {
// Switch to polar coordinates
PolarPoint prev_p = new PolarPoint(bp, prev);
PolarPoint next_p = new PolarPoint(bp, next);
// Compute arc angle between source and target
// and be sure that arc angle is positive and less than PI
double arc = next_p.theta - prev_p.theta;
arc = (arc + PI2) % (PI2);
// Do we have to go from previous to next or the opposite
boolean prev2next = arc < Math.PI ? true : false;
arc = prev2next ? arc : PI2 - arc;
// Check bendpoint radius against source and target
double bp_radius = CURVE_MAX_RADIUS;
bp_radius = Math.min(bp_radius, prev_p.r / 2.0);
bp_radius = Math.min(bp_radius, next_p.r / 2.0);
// Find center of bendpoint arc
PolarPoint center_p = new PolarPoint(bp_radius, (prev2next ? prev_p.theta : next_p.theta) + arc / 2.0);
Point center = center_p.toAbsolutePoint(bp);
// Compute source and target of bendpoint arc
double arc_radius = bp_radius * Math.sin(arc / 2.0);
double start_angle = (Math.PI + arc) / 2.0 + center_p.theta;
double full_angle = Math.PI - arc;
Point bpprev;
Point bpnext;
if (!prev2next) {
bpprev = new PolarPoint(arc_radius, start_angle).toAbsolutePoint(center);
bpnext = new PolarPoint(arc_radius, start_angle + full_angle).toAbsolutePoint(center);
} else {
bpprev = new PolarPoint(arc_radius, start_angle + full_angle).toAbsolutePoint(center);
bpnext = new PolarPoint(arc_radius, start_angle).toAbsolutePoint(center);
}
// Now that bendpoint position has been refined we can add line segment
addSegment(g, prev, bpprev, connections, linepoints);
// Create circle approximation
for (double a = 1; a < MAX_ITER; a++) {
if (prev2next)
linepoints.addPoint(new PolarPoint(arc_radius, start_angle + full_angle * (1 - a/ MAX_ITER)).toAbsolutePoint(center));
else
linepoints.addPoint(new PolarPoint(arc_radius, start_angle + full_angle * a / MAX_ITER).toAbsolutePoint(center));
}
// Prepare next iteration
prev = bpnext;
} else {
// Add line segment
addSegment(g, prev, bp, connections, linepoints);
// Prepare next iteration
prev = bp;
}
}
// Finally draw the polyLine
g.drawPolyline(linepoints);
}
@SuppressWarnings({ "rawtypes" })
private void addSegment(Graphics g, Point start, Point end, ArrayList connections, PointList linepoints){
// List of crossing points
ArrayList<Point> crosspoints = new ArrayList<Point>();
int radius = (int) JUMP_MAX_RADIUS;
// Add start point to the list
linepoints.addPoint(start);
// If line-jumps are enabled, draw them using half circles
if (Preferences.STORE.getBoolean(IPreferenceConstants.USE_LINE_JUMPS)) {
// Compute angle between line segment and horizontal line
PolarPoint end_p = new PolarPoint(start, end);
double angle = end_p.theta % Math.PI;
boolean reverse = (end_p.theta != angle);
// For each other connection, check if a crossing point exist.
// If yes, add it to the list
for (Iterator I = connections.iterator(); I.hasNext();) {
RoundedPolylineConnection conn = (RoundedPolylineConnection) I.next();
PointList bendpoints = conn.getPoints();
// Iterate on connection segments
for (int j = 0; j < bendpoints.size() - 1; j++) {
Point bp = bendpoints.getPoint(j);
Point next = bendpoints.getPoint(j + 1);
Point crosspoint = lineIntersect(start, end, bp, next);
// Check if crossing point found and not too close from ends
if (crosspoint != null
&& (new PolarPoint(crosspoint, start)).r > JUMP_MAX_RADIUS
&& (new PolarPoint(crosspoint, end)).r > JUMP_MAX_RADIUS
&& (new PolarPoint(crosspoint, bp)).r > JUMP_MAX_RADIUS
&& (new PolarPoint(crosspoint, next)).r > JUMP_MAX_RADIUS) {
double con_angle = ((new PolarPoint(bp, next)).theta % Math.PI);
if (angle > con_angle && !crosspoints.contains(crosspoint))
crosspoints.add(crosspoint);
}
}
}
// If crossing points found, render them using a half circle
if (crosspoints.size() != 0) {
// Sort crosspoints from start to end
crosspoints.add(start);
Collections.sort(crosspoints, new PointCompare());
if (crosspoints.get(0) != start) Collections.reverse(crosspoints);
// Do not add start point to the list a second time, so start at i=1
for (int i = 1; i < crosspoints.size(); i++ ) {
for (double a = 0; a <= MAX_ITER; a++) {
if (reverse)
linepoints.addPoint((new PolarPoint(radius, angle - a*Math.PI/MAX_ITER)).toAbsolutePoint(crosspoints.get(i)));
else
linepoints.addPoint((new PolarPoint(radius, angle - Math.PI + a*Math.PI/MAX_ITER)).toAbsolutePoint(crosspoints.get(i)));
}
}
}
}
// Add end point to the list
linepoints.addPoint(end);
}
@SuppressWarnings("rawtypes")
private ArrayList getAllConnections() {
ArrayList result = new ArrayList();
getAllConnections(getRoot(), result);
return result;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void getAllConnections(IFigure figure, ArrayList list) {
for (Iterator I = figure.getChildren().iterator(); I.hasNext();) {
IFigure child = (IFigure) I.next();
if (child == this)
continue;
getAllConnections(child, list);
if (!(child instanceof RoundedPolylineConnection))
continue;
list.add(child);
}
}
private IFigure getRoot() {
IFigure figure = this;
while (figure.getParent() != null)
figure = figure.getParent();
return figure;
}
private static Point lineIntersect(Point p1, Point p2, Point p3, Point p4) {
double denom = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);
if (denom == 0.0) { // Lines are parallel.
return null;
}
double ua = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x))/denom;
double ub = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x))/denom;
if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) {
// Get the intersection point.
Point c = new Point((int) (p1.x + ua*(p2.x - p1.x)), (int) (p1.y + ua*(p2.y - p1.y)));
Rectangle r1 = new Rectangle(p1, p2);
Rectangle r2 = new Rectangle(p3, p4);
if (r1.contains(c) && r2.contains(c)
&& !c.equals(p1.x, p1.y)
&& !c.equals(p2.x, p2.y)
&& !c.equals(p3.x, p3.y)
&& !c.equals(p4.x, p4.y))
return c;
else
return null;
}
return null;
}
private static class PointCompare implements Comparator<Point> {
@Override
public int compare(final Point a, final Point b) {
int delta_x = a.x - b.x;
int delta_y = a.y - b.y;
if (Math.abs(delta_x) > Math.abs(delta_y)) {
return (int) Math.signum(delta_x);
} else {
return (int) Math.signum(delta_y);
}
}
}
}
|
package uk.org.taverna.scufl2.translator.t2flow;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import uk.org.taverna.scufl2.api.annotation.Revision;
import uk.org.taverna.scufl2.api.common.Named;
import uk.org.taverna.scufl2.api.common.NamedSet;
import uk.org.taverna.scufl2.api.common.Scufl2Tools;
import uk.org.taverna.scufl2.api.common.URITools;
import uk.org.taverna.scufl2.api.configurations.Configuration;
import uk.org.taverna.scufl2.api.container.WorkflowBundle;
import uk.org.taverna.scufl2.api.core.BlockingControlLink;
import uk.org.taverna.scufl2.api.core.ControlLink;
import uk.org.taverna.scufl2.api.core.DataLink;
import uk.org.taverna.scufl2.api.core.Processor;
import uk.org.taverna.scufl2.api.core.Workflow;
import uk.org.taverna.scufl2.api.dispatchstack.DispatchStackLayer;
import uk.org.taverna.scufl2.api.io.ReaderException;
import uk.org.taverna.scufl2.api.iterationstrategy.IterationStrategyNode;
import uk.org.taverna.scufl2.api.iterationstrategy.IterationStrategyStack;
import uk.org.taverna.scufl2.api.iterationstrategy.IterationStrategyTopNode;
import uk.org.taverna.scufl2.api.iterationstrategy.PortNode;
import uk.org.taverna.scufl2.api.port.InputActivityPort;
import uk.org.taverna.scufl2.api.port.InputProcessorPort;
import uk.org.taverna.scufl2.api.port.InputWorkflowPort;
import uk.org.taverna.scufl2.api.port.OutputActivityPort;
import uk.org.taverna.scufl2.api.port.OutputProcessorPort;
import uk.org.taverna.scufl2.api.port.OutputWorkflowPort;
import uk.org.taverna.scufl2.api.port.ReceiverPort;
import uk.org.taverna.scufl2.api.port.SenderPort;
import uk.org.taverna.scufl2.api.profiles.ProcessorBinding;
import uk.org.taverna.scufl2.api.profiles.ProcessorInputPortBinding;
import uk.org.taverna.scufl2.api.profiles.ProcessorOutputPortBinding;
import uk.org.taverna.scufl2.api.profiles.Profile;
import uk.org.taverna.scufl2.api.property.PropertyLiteral;
import uk.org.taverna.scufl2.api.property.PropertyObject;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.Activity;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.AnnotatedGranularDepthPort;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.AnnotatedGranularDepthPorts;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.AnnotatedPorts;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.AnnotationAssertionImpl.NetSfTavernaT2AnnotationAnnotationAssertionImpl;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.AnnotationChain;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.Annotations;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.Condition;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.Conditions;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.ConfigBean;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.CrossProduct;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.Dataflow;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.Datalinks;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.DepthPort;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.DepthPorts;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.DispatchLayer;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.DispatchStack;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.DotProduct;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.GranularDepthPort;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.GranularDepthPorts;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.IterationNode;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.IterationNodeParent;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.Link;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.LinkType;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.Mapping;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.ObjectFactory;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.Port;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.PortProduct;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.Processors;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.Raven;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.Role;
import uk.org.taverna.scufl2.xml.t2flow.jaxb.TopIterationNode;
public class T2FlowParser {
private static final String T2FLOW_EXTENDED_XSD = "xsd/t2flow-extended.xsd";
@SuppressWarnings("unused")
private static final String T2FLOW_XSD = "xsd/t2flow.xsd";
private static final Logger logger = Logger.getLogger(T2FlowParser.class
.getCanonicalName());
public static final URI ravenURI = URI
.create("http://ns.taverna.org.uk/2010/xml/t2flow/raven/");
public static final URI configBeanURI = URI
.create("http://ns.taverna.org.uk/2010/xml/t2flow/configbean/");
public static <T extends Named> T findNamed(Collection<T> namedObjects,
String name) {
for (T named : namedObjects) {
if (named.getName().equals(name)) {
return named;
}
}
return null;
}
protected ThreadLocal<ParserState> parserState = new ThreadLocal<ParserState>() {
@Override
protected ParserState initialValue() {
return new ParserState();
};
};
private static Scufl2Tools scufl2Tools = new Scufl2Tools();
private static URITools uriTools = new URITools();
protected Set<T2Parser> t2Parsers = null;
protected final JAXBContext jaxbContext;
private boolean strict = false;
private boolean validating = false;
public final boolean isValidating() {
return validating;
}
public final void setValidating(boolean validating) {
this.validating = validating;
}
protected ServiceLoader<T2Parser> discoveredT2Parsers;
protected final ThreadLocal<Unmarshaller> unmarshaller;
public T2FlowParser() throws JAXBException {
jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
unmarshaller = new ThreadLocal<Unmarshaller>() {
@Override
protected Unmarshaller initialValue() {
try {
return jaxbContext.createUnmarshaller();
} catch (JAXBException e) {
logger.log(Level.SEVERE, "Could not create unmarshaller", e);
return null;
}
}
};
}
protected ReceiverPort findReceiverPort(Workflow wf, Link sink)
throws ReaderException {
String portName = sink.getPort();
if (portName == null) {
throw new ReaderException("Port name not specified");
}
String processorName = sink.getProcessor();
if (processorName == null) {
if (sink.getType().equals(LinkType.PROCESSOR)) {
throw new ReaderException(
"Link type was processor, but no processor name found");
}
OutputWorkflowPort candidate = wf.getOutputPorts().getByName(
portName);
if (candidate == null) {
throw new ReaderException("Link to unknown workflow port "
+ portName);
}
return candidate;
} else {
if (sink.getType().equals(LinkType.DATAFLOW)) {
throw new ReaderException(
"Link type was dataflow, but processor name was found");
}
Processor processor = wf.getProcessors().getByName(processorName);
if (processor == null) {
throw new ReaderException("Link to unknown processor "
+ processorName);
}
InputProcessorPort candidate = processor.getInputPorts().getByName(
portName);
if (candidate == null) {
throw new ReaderException("Link to unknown port " + portName
+ " in " + processorName);
}
return candidate;
}
}
protected SenderPort findSenderPort(Workflow wf, Link source)
throws ReaderException {
if (source.getType().equals(LinkType.MERGE)) {
throw new ReaderException(
"Link type Merge unexpected for sender ports");
}
String portName = source.getPort();
if (portName == null) {
throw new ReaderException("Port name not specified");
}
String processorName = source.getProcessor();
if (processorName == null) {
if (source.getType().equals(LinkType.PROCESSOR)) {
throw new ReaderException(
"Link type was processor, but no processor name found");
}
InputWorkflowPort candidate = wf.getInputPorts()
.getByName(portName);
if (candidate == null) {
throw new ReaderException("Link from unknown workflow port "
+ portName);
}
return candidate;
} else {
if (source.getType().equals(LinkType.DATAFLOW)) {
throw new ReaderException(
"Link type was dataflow, but processor name was found");
}
Processor processor = wf.getProcessors().getByName(processorName);
if (processor == null) {
throw new ReaderException("Link from unknown processor "
+ processorName);
}
OutputProcessorPort candidate = processor.getOutputPorts()
.getByName(portName);
if (candidate == null) {
throw new ReaderException("Link from unknown port " + portName
+ " in " + processorName);
}
return candidate;
}
}
protected T2Parser getT2Parser(URI classURI) {
for (T2Parser t2Parser : getT2Parsers()) {
if (t2Parser.canHandlePlugin(classURI)) {
return t2Parser;
}
}
return null;
}
public synchronized Set<T2Parser> getT2Parsers() {
Set<T2Parser> parsers = t2Parsers;
if (parsers != null) {
return parsers;
}
parsers = new HashSet<T2Parser>();
// TODO: Do we need to cache this, or is the cache in ServiceLoader
// fast enough?
if (discoveredT2Parsers == null) {
discoveredT2Parsers = ServiceLoader.load(T2Parser.class);
}
for (T2Parser parser : discoveredT2Parsers) {
parsers.add(parser);
}
return parsers;
}
public synchronized void setT2Parsers(Set<T2Parser> parsers) {
this.t2Parsers = parsers;
}
public boolean isStrict() {
return strict;
}
protected void makeProfile(uk.org.taverna.scufl2.xml.t2flow.jaxb.Workflow wf) {
Profile profile = new Profile(wf.getProducedBy());
profile.setParent(parserState.get().getCurrentWorkflowBundle());
parserState.get().getCurrentWorkflowBundle().setMainProfile(profile);
parserState.get().setCurrentProfile(profile);
}
private URI makeRavenURI(Raven raven, String className) {
if (raven == null) {
return ravenURI.resolve("undefined/" + uriTools.validFilename(className));
}
return ravenURI.resolve(uriTools.validFilename(raven.getGroup()) + "/"
+ uriTools.validFilename(raven.getArtifact()) + "/"
+ uriTools.validFilename(raven.getVersion()) + "/"
+ uriTools.validFilename(className));
}
private URI mapTypeFromRaven(Raven raven, String activityClass)
throws ReaderException {
URI classURI = makeRavenURI(raven, activityClass);
parserState.get().setCurrentT2Parser(null);
T2Parser t2Parser = getT2Parser(classURI);
if (t2Parser == null) {
String message = "Unknown T2 activity " + classURI
+ ", install supporting T2Parser";
if (isStrict()) {
throw new ReaderException(message);
} else {
logger.warning(message);
return classURI;
}
}
parserState.get().setCurrentT2Parser(t2Parser);
return t2Parser.mapT2flowRavenIdToScufl2URI(classURI);
}
protected uk.org.taverna.scufl2.api.activity.Activity parseActivity(
Activity origActivity) throws ReaderException {
Raven raven = origActivity.getRaven();
String activityClass = origActivity.getClazz();
URI activityId = mapTypeFromRaven(raven, activityClass);
uk.org.taverna.scufl2.api.activity.Activity newActivity = new uk.org.taverna.scufl2.api.activity.Activity();
newActivity.setConfigurableType(activityId);
newActivity.setName(parserState.get().getCurrentProcessorBinding()
.getName());
parserState.get().getCurrentProfile().getActivities()
.addWithUniqueName(newActivity);
newActivity.setParent(parserState.get().getCurrentProfile());
return newActivity;
}
protected void parseActivityBinding(Activity origActivity,
int activityPosition) throws ReaderException, JAXBException {
ProcessorBinding processorBinding = new ProcessorBinding();
processorBinding.setName(parserState.get().getCurrentProcessor()
.getName());
parserState.get().getCurrentProfile().getProcessorBindings()
.addWithUniqueName(processorBinding);
processorBinding.setBoundProcessor(parserState.get()
.getCurrentProcessor());
parserState.get().setCurrentProcessorBinding(processorBinding);
uk.org.taverna.scufl2.api.activity.Activity newActivity = parseActivity(origActivity);
parserState.get().setCurrentActivity(newActivity);
parserState.get().getCurrentProfile().getActivities().add(newActivity);
processorBinding.setBoundActivity(newActivity);
processorBinding.setActivityPosition(activityPosition);
parserState.get().setCurrentConfigurable(newActivity);
try {
parseConfiguration(origActivity.getConfigBean(),
Configures.activity);
} catch (JAXBException e) {
if (isStrict()) {
throw e;
}
logger.log(Level.WARNING, "Can't configure activity" + newActivity,
e);
}
parseActivityInputMap(origActivity.getInputMap());
parseActivityOutputMap(origActivity.getOutputMap());
parserState.get().setCurrentConfigurable(null);
parserState.get().setCurrentActivity(null);
parserState.get().setCurrentProcessorBinding(null);
}
enum Configures {
activity, dispatchLayer
};
protected void parseConfiguration(ConfigBean configBean,
Configures configures) throws JAXBException, ReaderException {
// Placeholder to check later if no configuration have been provided
Configuration UNCONFIGURED = new Configuration();
Configuration configuration = UNCONFIGURED;
if (parserState.get().getCurrentT2Parser() == null) {
String message = "No config parser for " + configures
+ parserState.get().getCurrentConfigurable();
if (isStrict()) {
throw new ReaderException(message);
}
return;
}
try {
configuration = parserState.get().getCurrentT2Parser()
.parseConfiguration(this, configBean, parserState.get());
} catch (ReaderException e) {
if (isStrict()) {
throw e;
}
}
if (configuration == null) {
// Perfectly valid - true for say Invoke layer
return;
}
if (configuration == UNCONFIGURED) {
if (isStrict()) {
throw new ReaderException("No configuration returned from "
+ parserState.get().getCurrentT2Parser() + " for "
+ configures
+ parserState.get().getCurrentConfigurable());
}
// We'll have to fake it
configuration = new Configuration();
configuration.setConfigurableType(configBeanURI.resolve("Config"));
URI fallBackURI = configBeanURI.resolve(configBean.getEncoding());
java.util.Map<URI, SortedSet<PropertyObject>> properties = configuration
.getPropertyResource().getProperties();
Object any = configBean.getAny();
Element element = (Element) configBean.getAny();
PropertyLiteral literal = new PropertyLiteral(element);
// literal.setLiteralValue(configBean.getAny().toString());
// literal.setLiteralType(PropertyLiteral.XML_LITERAL);
properties.get(fallBackURI).add(literal);
}
if (configures == Configures.activity) {
configuration.setName(parserState.get().getCurrentActivity()
.getName());
} else {
DispatchStackLayer layer = (DispatchStackLayer) parserState.get().getCurrentConfigurable();
configuration.setName(parserState.get().getCurrentProcessor().getName() +
"-dispatch-" + parserState.get().getCurrentDispatchStack().size());
}
parserState.get().getCurrentProfile().getConfigurations()
.addWithUniqueName(configuration);
configuration.setConfigures(parserState.get().getCurrentConfigurable());
parserState.get().getCurrentProfile().getConfigurations().addWithUniqueName(configuration);
}
public Unmarshaller getUnmarshaller() {
Unmarshaller u = unmarshaller.get();
if (!isValidating() && u.getSchema() != null) {
u.setSchema(null);
} else if (isValidating() && u.getSchema() == null) {
// Load and set schema to validate against
Schema schema;
try {
SchemaFactory schemaFactory = SchemaFactory
.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
List<URI> schemas = getAdditionalSchemas();
URL t2flowExtendedXSD = T2FlowParser.class
.getResource(T2FLOW_EXTENDED_XSD);
schemas.add(t2flowExtendedXSD.toURI());
List<Source> schemaSources = new ArrayList<Source>();
for (URI schemaUri : schemas) {
schemaSources.add(new StreamSource(schemaUri
.toASCIIString()));
}
Source[] sources = schemaSources
.toArray(new Source[schemaSources.size()]);
schema = schemaFactory.newSchema(sources);
} catch (SAXException e) {
throw new RuntimeException("Can't load schemas", e);
} catch (URISyntaxException e) {
throw new RuntimeException("Can't find schemas", e);
} catch (NullPointerException e) {
throw new RuntimeException("Can't find schemas", e);
}
u.setSchema(schema);
}
return u;
}
protected List<URI> getAdditionalSchemas() {
List<URI> uris = new ArrayList<URI>();
for (T2Parser parser : getT2Parsers()) {
List<URI> schemas = parser.getAdditionalSchemas();
if (schemas != null) {
uris.addAll(schemas);
}
}
return uris;
}
protected void parseActivityInputMap(
uk.org.taverna.scufl2.xml.t2flow.jaxb.Map inputMap)
throws ReaderException {
for (Mapping mapping : inputMap.getMap()) {
String fromProcessorOutput = mapping.getFrom();
String toActivityOutput = mapping.getTo();
ProcessorInputPortBinding processorInputPortBinding = new ProcessorInputPortBinding();
InputProcessorPort inputProcessorPort = findNamed(parserState.get()
.getCurrentProcessor().getInputPorts(), fromProcessorOutput);
if (inputProcessorPort == null) {
String message = "Invalid input port binding, "
+ "unknown processor port: " + fromProcessorOutput
+ "->" + toActivityOutput + " in "
+ parserState.get().getCurrentProcessor();
if (isStrict()) {
throw new ReaderException(message);
} else {
logger.log(Level.WARNING, message);
continue;
}
}
InputActivityPort inputActivityPort = parserState.get()
.getCurrentActivity().getInputPorts()
.getByName(toActivityOutput);
if (inputActivityPort == null) {
inputActivityPort = new InputActivityPort();
inputActivityPort.setName(toActivityOutput);
inputActivityPort.setParent(parserState.get()
.getCurrentActivity());
parserState.get().getCurrentActivity().getInputPorts()
.add(inputActivityPort);
}
if (inputActivityPort.getDepth() == null) {
inputActivityPort.setDepth(inputProcessorPort.getDepth());
}
processorInputPortBinding.setBoundActivityPort(inputActivityPort);
processorInputPortBinding.setBoundProcessorPort(inputProcessorPort);
parserState.get().getCurrentProcessorBinding()
.getInputPortBindings().add(processorInputPortBinding);
}
}
protected void parseActivityOutputMap(
uk.org.taverna.scufl2.xml.t2flow.jaxb.Map outputMap)
throws ReaderException {
for (Mapping mapping : outputMap.getMap()) {
String fromActivityOutput = mapping.getFrom();
String toProcessorOutput = mapping.getTo();
ProcessorOutputPortBinding processorOutputPortBinding = new ProcessorOutputPortBinding();
OutputProcessorPort outputProcessorPort = findNamed(parserState
.get().getCurrentProcessor().getOutputPorts(),
toProcessorOutput);
if (outputProcessorPort == null) {
String message = "Invalid output port binding, "
+ "unknown processor port: " + fromActivityOutput
+ "->" + toProcessorOutput + " in "
+ parserState.get().getCurrentProcessor();
if (isStrict()) {
throw new ReaderException(message);
} else {
logger.log(Level.WARNING, message);
continue;
}
}
OutputActivityPort outputActivityPort = parserState.get()
.getCurrentActivity().getOutputPorts()
.getByName(fromActivityOutput);
if (outputActivityPort == null) {
outputActivityPort = new OutputActivityPort();
outputActivityPort.setName(fromActivityOutput);
outputActivityPort.setParent(parserState.get()
.getCurrentActivity());
parserState.get().getCurrentActivity().getOutputPorts()
.add(outputActivityPort);
}
if (outputActivityPort.getDepth() == null) {
outputActivityPort.setDepth(outputProcessorPort.getDepth());
}
if (outputActivityPort.getGranularDepth() == null) {
outputActivityPort.setGranularDepth(outputProcessorPort
.getGranularDepth());
}
processorOutputPortBinding.setBoundActivityPort(outputActivityPort);
processorOutputPortBinding
.setBoundProcessorPort(outputProcessorPort);
parserState.get().getCurrentProcessorBinding()
.getOutputPortBindings().add(processorOutputPortBinding);
}
}
protected Workflow parseDataflow(Dataflow df, Workflow wf)
throws ReaderException, JAXBException {
parserState.get().setCurrentWorkflow(wf);
wf.setInputPorts(parseInputPorts(df.getInputPorts()));
wf.setOutputPorts(parseOutputPorts(df.getOutputPorts()));
wf.setProcessors(parseProcessors(df.getProcessors()));
wf.setDataLinks(parseDatalinks(df.getDatalinks()));
wf.setControlLinks(parseControlLinks(df.getConditions()));
Revision revision = parseIdentificationAnnotations(df.getAnnotations());
if (revision != null) {
wf.setCurrentRevision(revision);
}
parserState.get().setCurrentWorkflow(null);
return wf;
}
protected Revision parseIdentificationAnnotations(Annotations annotations) {
SortedMap<Calendar, UUID> revisions = new TreeMap<Calendar, UUID>();
for (JAXBElement<AnnotationChain> el : annotations
.getAnnotationChainOrAnnotationChain22()) {
NetSfTavernaT2AnnotationAnnotationAssertionImpl ann = el.getValue()
.getNetSfTavernaT2AnnotationAnnotationChainImpl()
.getAnnotationAssertions()
.getNetSfTavernaT2AnnotationAnnotationAssertionImpl();
String annClass = ann.getAnnotationBean().getClazz();
if (!annClass
.equals("net.sf.taverna.t2.annotation.annotationbeans.IdentificationAssertion")) {
continue;
}
for (Object obj : ann.getAnnotationBean().getAny()) {
if (!(obj instanceof Element)) {
continue;
}
Element elem = (Element) obj;
if (elem.getNamespaceURI() == null
&& elem.getLocalName().equals("identification")) {
String uuid = elem.getTextContent().trim();
String date = ann.getDate();
Calendar cal = parseDate(date);
revisions.put(cal, UUID.fromString(uuid));
}
}
}
Revision rev = null;
for (Entry<Calendar, UUID> entry : revisions.entrySet()) {
Calendar cal = entry.getKey();
UUID uuid = entry.getValue();
URI uri = Workflow.WORKFLOW_ROOT.resolve(uuid.toString() + "/");
rev = new Revision(uri, rev);
rev.setCreated(cal);
}
return rev;
}
private Calendar parseDate(String dateStr) {
// Based briefly on patterns used by
// com.thoughtworks.xstream.converters.basic.DateConverter
List<String> patterns = new ArrayList<String>();
patterns.add("yyyy-MM-dd HH:mm:ss.S z");
patterns.add("yyyy-MM-dd HH:mm:ss z");
patterns.add("yyyy-MM-dd HH:mm:ssz");
patterns.add("yyyy-MM-dd HH:mm:ss.S 'UTC'");
patterns.add("yyyy-MM-dd HH:mm:ss 'UTC'");
Date date;
for (String pattern : patterns) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern, Locale.ENGLISH);
try {
date = dateFormat.parse(dateStr);
GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"), Locale.ENGLISH);
cal.setTime(date);
return cal;
} catch (ParseException e) {
continue;
}
}
throw new IllegalArgumentException("Can't parse date: " + dateStr);
}
private Set<ControlLink> parseControlLinks(Conditions conditions)
throws ReaderException {
Set<ControlLink> links = new HashSet<ControlLink>();
for (Condition condition : conditions.getCondition()) {
NamedSet<Processor> processors = parserState.get()
.getCurrentWorkflow().getProcessors();
String target = condition.getTarget();
Processor block = processors.getByName(target);
if (block == null && isStrict()) {
throw new ReaderException(
"Unrecognized blocking processor in control link: "
+ target);
}
String control = condition.getControl();
Processor untilFinished = processors.getByName(control);
if (untilFinished == null && isStrict()) {
throw new ReaderException(
"Unrecognized untilFinished processor in control link: "
+ control);
}
links.add(new BlockingControlLink(block, untilFinished));
}
return links;
}
protected Set<DataLink> parseDatalinks(Datalinks origLinks)
throws ReaderException {
HashSet<DataLink> newLinks = new HashSet<DataLink>();
Map<ReceiverPort, AtomicInteger> mergeCounts = new HashMap<ReceiverPort, AtomicInteger>();
for (uk.org.taverna.scufl2.xml.t2flow.jaxb.DataLink origLink : origLinks
.getDatalink()) {
try {
SenderPort senderPort = findSenderPort(parserState.get()
.getCurrentWorkflow(), origLink.getSource());
ReceiverPort receiverPort = findReceiverPort(parserState.get()
.getCurrentWorkflow(), origLink.getSink());
DataLink newLink = new DataLink(parserState.get()
.getCurrentWorkflow(), senderPort, receiverPort);
AtomicInteger mergeCount = mergeCounts.get(receiverPort);
if (origLink.getSink().getType().equals(LinkType.MERGE)) {
if (mergeCount != null && mergeCount.intValue() < 1) {
throw new ReaderException(
"Merged and non-merged links to port "
+ receiverPort);
}
if (mergeCount == null) {
mergeCount = new AtomicInteger(0);
mergeCounts.put(receiverPort, mergeCount);
}
newLink.setMergePosition(mergeCount.getAndIncrement());
} else {
if (mergeCount != null) {
throw new ReaderException(
"More than one link to non-merged port "
+ receiverPort);
}
mergeCounts.put(receiverPort, new AtomicInteger(-1));
}
newLinks.add(newLink);
} catch (ReaderException ex) {
logger.log(Level.WARNING, "Could not translate link:\n"
+ origLink, ex);
if (isStrict()) {
throw ex;
}
continue;
}
}
return newLinks;
}
protected uk.org.taverna.scufl2.api.dispatchstack.DispatchStack parseDispatchStack(
DispatchStack dispatchStack) throws ReaderException {
uk.org.taverna.scufl2.api.dispatchstack.DispatchStack newStack = new uk.org.taverna.scufl2.api.dispatchstack.DispatchStack();
parserState.get().setCurrentDispatchStack(newStack);
try {
for (DispatchLayer dispatchLayer : dispatchStack.getDispatchLayer()) {
DispatchStackLayer layer = parseDispatchStack(dispatchLayer);
newStack.add(layer);
}
} finally {
parserState.get().setCurrentDispatchStack(null);
}
return newStack;
}
protected DispatchStackLayer parseDispatchStack(DispatchLayer dispatchLayer)
throws ReaderException {
DispatchStackLayer dispatchStackLayer = new DispatchStackLayer();
URI typeUri = mapTypeFromRaven(dispatchLayer.getRaven(),
dispatchLayer.getClazz());
dispatchStackLayer.setConfigurableType(typeUri);
parserState.get().setCurrentConfigurable(dispatchStackLayer);
try {
parseConfiguration(dispatchLayer.getConfigBean(),
Configures.dispatchLayer);
} catch (JAXBException ex) {
String message = "Can't parse configuration for dispatch layer in "
+ parserState.get().getCurrentProcessor();
logger.log(Level.WARNING, message, ex);
if (isStrict()) {
throw new ReaderException(message, ex);
}
}
return dispatchStackLayer;
}
@SuppressWarnings("boxing")
protected Set<InputWorkflowPort> parseInputPorts(
AnnotatedGranularDepthPorts originalPorts) throws ReaderException {
Set<InputWorkflowPort> createdPorts = new HashSet<InputWorkflowPort>();
for (AnnotatedGranularDepthPort originalPort : originalPorts.getPort()) {
InputWorkflowPort newPort = new InputWorkflowPort(parserState.get()
.getCurrentWorkflow(), originalPort.getName());
newPort.setDepth(originalPort.getDepth().intValue());
if (!originalPort.getGranularDepth()
.equals(originalPort.getDepth())) {
String message = "Specific input port granular depth not "
+ "supported in scufl2, port " + originalPort.getName()
+ " has depth " + originalPort.getDepth()
+ " and granular depth "
+ originalPort.getGranularDepth();
logger.log(Level.WARNING, message);
if (isStrict()) {
throw new ReaderException(message);
}
}
createdPorts.add(newPort);
}
return createdPorts;
}
protected IterationStrategyStack parseIterationStrategyStack(
uk.org.taverna.scufl2.xml.t2flow.jaxb.IterationStrategyStack originalStack)
throws ReaderException {
IterationStrategyStack newStack = new IterationStrategyStack();
List<TopIterationNode> strategies = originalStack.getIteration()
.getStrategy();
for (TopIterationNode strategy : strategies) {
IterationNode topNode = strategy.getCross();
if (topNode == null) {
topNode = strategy.getDot();
}
if (topNode == null) {
continue;
}
IterationNodeParent parent = (IterationNodeParent) topNode;
if (parent.getCrossOrDotOrPort().isEmpty()) {
continue;
}
try {
newStack.add((IterationStrategyTopNode) parseIterationStrategyNode(topNode));
} catch (ReaderException e) {
logger.warning(e.getMessage());
if (isStrict()) {
throw e;
}
}
}
return newStack;
}
protected IterationStrategyNode parseIterationStrategyNode(
IterationNode topNode) throws ReaderException {
if (topNode instanceof PortProduct) {
PortProduct portProduct = (PortProduct) topNode;
PortNode portNode = new PortNode();
portNode.setDesiredDepth(portProduct.getDepth().intValue());
String name = portProduct.getName();
Processor processor = parserState.get().getCurrentProcessor();
InputProcessorPort inputProcessorPort = processor.getInputPorts()
.getByName(name);
portNode.setInputProcessorPort(inputProcessorPort);
return portNode;
}
IterationStrategyNode node;
if (topNode instanceof DotProduct) {
node = new uk.org.taverna.scufl2.api.iterationstrategy.DotProduct();
} else if (topNode instanceof CrossProduct) {
node = new uk.org.taverna.scufl2.api.iterationstrategy.CrossProduct();
} else {
throw new ReaderException("Invalid node " + topNode);
}
List<IterationStrategyNode> children = (List<IterationStrategyNode>) node;
IterationNodeParent parent = (IterationNodeParent) topNode;
for (IterationNode child : parent.getCrossOrDotOrPort()) {
children.add(parseIterationStrategyNode(child));
}
return node;
}
protected Set<OutputWorkflowPort> parseOutputPorts(
AnnotatedPorts originalPorts) {
Set<OutputWorkflowPort> createdPorts = new HashSet<OutputWorkflowPort>();
for (Port originalPort : originalPorts.getPort()) {
OutputWorkflowPort newPort = new OutputWorkflowPort(parserState
.get().getCurrentWorkflow(), originalPort.getName());
createdPorts.add(newPort);
}
return createdPorts;
}
@SuppressWarnings("boxing")
protected Set<InputProcessorPort> parseProcessorInputPorts(
Processor newProc, DepthPorts origPorts) {
Set<InputProcessorPort> newPorts = new HashSet<InputProcessorPort>();
for (DepthPort origPort : origPorts.getPort()) {
InputProcessorPort newPort = new InputProcessorPort(newProc,
origPort.getName());
newPort.setDepth(origPort.getDepth().intValue());
// TODO: What about InputProcessorPort granular depth?
newPorts.add(newPort);
}
return newPorts;
}
@SuppressWarnings("boxing")
protected Set<OutputProcessorPort> parseProcessorOutputPorts(
Processor newProc, GranularDepthPorts origPorts) {
Set<OutputProcessorPort> newPorts = new HashSet<OutputProcessorPort>();
for (GranularDepthPort origPort : origPorts.getPort()) {
OutputProcessorPort newPort = new OutputProcessorPort(newProc,
origPort.getName());
newPort.setDepth(origPort.getDepth().intValue());
newPort.setGranularDepth(origPort.getGranularDepth().intValue());
newPorts.add(newPort);
}
return newPorts;
}
protected Set<Processor> parseProcessors(Processors originalProcessors)
throws ReaderException, JAXBException {
HashSet<Processor> newProcessors = new HashSet<Processor>();
for (uk.org.taverna.scufl2.xml.t2flow.jaxb.Processor origProc : originalProcessors
.getProcessor()) {
Processor newProc = new Processor(parserState.get()
.getCurrentWorkflow(), origProc.getName());
parserState.get().setCurrentProcessor(newProc);
newProc.setInputPorts(parseProcessorInputPorts(newProc,
origProc.getInputPorts()));
newProc.setOutputPorts(parseProcessorOutputPorts(newProc,
origProc.getOutputPorts()));
newProc.setDispatchStack(parseDispatchStack(origProc
.getDispatchStack()));
newProc.setIterationStrategyStack(parseIterationStrategyStack(origProc
.getIterationStrategyStack()));
newProcessors.add(newProc);
int i = 0;
for (Activity origActivity : origProc.getActivities().getActivity()) {
parseActivityBinding(origActivity, i++);
}
}
parserState.get().setCurrentProcessor(null);
return newProcessors;
}
@SuppressWarnings("unchecked")
public WorkflowBundle parseT2Flow(File t2File) throws IOException,
ReaderException, JAXBException {
JAXBElement<uk.org.taverna.scufl2.xml.t2flow.jaxb.Workflow> root = (JAXBElement<uk.org.taverna.scufl2.xml.t2flow.jaxb.Workflow>) getUnmarshaller()
.unmarshal(t2File);
return parseT2Flow(root.getValue());
}
@SuppressWarnings("unchecked")
public WorkflowBundle parseT2Flow(InputStream t2File) throws IOException,
JAXBException, ReaderException {
JAXBElement<uk.org.taverna.scufl2.xml.t2flow.jaxb.Workflow> root = (JAXBElement<uk.org.taverna.scufl2.xml.t2flow.jaxb.Workflow>) getUnmarshaller()
.unmarshal(t2File);
return parseT2Flow(root.getValue());
}
public WorkflowBundle parseT2Flow(
uk.org.taverna.scufl2.xml.t2flow.jaxb.Workflow wf)
throws ReaderException, JAXBException {
try {
parserState.get().setT2FlowParser(this);
WorkflowBundle wfBundle = new WorkflowBundle();
parserState.get().setCurrentWorkflowBundle(wfBundle);
makeProfile(wf);
// First a skeleton scan of workflows (for nested workflow configs)
Map<Dataflow, Workflow> dataflowMap = new HashMap<Dataflow, Workflow>();
for (Dataflow df : wf.getDataflow()) {
Workflow workflow = skeletonDataflow(df);
dataflowMap.put(df, workflow);
wfBundle.getWorkflows().addWithUniqueName(workflow);
workflow.setParent(wfBundle);
if (df.getRole().equals(Role.TOP)) {
wfBundle.setMainWorkflow(workflow);
wfBundle.setName(df.getName());
wfBundle.setGlobalBaseURI(WorkflowBundle.WORKFLOW_BUNDLE_ROOT
.resolve(df.getId() + "/"));
}
}
// Second stage
for (Dataflow df : wf.getDataflow()) {
Workflow workflow = dataflowMap.get(df);
parseDataflow(df, workflow);
}
if (isStrict() && wfBundle.getMainWorkflow() == null) {
throw new ReaderException("No main workflow");
}
scufl2Tools.setParents(wfBundle);
return wfBundle;
} finally {
parserState.remove();
}
}
protected Workflow skeletonDataflow(Dataflow df) {
Workflow wf = new Workflow();
parserState.get().setCurrentWorkflow(wf);
wf.setName(df.getName());
wf.setWorkflowIdentifier(Workflow.WORKFLOW_ROOT.resolve(df.getId()
+ "/"));
return wf;
}
public void setStrict(boolean strict) {
this.strict = strict;
}
}
|
package com.github.basking2.sdsai.itrex;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A parser that is JSON-esque, but removes some commas and quotes to better suite the particulars of this language.
*
* The JSON
*
* <code>
* [ "map", ["curry", "f"], ["list", 1, 2, 3]]
* </code>
*
* may be parsed to the same expression
*
* <code>
* [map [curry f] [list 1 2 3]]
* </code>
*
* String may still be used, but we allow for unquoted tokens.
*/
public class SimpleExpressionParser {
public static final Pattern SKIP_WS = Pattern.compile("^\\s*");
public static final Pattern COMMA = Pattern.compile("^\\s*,");
public static final Pattern OPEN_BRACKET = Pattern.compile("^\\s*\\[");
public static final Pattern CLOSE_BRACKET = Pattern.compile("^\\s*\\]");
public static final Pattern FIRST_QUOTE = Pattern.compile("^\\s*\"");
public static final Pattern QUOTED_STRING = Pattern.compile("^\"((?:\\\\|\\\"|[^\"])*)\"");
public static final Pattern INTEGER = Pattern.compile("^(?:-?\\d+)");
public static final Pattern LONG = Pattern.compile("^(?:-?\\d+)[lL]");
public static final Pattern DOUBLE = Pattern.compile("^(?:-?\\d+\\.\\d+|\\d+D|\\d+d)");
public static final Pattern WORD = Pattern.compile("^(?:\\w+)");
private final String expression;
private int position;
/**
* Construct the parser, but do not parse.
* @see #parse()
* @param expression An expression to parse.
*/
public SimpleExpressionParser(final String expression) {
this.expression = expression;
this.position = 0;
}
private static int matchOrNeg1(final String expression, final Pattern pattern, int start) {
Matcher m = pattern.matcher(expression).region(start, expression.length());
if (m.find()) {
return m.group().length();
}
return -1;
}
private static int firstQuote(final String expression, final int start) {
return matchOrNeg1(expression, FIRST_QUOTE, start);
}
private static int openBracket(final String expression, final int start) {
return matchOrNeg1(expression, OPEN_BRACKET, start);
}
private static int closeBracket(final String expression, final int start) {
return matchOrNeg1(expression, CLOSE_BRACKET, start);
}
private void skipWs() {
final Matcher m = SKIP_WS.matcher(expression).region(position, expression.length());
if (m.find()) {
position += m.group().length();
};
}
/**
* Skip past whitespace and a comma. Use in list construction.
*
* Lists do not require a comma, but one is tolerated.
*/
private void skipComma() {
final Matcher m = COMMA.matcher(expression).region(position, expression.length());
if (m.find()) {
position += m.group().length();
};
}
final Object parse() {
skipWs();
int i = openBracket(expression, position);
// This is a bracket expression.
if (i > 0) {
// Move the position up to the opening [ and parse that list.
position += i;
return parseList();
}
// At end of expression, return null.
if (position >= expression.length()) {
return null;
}
return parseLiteral();
}
/**
* When the position points after an opening [, this parses that list.
* @return
*/
final private List<Object> parseList() {
final ArrayList<Object> arrayList = new ArrayList<>();
int i;
for (
i = closeBracket(expression, position);
i == -1;
i = closeBracket(expression, position)
) {
arrayList.add(parse());
skipComma();
if (position >= expression.length()) {
throw new SimpleExpressionUnclosedListException();
}
}
position += i;
return arrayList;
}
/**
* Parse a quoted string, an double, a long, or an unquoted string.
* @return A Java object or null if nothing could be parsed.
*/
final private Object parseLiteral() {
// This is a quote!
int i = firstQuote(expression, position);
if (i >= 0) {
final Matcher m = QUOTED_STRING.matcher(expression).region(position, expression.length());
if (m.find()) {
position += m.group().length();
String token = m.group(1);
// Remove escaping.
token = token.replaceAll("\\\\(.)", "$1");
return token;
}
else {
throw new SExprRuntimeException("Unmatched \" starting at position "+position+".");
}
}
final Matcher doubleMatcher = DOUBLE.matcher(expression).region(position, expression.length());
if (doubleMatcher.find()) {
String token = doubleMatcher.group();
position += token.length();
if (token.endsWith("D") || token.endsWith("d")) {
token = token.substring(0, token.length()-1);
}
return Double.valueOf(token);
}
final Matcher longMatcher = LONG.matcher(expression).region(position, expression.length());
if (longMatcher.find()) {
String token = longMatcher.group();
position += token.length();
if (token.endsWith("L") || token.endsWith("l")) {
token = token.substring(0, token.length()-1);
}
return Long.valueOf(token);
}
final Matcher intMatcher = INTEGER.matcher(expression).region(position, expression.length());
if (intMatcher.find()) {
String token = intMatcher.group();
position += token.length();
return Integer.valueOf(token);
}
final Matcher wordMatcher = WORD.matcher(expression).region(position, expression.length());
if (wordMatcher.find()) {
position += wordMatcher.group().length();
return wordMatcher.group();
}
throw new SExprRuntimeException("Unexpected token at position "+position);
}
public static Object parseExpression(final String expression) {
return new SimpleExpressionParser(expression).parse();
}
/**
* Return the position in the expression string where parsing left off.
*
* @return the position in the expression string where parsing left off.
*/
public int getPosition() {
return position;
}
}
|
package com.dmdirc.commandparser;
import com.dmdirc.Config;
import com.dmdirc.Server;
import com.dmdirc.actions.ActionManager;
import com.dmdirc.actions.CoreActionType;
import com.dmdirc.ui.interfaces.InputWindow;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.Map;
/**
* Represents a generic command parser. A command parser takes a line of input
* from the user, determines if it is an attempt at executing a command (based
* on the character at the start of the string), and handles it appropriately.
* @author chris
*/
public abstract class CommandParser implements Serializable {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 1;
/**
* Commands that are associated with this parser.
*/
private final Map<String, Command> commands;
/** Creates a new instance of CommandParser. */
public CommandParser() {
commands = new Hashtable<String, Command>();
loadCommands();
}
/** Loads the relevant commands into the parser. */
protected abstract void loadCommands();
/**
* Registers the specified command with this parser.
* @param command Command to be registered
*/
public final void registerCommand(final Command command) {
commands.put(command.getSignature().toLowerCase(), command);
}
/**
* Unregisters the specified command with this parser.
* @param command Command to be unregistered
*/
public final void unregisterCommand(final Command command) {
commands.remove(command.getSignature().toLowerCase());
}
/**
* Parses the specified string as a command.
* @param origin The window in which the command was typed
* @param line The line to be parsed
* @param parseChannel Whether or not to try and parse the first argument
* as a channel name
*/
public final void parseCommand(final InputWindow origin,
final String line, final boolean parseChannel) {
if (line.length() == 0) {
return;
}
if (line.charAt(0) == Config.getCommandChar().charAt(0)) {
int offset = 1;
boolean silent = false;
if (line.charAt(offset) == Config.getOption("general", "silencechar").charAt(0)) {
silent = true;
offset++;
}
final String[] args = line.split(" ");
final String command = args[0].substring(offset);
String[] comargs;
assert args.length > 0;
if (args.length >= 2 && parseChannel && origin != null
&& origin.getContainer().getServer().getParser().isValidChannelName(args[1])
&& CommandManager.isChannelCommand(command)) {
final Server server = origin.getContainer().getServer();
if (server.hasChannel(args[1])) {
final StringBuilder newLine = new StringBuilder();
for (int i = 0; i < args.length; i++) {
if (i == 1) { continue; }
newLine.append(" ").append(args[i]);
}
server.getChannel(args[1]).getFrame().getCommandParser()
.parseCommand(origin, newLine.substring(1), false);
return;
} else {
// Do something haxy involving external commands here...
}
}
comargs = new String[args.length - 1];
System.arraycopy(args, 1, comargs, 0, args.length - 1);
final String signature = command + "/" + (comargs.length);
// Check the specific signature first, so that polyadic commands can
// have error handlers if there are too few arguments (e.g., msg/0 and
// msg/1 would return errors, so msg only gets called with 2+ args).
if (commands.containsKey(signature.toLowerCase())) {
executeCommand(origin, silent, commands.get(signature.toLowerCase()), comargs);
} else if (commands.containsKey(command.toLowerCase())) {
executeCommand(origin, silent, commands.get(command.toLowerCase()), comargs);
} else {
handleInvalidCommand(origin, command, comargs);
}
} else {
handleNonCommand(origin, line);
}
}
/**
* Parses the specified string as a command.
* @param origin The window in which the command was typed
* @param line The line to be parsed
*/
public final void parseCommand(final InputWindow origin,
final String line) {
parseCommand(origin, line, true);
}
/**
* Handles the specified string as a non-command.
* @param origin The window in which the command was typed
* @param line The line to be parsed
*/
public final void parseCommandCtrl(final InputWindow origin, final String line) {
handleNonCommand(origin, line);
}
/**
* Executes the specified command with the given arguments.
* @param origin The window in which the command was typed
* @param isSilent Whether the command is being silenced or not
* @param command The command to be executed
* @param args The arguments to the command
*/
protected abstract void executeCommand(final InputWindow origin,
final boolean isSilent, final Command command, final String... args);
/**
* Called when the user attempted to issue a command (i.e., used the command
* character) that wasn't found. It could be that the command has a different
* arity, or that it plain doesn't exist.
* @param origin The window in which the command was typed
* @param command The command the user tried to execute
* @param args The arguments passed to the command
*/
protected void handleInvalidCommand(final InputWindow origin,
final String command, final String... args) {
if (origin == null) {
ActionManager.processEvent(CoreActionType.UNKNOWN_COMMAND, null,
null, command, args);
} else {
final StringBuffer buff = new StringBuffer("unknownCommand");
ActionManager.processEvent(CoreActionType.UNKNOWN_COMMAND, buff,
origin.getContainer(), command, args);
origin.addLine(buff, command + "/" + args.length);
}
}
/**
* Called when the input was a line of text that was not a command. This normally
* means it is sent to the server/channel/user as-is, with no further processing.
* @param origin The window in which the command was typed
* @param line The line input by the user
*/
protected abstract void handleNonCommand(final InputWindow origin,
final String line);
}
|
package tlc2.tool.fp;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.function.LongBinaryOperator;
import java.util.function.ToLongFunction;
import java.util.logging.Level;
import tlc2.output.EC;
import tlc2.output.MP;
import tlc2.tool.fp.LongArrays.LongComparator;
import tlc2.tool.fp.management.DiskFPSetMXWrapper;
import tlc2.util.BufferedRandomAccessFile;
import util.Assert;
/**
* see OpenAddressing.tla
*/
@SuppressWarnings({ "serial" })
public final class OffHeapDiskFPSet extends NonCheckpointableDiskFPSet implements FPSetStatistic {
private static final int PROBE_LIMIT = Integer.getInteger(OffHeapDiskFPSet.class.getName() + ".probeLimit", 128);
static final long EMPTY = 0L;
private final LongAccumulator reprobe;
private final LongArray array;
/**
* The indexer maps a fingerprint to a in-memory bucket and the associated lock
*/
private final Indexer indexer;
private CyclicBarrier barrier;
/**
* completionException is set by the Runnable iff an exception occurs during
* eviction while the worker threads wait at barrier. Worker threads have to
* check completionException explicitly.
*/
private volatile RuntimeException completionException;
protected OffHeapDiskFPSet(final FPSetConfiguration fpSetConfig) throws RemoteException {
super(fpSetConfig);
final long positions = fpSetConfig.getMemoryInFingerprintCnt();
// Determine base address which varies depending on machine architecture.
this.array = new LongArray(positions);
this.reprobe = new LongAccumulator(new LongBinaryOperator() {
public long applyAsLong(long left, long right) {
return Math.max(left, right);
}
}, 0);
// If Hamming weight is 1, the logical index address can be calculated
// significantly faster by bit-shifting. However, with large memory
// sizes, only supporting increments of 2^n sizes would waste memory
// (e.g. either 32GiB or 64Gib). Hence, we check if the bitCount allows
// us to use bit-shifting. If not, we fall back to less efficient
// calculations.
if (Long.bitCount(positions) == 1) {
this.indexer = new BitshiftingIndexer(positions, fpSetConfig.getFpBits());
} else {
// non 2^n buckets cannot use a bit shifting indexer
this.indexer = new Indexer(positions, fpSetConfig.getFpBits());
}
// Use the non-concurrent flusher as the default. Will be replaced by
// the CyclicBarrier-Runnable later. Just set to prevent NPEs when
// eviction/flush is called before init.
this.flusher = new OffHeapMSBFlusher(array);
}
/* (non-Javadoc)
* @see tlc2.tool.fp.DiskFPSet#init(int, java.lang.String, java.lang.String)
*/
public void init(final int numThreads, String aMetadir, String filename)
throws IOException {
super.init(numThreads, aMetadir, filename);
array.zeroMemory(numThreads);
// This barrier gets run after one thread signals the need to suspend
// put and contains operations to evict to secondary. Signaling is done
// via the flusherChoosen AtomicBoolean. All threads (numThreads) will
// then await on the barrier and the Runnable be executed when the
// last of numThreads arrives.
// Compared to an AtomicBoolean, the barrier operation use locks and
// are thus comparably expensive.
barrier = new CyclicBarrier(numThreads, new Runnable() {
// Atomically evict and reset flusherChosen to make sure no
// thread re-read flusherChosen=true after an eviction and
// waits again.
public void run() {
// statistics
growDiskMark++;
final long timestamp = System.currentTimeMillis();
final long insertions = tblCnt.longValue();
final double lf = tblCnt.doubleValue() / (double) maxTblCnt;
final int r = reprobe.intValue();
// Check that the table adheres to our invariant. Otherwise, we
// can't hope to successfully evict it.
assert checkInput(array, indexer, r) : "Table violates invariants prior to eviction: "
+ array.toString();
// Only pay the price of creating threads when array is sufficiently large.
if (array.size() > 8192) {
OffHeapDiskFPSet.this.flusher = new ConcurrentOffHeapMSBFlusher(array, r, numThreads, insertions);
} else {
OffHeapDiskFPSet.this.flusher = new OffHeapMSBFlusher(array);
}
try {
flusher.flushTable(); // Evict()
} catch (RuntimeException e) {
completionException = e;
throw e;
} catch (IOException e) {
completionException = new RuntimeException(e);
throw completionException;
}
// statistics and logging again.
long l = System.currentTimeMillis() - timestamp;
flushTime += l;
LOGGER.log(Level.FINE,
"Flushed disk {0} {1}. time, in {2} sec after {3} insertions, load factor {4} and reprobe of {5}.",
new Object[] { ((DiskFPSetMXWrapper) diskFPSetMXWrapper).getObjectName(), getGrowDiskMark(), l,
insertions, lf, r });
// Release exclusive access. It has to be done by the runnable
// before workers waiting on the barrier wake up again.
Assert.check(flusherChosen.compareAndSet(true, false), EC.GENERAL);
}
});
}
private boolean checkEvictPending() {
if (flusherChosen.get()) {
try {
barrier.await();
if (completionException != null) {
throw completionException;
}
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
} catch (BrokenBarrierException bbe) {
barrier.reset();
if (completionException != null) {
throw completionException;
} else {
throw new RuntimeException(bbe);
}
}
return true;
}
return false;
}
/* (non-Javadoc)
* @see tlc2.tool.fp.DiskFPSet#sizeof()
*/
public long sizeof() {
long size = 44; // approx size of this DiskFPSet object
size += maxTblCnt * (long) LongSize;
size += getIndexCapacity() * 4;
return size;
}
/* (non-Javadoc)
* @see tlc2.tool.fp.DiskFPSet#needsDiskFlush()
*/
protected final boolean needsDiskFlush() {
return loadFactorExceeds(1d) || forceFlush;
}
/**
* This limits the (primary) in-memory hash table to grow beyond the given
* limit.
*
* @param limit
* A limit in the domain [0, 1] which restricts the hash table
* from growing past it.
* @return true iff the current hash table load exceeds the given limit
*/
private final boolean loadFactorExceeds(final double limit) {
final double d = (this.tblCnt.doubleValue()) / (double) this.maxTblCnt;
return d >= limit;
}
/* (non-Javadoc)
* @see tlc2.tool.fp.DiskFPSet#memLookup(long)
*/
final boolean memLookup(final long fp0) {
int r = reprobe.intValue();
for (int i = 0; i <= r; i++) {
final long position = indexer.getIdx(fp0, i);
final long l = array.get(position);
if (fp0 == (l & FLUSHED_MASK)) {
// zero the long msb (which is 1 if fp has been flushed to disk)
return true;
} else if (l == EMPTY) {
return false;
}
}
return false;
}
/* (non-Javadoc)
* @see tlc2.tool.fp.DiskFPSet#memInsert(long)
*/
final boolean memInsert(final long fp0) throws IOException {
for (int i = 0; i < PROBE_LIMIT; i++) {
final long position = indexer.getIdx(fp0, i);
final long expected = array.get(position);
if (expected == EMPTY || (expected < 0 && fp0 != (expected & FLUSHED_MASK))) {
// Increment reprobe if needed. Other threads might have
// increased concurrently. Since reprobe is strictly
// monotonic increasing, we need no retry when r larger.
reprobe.accumulate(i);
// Try to CAS the new fingerprint. In case of failure, reprobe
// is too large which we ignore. Will be eventually corrected
// by eviction.
if (array.trySet(position, expected, fp0)) {
this.tblCnt.increment();
return false;
}
// Cannot reduce reprobe to its value before we increased it.
// Another thread could have caused an increase to i too which
// would be lost.
}
// Expected is the fingerprint to be inserted.
if ((expected & FLUSHED_MASK) == fp0) {
return true;
}
}
// We failed to insert into primary. Consequently, lets try and make
// some room by signaling all threads to wait for eviction.
forceFlush();
// We've signaled for eviction to start or failed because some other
// thread beat us to it. Actual eviction and setting flusherChosen back
// to false is done by the Barrier's Runnable. We cannot set
// flusherChosen back to false after barrier.awaits returns because it
// leaves a window during which other threads read the old true value of
// flusherChosen a second time and immediately wait again.
return put(fp0);
}
/* (non-Javadoc)
* @see tlc2.tool.fp.FPSet#put(long)
*/
public final boolean put(final long fp) throws IOException {
if (checkEvictPending()) { return put(fp); }
// zeros the msb
final long fp0 = fp & FLUSHED_MASK;
// Only check primary and disk iff there exists a disk file. index is
// created when we wait and thus cannot race.
if (index != null) {
// Lookup primary memory
if (memLookup(fp0)) {
this.memHitCnt.increment();
return true;
}
// Lookup on disk
if (this.diskLookup(fp0)) {
this.diskHitCnt.increment();
return true;
}
}
// Lastly, try to insert into memory.
return memInsert(fp0);
}
/* (non-Javadoc)
* @see tlc2.tool.fp.FPSet#contains(long)
*/
public final boolean contains(final long fp) throws IOException {
// maintains happen-before with regards to successful put
if (checkEvictPending()) { return contains(fp); }
// zeros the msb
final long fp0 = fp & FLUSHED_MASK;
// Lookup in primary
if (memLookup(fp0)) {
return true;
}
// Lookup on secondary/disk
if (this.diskLookup(fp0)) {
diskHitCnt.increment();
return true;
}
return false;
}
/* (non-Javadoc)
* @see tlc2.tool.fp.DiskFPSet#forceFlush()
*/
public void forceFlush() {
flusherChosen.compareAndSet(false, true);
}
/* (non-Javadoc)
* @see tlc2.tool.fp.DiskFPSet#acquireTblWriteLock()
*/
void acquireTblWriteLock() {
// no-op for now
}
/* (non-Javadoc)
* @see tlc2.tool.fp.DiskFPSet#releaseTblWriteLock()
*/
void releaseTblWriteLock() {
// no-op for now
}
/* (non-Javadoc)
* @see tlc2.tool.fp.DiskFPSet#getTblCapacity()
*/
public long getTblCapacity() {
return maxTblCnt;
}
/* (non-Javadoc)
* @see tlc2.tool.fp.DiskFPSet#getTblLoad()
*/
public long getTblLoad() {
return getTblCnt();
}
/* (non-Javadoc)
* @see tlc2.tool.fp.DiskFPSet#getOverallCapacity()
*/
public long getOverallCapacity() {
return array.size();
}
/* (non-Javadoc)
* @see tlc2.tool.fp.DiskFPSet#getBucketCapacity()
*/
public long getBucketCapacity() {
// A misnomer, but bucketCapacity is obviously not applicable with open
// addressing.
return reprobe.longValue();
}
//
public static class Indexer {
private static final long minFingerprint = 1L; //Minimum possible fingerprint (0L marks an empty position)
private final float tblScalingFactor;
private final long maxFingerprint;
protected final long positions;
public Indexer(final long positions, final int fpBits) {
this(positions, fpBits, 0xFFFFFFFFFFFFFFFFL >>> fpBits);
assert fpBits > 0;
}
public Indexer(final long positions, final int fpBits, final long maxValue) {
this.positions = positions;
this.maxFingerprint = maxValue;
// (position-1L) because array is zero indexed.
this.tblScalingFactor = (positions - 1L) / ((maxFingerprint - minFingerprint) * 1f);
}
protected long getIdx(final long fp) {
return getIdx(fp, 0);
}
protected long getIdx(final long fp, final int probe) {
long idx = Math.round(tblScalingFactor * (fp - minFingerprint)) + probe;
return idx % positions;
}
}
public static class BitshiftingIndexer extends Indexer {
private final long prefixMask;
private final int rShift;
public BitshiftingIndexer(final long positions, final int fpBits) throws RemoteException {
super(positions, fpBits);
this.prefixMask = 0xFFFFFFFFFFFFFFFFL >>> fpBits;
long n = (0xFFFFFFFFFFFFFFFFL >>> fpBits) - (positions - 1);
int moveBy = 0;
while (n >= positions) {
moveBy++;
n = n >>> 1;
}
this.rShift = moveBy;
}
@Override
protected long getIdx(final long fp) {
return ((fp & prefixMask) >>> rShift);
}
@Override
protected long getIdx(final long fp, int probe) {
// Have to mod positions because probe might cause us to overshoot.
return (((fp & prefixMask) >>> rShift) + probe) % positions;
}
}
//
private LongComparator getLongComparator() {
return new LongComparator() {
public int compare(long fpA, long posA, long fpB, long posB) {
// Elements not in Nat \ {0} remain at their current
// position.
if (fpA <= EMPTY || fpB <= EMPTY) {
return 0;
}
final boolean wrappedA = indexer.getIdx(fpA) > posA;
final boolean wrappedB = indexer.getIdx(fpB) > posB;
if (wrappedA == wrappedB && posA > posB) {
return fpA < fpB ? -1 : 1;
} else if ((wrappedA ^ wrappedB)) {
if (posA < posB && fpA < fpB) {
return -1;
}
if (posA > posB && fpA > fpB) {
return -1;
}
}
return 0;
}
};
}
/**
* Returns the number of fingerprints stored in table/array in the range
* [start,limit].
*/
private long getTableOffset(final LongArray a, final long reprobe, final Indexer indexer, final long start,
final long limit) {
long occupied = 0L;
for (long pos = start; pos < limit; pos++) {
final long fp = a.get(pos % a.size());
if (fp <= EMPTY) {
continue;
}
final long idx = indexer.getIdx(fp);
if (idx > pos) {
// Ignore the elements that wrapped around the
// end when scanning the first partition.
continue;
}
if (idx + reprobe < pos) {
// Ignore the elements of the first partition
// when wrapping around for the last partition.
continue;
}
occupied = occupied + 1L;
}
return occupied;
}
private long getNextLower(long idx) {
// Reverse to the next non-evicted/empty fp that belongs to this partition.
long fp = array.get(idx);
while (fp <= EMPTY || indexer.getIdx(fp) > idx) {
fp = array.get(--idx);
}
return fp;
}
/**
* The number of fingerprints stored on disk smaller than fp.
*/
private long getDiskOffset(final int id, final long fp) throws IOException {
if (this.index == null) {
return 0L;
}
final int indexLength = this.index.length;
int loPage = 0, hiPage = indexLength - 1;
long loVal = this.index[loPage];
long hiVal = this.index[hiPage];
if (fp <= loVal) {
return 0L;
}
if (fp >= hiVal) {
return this.braf[id].length() / FPSet.LongSize;
}
// See DiskFPSet#diskLookup for comments.
// Lookup the corresponding disk page in index.
final double dfp = (double) fp;
while (loPage < hiPage - 1) {
final double dhi = (double) hiPage;
final double dlo = (double) loPage;
final double dhiVal = (double) hiVal;
final double dloVal = (double) loVal;
int midPage = (loPage + 1) + (int) ((dhi - dlo - 1.0) * (dfp - dloVal) / (dhiVal - dloVal));
if (midPage == hiPage) {
midPage
}
final long v = this.index[midPage];
if (fp < v) {
hiPage = midPage;
hiVal = v;
} else if (fp > v) {
loPage = midPage;
loVal = v;
} else {
return (midPage * 1L) * (NumEntriesPerPage * 1L);
}
}
// no page is in between loPage and hiPage at this point
Assert.check(hiPage == loPage + 1, EC.SYSTEM_INDEX_ERROR);
// Read the disk page and try to find the given fingerprint or the next
// smaller one. Calculate its offset in file.
long midEntry = -1L;
long loEntry = ((long) loPage) * NumEntriesPerPage;
long hiEntry = ((loPage == indexLength - 2) ? this.fileCnt - 1 : ((long) hiPage) * NumEntriesPerPage);
final BufferedRandomAccessFile raf = this.braf[id];
while (loEntry < hiEntry) {
midEntry = calculateMidEntry(loVal, hiVal, dfp, loEntry, hiEntry);
raf.seek(midEntry * LongSize);
final long v = raf.readLong();
if (fp < v) {
hiEntry = midEntry;
hiVal = v;
} else if (fp > v) {
loEntry = midEntry + 1;
loVal = v;
midEntry = loEntry;
} else {
break;
}
}
return midEntry;
}
public class ConcurrentOffHeapMSBFlusher extends OffHeapMSBFlusher {
private final int numThreads;
private final ExecutorService executorService;
private final int r;
private final long insertions;
/**
* The length of a single partition.
*/
private final long length;
private List<Future<Result>> offsets;
public ConcurrentOffHeapMSBFlusher(final LongArray array, final int r, final int numThreads,
final long insertions) {
super(array);
this.r = r;
this.numThreads = numThreads;
this.insertions = insertions;
this.length = (long) Math.floor(a.size() / numThreads);
this.executorService = Executors.newFixedThreadPool(numThreads);
}
/* (non-Javadoc)
* @see tlc2.tool.fp.DiskFPSet.Flusher#prepareTable()
*/
protected void prepareTable() {
final CyclicBarrier phase = new CyclicBarrier(this.numThreads);
final Collection<Callable<Result>> tasks = new ArrayList<Callable<Result>>(numThreads);
for (int i = 0; i < numThreads; i++) {
final int id = i;
tasks.add(new Callable<Result>() {
@Override
public Result call() throws Exception {
final boolean isFirst = id == 0;
final boolean isLast = id == numThreads - 1;
final long start = id * length;
final long end = isLast ? a.size() - 1L : start + length;
// Sort partition p_n. We have exclusive access.
LongArrays.sort(a, isFirst ? 0L : start + 1L, end, getLongComparator());
assert checkSorted(a, indexer, r, isFirst ? 0L : start + 1L, end) == -1L : String.format(
"Array %s not fully sorted at index %s and reprobe %s in range [%s,%s].", a.toString(),
checkSorted(array, indexer, r, start, end), r, start, end);
// Wait for the other threads sorting p_n+1 to be done
// before we stitch together p_n and p_n+1.
phase.await();
// Sort the range between partition p_n and
// p_n+1 bounded by reprobe.
LongArrays.sort(a, end - r+1L, end + r+1L, getLongComparator());
// Wait for table to be fully sorted before we calculate
// the offsets. Offsets can only be correctly calculated
// on a sorted table.
phase.await();
// Count the occupied positions for this
// partition. Occupied positions are those which
// get evicted (written to disk).
// This could be done as part of (insertion) sort
// above at the price of higher complexity. Thus,
// it's done here until it becomes a bottleneck.
final long limit = isLast ? a.size() + r : end;
long occupied = getTableOffset(a, r, indexer, start, limit);
if (index == null) {
// No index, no need to calculate a disk offset.
return new Result(occupied, 0L);
}
// Determine number of elements in the old/current file.
if (isFirst && isLast) {
return new Result(occupied, fileCnt);
} else if (isFirst) {
return new Result(occupied, getDiskOffset(id, getNextLower(end)));
} else if (isLast) {
return new Result(occupied, fileCnt - getDiskOffset(id, getNextLower(start)));
} else {
return new Result(occupied,
getDiskOffset(id, getNextLower(end)) - getDiskOffset(id, getNextLower(start)));
}
}
});
}
try {
offsets = executorService.invokeAll(tasks);
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
assert checkSorted(a, indexer, r) == -1L : String.format(
"Array %s not fully sorted at index %s and reprobe %s.", a.toString(),
checkSorted(array, indexer, r), r);
}
@Override
protected void mergeNewEntries(final RandomAccessFile[] inRAFs, final RandomAccessFile outRAF, final Iterator ignored, final int idx, final long cnt) throws IOException {
assert offsets.stream().mapToLong(new ToLongFunction<Future<Result>>() {
public long applyAsLong(Future<Result> future) {
try {
return future.get().getTable();
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
} catch (ExecutionException ee) {
throw new RuntimeException(ee);
}
}
}).sum() == insertions : "Missing inserted elements during eviction.";
assert offsets.stream().mapToLong(new ToLongFunction<Future<Result>>() {
public long applyAsLong(Future<Result> future) {
try {
return future.get().getDisk();
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
} catch (ExecutionException ee) {
throw new RuntimeException(ee);
}
}
}).sum() == fileCnt : "Missing disk elements during eviction.";
final Collection<Callable<Void>> tasks = new ArrayList<Callable<Void>>(numThreads);
// Id = 0
tasks.add(new Callable<Void>() {
public Void call() throws Exception {
final Result result = offsets.get(0).get();
final Iterator itr = new Iterator(a, result.getTable(), indexer);
ConcurrentOffHeapMSBFlusher.super.mergeNewEntries(inRAFs[0], outRAF, itr, 0, 0L, result.getDisk());
assert outRAF.getFilePointer() == result.getTotal()
* FPSet.LongSize : "First writer did not write expected amount of fingerprints to disk.";
return null;
}
});
// Id > 0
for (int i = 1; i < numThreads; i++) {
final int id = i;
tasks.add(new Callable<Void>() {
public Void call() throws Exception {
final RandomAccessFile tmpRAF = new BufferedRandomAccessFile(new File(tmpFilename), "rw");
tmpRAF.setLength(outRAF.length());
try {
// Sum up the combined number of elements in
// lower partitions.
long skipOutFile = 0L;
long skipInFile = 0L;
for (int j = 0; j < id; j++) {
skipInFile = skipInFile + offsets.get(j).get().getDisk();
skipOutFile = skipOutFile + offsets.get(j).get().getTotal();
}
// Set offsets into the out (tmp) file.
final Result result = offsets.get(id).get();
tmpRAF.seek(skipOutFile * FPSet.LongSize);
// Set offset and the number of elements the
// iterator is supposed to return.
final long table = result.getTable();
final Iterator itr = new Iterator(a, table, id * length, indexer);
final RandomAccessFile inRAF = inRAFs[id];
assert (skipInFile + result.getDisk()) * FPSet.LongSize <= inRAF.length();
inRAF.seek(skipInFile * FPSet.LongSize);
// Calculate where the index entries start and end.
final int idx = (int) Math.floor(skipOutFile / NumEntriesPerPage);
final long cnt = NumEntriesPerPage - (skipOutFile - (idx * NumEntriesPerPage));
// Stop reading after diskReads elements (after
// which the next thread continues) except for the
// last thread which reads until EOF. Pass 0 when
// nothing can be read from disk.
final long diskReads = id == numThreads - 1 ? fileCnt - skipInFile : result.getDisk();
ConcurrentOffHeapMSBFlusher.super.mergeNewEntries(inRAF, tmpRAF, itr, idx + 1, cnt, diskReads);
assert tmpRAF.getFilePointer() == (skipOutFile + result.getTotal()) * FPSet.LongSize : id
+ " writer did not write expected amount of fingerprints to disk.";
} finally {
tmpRAF.close();
}
return null;
}
});
}
// Combine the callable results.
try {
executorService.invokeAll(tasks);
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
} finally {
executorService.shutdown();
}
assert checkTable(a) : "Missed element during eviction.";
assert checkIndex(index) : "Inconsistent disk index.";
}
private class Result {
private final long occupiedTable;
private final long occupiedDisk;
public Result(long occupiedTable, long occupiedDisk) {
this.occupiedTable = occupiedTable;
this.occupiedDisk = occupiedDisk;
}
public long getDisk() {
return occupiedDisk;
}
public long getTable() {
return occupiedTable;
}
public long getTotal() {
return occupiedDisk + occupiedTable;
}
}
}
public class OffHeapMSBFlusher extends Flusher {
protected final LongArray a;
public OffHeapMSBFlusher(LongArray array) {
a = array;
}
/* (non-Javadoc)
* @see tlc2.tool.fp.DiskFPSet.Flusher#prepareTable()
*/
protected void prepareTable() {
super.prepareTable();
final int r = OffHeapDiskFPSet.this.reprobe.intValue();
assert checkInput(array, indexer, r) : "Table violates invariants prior to eviction";
// Sort with a single thread.
LongArrays.sort(a, 0, a.size() - 1L + r, getLongComparator());
assert checkSorted(a, indexer, r) == -1L : String.format(
"Array %s not fully sorted at index %s and reprobe %s.", a.toString(),
checkSorted(array, indexer, r), r);
}
/* (non-Javadoc)
* @see tlc2.tool.fp.MSBDiskFPSet#mergeNewEntries(java.io.RandomAccessFile, java.io.RandomAccessFile)
*/
@Override
protected void mergeNewEntries(RandomAccessFile[] inRAFs, RandomAccessFile outRAF) throws IOException {
final long buffLen = tblCnt.sum();
final Iterator itr = new Iterator(array, buffLen, indexer);
final int indexLen = calculateIndexLen(buffLen);
index = new long[indexLen];
mergeNewEntries(inRAFs, outRAF, itr, 0, 0L);
// maintain object invariants
fileCnt += buffLen;
}
protected void mergeNewEntries(RandomAccessFile[] inRAFs, RandomAccessFile outRAF, Iterator itr, int currIndex,
long counter) throws IOException {
inRAFs[0].seek(0);
mergeNewEntries(inRAFs[0], outRAF, itr, currIndex, counter, inRAFs[0].length() / FPSet.LongSize);
}
protected void mergeNewEntries(RandomAccessFile inRAF, RandomAccessFile outRAF, final Iterator itr,
int currIndex, long counter, long diskReads) throws IOException {
final int startIndex = currIndex;
// initialize positions in "buff" and "inRAF"
long value = 0L; // initialize only to make compiler happy
boolean eof = false;
if (fileCnt > 0) {
try {
value = inRAF.readLong();
diskReads
} catch (EOFException e) {
eof = true;
}
} else {
assert diskReads == 0L;
eof = true;
}
// merge while both lists still have elements remaining
boolean eol = false;
long fp = itr.next();
while (!eof || !eol) {
if ((value < fp || eol) && !eof) {
assert value > EMPTY : "Negative or zero fingerprint found: " + value;
outRAF.writeLong(value);
diskWriteCnt.increment();
// update in-memory index file
if (counter == 0) {
index[currIndex++] = value;
counter = NumEntriesPerPage;
}
counter
try {
final long next = inRAF.readLong();
assert next > value : next + " > " + value + " from disk.";
value = next;
if (diskReads
eof = true;
}
} catch (EOFException e) {
eof = true;
}
} else {
// prevent converting every long to String when assertion holds (this is expensive)
if (value == fp) {
//MAK: Commented cause a duplicate does not pose a risk for correctness.
// It merely indicates a bug somewhere.
//Assert.check(false, EC.TLC_FP_VALUE_ALREADY_ON_DISK,
// String.valueOf(value));
MP.printWarning(EC.TLC_FP_VALUE_ALREADY_ON_DISK, String.valueOf(value));
}
assert fp > EMPTY : "Wrote an invalid fingerprint to disk.";
outRAF.writeLong(fp);
diskWriteCnt.increment();
// update in-memory index file
if (counter == 0) {
index[currIndex++] = fp;
counter = NumEntriesPerPage;
}
counter
// we used one fp up, thus move to next one
if (itr.hasNext()) {
final long next = itr.next();
assert next > fp : next + " > " + fp + " from table at pos " + itr.pos + " "
+ a.toString(itr.pos - 10L, itr.pos + 10L);
fp = next;
} else {
eol = true;
}
}
}
// both sets used up completely
Assert.check(eof && eol, EC.GENERAL);
if (currIndex == index.length - 1) {
// Update the last element in index with the larger one of the
// current largest element of itr and the largest element of value.
index[index.length - 1] = Math.max(fp, value);
} else if (counter == 0) {
// Write the last index entry if counter reached zero in the
// while loop above.
index[currIndex] = Math.max(fp, value);
}
assert checkIndex(Arrays.copyOfRange(index, startIndex, currIndex)) : "Inconsistent disk index range.";
}
}
/* (non-Javadoc)
* @see tlc2.tool.fp.DiskFPSet#calculateIndexLen(long)
*/
protected int calculateIndexLen(final long tblcnt) {
int indexLen = super.calculateIndexLen(tblcnt);
if ((tblcnt + fileCnt - 1L) % NumEntriesPerPage == 0L) {
// This is the special case where the largest fingerprint
// happened is going to end up on the last entry of the previous
// page. Thus, we won't need the last extra index cell.
indexLen
}
return indexLen;
}
/**
* A non-thread safe Iterator whose next method returns the next largest
* element.
*/
public static class Iterator {
private enum WRAP {
ALLOWED, FORBIDDEN;
};
private final long elements;
private final LongArray array;
private final Indexer indexer;
private final WRAP canWrap;
private long pos = 0;
private long elementsRead = 0L;
public Iterator(final LongArray array, final long elements, final Indexer indexer) {
this(array, elements, 0L, indexer, WRAP.ALLOWED);
}
public Iterator(final LongArray array, final long elements, final long start, final Indexer indexer) {
this(array, elements, start, indexer, WRAP.FORBIDDEN);
}
public Iterator(final LongArray array, final long elements, final long start, final Indexer indexer,
final WRAP canWrap) {
this.array = array;
this.elements = elements;
this.indexer = indexer;
this.pos = start;
this.canWrap = canWrap;
}
/**
* Returns the next element in the iteration that is not EMPTY nor
* marked evicted.
* <p>
* THIS IS NOT SIDEEFFECT FREE. AFTERWARDS, THE ELEMENT WILL BE MARKED
* EVICTED.
*
* @return the next element in the iteration that is not EMPTY nor
* marked evicted.
* @exception NoSuchElementException
* iteration has no more elements.
*/
public long next() {
long elem = EMPTY;
do {
final long position = pos % array.size();
elem = array.get(position);
if (elem == EMPTY) {
pos = pos + 1L;
continue;
}
if (elem < EMPTY) {
pos = pos + 1L;
continue;
}
final long baseIdx = indexer.getIdx(elem);
if (baseIdx > pos) {
// This branch should only be active for thread with id 0.
assert canWrap == WRAP.ALLOWED;
pos = pos + 1L;
continue;
}
pos = pos + 1L;
// mark elem in array as being evicted.
array.set(position, elem | MARK_FLUSHED);
elementsRead = elementsRead + 1L;
return elem;
} while (hasNext());
throw new NoSuchElementException();
}
/**
* Returns <tt>true</tt> if the iteration has more elements. (In other
* words, returns <tt>true</tt> if <tt>next</tt> would return an element
* rather than throwing an exception.)
*
* @return <tt>true</tt> if the iterator has more elements.
*/
public boolean hasNext() {
return elementsRead < elements;
}
}
private static boolean checkInput(final LongArray array, final Indexer indexer, final int reprobe) {
for (long pos = 0; pos <= array.size() + reprobe - 1L; pos++) {
long tmp = array.get(pos % array.size());
if (tmp == EMPTY) {
continue;
}
if (tmp < EMPTY) {
// Convert evicted fps back.
tmp = tmp & FLUSHED_MASK;
}
final long idx = indexer.getIdx(tmp);
// Accept wrapped elements.
if (pos < reprobe && idx > (array.size() - 1L - pos - reprobe)) {
continue;
}
// Accept non-wrapped elements when pos > array.size
if (pos > array.size() - 1L && idx + reprobe < pos) {
continue;
}
// Accept any other valid elements where pos is within the range
// given by [idx,idx + reprobe].
if (idx <= pos && pos <= idx + reprobe) {
continue;
}
System.err.println(String.format("%s with idx %s at pos %s (reprobe: %s).", tmp, idx, pos, reprobe));
return false;
}
return true;
}
/**
* @return -1L iff array is sorted, index/position of the element that violates otherwise in the range [start, end].
*/
private static long checkSorted(final LongArray array, final Indexer indexer, final int reprobe, long start, long end) {
long e = 0L;
for (long pos = start; pos <= end; pos++) {
final long tmp = array.get(pos % array.size());
if (tmp <= EMPTY) {
continue;
}
final long idx = indexer.getIdx(tmp);
if (idx > pos) {
continue;
}
if (idx + reprobe < pos) {
continue;
}
if (e == 0L) {
// Initialize e with the first element that is not <=EMPTY
// or has wrapped.
e = tmp;
continue;
}
if (e >= tmp) {
System.err.println(String.format("%s >= %s at pos %s.", e, tmp, pos));
return pos;
}
e = tmp;
}
return -1L;
}
/**
* @return -1L iff array is sorted, index/position of the element that violates otherwise.
*/
private static long checkSorted(final LongArray array, final Indexer indexer, final int reprobe) {
return checkSorted(array, indexer, reprobe, 0, array.size() - 1L + reprobe);
}
private static boolean checkTable(LongArray array) {
for (long i = 0L; i < array.size(); i++) {
long elem = array.get(i);
if (elem > EMPTY) {
System.out.println(String.format("%s elem at pos %s.", elem, i));
return false;
}
}
return true;
}
private static boolean checkIndex(final long[] idx) {
for (int i = 1; i < idx.length; i++) {
if (idx[i - 1] >= idx[i]) {
return false;
}
}
return true;
}
}
|
package de.li2b2.shrine.broker.admin;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.sql.SQLException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.bind.JAXB;
import javax.xml.transform.TransformerException;
import org.aktin.broker.server.Aggregator;
import org.aktin.broker.server.Broker;
import org.aktin.broker.xml.RequestInfo;
import org.w3c.dom.Element;
import de.sekmi.li2b2.api.crc.Query;
import de.sekmi.li2b2.api.crc.QueryManager;
import de.sekmi.li2b2.api.crc.ResultType;
public class BrokerQueryManager implements QueryManager {
public static final String MEDIA_TYPE_I2B2_QUERY_DEFINITION = "text/vnd.i2b2.query-definition+xml";
private static final String MEDIA_TYPE_I2B2_RESULT_OUTPUT_LIST = "text/vnd.i2b2.result-output-list";
// private static final String MEDIA_TYPE_I2B2_RESULT_OUTPUT_LIST = "text/vnd.i2b2.result-output-list+xml";
// private static final String MEDIA_TYPE_I2B2_RESULT_ENVELOPE = "text/vnd.i2b2.result-envelope+xml";
// TODO directly use the BrokerBackend without the local HTTP layer
Broker broker;
Aggregator aggregator;
public BrokerQueryManager(Broker broker, Aggregator aggregator) {
// TODO empty constructor and set brokerEndpoint later
this.broker = broker;
this.aggregator = aggregator;
}
@Override
public Query runQuery(String userId, String groupId, Element queryDefinition, String[] result_types) throws IOException {
try {
int req = broker.createRequest(MEDIA_TYPE_I2B2_QUERY_DEFINITION, new StringReader(DOMUtils.toString(queryDefinition)));
String displayName = "Query "+req;
// add metadata
QueryMetadata meta = new QueryMetadata(displayName, userId, groupId, Instant.now());
meta.resultTypes = result_types;
// for debugging+logging use intermediate string
StringWriter tmp = new StringWriter();
JAXB.marshal(meta, tmp);
broker.setRequestDefinition(req, QueryMetadata.MEDIA_TYPE, new StringReader(tmp.toString()));
BrokerI2b2Query query = new BrokerI2b2Query(this, broker.getRequestInfo(req));
query.setMetadata(meta);
// post result output list for i2b2 nodes
broker.setRequestDefinition(req, MEDIA_TYPE_I2B2_RESULT_OUTPUT_LIST, new StringReader(String.join("\n", result_types)));
// publish query (XXX allow manual publishing through workplace folders later)
broker.setRequestPublished(req, Instant.now());
return query;
} catch (SQLException | TransformerException e) {
throw new IOException(e);
}
}
@Override
public Query getQuery(int queryId) throws IOException {
RequestInfo info;
try {
info = broker.getRequestInfo(queryId);
} catch (SQLException e) {
throw new IOException(e);
}
if( info == null ){
return null;
}
BrokerI2b2Query query = new BrokerI2b2Query(this, info);
if( !info.hasMediaType(QueryMetadata.MEDIA_TYPE) ){
// query was created without our tool. try to construct metadata
throw new UnsupportedOperationException("Externally created queries not supported yet");
}
query.loadMetadata();
return query;
}
@Override
public Iterable<? extends Query> listQueries(String userId) throws IOException{
List<RequestInfo> requests;
try {
requests = broker.listAllRequests();
} catch (SQLException e) {
throw new IOException(e);
}
List<BrokerI2b2Query> queries = new ArrayList<>(requests.size());
for( RequestInfo info : requests ){
// convert request
queries.add(new BrokerI2b2Query(this, info));
}
return queries;
}
@Override
public Iterable<? extends ResultType> getResultTypes() {
return Arrays.asList(ResultType.PATIENT_COUNT_XML, ResultType.PATIENT_GENDER_COUNT_XML, ResultType.PATIENT_AGE_COUNT_XML, ResultType.PATIENT_VITALSTATUS_COUNT_XML);
}
@Override
public void deleteQuery(int queryId) throws IOException{
// delete query globally
try {
broker.deleteRequest(queryId);
} catch (SQLException e) {
throw new IOException(e);
}
}
}
|
package to.etc.domui.util;
import java.io.*;
import java.lang.reflect.*;
import java.sql.*;
import java.util.*;
import javax.annotation.*;
import javax.servlet.http.*;
import to.etc.domui.annotations.*;
import to.etc.domui.component.meta.*;
import to.etc.domui.component.misc.*;
import to.etc.domui.dom.errors.*;
import to.etc.domui.dom.html.*;
import to.etc.domui.server.*;
import to.etc.domui.state.*;
import to.etc.domui.trouble.*;
import to.etc.util.*;
import to.etc.webapp.*;
import to.etc.webapp.nls.*;
final public class DomUtil {
static private int m_guidSeed;
private DomUtil() {}
static {
long val = System.currentTimeMillis() / 1000 / 60;
m_guidSeed = (int) val;
}
static public final void ie8Capable(HttpServletResponse req) throws IOException {
if(!(req instanceof WrappedHttpServetResponse))
return;
WrappedHttpServetResponse wsr = (WrappedHttpServetResponse) req;
wsr.setIE8Capable();
}
static public final boolean isEqual(final Object a, final Object b) {
if(a == b)
return true;
if(a == null || b == null)
return false;
return a.equals(b);
}
static public final boolean isEqual(final Object... ar) {
if(ar.length < 2)
throw new IllegalStateException("Silly.");
Object a = ar[0];
for(int i = ar.length; --i >= 1;) {
if(!isEqual(a, ar[i]))
return false;
}
return true;
}
static public <T> T getValueSafe(IInputNode<T> node) {
try {
return node.getValue();
} catch(ValidationException x) {
return null;
}
}
/**
* Returns T if the given Java Resource exists.
* @param clz
* @param name
* @return
*/
static public boolean classResourceExists(final Class< ? extends DomApplication> clz, final String name) {
InputStream is = clz.getResourceAsStream(name);
if(is == null)
return false;
try {
is.close();
} catch(Exception x) {
// IGNORE
}
return true;
}
static public final Class< ? > findClass(@Nonnull final ClassLoader cl, @Nonnull final String name) {
try {
return cl.loadClass(name);
} catch(Exception x) {
return null;
}
}
/**
* Returns T if the class represents an integer numeric type.
* @param clz
* @return
*/
static public boolean isIntegerType(Class< ? > clz) {
return clz == int.class || clz == Integer.class || clz == long.class || clz == Long.class || clz == Short.class || clz == short.class;
}
static public boolean isDoubleOrWrapper(Class< ? > clz) {
return clz == Double.class || clz == double.class;
}
static public boolean isFloatOrWrapper(Class< ? > clz) {
return clz == Float.class || clz == float.class;
}
static public boolean isIntegerOrWrapper(Class< ? > clz) {
return clz == Integer.class || clz == int.class;
}
static public boolean isShortOrWrapper(Class< ? > clz) {
return clz == Short.class || clz == short.class;
}
static public boolean isLongOrWrapper(Class< ? > clz) {
return clz == Long.class || clz == long.class;
}
/**
* Return T if the class represents a real (double or float) type.
* @param clz
* @return
*/
static public boolean isRealType(Class< ? > clz) {
return clz == float.class || clz == Float.class || clz == Double.class || clz == double.class;
}
/**
* Retrieves a value from an object using introspection. The name is the direct
* name of a method that *must* exist; it does not add a "get". If the method
* does not exist this throws an exception.
*
* @param inst
* @param name
* @return
*/
static public final Object getClassValue(@Nonnull final Object inst, @Nonnull final String name) throws Exception {
if(inst == null)
throw new IllegalStateException("The input object is null");
Class< ? > clz = inst.getClass();
Method m;
try {
m = clz.getMethod(name);
} catch(NoSuchMethodException x) {
throw new IllegalStateException("Unknown method '" + name + "()' on class=" + clz);
}
try {
return m.invoke(inst);
} catch(IllegalAccessException iax) {
throw new IllegalStateException("Cannot call method '" + name + "()' on class=" + clz + ": " + iax);
} catch(InvocationTargetException itx) {
Throwable c = itx.getCause();
if(c instanceof Exception)
throw (Exception) c;
else if(c instanceof Error)
throw (Error) c;
else
throw itx;
}
}
/**
* Resolve the property's value
* @param base
* @param path
* @return
*/
static public Object getPropertyValue(@Nonnull final Object base, @Nonnull final String path) {
int pos = 0;
int len = path.length();
Object next = base;
while(pos < len) {
if(next == null)
return null;
int npos = path.indexOf('.', pos);
String name;
if(npos == -1) {
name = path.substring(pos);
pos = len;
} else {
name = path.substring(pos, npos);
pos = npos;
}
if(name.length() == 0)
throw new IllegalStateException("Invalid property path: " + path);
//-- Do a single-property resolve;
next = getSinglePropertyValue(next, name);
if(pos < len) {
//-- Next thingy must be a '.'
if(path.charAt(pos) != '.')
throw new IllegalStateException("Invalid property path: " + path);
pos++;
}
}
return next;
}
static private Object getSinglePropertyValue(final Object base, final String name) {
try {
StringBuilder sb = new StringBuilder(name.length() + 3);
sb.append("get");
if(Character.isUpperCase(name.charAt(0)))
sb.append(name);
else {
sb.append(Character.toUpperCase(name.charAt(0)));
sb.append(name, 1, name.length());
}
Method m = base.getClass().getMethod(sb.toString());
return m.invoke(base);
} catch(NoSuchMethodException x) {
throw new IllegalStateException("No property '" + name + "' on class=" + base.getClass());
} catch(Exception x) {
Trouble.wrapException(x);
}
return null;
}
static public String createRandomColor() {
int value = (int) (0xffffff * Math.random());
return "#" + StringTool.intToStr(value, 16, 6);
}
static public IErrorFence getMessageFence(NodeBase start) {
for(;;) {
if(start == null)
throw new IllegalStateException("Cannot locate error fence. Did you call an error routine on an unattached Node?");
if(start instanceof NodeContainer) {
NodeContainer nc = (NodeContainer) start;
if(nc.getErrorFence() != null)
return nc.getErrorFence();
}
// if(start.getParent() == null) {
// return start.getPage().getErrorFence(); // Use the generic page's fence.
start = start.getParent();
}
}
//fix for call 28547: $ cant be used in window names in javascript function window.openWindow in IE7, so we have to use something else...
static private final char[] BASE64MAP = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_0".toCharArray();
/**
* Generate an unique identifier with reasonable expectations that it will be globally unique. This
* does not use the known GUID format but shortens the string by encoding into base64-like encoding.
* @return
*/
static public String generateGUID() {
byte[] bin = new byte[18];
ByteArrayUtil.setInt(bin, 0, m_guidSeed); // Start with the seed
ByteArrayUtil.setShort(bin, 4, (short) (Math.random() * 65536));
long v = System.currentTimeMillis() / 1000 - (m_guidSeed * 60);
ByteArrayUtil.setInt(bin, 6, (int) v);
ByteArrayUtil.setLong(bin, 10, System.nanoTime());
// ByteArrayUtil.setLong(bin, 6, System.currentTimeMillis());
// System.out.print(StringTool.toHex(bin)+" ");
StringBuilder sb = new StringBuilder((bin.length + 2) / 3 * 4);
//-- 3-byte to 4-byte conversion + 0-63 to ascii printable conversion
int sidx;
for(sidx = 0; sidx < bin.length - 2; sidx += 3) {
sb.append(BASE64MAP[(bin[sidx] >>> 2) & 0x3f]);
sb.append(BASE64MAP[(bin[sidx + 1] >>> 4) & 0xf | (bin[sidx] << 4) & 0x3f]);
sb.append(BASE64MAP[(bin[sidx + 2] >>> 6) & 0x3 | (bin[sidx + 1] << 2) & 0x3f]);
sb.append(BASE64MAP[bin[sidx + 2] & 0x3f]);
}
if(sidx < bin.length) {
sb.append(BASE64MAP[(bin[sidx] >>> 2) & 077]);
if(sidx < bin.length - 1) {
sb.append(BASE64MAP[(bin[sidx + 1] >>> 4) & 017 | (bin[sidx] << 4) & 077]);
sb.append(BASE64MAP[(bin[sidx + 1] << 2) & 077]);
} else
sb.append(BASE64MAP[(bin[sidx] << 4) & 077]);
}
return sb.toString();
}
static public void addUrlParameters(final StringBuilder sb, final IRequestContext ctx, boolean first) {
for(String name : ctx.getParameterNames()) {
if(name.equals(Constants.PARAM_CONVERSATION_ID))
continue;
for(String value : ctx.getParameters(name)) {
if(first) {
sb.append('?');
first = false;
} else
sb.append('&');
StringTool.encodeURLEncoded(sb, name);
sb.append('=');
StringTool.encodeURLEncoded(sb, value);
}
}
}
static public void addUrlParameters(final StringBuilder sb, final PageParameters ctx, boolean first) {
if(ctx == null)
return;
for(String name : ctx.getParameterNames()) {
if(name.equals(Constants.PARAM_CONVERSATION_ID))
continue;
String value = ctx.getString(name);
if(first) {
sb.append('?');
first = false;
} else
sb.append('&');
StringTool.encodeURLEncoded(sb, name);
sb.append('=');
StringTool.encodeURLEncoded(sb, value);
}
}
/**
*
* @param clz
* @param pp
* @return
*/
static public String createPageURL(Class< ? extends UrlPage> clz, PageParameters pp) {
StringBuilder sb = new StringBuilder();
sb.append(PageContext.getRequestContext().getRelativePath(clz.getName()));
sb.append(clz.getName());
sb.append('.');
sb.append(DomApplication.get().getUrlExtension());
addUrlParameters(sb, pp, true);
return sb.toString();
}
/**
* Generate an URL to some page with parameters.
*
* @param rurl The absolute or relative URL to whatever resource.
* @param pageParameters
* @return
*/
public static String createPageURL(String rurl, PageParameters pageParameters) {
StringBuilder sb = new StringBuilder();
if(DomUtil.isRelativeURL(rurl)) {
RequestContextImpl ctx = (RequestContextImpl) PageContext.getRequestContext();
sb.append(ctx.getRelativePath(rurl));
}
else
sb.append(rurl);
if(pageParameters != null) {
addUrlParameters(sb, pageParameters, true);
}
return sb.toString();
}
/**
* Calculate a full URL from a rurl. If the rurl starts with a scheme it is returned verbatim;
* if it starts with slash (host-relative path absolute) it is returned verbatim; in all other
* cases it is returned with the webapp context appended. Examples:
* <ul>
* <li>img/text.gif becomes /Itris_VO02/img/text.gif</li>
* <li>/ui/generic.gif remains the same</li>
* </ul>
* @param ci
* @param rurl
* @return
*/
static public String calculateURL(IRequestContext ci, String rurl) {
int pos = rurl.indexOf(":/");
if(pos > 0 && pos < 20)
return rurl;
if(rurl.startsWith("/"))
return rurl;
//-- Append context.
return ci.getRelativePath(rurl);
}
static public String[] decodeCID(final String param) {
if(param == null)
return null;
int pos = param.indexOf('.');
if(pos == -1)
throw new IllegalStateException("Missing '.' in $CID parameter");
String[] res = new String[]{param.substring(0, pos), param.substring(pos + 1)};
return res;
}
/**
* Ensures that all of a node tree has been built.
* @param p
*/
static public void buildTree(final NodeBase p) throws Exception {
p.build();
if(p instanceof NodeContainer) {
NodeContainer nc = (NodeContainer) p;
for(NodeBase c : nc)
buildTree(c);
}
}
/**
* Walks the tree starting at the node passed and returns the first instance of the given class
* that is found in a normal walk of the tree.
* @param <T>
* @param p
* @param clz
* @return
* @throws Exception
*/
static public <T extends NodeBase> T findComponentInTree(final NodeBase p, final Class<T> clz) throws Exception {
if(clz.isAssignableFrom(p.getClass()))
return (T) p;
p.build();
if(p instanceof NodeContainer) {
NodeContainer nc = (NodeContainer) p;
for(NodeBase c : nc) {
T res = findComponentInTree(c, clz);
if(res != null)
return res;
}
}
return null;
}
static public String nlsLabel(final String label) {
if(label == null)
return label;
if(label.charAt(0) != '~')
return label;
if(label.startsWith("~~"))
return label.substring(1);
//-- Lookup as a resource.
return "???" + label.substring(1) + "???";
}
/**
* Walks the entire table and adjusts it's colspans.
* @param t
*/
static public void adjustTableColspans(final Table table) {
//-- Count the max. row length (max #cells in a row)
int maxcol = 0;
for(NodeBase b : table) { // For all TBody's
if(b instanceof TBody) {
TBody tb = (TBody) b;
for(NodeBase b2 : tb) { // For all TR's
if(b2 instanceof TR) {
TR tr = (TR) b2;
int count = 0;
for(NodeBase b3 : tr) {
if(b3 instanceof TD) {
TD td = (TD) b3;
count += td.getColspan() > 0 ? td.getColspan() : 1;
}
}
if(count > maxcol)
maxcol = count;
}
}
}
}
/*
* Adjust all rows that have less cells than the maximum by specifying a colspan on every last cell.
*/
for(NodeBase b : table) { // For all TBody's
if(b instanceof TBody) {
TBody tb = (TBody) b;
for(NodeBase b2 : tb) { // For all TR's
if(b2 instanceof TR) {
TR tr = (TR) b2;
int count = 0;
for(NodeBase b3 : tr) {
if(b3 instanceof TD) {
TD td = (TD) b3;
count += td.getColspan() > 0 ? td.getColspan() : 1;
}
}
if(count < maxcol) {
//-- Find last TD
TD td = (TD) tr.getChild(tr.getChildCount() - 1);
td.setColspan(maxcol - count + 1); // Adjust colspan
}
}
}
}
}
}
/**
* This balances tables to ensure that all rows have an equal number of rows and
* columns, taking rowspans and colspans into effect.
* FIXME Boring, lotso work, complete later.
* @param t
*/
@SuppressWarnings("unused")
public static void balanceTable(Table t) {
List<List<TD>> matrix = new ArrayList<List<TD>>(40);
//-- Phase 1: start marking extends in the matrix.
int rowindex = 0;
int maxcols = 0;
for(NodeBase l0 : t) { // Expecting THead and TBodies here.
if(l0 instanceof THead || l0 instanceof TBody) {
//-- Walk all rows.
for(NodeBase trb : ((NodeContainer) l0)) {
if(!(trb instanceof TR))
throw new IllegalStateException("Unexpected child of type " + l0 + " in TBody/THead node (expecting TR)");
TR tr = (TR) trb;
int minrowspan = 1;
//-- Start traversing the TD's.
List<TD> baserowlist = getTdList(matrix, rowindex);
int colindex = 0;
for(NodeBase tdb : tr) {
if(!(tdb instanceof TD))
throw new IllegalStateException("Unexpected child of type " + tr + " in TBody/THead node (expecting TD)");
TD td = (TD) tdb;
int colspan = td.getColspan();
int rowspan = td.getRowspan();
if(colspan < 1)
colspan = 1;
if(rowspan < 1)
rowspan = 1;
}
rowindex += minrowspan;
}
} else
throw new IllegalStateException("Unexpected child of type " + l0 + " in TABLE node");
}
//-- Phase 2: for all cells, handle their row/colspan by recounting their spread
}
static private List<TD> getTdList(List<List<TD>> matrix, int row) {
while(matrix.size() <= row) {
matrix.add(new ArrayList<TD>());
}
return matrix.get(row);
}
/**
* Remove all HTML tags from the input and keep only the text content. Things like script tags and the like
* will be removed but their contents will be kept.
* @param sb
* @param in
*/
static public void stripHtml(final StringBuilder sb, final String in) {
HtmlScanner hs = new HtmlScanner();
int lpos = 0;
hs.setDocument(in);
for(;;) {
String tag = hs.nextTag(); // Find the next tag.
if(tag == null)
break;
//-- Append any text segment between the last tag and the current one,
int len = hs.getPos() - lpos;
if(len > 0)
sb.append(in, lpos, hs.getPos()); // Append the normal text fragment
//-- Skip this tag;
hs.skipTag();
lpos = hs.getPos(); // Position just after the >
}
if(hs.getPos() < in.length())
sb.append(in, hs.getPos(), in.length());
}
static public void dumpException(final Exception x) {
x.printStackTrace();
Throwable next = null;
for(Throwable curr = x; curr != null; curr = next) {
next = curr.getCause();
if(next == curr)
next = null;
if(curr instanceof SQLException) {
SQLException sx = (SQLException) curr;
while(sx.getNextException() != null) {
sx = sx.getNextException();
System.err.println("SQL NextException: " + sx);
}
}
}
}
static public String getJavaResourceRURL(final Class< ? > resourceBase, final String name) {
String rb = resourceBase.getName();
int pos = rb.lastIndexOf('.');
if(pos == -1)
throw new IllegalStateException("??");
return Constants.RESOURCE_PREFIX + rb.substring(0, pos + 1).replace('.', '/') + name;
}
public static void main(final String[] args) {
for(int i = 0; i < 10; i++)
System.out.println(generateGUID());
}
/**
* Returns T if the specified resource exists.
* @param clz
* @param cn
* @return
*/
public static boolean hasResource(final Class< ? extends UrlPage> clz, final String cn) {
InputStream is = null;
try {
is = clz.getResourceAsStream(cn);
return is != null;
} finally {
try {
if(is != null)
is.close();
} catch(Exception x) {}
}
}
static public String getClassNameOnly(final Class< ? > clz) {
String cn = clz.getName();
return cn.substring(cn.lastIndexOf('.') + 1);
}
/**
*
* @param ma
* @param clz
* @return
*/
static public BundleRef findBundle(final UIMenu ma, final Class< ? > clz) {
if(ma != null && ma.bundleBase() != Object.class) { // Bundle base class specified?
String s = ma.bundleName();
if(s.length() == 0) // Do we have a name?
s = "messages"; // If not use messages in this package
return BundleRef.create(ma.bundleBase(), s);
}
//-- No BundleBase- use class as resource base and look for 'classname' as the properties base.
if(clz != null) {
String s = clz.getName();
s = s.substring(s.lastIndexOf('.') + 1); // Get to base class name (no path)
BundleRef br = BundleRef.create(clz, s); // Get ref to this bundle;
if(br.exists())
return br; // Return if it has data
//-- Use messages bundle off this thing
return BundleRef.create(clz, "messages");
}
return null;
}
/**
* Returns the bundle for the specified class, defined as classname[nls].properties.
* @param clz
* @return
*/
static public BundleRef getClassBundle(final Class< ? > clz) {
String s = clz.getName();
s = s.substring(s.lastIndexOf('.') + 1); // Get to base class name (no path)
return BundleRef.create(clz, s); // Get ref to this bundle;
}
static public BundleRef getPackageBundle(final Class< ? > base) {
return BundleRef.create(base, "messages"); // Default package bundle is messages[nls].properties
}
/**
* Lookup a page Title bar text..
* @param clz
* @return
*/
static public String calcPageTitle(final Class< ? > clz) {
UIMenu ma = clz.getAnnotation(UIMenu.class); // Is annotated with UIMenu?
Locale loc = NlsContext.getLocale();
BundleRef br = findBundle(ma, clz);
//-- Explicit specification of the names?
if(ma != null && br != null) {
//-- Has menu annotation. Is there a title key?
if(ma.titleKey().length() != 0)
return br.getString(loc, ma.titleKey()); // When present it MUST exist.
//-- Is there a keyBase?
if(ma.baseKey().length() != 0) {
String s = br.findMessage(loc, ma.baseKey() + ".title"); // Is this base thing present?
if(s != null) // This can be not-present...
return s;
}
//-- No title. Can we use the menu label?
if(ma.labelKey().length() > 0)
return br.getString(loc, ma.labelKey()); // When present this must exist
//-- Try the label from keyBase..
if(ma.baseKey().length() != 0) {
String s = br.findMessage(loc, ma.baseKey() + ".label");
if(s != null) // This can be not-present...
return s;
}
}
//-- Try default page bundle and package bundle names.
br = getClassBundle(clz); // Find bundle for the class
String s = br.findMessage(loc, "title"); // Find title key
if(s != null)
return s;
s = br.findMessage(loc, "label");
if(s != null)
return s;
//-- Try package bundle.
br = getPackageBundle(clz);
String root = clz.getName();
root = root.substring(root.lastIndexOf('.') + 1); // Class name without package
s = br.findMessage(loc, root + ".title"); // Find title key
if(s != null)
return s;
s = br.findMessage(loc, root + ".label");
if(s != null)
return s;
//-- No annotation, or the annotation did not deliver data. Try the menu.
//-- Try metadata
ClassMetaModel cmm = MetaManager.findClassMeta(clz);
String name = cmm.getUserEntityName();
if(name != null)
return name;
//-- Nothing worked.... Return the class name as a last resort.
s = clz.getName();
return s.substring(s.lastIndexOf('.') + 1);
}
/**
* Lookup a page Title bar text..
* @param clz
* @return
*/
static public String calcPageLabel(final Class< ? > clz) {
UIMenu ma = clz.getAnnotation(UIMenu.class); // Is annotated with UIMenu?
Locale loc = NlsContext.getLocale();
BundleRef br = findBundle(ma, clz);
//-- Explicit specification of the names?
if(ma != null && br != null) {
//-- Has menu annotation. Is there a title key?
if(ma.titleKey().length() != 0)
return br.getString(loc, ma.titleKey()); // When present it MUST exist.
//-- Is there a keyBase?
if(ma.baseKey().length() != 0) {
String s = br.findMessage(loc, ma.baseKey() + ".label"); // Is this base thing present?
if(s != null) // This can be not-present...
return s;
}
//-- No title. Can we use the menu label?
if(ma.labelKey().length() > 0)
return br.getString(loc, ma.labelKey()); // When present this must exist
//-- Try the label from keyBase..
if(ma.baseKey().length() != 0) {
String s = br.findMessage(loc, ma.baseKey() + ".title");
if(s != null) // This can be not-present...
return s;
}
}
//-- Try default page bundle and package bundle names.
br = getClassBundle(clz); // Find bundle for the class
String s = br.findMessage(loc, "label"); // Find title key
if(s != null)
return s;
s = br.findMessage(loc, "title");
if(s != null)
return s;
//-- Try package bundle.
br = getPackageBundle(clz);
String root = clz.getName();
root = root.substring(root.lastIndexOf('.') + 1); // Class name without package
s = br.findMessage(loc, root + ".label"); // Find title key
if(s != null)
return s;
s = br.findMessage(loc, root + ".title");
if(s != null)
return s;
//-- No annotation, or the annotation did not deliver data. Try the menu.
return null;
}
/* CODING: Resource Bundle utilities. */
/**
* Locates the default page bundle for a page. The lookup of the bundle
* is as follows (first match returns):
* <ul>
* <li>If the page has an @UIMenu annotation use it's bundleBase and bundleName to find the page bundle. It is an error to specify a nonexistent bundle here.</li>
* <li>Try a bundle with the same name as the page class</li>
* </ul>
* If this fails return null.
*
* @param urlPage
* @return
*/
public static BundleRef findPageBundle(UrlPage urlPage) {
if(urlPage == null)
throw new NullPointerException("Page cannot be null here");
//-- Try to locate UIMenu-based resource
UIMenu uim = urlPage.getClass().getAnnotation(UIMenu.class);
if(uim != null) {
if(uim.bundleBase() != Object.class || uim.bundleName().length() != 0) {
//-- We have a specification for the bundle- it must exist
BundleRef br = findBundle(uim, urlPage.getClass());
if(!br.exists())
throw new ProgrammerErrorException("@UIMenu bundle specified (" + uim.bundleBase() + "," + uim.bundleName() + ") but does not exist on page class " + urlPage.getClass());
return br;
}
}
//-- Try page class related bundle.
String fullname = urlPage.getClass().getName();
int ix = fullname.lastIndexOf('.');
String cn = fullname.substring(ix + 1); // Classname only,
BundleRef br = BundleRef.create(urlPage.getClass(), cn); // Try to find
if(br.exists())
return br;
//-- Finally: allow 'messages' bundle in this package, if present
br = BundleRef.create(urlPage.getClass(), "messages");
if(br.exists())
return br;
return null; // Failed to get bundle.
}
/**
* If the string passed starts with ~ start page resource bundle translation.
* @param nodeBase
* @param title
* @return
*/
public static String replaceTilded(NodeBase nodeBase, String txt) {
if(txt == null) // Unset - exit
return null;
if(!txt.startsWith("~"))
return txt;
if(txt.startsWith("~~")) // Dual tilde escapes and returns a single-tilded thingy.
return txt.substring(1);
//-- Must do replacement
Page p = nodeBase.getPage();
if(p == null)
throw new ProgrammerErrorException("Attempt to retrieve a page-bundle's key (" + txt + "), but the node (" + nodeBase + ")is not attached to a page");
return p.getBody().$(txt);
}
/* CODING: Error message visualisation utilities. */
/**
* Render a text string that possibly contains some simple HTML constructs as a DomUI
* node set into the container passed. The code currently accepts: B, BR, I, EM, STRONG
* as tags.
*/
static public void renderHtmlString(NodeContainer d, String text) {
if(text == null || text.length() == 0)
return;
StringBuilder sb = new StringBuilder(text.length()); // rll string segment buffer
List<NodeContainer> nodestack = Collections.EMPTY_LIST; // generated html stack (embedding)
/*
* Enter a scan loop. The scan loop has two sections; the first one scans the TEXT between tags and adds it
* to the string buffer. The second loop scans a tag and handles it properly. After that we return to scanning
* text etc until the string is done.
*/
int ix = 0;
int len = text.length();
NodeContainer top = d;
for(;;) {
//-- Text scan: scan content and add to the buffer until a possible tag start character is found.
while(ix < len) {
char c = text.charAt(ix);
if(c == '<')
break;
sb.append(c);
ix++;
}
//-- Ok; we possibly have some text in the buffer and have reached a tag or eoln.
if(ix >= len)
break;
//-- Tag scan. We find the end of the tag and check if we recognise it. We currently are on the open '<'.
int tix = ix + 1; // Get past >
String tag = null;
while(tix < len) {
char c = text.charAt(tix++);
if(c == '>') {
//-- Found an end tag- set the tag found.
tag = text.substring(ix, tix); // Get whole tag including <>.
break;
}
}
//-- If no tag was found (missing >) we have a literal < so copy it.
if(tag == null) {
//-- Literal <. Copy to text string and continue scanning text
sb.append('<');
ix++; // Skip over <.
} else {
//-- Some kind of text between <>. Scan for recognised constructs; open tags 1st
if(tag.equalsIgnoreCase("<br>") || tag.equalsIgnoreCase("<br/>") || tag.equalsIgnoreCase("<br />")) {
//-- Newline. Append a BR node.
appendOptionalText(top, sb);
top.add(new BR());
ix = tix;
} else if(tag.equalsIgnoreCase("<b>") || tag.equalsIgnoreCase("<strong>")) {
appendOptionalText(top, sb);
ix = tix;
NodeContainer n = new Span();
n.setCssClass("ui-txt-b");
nodestack = appendContainer(nodestack, n);
top.add(n);
top = n;
} else if(tag.equalsIgnoreCase("<i>") || tag.equalsIgnoreCase("<em>")) {
appendOptionalText(top, sb);
ix = tix;
NodeContainer n = new Span();
n.setCssClass("ui-txt-i");
nodestack = appendContainer(nodestack, n);
top.add(n);
top = n;
} else if(tag.startsWith("</")) {
//-- Some kind of end tag.
tag = tag.substring(2, tag.length() - 1).trim(); // Remove </ >
if(tag.equalsIgnoreCase("b") || tag.equalsIgnoreCase("i") || tag.equalsIgnoreCase("strong") || tag.equalsIgnoreCase("em")) {
//-- Recognised end tag: pop node stack.
ix = tix;
appendOptionalText(top, sb); // Append the text for this node because it ends.
if(nodestack.size() > 0) {
nodestack.remove(nodestack.size() - 1);
if(nodestack.size() == 0)
top = d;
else
top = nodestack.get(nodestack.size() - 1);
}
} else {
//-- Unrecognised end tag: just add
sb.append('<');
ix++;
}
} else {
//-- Unrecognised thingy: copy < verbatim and scan on.
sb.append('<');
ix++;
}
}
}
//-- We have reached eo$. If there is text left in the buffer render it in the last node added, then be done.
if(sb.length() > 0)
top.add(sb.toString());
}
/**
* This scans the input, and only copies "safe" html, which is HTML with only
* simple constructs. It checks to make sure the resulting document is xml-safe (well-formed),
* if the input is not well-formed it will add or remove tags until the result is valid.
*
* @param sb
* @param html
*/
static public void htmlRemoveUnsafe(StringBuilder outsb, String text) {
if(text == null || text.length() == 0)
return;
new HtmlTextScanner().scan(outsb, text);
}
static public String htmlRemoveUnsafe(String html) {
if(html == null || html.length() == 0)
return "";
StringBuilder sb = new StringBuilder(html.length() + 20);
htmlRemoveUnsafe(sb, html);
return sb.toString();
}
static public void htmlRemoveAll(StringBuilder outsb, String text, boolean lf) {
if(text == null || text.length() == 0)
return;
new HtmlTextScanner().scanAndRemove(outsb, text, lf);
}
static public String htmlRemoveAll(String html, boolean lf) {
if(html == null || html.length() == 0)
return "";
StringBuilder sb = new StringBuilder(html.length() + 20);
htmlRemoveAll(sb, html, lf);
return sb.toString();
}
static public List<NodeContainer> appendContainer(List<NodeContainer> stack, NodeContainer it) {
if(stack == Collections.EMPTY_LIST)
stack = new ArrayList<NodeContainer>();
stack.add(it);
return stack;
}
static private void appendOptionalText(NodeContainer nc, StringBuilder sb) {
if(sb.length() == 0)
return;
nc.add(sb.toString());
sb.setLength(0);
}
/**
* This scans an error messages for simple HTML and renders that as DomUI nodes. The rendered content gets added to
* the container passed.
*/
static public void renderErrorMessage(NodeContainer d, UIMessage m) {
if(d.getCssClass() == null)
d.setCssClass("ui-msg ui-msg-" + m.getType().name().toLowerCase());
d.setUserObject(m);
String text = m.getErrorLocation() != null ? "<b>" + m.getErrorLocation() + "</b>" + ": " + m.getMessage() : m.getMessage();
renderHtmlString(d, text);
if(m.getErrorNode() != null) {
m.getErrorNode().addCssClass("ui-input-err");
}
}
/**
* Obtain a parameter and convert it to a Long wrapper.
* @param pp
* @param name
* @param def
* @return
*/
static public Long getLongParameter(PageParameters pp, String name, Long def) {
String s = pp.getString(name, null); // Parameter present?
if(s == null || s.trim().length() == 0)
return def;
try {
return Long.valueOf(s.trim());
} catch(Exception x) {
throw new UIException(Msgs.BUNDLE, Msgs.X_INVALID_PARAMETER, name);
}
}
/**
* Convert a CSS size string like '200px' into the 200... If the size string is in any way
* invalid this returns -1.
*
* @param css
* @return
*/
static public int pixelSize(String css) {
if(!css.endsWith("px"))
return -1;
try {
return Integer.parseInt(css.substring(0, css.length() - 2).trim());
} catch(Exception x) {
return -1;
}
}
/* CODING: Tree walking helpers. */
static public interface IPerNode {
/** When this object instance is returned by the before(NodeBase) method we SKIP the downwards traversal. */
static public final Object SKIP = new Object();
/**
* Called when the node is first encountered in the tree. It can return null causing the rest of the tree
* to be traversed; if it returns the constant IPerNode.SKIP the subtree starting at this node will not
* be traversed but the rest of the tree will. When you return SKIP the {@link IPerNode#after(NodeBase)} method
* will not be called for this node. Returning any other value will stop the node traversal process
* and return that value to the caller of {@link DomUtil#walkTree(NodeBase, IPerNode)}.
* @param n
* @return
* @throws Exception
*/
public Object before(NodeBase n) throws Exception;
/**
* Called when all child nodes of the specified node have been traversed. When this returns a non-null
* value this will terminate the tree walk and return that value to the called of {@link DomUtil#walkTree(NodeBase, IPerNode)}.
* @param n
* @return
* @throws Exception
*/
public Object after(NodeBase n) throws Exception;
}
/**
* Walks a node tree, calling the handler for every node in the tree. As soon as
* a handler returns not-null traversing stops and that object gets returned.
* @param handler
* @return
* @throws Exception
*/
static public Object walkTree(NodeBase root, IPerNode handler) throws Exception {
if(root == null)
return null;
Object v = handler.before(root);
if(v == IPerNode.SKIP)
return null;
if(v != null)
return v;
if(root instanceof NodeContainer) {
for(NodeBase ch : (NodeContainer) root) {
v = walkTree(ch, handler);
if(v != null)
return v;
}
}
return handler.after(root);
}
/**
* This clears the 'modified' flag for all nodes in the subtree that implement {@link IHasModifiedIndication}.
* @param root The subtree to traverse
*/
static public void clearModifiedFlag(NodeBase root) {
try {
walkTree(root, new IPerNode() {
public Object before(NodeBase n) throws Exception {
if(n instanceof IHasModifiedIndication)
((IHasModifiedIndication) n).setModified(false);
return null;
}
public Object after(NodeBase n) throws Exception {
return null;
}
});
} catch(Exception x) { // Cannot happen.
throw new RuntimeException(x);
}
}
/**
* Walks the subtree and asks any node implementing {@link IHasModifiedIndication} whether it has been
* modified; return as soon as one node tells us it has been modified.
* @param root
*/
static public boolean isModified(NodeBase root) {
try {
Object res = walkTree(root, new IPerNode() {
public Object before(NodeBase n) throws Exception {
if(n instanceof IHasModifiedIndication) {
if(((IHasModifiedIndication) n).isModified())
return Boolean.TRUE;
}
if(n instanceof IUserInputModifiedFence)
return SKIP;
return null;
}
public Object after(NodeBase n) throws Exception {
return null;
}
});
return res != null;
} catch(Exception x) { // Cannot happen.
throw new RuntimeException(x);
}
}
/**
* Update modified flag of node. Propagate notify signal up to final modified fence in parant tree, if any is defined.
* Use it to set modified flag as result of handling of user data modification.
* @param node
*/
static public void setModifiedFlag(NodeBase node) {
NodeBase n = node;
while(n != null) {
boolean wasModifiedBefore = false;
if(n instanceof IHasModifiedIndication) {
wasModifiedBefore = ((IHasModifiedIndication) n).isModified();
((IHasModifiedIndication) n).setModified(true);
}
if(n instanceof IUserInputModifiedFence) {
if(!wasModifiedBefore) {
((IUserInputModifiedFence) n).onModifyFlagRaised();
}
if(((IUserInputModifiedFence) n).isFinalUserInputModifiedFence()) {
return;
}
}
n = (NodeBase) n.getParent(IUserInputModifiedFence.class);
}
}
/**
* Checks if string is blank.
* @param s String to be validated.
* @return true if it is blank, false otherwise.
*/
static public boolean isBlank(String s) {
return s == null || s.trim().length() == 0;
}
static public boolean isRelativeURL(String in) {
if(in == null)
return false;
if(in.startsWith("http:") || in.startsWith("https:") || in.startsWith("/"))
return false;
return true;
}
static public String createOpenWindowJS(Class< ? > targetClass, PageParameters targetParameters, WindowParameters newWindowParameters) {
//-- We need a NEW window session. Create it,
RequestContextImpl ctx = (RequestContextImpl) PageContext.getRequestContext();
WindowSession cm = ctx.getSession().createWindowSession();
//-- Send a special JAVASCRIPT open command, containing the shtuff.
StringBuilder sb = new StringBuilder();
sb.append("DomUI.openWindow('");
sb.append(ctx.getRelativePath(targetClass.getName()));
sb.append(".ui?");
StringTool.encodeURLEncoded(sb, Constants.PARAM_CONVERSATION_ID);
sb.append('=');
sb.append(cm.getWindowID());
sb.append(".x");
if(targetParameters != null)
DomUtil.addUrlParameters(sb, targetParameters, false);
sb.append("','");
sb.append(cm.getWindowID());
sb.append("','");
sb.append("resizable=");
sb.append(newWindowParameters.isResizable() ? "yes" : "no");
sb.append(",scrollbars=");
sb.append(newWindowParameters.isShowScrollbars() ? "yes" : "no");
sb.append(",toolbar=");
sb.append(newWindowParameters.isShowToolbar() ? "yes" : "no");
sb.append(",location=");
sb.append(newWindowParameters.isShowLocation() ? "yes" : "no");
sb.append(",directories=");
sb.append(newWindowParameters.isShowDirectories() ? "yes" : "no");
sb.append(",status=");
sb.append(newWindowParameters.isShowStatus() ? "yes" : "no");
sb.append(",menubar=");
sb.append(newWindowParameters.isShowMenubar() ? "yes" : "no");
sb.append(",copyhistory=");
sb.append(newWindowParameters.isCopyhistory() ? "yes" : "no");
if(newWindowParameters.getWidth() > 0) {
sb.append(",width=");
sb.append(newWindowParameters.getWidth());
}
if(newWindowParameters.getHeight() > 0) {
sb.append(",height=");
sb.append(newWindowParameters.getHeight());
}
sb.append("');");
return sb.toString();
}
static public String createOpenWindowJS(String url, WindowParameters newWindowParameters) {
//-- We need a NEW window session. Create it,
RequestContextImpl ctx = (RequestContextImpl) PageContext.getRequestContext();
WindowSession cm = ctx.getSession().createWindowSession();
//-- Send a special JAVASCRIPT open command, containing the shtuff.
StringBuilder sb = new StringBuilder();
sb.append("DomUI.openWindow('");
sb.append(url);
sb.append("','");
sb.append(cm.getWindowID());
sb.append("','");
sb.append("resizable=");
sb.append(newWindowParameters.isResizable() ? "yes" : "no");
sb.append(",scrollbars=");
sb.append(newWindowParameters.isShowScrollbars() ? "yes" : "no");
sb.append(",toolbar=");
sb.append(newWindowParameters.isShowToolbar() ? "yes" : "no");
sb.append(",location=");
sb.append(newWindowParameters.isShowLocation() ? "yes" : "no");
sb.append(",directories=");
sb.append(newWindowParameters.isShowDirectories() ? "yes" : "no");
sb.append(",status=");
sb.append(newWindowParameters.isShowStatus() ? "yes" : "no");
sb.append(",menubar=");
sb.append(newWindowParameters.isShowMenubar() ? "yes" : "no");
sb.append(",copyhistory=");
sb.append(newWindowParameters.isCopyhistory() ? "yes" : "no");
if(newWindowParameters.getWidth() > 0) {
sb.append(",width=");
sb.append(newWindowParameters.getWidth());
}
if(newWindowParameters.getHeight() > 0) {
sb.append(",height=");
sb.append(newWindowParameters.getHeight());
}
sb.append("');");
return sb.toString();
}
public static boolean isWhitespace(char c) {
return c == '\u00a0' || Character.isWhitespace(c);
}
}
|
package fi.nls.oskari.search.channel;
import fi.nls.oskari.annotation.Oskari;
import fi.nls.oskari.service.OskariComponentManager;
import fi.nls.oskari.wfs.WFSSearchChannelsConfiguration;
import fi.nls.oskari.wfs.WFSSearchChannelsService;
import java.util.HashSet;
import java.util.Set;
@Oskari
public class WFSChannelProvider extends ChannelProvider {
public Set<SearchChannel> getChannels() {
WFSSearchChannelsService channelService = OskariComponentManager.getComponentOfType(WFSSearchChannelsService.class);
Set<SearchChannel> list = new HashSet<>();
for(WFSSearchChannelsConfiguration config : channelService.findChannels()) {
WFSSearchChannel channel = new WFSSearchChannel(config);
channel.init();
list.add(channel);
}
return list;
}
public void channelRemoved(WFSSearchChannelsConfiguration config) {
channelRemoved(new WFSSearchChannel(config));
}
public void channelAdded(WFSSearchChannelsConfiguration config) {
channelAdded(new WFSSearchChannel(config));
}
public void channelUpdated(WFSSearchChannelsConfiguration config) {
WFSSearchChannel channel = new WFSSearchChannel(config);
channelRemoved(channel);
channelAdded(channel);
}
}
|
package com.ecyrd.jspwiki.event;
import com.ecyrd.jspwiki.WikiEngine;
/**
* A utility class that adds some JSPWiki-specific functionality to the
* WikiEventManager (which is really a general-purpose event manager).
*
* @author Murray Altheim
* @since 2.4.20
*/
public class WikiEventUtils
{
/**
* This ungainly convenience method adds a WikiEventListener to the
* appropriate component of the provided client Object, to listen
* for events of the provided type (or related types, see the table
* below).
* <p>
* If the type value is valid but does not match any WikiEvent type
* known to this method, this will just attach the listener to the
* client Object. This may mean that the Object never fires events
* of the desired type; type-to-client matching is left to you to
* guarantee. Silence is golden, but not if you want those events.
* </p>
* <p>
* Most event types expect a WikiEngine as the client, with the rest
* attaching the listener directly to the supplied source object, as
* described below:
* </p>
* <table border="1" cellpadding="4">
* <tr><th>WikiEvent Type(s) </th><th>Required Source Object </th><th>Actually Attached To </th>
* </tr>
* <tr><td>any WikiEngineEvent </td><td>WikiEngine </td><td>WikiEngine </td></tr>
* <tr><td>WikiPageEvent.PAGE_LOCK,
* WikiPageEvent.PAGE_UNLOCK </td><td>WikiEngine or
* PageManager </td><td>PageManager </td></tr>
* <tr><td>WikiPageEvent.PAGE_REQUESTED,
* WikiPageEvent.PAGE_DELIVERED </td>
* <td>WikiServletFilter </td>
* <td>WikiServletFilter </td></tr>
* <tr><td>WikiPageEvent (<a href="#pbeTypes">phase boundary event</a>)</td>
* <td>WikiEngine </td><td>FilterManager </td></tr>
* <tr><td>WikiPageEvent (<a href="#ipeTypes">in-phase event</a>)</td>
* <tr><td>WikiPageEvent (in-phase event)</td>
* <td>any </td><td>source object </td></tr>
* <tr><td>WikiSecurityEvent </td><td>any </td><td>source object </td></tr>
* <tr><td>any other valid type </td><td>any </td><td>source object </td></tr>
* <tr><td>any invalid type </td><td>any </td><td>nothing </td></tr>
* </table>
*
* <p id="pbeTypes"><small><b>phase boundary event types:</b>
* <tt>WikiPageEvent.PRE_TRANSLATE_BEGIN</tt>, <tt>WikiPageEvent.PRE_TRANSLATE_END</tt>,
* <tt>WikiPageEvent.POST_TRANSLATE_BEGIN</tt>, <tt>WikiPageEvent.POST_TRANSLATE_END</tt>,
* <tt>WikiPageEvent.PRE_SAVE_BEGIN</tt>, <tt>WikiPageEvent.PRE_SAVE_END</tt>,
* <tt>WikiPageEvent.POST_SAVE_BEGIN</tt>, and <tt>WikiPageEvent.POST_SAVE_END</tt>.
* </small></p>
* <p id="ipeTypes"><small><b>in-phase event types:</b>
* <tt>WikiPageEvent.PRE_TRANSLATE</tt>, <tt>WikiPageEvent.POST_TRANSLATE</tt>,
* <tt>WikiPageEvent.PRE_SAVE</tt>, and <tt>WikiPageEvent.POST_SAVE</tt>.
* </small></p>
*
* <p>
* <b>Note:</b> The <i>Actually Attached To</i> column may also be considered as the
* class(es) that fire events of the type(s) shown in the <i>WikiEvent Type</i> column.
* </p>
*
* @see com.ecyrd.jspwiki.event.WikiEvent
* @see com.ecyrd.jspwiki.event.WikiEngineEvent
* @see com.ecyrd.jspwiki.event.WikiPageEvent
* @see com.ecyrd.jspwiki.event.WikiSecurityEvent
* @throws ClassCastException if there is a type mismatch between certain event types and the client Object
*/
public static synchronized void addWikiEventListener(
Object client, int type, WikiEventListener listener )
{
// Make sure WikiEventManager exists
WikiEventManager.getInstance();
// first, figure out what kind of event is expected to be generated this does
// tie us into known types, but WikiEvent.isValidType() will return true so
// long as the type was set to any non-ERROR or non-UNKNOWN value
if ( WikiEngineEvent.isValidType(type) ) // add listener directly to WikiEngine
{
WikiEventManager.addWikiEventListener( client, listener );
}
else if ( WikiPageEvent.isValidType(type) ) // add listener to one of several options
{
if( type == WikiPageEvent.PAGE_LOCK
|| type == WikiPageEvent.PAGE_UNLOCK ) // attach to PageManager
{
if( client instanceof WikiEngine )
{
WikiEventManager.addWikiEventListener( ((WikiEngine)client).getPageManager(), listener );
}
else // if ( client instanceof PageManager ) // no filter?
{
WikiEventManager.addWikiEventListener( client, listener );
}
}
else if( type == WikiPageEvent.PAGE_REQUESTED
|| type == WikiPageEvent.PAGE_DELIVERED ) // attach directly to WikiServletFilter
{
WikiEventManager.addWikiEventListener( client, listener );
}
else if( type == WikiPageEvent.PRE_TRANSLATE_BEGIN
|| type == WikiPageEvent.PRE_TRANSLATE_END
|| type == WikiPageEvent.POST_TRANSLATE_BEGIN
|| type == WikiPageEvent.POST_TRANSLATE_END
|| type == WikiPageEvent.PRE_SAVE_BEGIN
|| type == WikiPageEvent.PRE_SAVE_END
|| type == WikiPageEvent.POST_SAVE_BEGIN
|| type == WikiPageEvent.POST_SAVE_END ) // attach to FilterManager
{
WikiEventManager.addWikiEventListener( ((WikiEngine)client).getFilterManager(), listener );
}
else //if ( type == WikiPageEvent.PRE_TRANSLATE
// || type == WikiPageEvent.POST_TRANSLATE
// || type == WikiPageEvent.PRE_SAVE
// || type == WikiPageEvent.POST_SAVE ) // attach to client
{
WikiEventManager.addWikiEventListener( client, listener );
}
}
else if( WikiSecurityEvent.isValidType(type) ) // add listener to the client
{
// currently just attach it to the client (we are ignorant of other options)
WikiEventManager.addWikiEventListener( client, listener );
}
else if( WikiEvent.isValidType(type) ) // we don't know what to do
{
WikiEventManager.addWikiEventListener( client, listener );
}
else // is error or unknown
{
// why are we being called with this?
}
}
} // end com.ecyrd.jspwiki.event.WikiEventUtils
|
package ceylon.language;
import ceylon.language.Integer;
public class ArrayListImpl<T>
implements Sequence<T>
{
java.util.ArrayList<T> data;
public Integer length() {
return Integer.instance(data.size());
}
@SuppressWarnings("unchecked")
public T value(Integer key) {
return data.get(key.intValue());
}
ArrayListImpl(T[] args) {
data = new java.util.ArrayList<T>(java.util.Arrays.asList(args));
}
ArrayListImpl() {
data = new java.util.ArrayList<T>();
}
public ArrayListImpl(Natural initialCapacity) {
System.out.println(initialCapacity.intValue());
data = new java.util.ArrayList<T>(initialCapacity.intValue());
}
public static <N> ArrayListImpl<N> of (N... args) {
return new ArrayListImpl<N>(args);
}
public ArrayListImpl<T> append(ArrayListImpl<T> l) {
ArrayListImpl<T> newList = newInstance();
newList.data = new java.util.ArrayList<T>(data) ;
if (l != null) {
newList.data.addAll(l.data);
}
return newList;
}
protected ArrayListImpl<T> newInstance() {
try {
return getClass().newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void $set(Integer key, T value) {
data.add(key.intValue(), value);
}
public void set(Integer key, T value) {
data.add(key.intValue(), value);
}
public static <T> ArrayList<T> arrayListOf(T[] args) {
ArrayList l = new ArrayList();
l.data = new java.util.ArrayList<T>(java.util.Arrays.asList(args));
return l;
}
public Iterator<T> iterator() {
throw new RuntimeException(this.toString());
}
}
|
package org.phenotips.vocabulary.internal.solr;
import org.phenotips.vocabulary.VocabularyTerm;
import org.xwiki.component.annotation.Component;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import javax.inject.Named;
import javax.inject.Singleton;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.DisMaxParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.params.SpellingParams;
/**
* Provides access to the Human Phenotype Ontology (HPO). The ontology prefix is {@code HP}.
*
* @version $Id$
* @since 1.0M8
*/
@Component
@Named("hpo")
@Singleton
public class HumanPhenotypeOntology extends AbstractOBOSolrVocabulary
{
/** For determining if a query is a an id. */
private static final Pattern ID_PATTERN = Pattern.compile("^HP:[0-9]+$", Pattern.CASE_INSENSITIVE);
@Override
protected String getName()
{
return "hpo";
}
@Override
public String getDefaultSourceLocation()
{
return "http://purl.obolibrary.org/obo/hp.obo";
}
@Override
protected int getSolrDocsPerBatch()
{
/* This number should be sufficient to index the whole ontology in one go */
return 15000;
}
@Override
public Set<String> getAliases()
{
Set<String> result = new HashSet<String>();
result.add(getName());
result.add("HP");
result.add("HPO");
return result;
}
@Override
public List<VocabularyTerm> search(String query, int rows, String sort, String customFq)
{
if (StringUtils.isBlank(query)) {
return Collections.emptyList();
}
boolean isId = this.isId(query);
Map<String, String> options = this.getStaticSolrParams();
if (!isId) {
options.putAll(this.getStaticFieldSolrParams());
}
List<VocabularyTerm> result = new LinkedList<>();
for (SolrDocument doc : this.search(produceDynamicSolrParams(query, rows, sort, customFq, isId), options)) {
result.add(new SolrVocabularyTerm(doc, this));
}
return result;
}
private Map<String, String> getStaticSolrParams()
{
Map<String, String> params = new HashMap<>();
params.put("spellcheck", Boolean.toString(true));
params.put(SpellingParams.SPELLCHECK_COLLATE, Boolean.toString(true));
params.put(SpellingParams.SPELLCHECK_COUNT, "100");
params.put(SpellingParams.SPELLCHECK_MAX_COLLATION_TRIES, "3");
params.put("lowercaseOperators", Boolean.toString(false));
params.put("defType", "edismax");
return params;
}
private Map<String, String> getStaticFieldSolrParams()
{
Map<String, String> params = new HashMap<>();
params.put(DisMaxParams.PF, "name^20 nameSpell^36 nameExact^100 namePrefix^30 "
+ "synonym^15 synonymSpell^25 synonymExact^70 synonymPrefix^20 "
+ "text^3 textSpell^5");
params.put(DisMaxParams.QF,
"name^10 nameSpell^18 nameStub^5 synonym^6 synonymSpell^10 synonymStub^3 text^1 textSpell^2 textStub^0.5");
return params;
}
private SolrParams produceDynamicSolrParams(String originalQuery, Integer rows, String sort, String customFq,
boolean isId)
{
String query = originalQuery.trim();
ModifiableSolrParams params = new ModifiableSolrParams();
String escapedQuery = ClientUtils.escapeQueryChars(query);
if (isId) {
params.add(CommonParams.FQ, StringUtils.defaultIfBlank(customFq,
new MessageFormat("id:{0} alt_id:{0}").format(new String[] { escapedQuery })));
} else {
params.add(CommonParams.FQ, StringUtils.defaultIfBlank(customFq, "term_category:HP\\:0000118"));
}
params.add(CommonParams.Q, escapedQuery);
params.add(SpellingParams.SPELLCHECK_Q, query);
params.add(CommonParams.ROWS, rows.toString());
if (StringUtils.isNotBlank(sort)) {
params.add(CommonParams.SORT, sort);
}
return params;
}
private boolean isId(String query)
{
return ID_PATTERN.matcher(query).matches();
}
}
|
package responders;
import library.Constants;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
import tokens.Response;
public class MentionResponder extends Responder {
// Placeholder example auto handler
@Override
public Response process(MessageReceivedEvent event) {
setup(event);
if( containsIgnoreCase(messageText, " " + Constants.NAME + " ") ) {
response = "What is it?";
if( Constants.DEBUG ) {System.out.println("\t\t\t\tMentionResponder triggered.");}
} else if( Constants.DEBUG ) {System.out.println("\t\t\t\tMentionResponder unactivated.");}
if( Constants.DEBUG ) {System.out.println("\t\t\tMentionResponder processed.");}
return build();
}
}
|
package com.ecyrd.jspwiki.plugin;
import org.apache.oro.text.regex.*;
import org.apache.log4j.Logger;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.Map;
import java.util.Vector;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.HashMap;
import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.FileUtil;
import com.ecyrd.jspwiki.TextUtil;
import com.ecyrd.jspwiki.InternalWikiException;
import com.ecyrd.jspwiki.util.ClassUtil;
/**
* Manages plugin classes. There exists a single instance of PluginManager
* per each instance of WikiEngine, that is, each JSPWiki instance.
* <P>
* A plugin is defined to have three parts:
* <OL>
* <li>The plugin class
* <li>The plugin parameters
* <li>The plugin body
* </ol>
*
* For example, in the following line of code:
* <pre>
* [{INSERT com.ecyrd.jspwiki.plugin.FunnyPlugin foo='bar'
* blob='goo'
*
* abcdefghijklmnopqrstuvw
* 01234567890}]
* </pre>
*
* The plugin class is "com.ecyrd.jspwiki.plugin.FunnyPlugin", the
* parameters are "foo" and "blob" (having values "bar" and "goo",
* respectively), and the plugin body is then
* "abcdefghijklmnopqrstuvw\n01234567890". The plugin body is
* accessible via a special parameter called "_body".
* <p>
* If the parameter "debug" is set to "true" for the plugin,
* JSPWiki will output debugging information directly to the page if there
* is an exception.
* <P>
* The class name can be shortened, and marked without the package.
* For example, "FunnyPlugin" would be expanded to
* "com.ecyrd.jspwiki.plugin.FunnyPlugin" automatically. It is also
* possible to defined other packages, by setting the
* "jspwiki.plugin.searchPath" property. See the included
* jspwiki.properties file for examples.
* <P>
* Even though the nominal way of writing the plugin is
* <pre>
* [{INSERT pluginclass WHERE param1=value1...}],
* </pre>
* it is possible to shorten this quite a lot, by skipping the
* INSERT, and WHERE words, and dropping the package name. For
* example:
*
* <pre>
* [{INSERT com.ecyrd.jspwiki.plugin.Counter WHERE name='foo'}]
* </pre>
*
* is the same as
* <pre>
* [{Counter name='foo'}]
* </pre>
*
* @author Janne Jalkanen
* @since 1.6.1
*/
public class PluginManager
{
private static Logger log = Logger.getLogger( PluginManager.class );
/**
* This is the default package to try in case the instantiation
* fails.
*/
public static final String DEFAULT_PACKAGE = "com.ecyrd.jspwiki.plugin";
/**
* The property name defining which packages will be searched for properties.
*/
public static final String PROP_SEARCHPATH = "jspwiki.plugin.searchPath";
/**
* The name of the body content. Current value is "_body".
*/
public static final String PARAM_BODY = "_body";
/**
* A special name to be used in case you want to see debug output
*/
public static final String PARAM_DEBUG = "debug";
Vector m_searchPath = new Vector();
Pattern m_pluginPattern;
private boolean m_pluginsEnabled = true;
/**
* Create a new PluginManager.
*
* @param props Contents of a "jspwiki.properties" file.
*/
public PluginManager( Properties props )
{
String packageNames = props.getProperty( PROP_SEARCHPATH );
if( packageNames != null )
{
StringTokenizer tok = new StringTokenizer( packageNames, "," );
while( tok.hasMoreTokens() )
{
m_searchPath.add( tok.nextToken() );
}
}
// The default package is always added.
m_searchPath.add( DEFAULT_PACKAGE );
PatternCompiler compiler = new Perl5Compiler();
try
{
m_pluginPattern = compiler.compile( "\\{?(INSERT)?\\s*([\\w\\._]+)[ \\t]*(WHERE)?[ \\t]*" );
}
catch( MalformedPatternException e )
{
log.fatal("Internal error: someone messed with pluginmanager patterns.", e );
throw new InternalWikiException( "PluginManager patterns are broken" );
}
}
/**
* Enables or disables plugin execution.
*/
public void enablePlugins( boolean enabled )
{
m_pluginsEnabled = enabled;
}
/**
* Returns plugin execution status. If false, plugins are not
* executed when they are encountered on a WikiPage, and an
* empty string is returned in their place.
*/
public boolean pluginsEnabled()
{
return( m_pluginsEnabled );
}
/**
* Returns true if the link is really command to insert
* a plugin.
* <P>
* Currently we just check if the link starts with "{INSERT",
* or just plain "{" but not "{$".
*
* @param link Link text, i.e. the contents of text between [].
* @return True, if this link seems to be a command to insert a plugin here.
*/
public static boolean isPluginLink( String link )
{
return link.startsWith("{INSERT") ||
(link.startsWith("{") && !link.startsWith("{$"));
}
/**
* Attempts to locate a plugin class from the class path
* set in the property file.
*
* @param classname Either a fully fledged class name, or just
* the name of the file (that is,
* "com.ecyrd.jspwiki.plugin.Counter" or just plain "Counter").
*
* @return A found class.
*
* @throws ClassNotFoundException if no such class exists.
*/
private Class findPluginClass( String classname )
throws ClassNotFoundException
{
return ClassUtil.findClass( m_searchPath, classname );
}
/**
* Outputs a HTML-formatted version of a stack trace.
*/
private String stackTrace( Map params, Throwable t )
{
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter( sw );
out.println("<div class=\"debug\">");
out.println("Plugin execution failed, stack trace follows:");
out.println("<pre>");
t.printStackTrace( out );
out.println("</pre>");
out.println("<b>Parameters to the plugin</b>");
out.println("<ul>");
for( Iterator i = params.keySet().iterator(); i.hasNext(); )
{
String key = (String) i.next();
out.println(" <li>'"+key+"'='"+params.get(key)+"'</li>");
}
out.println("</ul>");
out.println("</div>");
out.flush();
return sw.toString();
}
/**
* Executes a plugin class in the given context.
* <P>Used to be private, but is public since 1.9.21.
*
* @param context The current WikiContext.
* @param classname The name of the class. Can also be a
* shortened version without the package name, since the class name is searched from the
* package search path.
*
* @param params A parsed map of key-value pairs.
*
* @return Whatever the plugin returns.
*
* @throws PluginException If the plugin execution failed for
* some reason.
*
* @since 2.0
*/
public String execute( WikiContext context,
String classname,
Map params )
throws PluginException
{
if( !m_pluginsEnabled )
return( "" );
try
{
Class pluginClass;
WikiPlugin plugin;
log.info("DEBUG="+params.get(PARAM_DEBUG));
boolean debug = TextUtil.isPositive( (String) params.get( PARAM_DEBUG ) );
pluginClass = findPluginClass( classname );
// Create...
try
{
plugin = (WikiPlugin) pluginClass.newInstance();
}
catch( InstantiationException e )
{
throw new PluginException( "Cannot instantiate plugin "+classname, e );
}
catch( IllegalAccessException e )
{
throw new PluginException( "Not allowed to access plugin "+classname, e );
}
catch( Exception e )
{
throw new PluginException( "Instantiation of plugin "+classname+" failed.", e );
}
// ...and launch.
try
{
return plugin.execute( context, params );
}
catch( PluginException e )
{
if( debug )
{
return stackTrace( params, e );
}
// Just pass this exception onward.
throw (PluginException) e.fillInStackTrace();
}
catch( Throwable t )
{
// But all others get captured here.
log.info( "Plugin failed while executing:", t );
if( debug )
{
return stackTrace( params, t );
}
throw new PluginException( "Plugin failed", t );
}
}
catch( ClassNotFoundException e )
{
throw new PluginException( "Could not find plugin "+classname, e );
}
catch( ClassCastException e )
{
throw new PluginException( "Class "+classname+" is not a Wiki plugin.", e );
}
}
/**
* Parses plugin arguments. Handles quotes and all other kewl
* stuff.
*
* @param argstring The argument string to the plugin. This is
* typically a list of key-value pairs, using "'" to escape
* spaces in strings, followed by an empty line and then the
* plugin body.
*
* @return A parsed list of parameters. The plugin body is put
* into a special parameter defined by PluginManager.PARAM_BODY.
*
* @throws IOException If the parsing fails.
*/
public Map parseArgs( String argstring )
throws IOException
{
HashMap arglist = new HashMap();
StringReader in = new StringReader(argstring);
StreamTokenizer tok = new StreamTokenizer(in);
int type;
String param = null, value = null;
tok.eolIsSignificant( true );
boolean potentialEmptyLine = false;
boolean quit = false;
while( !quit )
{
String s;
type = tok.nextToken();
switch( type )
{
case StreamTokenizer.TT_EOF:
quit = true;
s = null;
break;
case StreamTokenizer.TT_WORD:
s = tok.sval;
potentialEmptyLine = false;
break;
case StreamTokenizer.TT_EOL:
quit = potentialEmptyLine;
potentialEmptyLine = true;
s = null;
break;
case StreamTokenizer.TT_NUMBER:
s = Integer.toString( new Double(tok.nval).intValue() );
potentialEmptyLine = false;
break;
case '\'':
s = tok.sval;
break;
default:
s = null;
}
// Assume that alternate words on the line are
// parameter and value, respectively.
if( s != null )
{
if( param == null )
{
param = s;
}
else
{
value = s;
arglist.put( param, value );
// log.debug("ARG: "+param+"="+value);
param = null;
}
}
}
// Now, we'll check the body.
if( potentialEmptyLine )
{
StringWriter out = new StringWriter();
FileUtil.copyContents( in, out );
String bodyContent = out.toString();
if( bodyContent != null )
{
arglist.put( PARAM_BODY, bodyContent );
}
}
return arglist;
}
/**
* Parses a plugin. Plugin commands are of the form:
* [{INSERT myplugin WHERE param1=value1, param2=value2}]
* myplugin may either be a class name or a plugin alias.
* <P>
* This is the main entry point that is used.
*
* @param context The current WikiContext.
* @param commandline The full command line, including plugin
* name, parameters and body.
*
* @return HTML as returned by the plugin, or possibly an error
* message.
*/
public String execute( WikiContext context,
String commandline )
throws PluginException
{
if( !m_pluginsEnabled )
return( "" );
PatternMatcher matcher = new Perl5Matcher();
try
{
if( matcher.contains( commandline, m_pluginPattern ) )
{
MatchResult res = matcher.getMatch();
String plugin = res.group(2);
String args = commandline.substring(res.endOffset(0),
commandline.length() -
(commandline.charAt(commandline.length()-1) == '}' ? 1 : 0 ) );
Map arglist = parseArgs( args );
return execute( context, plugin, arglist );
}
}
catch( NoSuchElementException e )
{
String msg = "Missing parameter in plugin definition: "+commandline;
log.warn( msg, e );
throw new PluginException( msg );
}
catch( IOException e )
{
String msg = "Zyrf. Problems with parsing arguments: "+commandline;
log.warn( msg, e );
throw new PluginException( msg );
}
// FIXME: We could either return an empty string "", or
// the original line. If we want unsuccessful requests
// to be invisible, then we should return an empty string.
return commandline;
}
/*
// FIXME: Not functioning, needs to create or fetch PageContext from somewhere.
public class TagPlugin implements WikiPlugin
{
private Class m_tagClass;
public TagPlugin( Class tagClass )
{
m_tagClass = tagClass;
}
public String execute( WikiContext context, Map params )
throws PluginException
{
WikiPluginTag plugin = m_tagClass.newInstance();
}
}
*/
}
|
package rit.eyeTracking;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Maintains the connections between sources, filters and drains.
*/
public class FilterChain<T> implements EyeTrackingListener {
private final List<Filter<T>> filters;
private final List<Filter<T>> runtimeFilters = new ArrayList<Filter<T>>();
public FilterChain(Filter<T>[] filters) {
this.filters = new CopyOnWriteArrayList<Filter<T>>(Arrays.asList(filters));
}
public boolean hasFilter(Class<?> clazz) {
for(Filter<T> filter: filters) {
if(filter.getClass() == clazz)
return true;
}
return false;
}
/**
* Returns the instance of the given filterClass from the filterChain, or null.
*
* @param filterClass
* @return
*/
@SuppressWarnings("unchecked")
public <S extends Filter<T>> S getFilter(Class<?> filterClass) {
for(Filter<T> filter: filters) {
if(filter.getClass() == filterClass)
return (S)filter;
}
return null;
}
/**
* Adds a filter to the beginning of the chain.
*
* @param filter
*
* @deprecated Filters should be ordered automatically based on the
* attributes they create and consume. An exception should be
* raised if an attempt is made to access an attribute not declared
* as being consumed by the filter.
*/
public void prepend(Filter<T> filter) {
filters.add(0, filter);
runtimeFilters.add(0, filter);
}
/**
* Add a filter at runtime, e.g. to enable plugins to transparently access
* information provided in the event stream without requiring the user to
* edit the filter chain configuration file.
*
* @param filter
*/
public void add(Filter<T> filter) {
filters.add(filter);
runtimeFilters.add(filter);
}
public void remove(Filter<T> filter) {
if(runtimeFilters.contains(filter)) {
filters.remove(filter);
runtimeFilters.remove(filter);
} else {
throw new IllegalArgumentException("Cannot remove filter not added at runtime");
}
}
public void start(T obj, EyeTrackingListener listener, Mode mode) {
for(Filter<T> filter : filters) {
filter.start(obj, listener, mode);
}
}
public void stop(T obj, EyeTrackingListener listener, Mode mode) {
for(Filter<T> filter : filters) {
filter.stop(obj, listener, mode);
}
}
@Override
public void notify(Event e, EyeTrackingListener listener, Mode mode) {
for(Filter<T> filter : filters) {
filter.notify(e, listener, mode);
}
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("FilterChain:\n");
for(Filter<T> filter: filters) {
sb.append(filter.getClass().getName()+"\n");
}
return sb.toString();
}
}
|
package org.duracloud.services.script;
import org.duracloud.services.BaseService;
import org.duracloud.services.ComputeService;
import org.duracloud.services.script.error.ScriptServiceException;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Dictionary;
import java.util.Map;
public class ScriptService extends BaseService implements ComputeService, ManagedService {
public static enum OS {
Windows, Linux, MacOSX
}
private static final String START_SCRIPT = "start";
private static final String STOP_SCRIPT = "stop";
private static final String WIN_EXT = ".bat";
private static final String LIN_EXT = ".sh";
private final Logger log = LoggerFactory.getLogger(ScriptService.class);
@Override
public void start() throws Exception {
File workDir = new File(getServiceWorkDir());
log.info("Starting Script Service: " + workDir.getName());
this.setServiceStatus(ServiceStatus.STARTING);
String startScriptName = getScriptName(START_SCRIPT);
checkScriptExists(startScriptName);
String script = new File(workDir, startScriptName).getAbsolutePath();
log.info("Running Script: " + script);
ProcessBuilder pb = new ProcessBuilder(script);
pb.directory(workDir);
Process p = pb.start();
this.setServiceStatus(ServiceStatus.STARTED);
}
@Override
public void stop() throws Exception {
File workDir = new File(getServiceWorkDir());
log.info("Stopping Script Service: " + workDir.getName());
this.setServiceStatus(ServiceStatus.STOPPING);
String stopScriptName = getScriptName(STOP_SCRIPT);
checkScriptExists(stopScriptName);
String script = new File(workDir, stopScriptName).getAbsolutePath();
log.info("Running Script: " + script);
ProcessBuilder pb = new ProcessBuilder(script);
pb.directory(workDir);
Process p = pb.start();
this.setServiceStatus(ServiceStatus.STOPPED);
}
private String getScriptName(String script) {
OS os = determineOS();
String scriptFileName = script;
if (os.equals(OS.Linux) || os.equals(OS.MacOSX)) { // Linux or Mac
scriptFileName = scriptFileName + LIN_EXT;
} else { // Windows
scriptFileName = scriptFileName + WIN_EXT;
}
return scriptFileName;
}
private void checkScriptExists(String scriptName) {
File scriptFile = new File(getServiceWorkDir(), scriptName);
if (!scriptFile.exists()) {
String error =
"No script available at: " + scriptFile.getAbsolutePath();
throw new ScriptServiceException(error);
} else {
scriptFile.setExecutable(true);
}
}
public OS determineOS() {
String osName = System.getProperty("os.name");
if (osName.toLowerCase().indexOf("windows") >= 0) {
return OS.Windows;
} else if (osName.toLowerCase().indexOf("linux") >= 0) {
return OS.Linux;
} else if (osName.toLowerCase().indexOf("mac os x") >= 0) {
return OS.MacOSX;
} else {
String error = "No script version available for OS: " + osName;
throw new ScriptServiceException(error);
}
}
@Override
public Map<String, String> getServiceProps() {
Map<String, String> props = super.getServiceProps();
return props;
}
@SuppressWarnings("unchecked")
public void updated(Dictionary config) throws ConfigurationException {
// Implementation not needed. Update performed through setters.
}
}
|
package com.fullmetalgalaxy.model.persist;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.Transient;
import com.fullmetalgalaxy.model.BoardFireCover;
import com.fullmetalgalaxy.model.EnuColor;
import com.fullmetalgalaxy.model.GameEventStack;
import com.fullmetalgalaxy.model.GameStatus;
import com.fullmetalgalaxy.model.HexCoordinateSystem;
import com.fullmetalgalaxy.model.HexTorusCoordinateSystem;
import com.fullmetalgalaxy.model.LandType;
import com.fullmetalgalaxy.model.Location;
import com.fullmetalgalaxy.model.MapShape;
import com.fullmetalgalaxy.model.Mobile;
import com.fullmetalgalaxy.model.RpcFmpException;
import com.fullmetalgalaxy.model.RpcUtil;
import com.fullmetalgalaxy.model.Sector;
import com.fullmetalgalaxy.model.SharedMethods;
import com.fullmetalgalaxy.model.Tide;
import com.fullmetalgalaxy.model.TokenType;
import com.fullmetalgalaxy.model.constant.ConfigGameTime;
import com.fullmetalgalaxy.model.constant.FmpConstant;
import com.fullmetalgalaxy.model.pathfinder.PathGraph;
import com.fullmetalgalaxy.model.pathfinder.PathMobile;
import com.fullmetalgalaxy.model.pathfinder.PathNode;
import com.fullmetalgalaxy.model.persist.gamelog.AnEvent;
import com.fullmetalgalaxy.model.persist.gamelog.EbEvtMessage;
import com.fullmetalgalaxy.model.persist.gamelog.EbEvtMove;
import com.fullmetalgalaxy.model.persist.gamelog.EventsPlayBuilder;
import com.fullmetalgalaxy.model.persist.triggers.EbTrigger;
/**
* @author Kroc
* This class represent the board model on both client/server side.
* ie: all data needed by the board application on client side to run correctly.
*/
public class Game extends GameData implements PathGraph, GameEventStack
{
private static final long serialVersionUID = -717221858626185781L;
transient private TokenIndexSet m_tokenIndexSet = null;
transient private GameEventStack m_eventStack = this;
transient private BoardFireCover m_fireCover = null;
transient private HexCoordinateSystem m_coordinateSystem = null;
public Game()
{
super();
init();
}
public Game(EbGamePreview p_preview, EbGameData p_data)
{
super(p_preview, p_data);
}
private void init()
{
setConfigGameTime( ConfigGameTime.Standard );
}
@Override
public void reinit()
{
super.reinit();
this.init();
}
public HexCoordinateSystem getCoordinateSystem()
{
if( m_coordinateSystem == null )
{
if( getMapShape() == MapShape.Flat )
{
m_coordinateSystem = new HexCoordinateSystem();
} else {
m_coordinateSystem = new HexTorusCoordinateSystem( getMapShape(), getLandWidth(),
getLandHeight() );
}
}
return m_coordinateSystem;
}
/**
*
* @return true if game message start with recording tag
*/
public boolean isRecordingScript()
{
return getMessage() != null
&& getMessage().startsWith( EventsPlayBuilder.GAME_MESSAGE_RECORDING_TAG );
}
/**
* if game is in parallel mode, search the registration that lock an hexagon.
* @param p_position
* @return null if no registration lock that hexagon
*/
public EbTeam getOtherTeamBoardLocked(EbRegistration p_myRegistration,
AnBoardPosition p_position, long p_currentTime)
{
if( !isParallel() || p_position == null || p_position.getX() < 0 )
{
return null;
}
for( EbTeam team : getTeams() )
{
if( p_myRegistration.getTeam( this ) != team && team.getEndTurnDate() != null
&& team.getLockedPosition() != null )
{
if( team.getEndTurnDate().getTime() < p_currentTime )
{
team.setEndTurnDate( null );
team.setLockedPosition( null );
}
else if( getCoordinateSystem().getDiscreteDistance(
team.getLockedPosition(), p_position ) <= FmpConstant.parallelLockRadius )
{
return team;
}
}
}
return null;
}
public void addToken(EbToken p_token)
{
if( p_token.getId() == 0 )
{
p_token.setId( getNextLocalId() );
p_token.setVersion( 1 );
}
if( !getSetToken().contains( p_token ) )
{
getSetToken().add( p_token );
getTokenIndexSet().addToken( p_token );
getBoardFireCover().incFireCover( p_token );
if( p_token.containToken() )
{
for( EbToken token : p_token.getContains() )
{
addToken( token );
}
}
}
updateLastTokenUpdate( null );
}
public boolean haveNewMessage(Date p_since)
{
if( p_since == null )
return true;
int index = getLogs().size() - 1;
Date lastEventDate = null;
while( index > 0 && (lastEventDate == null || lastEventDate.after( p_since )) )
{
if( getLogs().get( index ) instanceof EbEvtMessage )
{
return true;
}
lastEventDate = getLogs().get( index ).getLastUpdate();
index
}
return false;
}
public void addEvent(AnEvent p_action)
{
p_action.setGame( this );
if( p_action.getId() == 0 )
{
p_action.setId( getNextLocalId() );
}
else if( p_action.getId() != getNextLocalId() )
{
RpcUtil.logError( "EbGame::addEvent(): p_action.getId() != getNextLocalId()" );
}
if( !getLogs().contains( p_action ) )
{
getLogs().add( p_action );
}
else
{
RpcUtil.logError( "EbGame::addEvent(): logs already contain " + p_action );
}
}
public Date getEndDate()
{
if( getLastLog() != null )
{
return getLastLog().getLastUpdate();
}
else
{
return getLastUpdate();
}
}
@Override
public AnEvent getLastGameLog()
{
if( getLogs().size() > 0 )
{
return getLogs().get( getLogs().size() - 1 );
}
return null;
}
@Override
public AnEvent getLastGameLog(int p_count)
{
if( getLogs().size() < p_count )
{
return null;
}
return getLogs().get( getLogs().size() - (1 + p_count) );
}
public AnEvent getLastLog()
{
if( m_eventStack == null )
{
return getLastGameLog();
}
AnEvent event = m_eventStack.getLastGameLog();
if( event == null )
{
return getLastGameLog();
}
return event;
}
public AnEvent getLastLog(int p_count)
{
if( m_eventStack == null )
{
return getLastGameLog( p_count );
}
AnEvent event = m_eventStack.getLastGameLog( p_count );
if( event == null )
{
return getLastGameLog( p_count );
}
return event;
}
public GameEventStack getGameEventStack()
{
return m_eventStack;
}
public void setGameEventStack(GameEventStack p_stack)
{
m_eventStack = p_stack;
}
public int getNextTideChangeTimeStep()
{
return getLastTideChange() + getEbConfigGameTime().getTideChangeFrequency();
}
public Date estimateTimeStepDate(int p_step)
{
long timeStepDurationInMili = getEbConfigGameTime().getTimeStepDurationInMili();
if( !isParallel() )
{
timeStepDurationInMili *= getSetRegistration().size();
}
return new Date( getLastTimeStepChange().getTime() + (p_step - getCurrentTimeStep())
* timeStepDurationInMili );
}
public Date estimateNextTimeStep()
{
return estimateTimeStepDate( getCurrentTimeStep() + 1 );
}
public Date estimateNextTideChange()
{
return estimateTimeStepDate( getNextTideChangeTimeStep() );
}
/**
* If the game is paused, return a dummy value
* @return the endingDate
*/
public Date estimateEndingDate()
{
Date date = null;
if( getStatus() != GameStatus.Running )
{
date = new Date( Long.MAX_VALUE );
}
else
{
date = estimateTimeStepDate( getEbConfigGameTime().getTotalTimeStep() );
}
return date;
}
/**
* return the bitfields of all opponents fire cover at the given position.
* @param p_token
* @return
*/
public EnuColor getOpponentFireCover(int p_myColorValue, AnBoardPosition p_position)
{
EnuColor fireCover = getBoardFireCover().getFireCover( p_position );
fireCover.removeColor( p_myColorValue );
return fireCover;
}
/**
* @return true if the colored player have at least one weather hen to predict future tides.
*/
public int countWorkingWeatherHen(EnuColor p_color)
{
int count = 0;
for( Iterator<EbToken> it = getSetToken().iterator(); it.hasNext(); )
{
EbToken token = (EbToken)it.next();
if( (p_color.isColored( token.getColor() ))
&& (token.getType() == TokenType.WeatherHen)
&& (token.getColor() != EnuColor.None)
&& (token.getLocation() == Location.Board)
&& (isTokenTideActive( token ))
&& (isTokenFireActive( token ) ) )
{
count++;
}
}
return count;
}
/**
* @return true if the logged player have at least one Freighter landed.
*/
public boolean isLanded(EnuColor p_color)
{
for( Iterator<EbToken> it = getSetToken().iterator(); it.hasNext(); )
{
EbToken token = (EbToken)it.next();
if( (p_color.isColored( token.getColor() )) && (token.getType() == TokenType.Freighter)
&& (token.getLocation() == Location.Board) )
{
return true;
}
}
return false;
}
/**
*
* @param p_token
* @return all color of this token owner. no color if p_token have no color
*/
public EnuColor getTokenOwnerColor(EbToken p_token)
{
// first determine the token owner color
EnuColor tokenOwnerColor = p_token.getEnuColor();
if( tokenOwnerColor.getValue() != EnuColor.None )
{
for( EbRegistration registration : getSetRegistration() )
{
if( registration.getEnuColor().isColored( p_token.getColor() ) )
{
tokenOwnerColor.addColor( registration.getColor() );
break;
}
}
}
return tokenOwnerColor;
}
public EnuColor getTokenTeamColors(EbToken p_token)
{
// first determine the token owner color
EnuColor tokenOwnerColor = p_token.getEnuColor();
if( tokenOwnerColor.getValue() != EnuColor.None )
{
for( EbTeam team : getTeams() )
{
EnuColor color = new EnuColor(team.getColors( getPreview() ));
if( color.isColored( p_token.getColor() ) )
{
tokenOwnerColor.addColor( color );
break;
}
}
}
return tokenOwnerColor;
}
/**
* return the bitfields of all opponents fire cover on this token.<br/>
* note: if p_token is color less or not on board, always return EnuColor.None
* @param p_token
* @return
*/
public EnuColor getOpponentFireCover(EbToken p_token)
{
if( p_token.getLocation() != Location.Board || p_token.getColor() == EnuColor.None )
{
return new EnuColor( EnuColor.None );
}
// first determine the token owner color
EnuColor tokenTeamColor = getTokenTeamColors( p_token );
EnuColor fireCover = getOpponentFireCover( tokenTeamColor.getValue(), p_token.getPosition() );
if( p_token.getHexagonSize() == 2 )
{
fireCover.addColor( getOpponentFireCover( tokenTeamColor.getValue(),
(AnBoardPosition)p_token.getExtraPositions(getCoordinateSystem()).get( 0 ) ) );
}
return fireCover;
}
/**
* @param p_token
* true if this token is in a forbidden position. ie: if p_token is a tank near another on mountain.
* @return the token with witch this token is cheating
*/
public EbToken getTankCheating(EbToken p_token)
{
if( p_token.getType() != TokenType.Tank || p_token.getLocation() != Location.Board )
{
return null;
}
AnBoardPosition tokenPosition = p_token.getPosition();
if( getLand( tokenPosition ) != LandType.Montain )
{
return null;
}
Sector sectorValues[] = Sector.values();
for( int i = 0; i < sectorValues.length; i++ )
{
AnBoardPosition neighborPosition = getCoordinateSystem().getNeighbor( tokenPosition, sectorValues[i] );
EnuColor tokenTeamColor = getTokenTeamColors( p_token );
if( getLand( neighborPosition ) == LandType.Montain )
{
EbToken token = getToken( neighborPosition );
if( (token != null) && (token.getType() == TokenType.Tank)
&& (tokenTeamColor.isColored( token.getColor() )) )
{
// this tank is cheating
return token;
}
}
}
return null;
}
/**
* similar to 'getTankCheating' but simply return true if this token is in a forbidden position
* AND is the one which should be tag as cheater.
* => only of the tow tank: the lower ID
* @param p_token
* @return
*/
public boolean isTankCheating(EbToken p_token)
{
EbToken nearTank = getTankCheating(p_token);
return (nearTank!=null) && (nearTank.getId() > p_token.getId());
}
/**
* Should be called only on server side.
* Move a token and all token he contain into any other token in the game.
* @param p_tokenToMove
* @param p_tokenCarrier must be included in TokenList
* @throws RpcFmpException
*
*/
public void moveToken(EbToken p_tokenToMove, EbToken p_tokenCarrier) // throws
// RpcFmpException
{
getBoardFireCover().decFireCover( p_tokenToMove );
m_tokenIndexSet.setPosition( p_tokenToMove, Location.Token );
if( p_tokenToMove.getCarrierToken() != null )
{
// first unload from token
p_tokenToMove.getCarrierToken().unloadToken( p_tokenToMove );
}
p_tokenCarrier.loadToken( p_tokenToMove );
if( p_tokenToMove.canBeColored() )
{
// if a token enter inside another token, it take his color
p_tokenToMove.setColor( p_tokenCarrier.getColor() );
}
getBoardFireCover().incFireCover( p_tokenToMove );
// incFireCover( p_tokenToMove );
// this update is here only to refresh token display during time mode
updateLastTokenUpdate( null );
}
/**
* Warning: this method don't check anything about fire disabling flag.
* @param p_token
* @param p_newColor
*/
public void changeTokenColor(EbToken p_token, int p_newColor)
{
getBoardFireCover().decFireCover( p_token );
p_token.setColor( p_newColor );
getBoardFireCover().incFireCover( p_token );
if( p_token.containToken() )
{
for( EbToken token : p_token.getContains() )
{
if( token.canBeColored() )
{
token.setColor( p_newColor );
}
}
}
}
/**
* Move a token to any other position on the board.
* @param p_token
* @param p_position have to be inside the board (no check are performed).
*/
public void moveToken(EbToken p_token, AnBoardPosition p_position)
{
getBoardFireCover().decFireCover( p_token );
if( p_token.getCarrierToken() != null )
{
// first unload from token
p_token.getCarrierToken().unloadToken( p_token );
}
getTokenIndexSet().setPosition( p_token, new AnBoardPosition( p_position ) );
getBoardFireCover().incFireCover( p_token );
// this update is here only to refresh token display during time mode
updateLastTokenUpdate( null );
}
/**
* Warning: if you use this method with p_location == Board, you should be sure
* that his position is already set to the right value.
* @param p_token
* @param p_locationValue should be EnuLocation.Graveyard or EnuLocation.Orbit
* @throws RpcFmpException
*/
public void moveToken(EbToken p_token, Location p_location) throws RpcFmpException
{
getBoardFireCover().decFireCover( p_token );
if( p_token.getCarrierToken() != null )
{
// first unload from token
p_token.getCarrierToken().unloadToken( p_token );
}
getTokenIndexSet().setPosition( p_token, p_location );
getBoardFireCover().incFireCover( p_token );
// this update is here only to refresh token display during time mode
updateLastTokenUpdate( null );
}
public void removeToken(EbToken p_token)
{
try
{
moveToken( p_token, Location.Graveyard );
} catch( RpcFmpException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
getTokenIndexSet().removeToken( p_token );
getSetToken().remove( p_token );
p_token.incVersion();
}
public EbTeam getWinnerTeam()
{
EbTeam winner = null;
int point = 0;
for( EbTeam team : getTeams() )
{
if( team.estimateWinningScore(this) > point )
{
winner = team;
point = team.estimateWinningScore( this );
}
}
return winner;
}
public List<EbTeam> getTeamByWinningRank()
{
List<EbTeam> sortedTeam = new ArrayList<EbTeam>();
Map<EbTeam, Integer> winningPoint = new HashMap<EbTeam, Integer>();
for( EbTeam team : getTeams() )
{
int wp = team.estimateWinningScore(this);
int index = 0;
while( index < sortedTeam.size() )
{
if( wp > winningPoint.get( sortedTeam.get( index ) ) )
{
break;
}
index++;
}
winningPoint.put( team, wp );
sortedTeam.add( index, team );
}
return sortedTeam;
}
/**
* return next registration which control at least one freighter on board.
* If no registration control any freighter on board, return the current players registration.
* If p_currentIndex == -1, return the first registration that control one freighter
* @param p_currentIndex
* @return
*/
public EbTeam getNextTeam2Play(int p_currentIndex)
{
int index = p_currentIndex;
List<EbTeam> teams = getTeamByPlayOrder();
EbTeam team = null;
do
{
index++;
try
{
team = teams.get( index );
} catch( Exception e )
{
team = null;
}
if( team == null )
{
// next turn !
index = 0;
team = teams.get( index );
// avoid infinite loop
if( p_currentIndex < 0 )
break;
}
assert team != null;
} while( (team.getOnBoardFreighterCount( this ) == 0 || !team.haveAccount( getPreview() ))
&& (index != p_currentIndex) );
return team;
}
/**
* count the number of freighter remaining on board this player control
* @param p_registration
* @return true if player have at least one freighter on board or in orbit
*/
protected boolean haveBoardFreighter(EbRegistration p_registration)
{
if( p_registration.getColor() == EnuColor.None )
{
return false;
}
if( !getAllowedTakeOffTurns().isEmpty()
&& getCurrentTimeStep() < getAllowedTakeOffTurns().get( 0 ) )
{
return true;
}
for( EbToken token : getSetToken() )
{
if( (token.getType() == TokenType.Freighter)
&& (p_registration.getEnuColor().isColored( token.getColor() ))
&& ((token.getLocation() == Location.Board) || (token.getLocation() == Location.Orbit)) )
{
return true;
}
}
return false;
}
/**
*
* @param p_registration
* @return false if player can't deploy unit for free
*/
public boolean canDeployUnit(EbRegistration p_registration)
{
if( getEbConfigGameTime().getDeploymentTimeStep() < getCurrentTimeStep() )
{
// too late
return false;
}
if( !isParallel() && getEbConfigGameTime().getDeploymentTimeStep() != getCurrentTimeStep() )
{
// too early
return false;
}
// check that, in parallel, player don't wan't to deploy after his first
// move
if( isParallel() )
{
int index = getLogs().size();
while( index > 0 )
{
index
AnEvent event = getLogs().get( index );
if( event instanceof EbEvtMove
&& ((EbEvtMove)event).getMyRegistration( this ).getId() == p_registration.getId() )
{
return false;
}
}
}
return true;
}
/**
*
* @return time step duration multiply by the players count.
*/
public long getFullTurnDurationInMili()
{
return getEbConfigGameTime().getTimeStepDurationInMili() * getSetRegistration().size();
}
/**
* offset height in pixel to display token image in tactic zoom.
* it represent the land height.
* take in account tide.
* @param p_x
* @param p_y
* @return
*/
public int getLandPixOffset(AnPair p_position)
{
LandType land = getLand( p_position );
switch( land )
{
default:
return getLandPixOffset( land );
case Sea:
if( getCurrentTide() == Tide.Low )
{
return getLandPixOffset( LandType.Sea );
}
case Reef:
if( getCurrentTide() != Tide.Hight )
{
return getLandPixOffset( LandType.Reef );
}
case Marsh:
return getLandPixOffset( LandType.Marsh );
}
}
/**
* offset height in pixel to display token image in tactic zoom.
* it represent the land height.
* do not take in account tide
*/
public static int getLandPixOffset(LandType p_landValue)
{
switch( p_landValue )
{
case Montain:
return -7;
case Sea:
return 6;
case Reef:
return 5;
case Marsh:
return 2;
default:
return 0;
}
}
// come from token list
/**
* it keep the latest lastUpdate of the token list.
*/
@Transient
private Date m_lastTokenUpdate = new Date( 0 );
public Date getLastTokenUpdate()
{
if( m_lastTokenUpdate == null )
{
m_lastTokenUpdate = new Date( SharedMethods.currentTimeMillis() );
}
return m_lastTokenUpdate;
}
public void updateLastTokenUpdate(Date p_lastUpdate)
{
if( p_lastUpdate == null )
{
m_lastTokenUpdate = new Date( SharedMethods.currentTimeMillis() );
}
else if( p_lastUpdate.after( m_lastTokenUpdate ) )
{
m_lastTokenUpdate = p_lastUpdate;
}
}
/**
*
* @param p_registration
* @return first freighter owned by p_registration. null if not found.
*/
public EbToken getFreighter( EbRegistration p_registration)
{
if( p_registration == null )
{
return null;
}
EnuColor color = p_registration.getEnuColor();
for( EbToken token : getSetToken() )
{
if( token.getType() == TokenType.Freighter && token.getColor() != EnuColor.None
&& color.isColored( token.getColor() ) )
{
return token;
}
}
return null;
}
public List<EbToken> getAllFreighter(int p_color)
{
EnuColor color = new EnuColor( p_color );
List<EbToken> list = new ArrayList<EbToken>();
if( color == null || color.getNbColor() == 0 )
{
return list;
}
for( EbToken token : getSetToken() )
{
if( token.getType() == TokenType.Freighter && token.getColor() != EnuColor.None
&& color.isColored( token.getColor() ) )
{
list.add( token );
}
}
return list;
}
/**
* search over m_token for a token
* @param p_id
* @return null if no token found
*/
public EbToken getToken(long p_id)
{
return getTokenIndexSet().getToken( p_id );
}
/**
* search over m_token and m_tokenLocation for the most relevant token at a given position
* @param p_position
* @return the first colored (or by default the first colorless) token encountered at given position.
*/
public EbToken getToken(AnBoardPosition p_position)
{
Set<EbToken> list = getAllToken( p_position );
EbToken token = null;
for( Iterator<EbToken> it = list.iterator(); it.hasNext(); )
{
EbToken nextToken = (EbToken)it.next();
if( (token == null) || (token.getZIndex() < nextToken.getZIndex()) )
{
token = nextToken;
}
}
return token;
}
/**
* This method extract one specific token in the token list.
* @param p_position
* @param p_tokenType
* @return null if not found
*/
public EbToken getToken(AnBoardPosition p_position, TokenType p_tokenType)
{
EbToken token = null;
for( Iterator<EbToken> it = getAllToken( p_position ).iterator(); it.hasNext(); )
{
EbToken nextToken = (EbToken)it.next();
if( nextToken.getType() == p_tokenType )
{
token = nextToken;
}
}
return token;
}
/**
* note: this method assume that every token are located only once to a single position.
* (ie the couple [tokenId;position] is unique in m_tokenLocation)
* @param p_position
* @return a list of all token located at p_position
*/
public Set<EbToken> getAllToken(AnBoardPosition p_position)
{
Set<EbToken> allTokens = getTokenIndexSet().getAllToken(
getCoordinateSystem().normalizePosition( p_position ) );
if( allTokens != null )
{
return new HashSet<EbToken>(allTokens);
}
return new HashSet<EbToken>();
}
/**
* determine if this token can load the given token
* @param p_carrier the token we want load
* @param p_token the token we want load
* @return
*/
public boolean canTokenLoad(EbToken p_carrier, EbToken p_token)
{
assert p_carrier != null;
assert p_token != null;
if( !p_carrier.canLoad( p_token.getType() ) )
{
return false;
}
int freeLoadingSpace = p_carrier.getType().getLoadingCapability();
if( p_carrier.containToken() )
{
for( EbToken token : p_carrier.getContains() )
{
freeLoadingSpace -= token.getType().getLoadingSize();
}
}
return freeLoadingSpace >= p_token.getFullLoadingSize();
}
/**
* the number of destructor owned by p_registration which can fire on this hexagon
* @param p_x
* @param p_y
* @param p_registration
* @return
*/
public int getFireCover(int p_x, int p_y, EbTeam p_team)
{
EnuColor regColor = new EnuColor( p_team.getFireColor() );
return getBoardFireCover().getFireCover( new AnBoardPosition( p_x, p_y ), regColor );
}
public void invalidateFireCover()
{
getBoardFireCover().invalidateFireCover();
}
public BoardFireCover getBoardFireCover()
{
if( m_fireCover == null )
{
m_fireCover = new BoardFireCover( this );
}
return m_fireCover;
}
/**
* determine if this token is active depending of current tide.
* ie: not under water for lands unit or land for see units.
* @param p_token
* @return
*/
public boolean isTokenTideActive(EbToken p_token)
{
if( (p_token == null) )
{
return false;
}
// if p_token is contained by another token, p_token is active only if
// this
// other token is active
if( (p_token.getLocation() == Location.Token)
|| (p_token.getLocation() == Location.ToBeConstructed) )
{
return isTokenTideActive( (EbToken)p_token.getCarrierToken() );
}
if( (p_token.getLocation() == Location.Graveyard) )
{
return false;
}
if( p_token.getLocation() == Location.Orbit )
{
return true;
}
// ok so token if on board.
// determine, according to current tide, if the first position is sea,
// plain or montain
LandType landValue = getLand( p_token.getPosition() ).getLandValue( getCurrentTide() );
if( landValue == LandType.None )
{
return false;
}
switch( p_token.getType() )
{
case Barge:
LandType extraLandValue = getLand( p_token.getExtraPositions(getCoordinateSystem()).get( 0 ) )
.getLandValue( getCurrentTide() );
if( extraLandValue != LandType.Sea )
{
if( getToken( p_token.getExtraPositions(getCoordinateSystem()).get( 0 ), TokenType.Sluice ) != null )
{
return true;
}
return false;
}
case Speedboat:
case Tarask:
case Crayfish:
if( landValue != LandType.Sea )
{
if( getToken( p_token.getPosition(), TokenType.Sluice ) != null )
{
return true;
}
return false;
}
return true;
case Heap:
case Tank:
case Crab:
case WeatherHen:
case Ore0:
case Ore:
case Ore3:
case Ore5:
if( landValue == LandType.Sea )
{
if( getToken( p_token.getPosition(), TokenType.Pontoon ) != null )
{
return true;
}
return false;
}
return true;
case Turret:
case Freighter:
case Pontoon:
case Sluice:
case Hovertank:
default:
return true;
}
}
/**
* determine if this token is active depending of opponents fire cover.<br/>
* note that even if we don't display any warning, this method will return false
* for an uncolored token.
* @param p_token
* @return
*/
public boolean isTokenFireActive(EbToken p_token)
{
EnuColor teamColor = getTokenTeamColors( p_token );
return((p_token.getType() == TokenType.Freighter) || (p_token.getType() == TokenType.Turret)
|| (teamColor.getValue() == EnuColor.None) || (getOpponentFireCover(
teamColor.getValue(), p_token.getPosition() ).getValue() == EnuColor.None));
}
/**
* determine weather the given token can produce or not a fire cover.
* If not, his fire cover will increment the disabled fire cover to show it to player
* @param p_token
* @return
*/
public boolean isTokenFireCoverDisabled(EbToken p_token)
{
if( p_token == null || !p_token.getType().isDestroyer() )
{
return false;
}
// if( !isTokenFireActive( p_token ) )
if( p_token.isFireDisabled() )
{
return true;
}
if( !isTokenTideActive( p_token ) )
{
return true;
}
if( isTankCheating( p_token ) )
{
return true;
}
return false;
}
/**
* TODO half redundant with isTokenTideActive
* note that any token are allowed to voluntary stuck themself into reef of marsh
* @param p_token
* @param p_position
* @return true if token can move to p_position according to tide
*/
public boolean canTokenMoveOn(EbToken p_token, AnBoardPosition p_position)
{
if( (p_token == null) || (!isTokenTideActive( p_token )) || (p_position == null)
|| (p_position.getX() < 0) || (p_position.getY() < 0) )
{
return false;
}
if( p_token.getHexagonSize() == 2 )
{
AnBoardPosition position = getCoordinateSystem().getNeighbor( p_position, p_position.getSector() );
EbToken tokenPontoon = getToken( position, TokenType.Pontoon );
if( tokenPontoon == null )
tokenPontoon = getToken( position, TokenType.Sluice );
if( tokenPontoon != null )
{
return tokenPontoon.canLoad( p_token.getType() );
}
// check this token is allowed to move on this hexagon
if( p_token.canMoveOn( this, getLand( position ) ) == false )
{
return false;
}
}
EbToken tokenPontoon = getToken( p_position, TokenType.Pontoon );
if( tokenPontoon == null )
tokenPontoon = getToken( p_position, TokenType.Sluice );
if( tokenPontoon != null )
{
return tokenPontoon.canLoad( p_token.getType() );
}
// check this token is allowed to move on this hexagon
return p_token.canMoveOn( this, getLand( p_position ) );
}
/**
* determine if this token can fire onto a given position
* Warning: it doesn't check tide or fire disable flag !
* @param p_token
* @param p_position
* @return
*/
public boolean canTokenFireOn(EbToken p_token, AnBoardPosition p_position)
{
if( (p_token.getLocation() != Location.Board) || (!p_token.getType().isDestroyer()) )
{
return false;
}
return getCoordinateSystem().getDiscreteDistance( p_token.getPosition(), p_position ) <= (getTokenFireLength( p_token ));
}
/**
* determine if this token can fire onto a given token
* Warning: it doesn't check tide or fire disable flag !
* @param p_token
* @param p_tokenTarget
* @return
*/
public boolean canTokenFireOn(EbToken p_token, EbToken p_tokenTarget)
{
if( canTokenFireOn( p_token, p_tokenTarget.getPosition() ) )
{
return true;
}
for( AnBoardPosition position : p_tokenTarget.getExtraPositions(getCoordinateSystem()) )
{
if( canTokenFireOn( p_token, position ) )
{
return true;
}
}
return false;
}
/**
*
* @return the fire length of this token.
*/
public int getTokenFireLength(EbToken p_token)
{
if( (p_token == null) || p_token.getLocation() != Location.Board )
{
return 0;
}
switch( p_token.getType() )
{
case Turret:
case Speedboat:
case Hovertank:
return 2;
case Tank:
if( getLand( p_token.getPosition() ) == LandType.Montain )
{
return 3;
}
return 2;
case Heap:
case Tarask:
return 3;
case Freighter:
case Barge:
case Crab:
case WeatherHen:
case Pontoon:
case Ore:
default:
return 0;
}
}
public boolean isPontoonLinkToGround(EbToken p_token)
{
if( p_token.getType() != TokenType.Pontoon )
{
return false;
}
Set<EbToken> checkedPontoon = new HashSet<EbToken>();
return isPontoonLinkToGround( p_token, checkedPontoon );
}
public boolean isPontoonLinkToGround(AnBoardPosition p_position)
{
LandType land = getLand( p_position ).getLandValue( getCurrentTide() );
if( (land == LandType.Plain) || (land == LandType.Montain) )
{
return true;
}
for( AnBoardPosition neighborPosition : getCoordinateSystem().getAllNeighbors( p_position ) )
{
land = getLand( neighborPosition ).getLandValue( getCurrentTide() );
if( (land == LandType.Plain) || (land == LandType.Montain) )
{
return true;
}
}
EbToken otherPontoon = getToken( p_position, TokenType.Pontoon );
Set<EbToken> checkedPontoon = new HashSet<EbToken>();
if( otherPontoon != null )
{
checkedPontoon.add( otherPontoon );
}
for( AnBoardPosition neighborPosition : getCoordinateSystem().getAllNeighbors( p_position ) )
{
otherPontoon = getToken( neighborPosition, TokenType.Pontoon );
if( otherPontoon != null )
{
checkedPontoon.add( otherPontoon );
if( isPontoonLinkToGround( otherPontoon, checkedPontoon ) )
{
return true;
}
}
}
// check if pontoon is connected to freighter at high tide
if( getCurrentTide() == Tide.Hight )
{
for( AnBoardPosition neighborPosition : getCoordinateSystem().getAllNeighbors( p_position ) )
{
if( getToken( neighborPosition, TokenType.Freighter ) != null )
return true;
}
}
return false;
}
private boolean isPontoonLinkToGround(EbToken p_token, Set<EbToken> p_checkedPontoon)
{
LandType land = getLand( p_token.getPosition() ).getLandValue( getCurrentTide() );
if( (land == LandType.Plain) || (land == LandType.Montain) )
{
return true;
}
for( AnBoardPosition neighborPosition : getCoordinateSystem().getAllNeighbors( p_token.getPosition() ) )
{
land = getLand( neighborPosition )
.getLandValue( getCurrentTide() );
if( (land == LandType.Plain) || (land == LandType.Montain) )
{
return true;
}
}
EbToken otherPontoon = null;
for( AnBoardPosition neighborPosition : getCoordinateSystem().getAllNeighbors( p_token.getPosition() ) )
{
otherPontoon = getToken( neighborPosition, TokenType.Pontoon );
if( (otherPontoon != null) && (!p_checkedPontoon.contains( otherPontoon )) )
{
p_checkedPontoon.add( otherPontoon );
if( isPontoonLinkToGround( otherPontoon, p_checkedPontoon ) )
{
return true;
}
}
}
// check if pontoon is connected to freighter at high tide
if( getCurrentTide() == Tide.Hight )
{
for( AnBoardPosition neighborPosition : getCoordinateSystem().getAllNeighbors( p_token.getPosition() ) )
{
if( getToken( neighborPosition, TokenType.Freighter ) != null )
return true;
}
}
return false;
}
/**
* put p_token and all linked pontoon to graveyard.
* @param p_token must be a pontoon
* @param p_fdRemoved fire disabling that was removed are added to this list
* @return list of all tokens removed from board to graveyard (pontoons and token on them).
* Token have to be put back on board in the same order.
* @throws RpcFmpException
*/
public ArrayList<Long> chainRemovePontoon(EbToken p_token, List<FireDisabling> p_fdRemoved) throws RpcFmpException
{
assert p_token.getType() == TokenType.Pontoon;
ArrayList<Long> pontoons = new ArrayList<Long>();
// backup pontoon's id first (to put back on board first)
pontoons.add( p_token.getId() );
AnBoardPosition position = p_token.getPosition();
// remove all tokens on pontoon
Set<EbToken> tokens = getAllToken( position );
for(EbToken token : tokens)
{
if(token != p_token)
{
// remove his fire disabling list
if( token.getFireDisablingList() != null )
{
List<FireDisabling> fdRemoved = new ArrayList<FireDisabling>();
fdRemoved.addAll( token.getFireDisablingList() );
p_fdRemoved.addAll( fdRemoved );
getBoardFireCover().removeFireDisabling( fdRemoved );
}
// remove token on pontoon
pontoons.add( token.getId() );
moveToken( token, Location.Graveyard );
token.incVersion();
}
}
// then remove pontoon
moveToken( p_token, Location.Graveyard );
p_token.incVersion();
// finally remove other linked pontoons
for( AnBoardPosition neighborPosition : getCoordinateSystem().getAllNeighbors( position ) )
{
EbToken otherPontoon = getToken( neighborPosition, TokenType.Pontoon );
if( otherPontoon != null )
{
pontoons.addAll( chainRemovePontoon( otherPontoon, p_fdRemoved ) );
}
}
return pontoons;
}
// TODO move this to another class
@Transient
private Set<com.fullmetalgalaxy.model.persist.AnBoardPosition> m_allowedNodeGraphCache = new HashSet<com.fullmetalgalaxy.model.persist.AnBoardPosition>();
@Transient
private Set<com.fullmetalgalaxy.model.persist.AnBoardPosition> m_forbidenNodeGraphCache = new HashSet<com.fullmetalgalaxy.model.persist.AnBoardPosition>();
public void resetPathGraph()
{
m_allowedNodeGraphCache.clear();
m_forbidenNodeGraphCache.clear();
}
/* (non-Javadoc)
* @see com.fullmetalgalaxy.model.pathfinder.PathGraph#getAvailableNode(com.fullmetalgalaxy.model.pathfinder.PathNode)
*/
@Override
public Set<com.fullmetalgalaxy.model.pathfinder.PathNode> getAvailableNode(PathNode p_fromNode,
PathMobile p_mobile)
{
assert p_mobile != null;
AnBoardPosition position = (AnBoardPosition)p_fromNode;
Mobile mobile = (Mobile)p_mobile;
Set<com.fullmetalgalaxy.model.pathfinder.PathNode> nodes = new HashSet<com.fullmetalgalaxy.model.pathfinder.PathNode>();
for( AnBoardPosition neighborPosition : getCoordinateSystem().getAllNeighbors( position ) )
{
if( mobile.getToken() == null )
{
nodes.add( neighborPosition );
}
else
{
// looking in cache first
if( m_allowedNodeGraphCache.contains( neighborPosition ) )
{
nodes.add( neighborPosition );
}
else if( m_forbidenNodeGraphCache.contains( neighborPosition ) )
{
// do nothing
}
else
{
// this position wasn't explored yet
if( mobile.getToken().canMoveOn( this, mobile.getRegistration(), neighborPosition ) )
{
m_allowedNodeGraphCache.add( neighborPosition );
nodes.add( neighborPosition );
}
else
{
m_forbidenNodeGraphCache.add( neighborPosition );
}
}
}
}
return nodes;
}
/* (non-Javadoc)
* @see com.fullmetalgalaxy.model.pathfinder.PathGraph#heuristic(com.fullmetalgalaxy.model.pathfinder.PathNode, com.fullmetalgalaxy.model.pathfinder.PathNode)
*/
@Override
public float heuristic(PathNode p_fromNode, PathNode p_toNode, PathMobile p_mobile)
{
return (float)getCoordinateSystem().getDiscreteDistance( ((AnBoardPosition)p_fromNode), (AnBoardPosition)p_toNode );
}
public List<AnEvent> createTriggersEvents()
{
// get all events
List<AnEvent> events = new ArrayList<AnEvent>();
for( EbTrigger trigger : getTriggers() )
{
events.addAll( trigger.createEvents( this ) );
}
return events;
}
/**
* execute all game's trigger
* @return true if at least on trigger was executed.
*/
public void execTriggers()
{
// execute new events
for( AnEvent event : createTriggersEvents() )
{
try
{
event.exec( this );
addEvent( event );
} catch( RpcFmpException e )
{
// print error and continue executing events
e.printStackTrace();
}
}
}
/**
* @return the tokenIndexSet. never return null;
*/
private TokenIndexSet getTokenIndexSet()
{
if( m_tokenIndexSet == null )
{
m_tokenIndexSet = new TokenIndexSet( getCoordinateSystem(), getSetToken() );
}
return m_tokenIndexSet;
}
}
|
package ru.frozen.prolen;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.Array;
import ru.frozen.prolen.core.gameobject.MeshRenderer;
import ru.frozen.prolen.core.gameobject.Motion;
import ru.frozen.prolen.core.gameobject.Transform;
import ru.frozen.prolen.core.gameobject.GameObject;
import ru.frozen.prolen.core.graphics.SceneRenderer;
public class GameScreen implements Screen {
SceneRenderer renderer = new SceneRenderer();
int t = 0, l = 0;
GameObject m;
GameObject shell;
Array<GameObject> shells = new Array<>();
public GameScreen() {
Gdx.gl.glClearColor(0.5f,0.5f,0.5f,1f);
TextureRegion morda = new TextureRegion(new Texture(Gdx.files.internal("morda.png")));
TextureRegion two = new TextureRegion(new Texture(Gdx.files.internal("2.png")));
TextureRegion four_cher = new TextureRegion(new Texture(Gdx.files.internal("4cher.png")));
TextureRegion four_cherkras = new TextureRegion(new Texture(Gdx.files.internal("4cherkras.png")));
m = createMorda(morda, 5);
m.motion.xy_velocity = 20;
m.motion.moveTo(200, 200);
m.motion.a_velocity = 20;
m.motion.rotateTo(100);
renderer.addGO(m);
shell = createMorda(two,6);
shell.transform.setPosition(0, 30);
shell.motion.xy_velocity = 20;
shell.motion.move_forward = true;
}
public GameObject createMorda(TextureRegion t,int z_order) {
GameObject g = new GameObject("test");
g.transform = new Transform();
g.transform.setPosition((float) Math.random() * Gdx.graphics.getWidth(),
(float) Math.random() * Gdx.graphics.getHeight());
g.renderer = new MeshRenderer(t,null,z_order);
g.renderer.setLinearFilter();
g.motion = new Motion();
g.updateData(0.2f);
g.updateData(0.2f);//test git
return g;
}
@Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
m.updateData(delta);
for (int i = 0; i < shells.size; i++) shells.get(i).updateData(delta);
if(!m.motion.haveXYTarget) {
switch (t) {
case 0: m.motion.moveTo(100,100); break;
case 1: m.motion.moveTo(300,100); break;
case 2: m.motion.moveTo(5, 400); break;
}
t++;
}
if(!m.motion.haveATarget) {
switch (l) {
case 0:
m.motion.rotateTo(30);
GameObject s = shell.copy();
renderer.addGO(s);
shells.add(s);
m.shoot(s);
break;
case 1:
m.motion.rotateTo(30);
s = shell.copy();
renderer.addGO(s);
shells.add(s);
m.shoot(s);
break;
case 2:
m.motion.rotateTo(30);
s = shell.copy();
renderer.addGO(s);
shells.add(s);
m.shoot(s);
break;
}
l++;
}
renderer.render();
}
@Override
public void resize(int width, int height) {
renderer.resize(width, height);
}
@Override
public void show() {
}
@Override
public void hide() {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void dispose() {
}
}
|
package com.drone.ui;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.vaadin.spring.UIScope;
import org.vaadin.spring.VaadinComponent;
import org.vaadin.spring.events.EventBus;
import org.vaadin.spring.events.EventBusListenerMethod;
import com.drone.Drone;
import com.drone.event.DroneBatteryEvent;
import com.drone.ui.charts.BatteryLevelGauge;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.HorizontalLayout;
@VaadinComponent
@UIScope
public class GaugePanel extends CustomComponent implements InitializingBean {
private static final long serialVersionUID = 4035048387445957610L;
@Autowired
private Drone drone;
private BatteryLevelGauge battery;
private HorizontalLayout layout;
@Autowired
private EventBus eventBus;
public GaugePanel() {
layout = new HorizontalLayout();
layout.setWidth(100, Unit.PERCENTAGE);
battery = new BatteryLevelGauge();
layout.addComponent(battery);
layout.setExpandRatio(battery, 1);
layout.setComponentAlignment(battery, Alignment.TOP_RIGHT);
addStyleName("gauge-panel");
setCompositionRoot(layout);
}
@Override
public void afterPropertiesSet() throws Exception {
eventBus.subscribe(this);
}
@EventBusListenerMethod
protected void onBatteryLevelEvent(DroneBatteryEvent event) {
battery.setBatteryLevel(event.getBatteryLevel());
}
}
|
package org.slc.sli.api.security.context.traversal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.slc.sli.api.security.context.resolver.EdOrgToChildEdOrgNodeFilter;
import org.slc.sli.api.security.context.traversal.graph.NodeFilter;
import org.slc.sli.api.security.context.traversal.graph.SecurityNode;
import org.slc.sli.api.security.context.traversal.graph.SecurityNodeBuilder;
import org.slc.sli.api.security.context.traversal.graph.SecurityNodeConnection;
import org.slc.sli.common.constants.EntityNames;
import org.slc.sli.common.constants.ResourceNames;
/**
* Basic brute force path finding implementation.
*/
@Component
public class BrutePathFinder implements SecurityPathFinder {
private Map<String, SecurityNode> nodeMap;
private Map<String, List<SecurityNode>> prePath;
private List<String> excludePath;
@Autowired
private EdOrgToChildEdOrgNodeFilter edorgFilter;
@Autowired
private NodeFilter sectionGracePeriodNodeFilter;
@Autowired
private NodeFilter studentGracePeriodNodeFilter;
@PostConstruct
public void init() {
nodeMap = new HashMap<String, SecurityNode>();
prePath = new HashMap<String, List<SecurityNode>>();
excludePath = new ArrayList<String>();
nodeMap.put(EntityNames.TEACHER,
SecurityNodeBuilder.buildNode(EntityNames.TEACHER, EntityNames.STAFF)
.addConnection(EntityNames.SECTION, "sectionId", ResourceNames.TEACHER_SECTION_ASSOCIATIONS,
sectionGracePeriodNodeFilter)
.addConnection(EntityNames.TEACHER_SECTION_ASSOCIATION, "teacherId")
.addConnection(EntityNames.SCHOOL, "schoolId", ResourceNames.TEACHER_SCHOOL_ASSOCIATIONS,
edorgFilter)
.addConnection(EntityNames.TEACHER_SCHOOL_ASSOCIATION, "teacherId")
.construct());
nodeMap.put(
EntityNames.SCHOOL,
SecurityNodeBuilder.buildNode(EntityNames.SCHOOL, EntityNames.EDUCATION_ORGANIZATION)
.addConnection(EntityNames.TEACHER, "teacherId", ResourceNames.TEACHER_SCHOOL_ASSOCIATIONS)
.addConnection(EntityNames.TEACHER_SCHOOL_ASSOCIATION, "schoolId")
.addConnection(EntityNames.STAFF, "staffReference",
ResourceNames.STAFF_EDUCATION_ORGANIZATION_ASSOCIATIONS)
.addConnection(EntityNames.STAFF_ED_ORG_ASSOCIATION, "educationOrganizationReference")
.construct());
nodeMap.put(EntityNames.SECTION,
SecurityNodeBuilder.buildNode(EntityNames.SECTION)
.addConnection(EntityNames.TEACHER, "teacherId", ResourceNames.TEACHER_SECTION_ASSOCIATIONS)
.addConnection(EntityNames.TEACHER_SECTION_ASSOCIATION, "sectionId")
.addConnection(EntityNames.STUDENT, "studentId", ResourceNames.STUDENT_SECTION_ASSOCIATIONS)
.addConnection(EntityNames.STUDENT_SECTION_ASSOCIATION, "sectionId")
.addConnection(EntityNames.COURSE, "courseId", EntityNames.SECTION)
.addConnection(EntityNames.SESSION, "sessionId", EntityNames.SECTION)
.addConnection(EntityNames.PROGRAM, "programReference")
.addConnection(EntityNames.SECTION_ASSESSMENT_ASSOCIATION, "sectionId")
.construct());
nodeMap.put(EntityNames.STUDENT,
SecurityNodeBuilder.buildNode(EntityNames.STUDENT)
.addConnection(EntityNames.SECTION, "sectionId", ResourceNames.STUDENT_SECTION_ASSOCIATIONS)
.addConnection(EntityNames.STUDENT_SECTION_ASSOCIATION, "studentId")
.addConnection(EntityNames.ASSESSMENT, "assessmentId", ResourceNames.STUDENT_ASSESSMENT_ASSOCIATIONS)
.addConnection(EntityNames.STUDENT_ASSESSMENT_ASSOCIATION, "studentId")
.addConnection(EntityNames.ATTENDANCE, "studentId")
.addConnection(EntityNames.DISCIPLINE_ACTION, "studentId")
.addConnection(EntityNames.DISCIPLINE_INCIDENT, "disciplineIncidentId",
ResourceNames.STUDENT_DISCIPLINE_INCIDENT_ASSOCIATIONS)
.addConnection(EntityNames.STUDENT_DISCIPLINE_INCIDENT_ASSOCIATION, "studentId")
.addConnection(EntityNames.PARENT, "parentId", ResourceNames.STUDENT_PARENT_ASSOCIATIONS)
.addConnection(EntityNames.STUDENT_PARENT_ASSOCIATION, "studentId")
.addConnection(EntityNames.STUDENT_PROGRAM_ASSOCIATION, "studentId")
.addConnection(EntityNames.STUDENT_TRANSCRIPT_ASSOCIATION, "studentId")
.addConnection(EntityNames.COHORT, "cohortId", ResourceNames.STUDENT_COHORT_ASSOCIATIONS)
.addConnection(EntityNames.STUDENT_COHORT_ASSOCIATION, "studentId")
.construct());
nodeMap.put(EntityNames.STAFF,
SecurityNodeBuilder.buildNode(EntityNames.STAFF)
.addConnection(EntityNames.EDUCATION_ORGANIZATION, "educationOrganizationReference",
ResourceNames.STAFF_EDUCATION_ORGANIZATION_ASSOCIATIONS, edorgFilter)
.addConnection(EntityNames.STAFF_ED_ORG_ASSOCIATION, "staffReference")
.addConnection(EntityNames.STAFF_PROGRAM_ASSOCIATION, "staffId")
.addConnection(EntityNames.COHORT, "cohortId", ResourceNames.STAFF_COHORT_ASSOCIATIONS)
.addConnection(EntityNames.STAFF_COHORT_ASSOCIATION, "staffId")
.construct());
nodeMap.put(EntityNames.EDUCATION_ORGANIZATION,
SecurityNodeBuilder.buildNode(EntityNames.EDUCATION_ORGANIZATION)
.addConnection(EntityNames.STAFF, "staffReference", ResourceNames.STAFF_EDUCATION_ORGANIZATION_ASSOCIATIONS)
.addConnection(EntityNames.STAFF_ED_ORG_ASSOCIATION, "educationOrganizationReference")
.addConnection(EntityNames.STUDENT, "studentId", ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS, studentGracePeriodNodeFilter)
.addConnection(EntityNames.STUDENT_SCHOOL_ASSOCIATION, "schoolId")
.addConnection(EntityNames.SCHOOL, "", "")
.addConnection(EntityNames.PROGRAM, "programReference") //TODO: fix XSD
.addConnection(EntityNames.SECTION, "schoolId")
.construct());
// Leaf Nodes are unconnected
nodeMap.put(EntityNames.STUDENT_SECTION_ASSOCIATION, SecurityNodeBuilder.buildNode(EntityNames.STUDENT_SECTION_ASSOCIATION).construct());
nodeMap.put(EntityNames.STUDENT_ASSESSMENT_ASSOCIATION, SecurityNodeBuilder.buildNode(EntityNames.STUDENT_ASSESSMENT_ASSOCIATION).construct());
nodeMap.put(EntityNames.STUDENT_DISCIPLINE_INCIDENT_ASSOCIATION, SecurityNodeBuilder.buildNode(EntityNames.STUDENT_DISCIPLINE_INCIDENT_ASSOCIATION).construct());
nodeMap.put(EntityNames.STUDENT_PROGRAM_ASSOCIATION, SecurityNodeBuilder.buildNode(EntityNames.STUDENT_PROGRAM_ASSOCIATION).construct());
nodeMap.put(EntityNames.STUDENT_TRANSCRIPT_ASSOCIATION, SecurityNodeBuilder.buildNode(EntityNames.STUDENT_TRANSCRIPT_ASSOCIATION).construct());
nodeMap.put(EntityNames.STUDENT_COHORT_ASSOCIATION, SecurityNodeBuilder.buildNode(EntityNames.STUDENT_COHORT_ASSOCIATION).construct());
nodeMap.put(EntityNames.STUDENT_PROGRAM_ASSOCIATION, SecurityNodeBuilder.buildNode(EntityNames.STUDENT_PROGRAM_ASSOCIATION).construct());
nodeMap.put(EntityNames.STUDENT_SCHOOL_ASSOCIATION, SecurityNodeBuilder.buildNode(EntityNames.STUDENT_SCHOOL_ASSOCIATION).construct());
nodeMap.put(EntityNames.STUDENT_PARENT_ASSOCIATION, SecurityNodeBuilder.buildNode(EntityNames.STUDENT_PARENT_ASSOCIATION).construct());
nodeMap.put(EntityNames.STAFF_ED_ORG_ASSOCIATION, SecurityNodeBuilder.buildNode(EntityNames.STAFF_ED_ORG_ASSOCIATION).construct());
nodeMap.put(EntityNames.STAFF_PROGRAM_ASSOCIATION, SecurityNodeBuilder.buildNode(EntityNames.STAFF_PROGRAM_ASSOCIATION).construct());
nodeMap.put(EntityNames.STAFF_COHORT_ASSOCIATION, SecurityNodeBuilder.buildNode(EntityNames.STAFF_COHORT_ASSOCIATION).construct());
nodeMap.put(EntityNames.TEACHER_SECTION_ASSOCIATION, SecurityNodeBuilder.buildNode(EntityNames.TEACHER_SECTION_ASSOCIATION).construct());
nodeMap.put(EntityNames.TEACHER_SCHOOL_ASSOCIATION, SecurityNodeBuilder.buildNode(EntityNames.TEACHER_SCHOOL_ASSOCIATION).construct());
nodeMap.put(EntityNames.SECTION_ASSESSMENT_ASSOCIATION, SecurityNodeBuilder.buildNode(EntityNames.SECTION_ASSESSMENT_ASSOCIATION).construct());
nodeMap.put(EntityNames.ASSESSMENT, SecurityNodeBuilder.buildNode(EntityNames.ASSESSMENT).construct());
nodeMap.put(EntityNames.ATTENDANCE, SecurityNodeBuilder.buildNode(EntityNames.ATTENDANCE).construct());
nodeMap.put(EntityNames.COHORT, SecurityNodeBuilder.buildNode(EntityNames.COHORT).construct());
nodeMap.put(EntityNames.COURSE, SecurityNodeBuilder.buildNode(EntityNames.COURSE).construct());
nodeMap.put(EntityNames.DISCIPLINE_ACTION, SecurityNodeBuilder.buildNode(EntityNames.DISCIPLINE_ACTION).construct());
nodeMap.put(EntityNames.DISCIPLINE_INCIDENT, SecurityNodeBuilder.buildNode(EntityNames.DISCIPLINE_INCIDENT).construct());
nodeMap.put(EntityNames.PROGRAM, SecurityNodeBuilder.buildNode(EntityNames.PROGRAM).construct());
nodeMap.put(EntityNames.SESSION, SecurityNodeBuilder.buildNode(EntityNames.SESSION).construct());
nodeMap.put(EntityNames.PARENT, SecurityNodeBuilder.buildNode(EntityNames.PARENT).construct());
// excludePath.add(EntityNames.TEACHER + EntityNames.SECTION);
excludePath.add(EntityNames.TEACHER + EntityNames.EDUCATION_ORGANIZATION);
//excludePath.add(EntityNames.TEACHER + EntityNames.COHORT);
excludePath.add(EntityNames.TEACHER + EntityNames.PROGRAM);
//excludePath.add(EntityNames.STAFF + EntityNames.COHORT);
excludePath.add(EntityNames.STAFF + EntityNames.PROGRAM);
excludePath.add(EntityNames.STAFF + EntityNames.DISCIPLINE_INCIDENT);
excludePath.add(EntityNames.STAFF + EntityNames.DISCIPLINE_ACTION);
excludePath.add(EntityNames.TEACHER + EntityNames.STUDENT_SCHOOL_ASSOCIATION);
prePath.put(
EntityNames.STAFF + EntityNames.STAFF,
Arrays.asList(nodeMap.get(EntityNames.STAFF), nodeMap.get(EntityNames.EDUCATION_ORGANIZATION),
nodeMap.get(EntityNames.STAFF)));
prePath.put(
EntityNames.STAFF + EntityNames.SECTION,
Arrays.asList(nodeMap.get(EntityNames.STAFF), nodeMap.get(EntityNames.EDUCATION_ORGANIZATION),
nodeMap.get(EntityNames.SECTION)));
prePath.put(
EntityNames.STAFF + EntityNames.COURSE,
Arrays.asList(nodeMap.get(EntityNames.STAFF), nodeMap.get(EntityNames.EDUCATION_ORGANIZATION),
nodeMap.get(EntityNames.SECTION), nodeMap.get(EntityNames.COURSE)));
prePath.put(
EntityNames.STAFF + EntityNames.SESSION,
Arrays.asList(nodeMap.get(EntityNames.STAFF), nodeMap.get(EntityNames.EDUCATION_ORGANIZATION),
nodeMap.get(EntityNames.SECTION), nodeMap.get(EntityNames.SESSION)));
prePath.put(
EntityNames.STAFF + EntityNames.TEACHER,
Arrays.asList(nodeMap.get(EntityNames.STAFF), nodeMap.get(EntityNames.EDUCATION_ORGANIZATION),
nodeMap.get(EntityNames.SCHOOL), nodeMap.get(EntityNames.TEACHER)));
prePath.put(
EntityNames.STAFF + EntityNames.SCHOOL,
Arrays.asList(nodeMap.get(EntityNames.STAFF), nodeMap.get(EntityNames.EDUCATION_ORGANIZATION),
nodeMap.get(EntityNames.SCHOOL)));
prePath.put(
EntityNames.TEACHER + EntityNames.TEACHER,
Arrays.asList(nodeMap.get(EntityNames.TEACHER), nodeMap.get(EntityNames.SCHOOL),
nodeMap.get(EntityNames.TEACHER)));
prePath.put(
EntityNames.TEACHER + EntityNames.SECTION,
Arrays.asList(nodeMap.get(EntityNames.TEACHER), nodeMap.get(EntityNames.SECTION),
nodeMap.get(EntityNames.STUDENT), nodeMap.get(EntityNames.SECTION)));
prePath.put(
EntityNames.TEACHER + EntityNames.COURSE,
Arrays.asList(nodeMap.get(EntityNames.TEACHER), nodeMap.get(EntityNames.SECTION),
nodeMap.get(EntityNames.STUDENT), nodeMap.get(EntityNames.SECTION),
nodeMap.get(EntityNames.COURSE)));
prePath.put(
EntityNames.TEACHER + EntityNames.SESSION,
Arrays.asList(nodeMap.get(EntityNames.TEACHER), nodeMap.get(EntityNames.SECTION),
nodeMap.get(EntityNames.STUDENT), nodeMap.get(EntityNames.SECTION),
nodeMap.get(EntityNames.SESSION)));
}
@Override
public List<SecurityNode> find(String from, String to) {
return find(from, to, new ArrayList<SecurityNode>());
}
public List<SecurityNode> find(String from, String to, List<SecurityNode> path) {
SecurityNode current = nodeMap.get(from);
path.add(current);
if (from.equals(to)) {
return path;
}
for (SecurityNodeConnection connection : current.getConnections()) {
SecurityNode next = nodeMap.get(connection.getConnectionTo());
if (path.contains(next)) { //cycle
continue;
}
List<SecurityNode> newPath = find(next.getName(), to, path);
if (newPath != null) {
return newPath;
}
}
debug("NO PATH FOUND FROM {} to {}", new String[]{ from, to });
path.remove(current);
return null;
}
/*
* (non-Javadoc)
*
* @see
* org.slc.sli.api.security.context.traversal.SecurityPathFinder#getPreDefinedPath(java.lang
* .String, java.lang.String)
*/
@Override
public List<SecurityNode> getPreDefinedPath(String from, String to) {
if (prePath.containsKey(from + to)) {
return prePath.get(from + to);
}
return new ArrayList<SecurityNode>();
}
private boolean checkForFinalNode(String to, SecurityNode temp) {
return temp.getName().equals(to);
}
public void setNodeMap(Map<String, SecurityNode> nodeMap) {
this.nodeMap = nodeMap;
}
/**
* @return the nodeMap
*/
public Map<String, SecurityNode> getNodeMap() {
return nodeMap;
}
public boolean isPathExcluded(String from, String to) {
return excludePath.contains(from + to);
}
}
|
package com.intellij.psi.impl.source.resolve.reference;
import com.intellij.ant.impl.dom.impl.RegisterInPsi;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.*;
import com.intellij.psi.filters.*;
import com.intellij.psi.filters.position.NamespaceFilter;
import com.intellij.psi.filters.position.ParentElementFilter;
import com.intellij.psi.filters.position.TokenTypeFilter;
import com.intellij.psi.impl.source.jsp.jspJava.JspDirective;
import com.intellij.psi.impl.source.resolve.ResolveUtil;
import com.intellij.psi.impl.source.resolve.reference.impl.manipulators.PlainFileManipulator;
import com.intellij.psi.impl.source.resolve.reference.impl.manipulators.XmlAttributeValueManipulator;
import com.intellij.psi.impl.source.resolve.reference.impl.manipulators.XmlTokenManipulator;
import com.intellij.psi.impl.source.resolve.reference.impl.manipulators.XmlTagValueManipulator;
import com.intellij.psi.impl.source.resolve.reference.impl.providers.*;
import com.intellij.psi.impl.meta.MetaRegistry;
import com.intellij.psi.xml.*;
import com.intellij.xml.util.HtmlUtil;
import com.intellij.xml.util.XmlUtil;
import com.intellij.lang.properties.PropertiesReferenceProvider;
import com.intellij.util.ArrayUtil;
import java.util.*;
public class ReferenceProvidersRegistry implements ProjectComponent {
private final List<Class> myTempScopes = new ArrayList<Class>();
private final List<ProviderBinding> myBindings = new ArrayList<ProviderBinding>();
private final List<Pair<Class, ElementManipulator>> myManipulators = new ArrayList<Pair<Class, ElementManipulator>>();
private final Map<ReferenceProviderType,PsiReferenceProvider> myReferenceTypeToProviderMap = new HashMap<ReferenceProviderType, PsiReferenceProvider>(5);
static public class ReferenceProviderType {
private String myId;
public ReferenceProviderType(String id) { myId = id; }
public String toString() { return myId; }
}
public static ReferenceProviderType PROPERTY_FILE_KEY_PROVIDER = new ReferenceProviderType("Property File Key Provider");
public static ReferenceProviderType CLASS_REFERENCE_PROVIDER = new ReferenceProviderType("Class Reference Provider");
public static ReferenceProviderType PATH_REFERENCES_PROVIDER = new ReferenceProviderType("Path References Provider");
public static ReferenceProviderType CSS_CLASS_OR_ID_KEY_PROVIDER = new ReferenceProviderType("Css Class or ID Provider");
public static final ReferenceProvidersRegistry getInstance(Project project) {
return project.getComponent(ReferenceProvidersRegistry.class);
}
public void registerTypeWithProvider(ReferenceProviderType type, PsiReferenceProvider provider) {
myReferenceTypeToProviderMap.put(type, provider);
}
private ReferenceProvidersRegistry() {
// Temp scopes declarations
myTempScopes.add(PsiIdentifier.class);
// Manipulators mapping
registerManipulator(XmlAttributeValue.class, new XmlAttributeValueManipulator());
registerManipulator(PsiPlainTextFile.class, new PlainFileManipulator());
registerManipulator(XmlToken.class, new XmlTokenManipulator());
registerManipulator(XmlTag.class, new XmlTagValueManipulator());
// Binding declarations
myReferenceTypeToProviderMap.put(CLASS_REFERENCE_PROVIDER, new JavaClassReferenceProvider());
myReferenceTypeToProviderMap.put(PATH_REFERENCES_PROVIDER, new JspxIncludePathReferenceProvider());
myReferenceTypeToProviderMap.put(PROPERTY_FILE_KEY_PROVIDER, new PropertiesReferenceProvider());
registerXmlAttributeValueReferenceProvider(
new String[]{"class", "type"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new TextFilter("useBean"),
new NamespaceFilter(XmlUtil.JSP_URI)
), 2
)
), getProviderByType(CLASS_REFERENCE_PROVIDER)
);
RegisterInPsi.referenceProviders(this);
registerXmlAttributeValueReferenceProvider(
new String[]{"extends"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new OrFilter(
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("directive.page")
),
new AndFilter(
new ClassFilter(JspDirective.class),
new TextFilter("page")
)
),
new NamespaceFilter(XmlUtil.JSP_URI)
),
2
)
), getProviderByType(CLASS_REFERENCE_PROVIDER)
);
registerXmlAttributeValueReferenceProvider(
new String[]{"type"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new OrFilter(
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("directive.attribute")
),
new AndFilter(
new ClassFilter(JspDirective.class),
new TextFilter("attribute")
)
),
new NamespaceFilter(XmlUtil.JSP_URI)
),
2
)
), getProviderByType(CLASS_REFERENCE_PROVIDER)
);
registerXmlAttributeValueReferenceProvider(
new String[]{"variable-class"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new OrFilter(
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("directive.variable")
),
new AndFilter(
new ClassFilter(JspDirective.class),
new TextFilter("variable")
)
),
new NamespaceFilter(XmlUtil.JSP_URI)
),
2
)
), getProviderByType(CLASS_REFERENCE_PROVIDER)
);
registerXmlAttributeValueReferenceProvider(
new String[] { "import" },
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new OrFilter(
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("directive.page")
),
new AndFilter(
new ClassFilter(JspDirective.class),
new TextFilter("page")
)
),
new NamespaceFilter(XmlUtil.JSP_URI)
),
2
)
),
new JspImportListReferenceProvider()
);
registerXmlAttributeValueReferenceProvider(
new String[]{"errorPage"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.JSP_URI),
new OrFilter(
new AndFilter(
new ClassFilter(JspDirective.class),
new TextFilter("page")
),
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("directive.page")
))
), 2
)
), getProviderByType(PATH_REFERENCES_PROVIDER)
);
registerXmlAttributeValueReferenceProvider(
new String[]{"file"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.JSP_URI),
new OrFilter(
new AndFilter(
new ClassFilter(JspDirective.class),
new TextFilter("include")
),
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("directive.include")
))
), 2
)
), getProviderByType(PATH_REFERENCES_PROVIDER)
);
registerXmlAttributeValueReferenceProvider(
new String[]{"value"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.JSTL_CORE_URI),
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("url")
)
), 2
)
), getProviderByType(PATH_REFERENCES_PROVIDER)
);
registerXmlAttributeValueReferenceProvider(
new String[]{"url"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.JSTL_CORE_URI),
new AndFilter(
new ClassFilter(XmlTag.class),
new OrFilter(
new TextFilter("import"),
new TextFilter("redirect")
)
)
), 2
)
), getProviderByType(PATH_REFERENCES_PROVIDER)
);
registerXmlAttributeValueReferenceProvider(
new String[]{"key"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new OrFilter(
new NamespaceFilter(XmlUtil.JSTL_FORMAT_URI),
new NamespaceFilter(XmlUtil.STRUTS_BEAN_URI)
),
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("message")
)
), 2
)
), getProviderByType(PROPERTY_FILE_KEY_PROVIDER)
);
registerXmlAttributeValueReferenceProvider(
new String[]{"altKey","titleKey","pageKey","srcKey"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.STRUTS_HTML_URI),
new ClassFilter(XmlTag.class)
), 2
)
), getProviderByType(PROPERTY_FILE_KEY_PROVIDER)
);
registerXmlAttributeValueReferenceProvider(
new String[]{"code"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.SPRING_URI),
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("message", "theme")
)
), 2
)
), getProviderByType(PROPERTY_FILE_KEY_PROVIDER)
);
registerXmlAttributeValueReferenceProvider(
new String[]{"page"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.JSP_URI),
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("include")
)
), 2
)
), getProviderByType(PATH_REFERENCES_PROVIDER)
);
registerXmlAttributeValueReferenceProvider(
new String[]{"tagdir"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.JSP_URI),
new AndFilter(
new ClassFilter(JspDirective.class),
new TextFilter("taglib")
)
), 2
)
), getProviderByType(PATH_REFERENCES_PROVIDER)
);
registerXmlAttributeValueReferenceProvider(
new String[] { "uri" },
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.JSP_URI),
new AndFilter(
new ClassFilter(JspDirective.class),
new TextFilter("taglib")
)
), 2
)
),
new JspUriReferenceProvider()
);
final JavaClassListReferenceProvider classListProvider = new JavaClassListReferenceProvider();
registerXmlAttributeValueReferenceProvider(
null,
new NotFilter(new ParentElementFilter(new NamespaceFilter(XmlUtil.ANT_URI), 2)),
classListProvider
);
registerReferenceProvider(new TokenTypeFilter(XmlTokenType.XML_DATA_CHARACTERS), XmlToken.class,
classListProvider);
registerReferenceProvider(
new ScopeFilter(
new AndFilter(
new TextFilter(
new String[] {
"function-class", "tag-class", "tei-class", "variable-class", "type", "path",
"function-signature", "name", "name-given"
}
),
new NamespaceFilter(MetaRegistry.TAGLIB_URIS)
)
),
XmlTag.class,
new TaglibReferenceProvider( getProviderByType(CLASS_REFERENCE_PROVIDER) )
);
final DtdReferencesProvider dtdReferencesProvider = new DtdReferencesProvider();
registerReferenceProvider(null, XmlEntityRef.class,dtdReferencesProvider);
URIReferenceProvider uriProvider = new URIReferenceProvider();
registerXmlAttributeValueReferenceProvider(
null,
dtdReferencesProvider.getSystemReferenceFilter(),
uriProvider
);
//registerReferenceProvider(PsiPlainTextFile.class, new JavaClassListReferenceProvider());
HtmlUtil.HtmlReferenceProvider provider = new HtmlUtil.HtmlReferenceProvider();
registerXmlAttributeValueReferenceProvider(
null,
provider.getFilter(),
provider
);
final PsiReferenceProvider filePathReferenceProvider = new FilePathReferenceProvider();
registerReferenceProvider(PsiLiteralExpression.class, filePathReferenceProvider);
registerXmlAttributeValueReferenceProvider(
new String[] {"ref","type","base","name"},
new ScopeFilter(
new ParentElementFilter(
new NamespaceFilter(MetaRegistry.SCHEMA_URIS), 2
)
),
new SchemaReferencesProvider()
);
registerXmlAttributeValueReferenceProvider(
new String[] {"schemaLocation"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(MetaRegistry.SCHEMA_URIS),
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("import","include")
)
), 2
)
),
uriProvider
);
registerXmlAttributeValueReferenceProvider(
null,
uriProvider.getNamespaceAttributeFilter(),
uriProvider
);
final JspReferencesProvider jspReferencesProvider = new JspReferencesProvider();
registerXmlAttributeValueReferenceProvider(
new String[] {"fragment","name","property","id","name-given"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new ClassFilter(XmlTag.class),
new NamespaceFilter(XmlUtil.JSP_URI)
), 2
)
),
jspReferencesProvider
);
registerXmlAttributeValueReferenceProvider(
new String[] {"var"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new ClassFilter(XmlTag.class),
new NamespaceFilter(XmlUtil.JSTL_CORE_URI)
), 2
)
),
jspReferencesProvider
);
}
public void registerReferenceProvider(ElementFilter elementFilter, Class scope, PsiReferenceProvider provider) {
if (scope == XmlAttributeValue.class) {
registerXmlAttributeValueReferenceProvider(null, elementFilter, provider);
return;
}
final SimpleProviderBinding binding = new SimpleProviderBinding(elementFilter, scope);
binding.registerProvider(provider);
myBindings.add(binding);
}
public void registerXmlAttributeValueReferenceProvider(String[] attributeNames, ElementFilter elementFilter, PsiReferenceProvider provider) {
XmlAttributeValueProviderBinding attributeValueProviderBinding = null;
for(ProviderBinding binding:myBindings) {
if (binding instanceof XmlAttributeValueProviderBinding) {
attributeValueProviderBinding = (XmlAttributeValueProviderBinding)binding;
break;
}
}
if (attributeValueProviderBinding == null) {
attributeValueProviderBinding = new XmlAttributeValueProviderBinding();
myBindings.add(attributeValueProviderBinding);
}
attributeValueProviderBinding.registerProvider(
attributeNames,
elementFilter,
provider
);
}
public PsiReferenceProvider getProviderByType(ReferenceProviderType type) {
return myReferenceTypeToProviderMap.get(type);
}
public void registerReferenceProvider(Class scope, PsiReferenceProvider provider) {
registerReferenceProvider(null, scope, provider);
}
public PsiReferenceProvider[] getProvidersByElement(PsiElement element) {
PsiReferenceProvider[] ret = PsiReferenceProvider.EMPTY_ARRAY;
PsiElement current;
do {
current = element;
for (final ProviderBinding binding : myBindings) {
final PsiReferenceProvider[] acceptableProviders = binding.getAcceptableProviders(current);
if (acceptableProviders != null && acceptableProviders.length > 0) {
ret = ArrayUtil.mergeArrays(ret, acceptableProviders, PsiReferenceProvider.class);
}
}
element = ResolveUtil.getContext(element);
}
while (!isScopeFinal(current.getClass()));
return ret;
}
public <T extends PsiElement> ElementManipulator<T> getManipulator(T element) {
if(element == null) return null;
for (final Pair<Class, ElementManipulator> pair : myManipulators) {
if (pair.getFirst().isAssignableFrom(element.getClass())) {
return (ElementManipulator<T>)pair.getSecond();
}
}
return null;
}
public <T extends PsiElement> void registerManipulator(Class<T> elementClass, ElementManipulator<T> manipulator) {
myManipulators.add(new Pair<Class, ElementManipulator>(elementClass, manipulator));
}
private boolean isScopeFinal(Class scopeClass) {
for (final Class aClass : myTempScopes) {
if (aClass.isAssignableFrom(scopeClass)) {
return false;
}
}
return true;
}
public void projectOpened() {}
public void projectClosed() {}
public String getComponentName() {
return "Reference providers registry";
}
public void initComponent() {}
public void disposeComponent() {}
}
|
package org.lamport.tla.toolbox.spec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IAdapterManager;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.text.ITextSelection;
import org.lamport.tla.toolbox.Activator;
import org.lamport.tla.toolbox.spec.parser.IParseConstants;
import org.lamport.tla.toolbox.tool.SpecLifecycleParticipant;
import org.lamport.tla.toolbox.util.AdapterFactory;
import org.lamport.tla.toolbox.util.ResourceHelper;
import org.lamport.tla.toolbox.util.compare.ResourceNameComparator;
import org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper;
import pcal.TLAtoPCalMapping;
import tla2sany.modanalyzer.SpecObj;
/**
* Represents a specification handle in the toolbox
*
* In June 2010, LL added some fields by which handlers of different commands
* could communicate with one another. I'm sure there's a more elegant way to
* do this that involves another few levels of indirection, but I have the old-fashioned
* belief that doing things the easy way and commenting what you do is better than
* doing things the correct way that makes it impossible to figure out what
* the hell is going on without learning yet another almost but not quite completely
* undocumented Eclipse feature.
*
*
* @version $Id$
* @author Simon Zambrovski
*/
public class Spec implements IAdaptable
{
/**
* specnames2mappings.get(filename) is the TLAtoPCalMapping object produced by the
* PlusCal translator for the file named tpMappingNames[i], where the
* file name is the module name + ".tla". (Sometimes it's easier to
* get the file name, and sometimes the module name, and it's easier to
* add a ".tla" than to remove it.)
* <p>
* There are two public procedures for manipulating these fields:
*
* @see Spec#setTpMapping(TLAtoPCalMapping, String)
* @see Spec#getTpMapping(String)
*/
private final Map<String, TLAtoPCalMapping> spec2mappings = new HashMap<String, TLAtoPCalMapping>();
/**
* The following fields are used for remembering the jumping-off
* point for a Goto Declaration or ShowDefinitions command, so we can return to it
* with a Return from Goto Declaration command. They should probably
* be changed to arrays so we can call return from a Sequence of such commands.
*/
private String openDeclModuleName;
private ITextSelection openDeclSelection;
/**
* The following fields are used to remember the result of a Show Uses command so
* the Goto Next Use and Goto Previous Use commands know where to go.
*
* The name of the module whose instances are being shown. If there
* are more than one, this is set by user selection from a pop-up
* dialog.
*/
private String moduleToShow = null;
/**
* The markers to be shown, sorted by the locations in which they
* originally appeared. I don't think that order can change,
* but what do I know?
*/
private IMarker[] markersToShow = null;
/**
* The index of the marker in markersToShow that is currently being
* shown.
*/
private int currentSelection = 0;
/* project handle */
private IProject project;
/* root module handle */
private IFile rootFile;
/* status of the specification */
private int status;
/* the semantic tree produced by the parser */
private SpecObj specObj;
/**
* Creates a Spec handle for existing project. Use the factory method
* {@link Spec#createNewSpec(String, String, Date)} if the project reference is not available
*
* @param project
* project handle
*/
public Spec(IProject project)
{
this.project = project;
initProjectProperties();
}
/**
* Factory method Creates a new specification, the underlying IProject link the root file
*
* @param name the name of the specification
* @param rootFilename the path to the root file name
* @param importExisting
*
* Note: when importing an existing spec, the contents of the .toolbox directory needs to
* be fixed because it contains absolute path names, which may be incorrect if the
* spec was moved from someplace else. Here are the files that may need changing:
*
* .toolbox/.project : <location> entries
* This definitely needs to be changed.
* .toolbox/.setting/... .prefs : ProjectRootFile entry.
* This file is rewritten when the spec is created, so it may not need
* to be changed.
*
* Experiment shows that the rootFilename argument contains the complete path name,
* from which one could extract the path names of those files and then rewrite them
* as needed.
* @param monitor
*/
public static Spec createNewSpec(String name, String rootFilename, boolean importExisting, IProgressMonitor monitor)
{
IProject project = ResourceHelper.getProject(name, rootFilename, true, importExisting, monitor);
PreferenceStoreHelper.storeRootFilename(project, rootFilename);
Spec spec = new Spec(project);
spec.setLastModified();
return spec;
}
/**
* initializes the root module from the project properties
*/
public void initProjectProperties()
{
this.rootFile = PreferenceStoreHelper.readProjectRootFile(project);
this.specObj = null;
this.status = IParseConstants.UNPARSED;
// Initialize the spec's ToolboxDirSize property.
// Added by LL and Dan on 21 May 2010
ResourceHelper.setToolboxDirSize(this.project);
// Assert.isNotNull(this.rootFile);
// This assertion was preventing the Toolbox from starting, so LL
// comented it out on 19 Mar 2011 and added the log message
// on 3 Apr 2011.
// To report this problem to the user, one can do the following:
// - Add a failed field to the Spec object, initialized to false
// - Set this field to true when the error occurs.
// After the statement
// spec = new Spec(projects[i]);
// in the constructor of WorkspaceSpecManager, test this field and,
// if true, take the appropriate action--probably popping up a warning
// (if that's possible) or else putting the name of the spec in the
// log, and also probably not executing the addSpec command that follows
// this statement.
if (this.rootFile == null)
{
Activator.logError("A spec did not load correctly, probably because it was modified outside the Toolbox." +
"\n Error occurred in toolbox/spec/Spec.initProjectProperties()", null);
}
// Initialize TLAtoPCalMapping here for the root module to have it
// available the moment the user needs it the first time. This is just an
// optimization because the mapping would be looked up later
// automatically, but has the advantage that it is not done on the UI thread.
this.getTpMapping(this.rootFile.getName());
}
/**
* @return the lastModified
*/
public Date getLastModified()
{
if (IResource.NULL_STAMP == project.getModificationStamp())
{
return null;
}
return new Date(project.getModificationStamp());
}
/**
* Touches the underlying resource
*/
public void setLastModified()
{
try
{
project.touch(new NullProgressMonitor());
} catch (CoreException e)
{
Activator.logError("Error changing the timestamp of the spec", e);
}
}
/**
* Retrieves the underlying project file
*
* @return the project
*/
public IProject getProject()
{
return project;
}
/**
* @return the name
*/
public String getName()
{
return project.getName();
}
/**
* Retrieves the path to the file containing the root module
* This is a convenience method for {@link getRootFile()#getLocation()#toOSString()}
* @return the OS representation of the root file
*/
public String getRootFilename()
{
IPath location = rootFile.getLocation();
return location.toOSString();
}
/**
* Retrieves the handle to the root file
*
* @return IFile of the root
*/
public IFile getRootFile()
{
return this.rootFile;
}
/**
* Retrieves parsing status
*
* See {@link IParseConstants} for possible values of status.
*
* @return the status
*/
public int getStatus()
{
return status;
}
/**
* Sets parsing status. As a side effect the {@link SpecLifecycleParticipant}s get informed
*
* @param status the status to set
*/
public void setStatus(int status)
{
this.status = status;
// informs
Activator.getSpecManager().specParsed(this);
}
/**
* @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
*/
public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter)
{
// lookup the IAdapterManager service
IAdapterManager manager = Platform.getAdapterManager();
// forward the request to IAdapterManager service
return manager.getAdapter(this, adapter);
}
/**
* Retrieves the list of modules in the spec, or an empty list if no modules
* <br>
* The list is sorted on the resource name
*
* @return
*/
public IResource[] getModuleResources()
{
// TODO relate this list to the list of modules, which result after parse
IResource[] modules = null;
try
{
modules = getProject().members(IResource.NONE);
// sort the markers
List<IResource> moduleList = new ArrayList<IResource>(Arrays.asList(modules));
Collections.sort(moduleList, new ResourceNameComparator());
return moduleList.toArray(new IResource[moduleList.size()]);
} catch (CoreException e)
{
Activator.logError("Error retrieving the the spec modules", e);
modules = new IResource[0];
}
return modules;
}
/**
* Returns the SpecObj
*/
public SpecObj getRootModule()
{
return this.specObj;
}
/**
* Returns the SpecObj only on valid status
*/
public SpecObj getValidRootModule()
{
if (AdapterFactory.isProblemStatus(this.status))
{
return null;
}
return getRootModule();
}
/**
* Sets the new spec object
* @param specObj
*/
public void setSpecObj(SpecObj specObj)
{
this.specObj = specObj;
}
/**
* @param openDeclModuleName the openDeclModuleName to set
*/
public void setOpenDeclModuleName(String openDeclModuleName)
{
this.openDeclModuleName = openDeclModuleName;
}
/**
* @return the openDeclModuleName
*/
public String getOpenDeclModuleName()
{
return openDeclModuleName;
}
/**
* @param openDeclSelection the openDeclSelection to set
*/
public void setOpenDeclSelection(ITextSelection openDeclSelection)
{
this.openDeclSelection = openDeclSelection;
}
/**
* @return the openDeclSelection
*/
public ITextSelection getOpenDeclSelection()
{
return openDeclSelection;
}
/**
* @param moduleToShow the moduleToShow to set
*/
public void setModuleToShow(String moduleToShow)
{
this.moduleToShow = moduleToShow;
}
/**
* @return the moduleToShow
*/
public String getModuleToShow()
{
return moduleToShow;
}
/**
* @param markersToShow the markersToShow to set
*/
public void setMarkersToShow(IMarker[] markersToShow)
{
this.markersToShow = markersToShow;
}
/**
* @return the markersToShow
*/
public IMarker[] getMarkersToShow()
{
return markersToShow;
}
/**
* @param currentSelection the currentSelection to set
*/
public void setCurrentSelection(int currentSelection)
{
this.currentSelection = currentSelection;
}
/**
* @return the currentSelection
*/
public int getCurrentSelection()
{
return currentSelection;
}
private final Lock lock = new ReentrantLock(true);
/**
* @param filename
* The filename of the {@link Spec} for which the
* {@link TLAtoPCalMapping} is asked for.
* @return A {@link TLAtoPCalMapping} for the given {@link Spec}'s filename
* or <code>null</code> if no mapping exist.
*/
public TLAtoPCalMapping getTpMapping(final String filename) {
lock.lock();
try {
TLAtoPCalMapping mapping = spec2mappings.get(filename);
// In-memory cache miss and thus try to read the mapping from its disc
// file. If there exists no disk file, we assume there has never existed
// a mapping.
if (mapping == null) {
mapping = ResourceHelper.readTLAtoPCalMapping(project, filename);
if (mapping == null) {
mapping = new NullTLAtoPCalMapping();
}
spec2mappings.put(filename, mapping);
}
// Always return null if the mapping maps to a NullTLAtoPCalMapping as
// our consumers expect null to indicate a non-existent mapping.
if (mapping instanceof NullTLAtoPCalMapping) {
return null;
}
return mapping;
} finally {
lock.unlock();
}
}
public TLAtoPCalMapping setTpMapping(final TLAtoPCalMapping mapping,
final String filename, final IProgressMonitor monitor) {
lock.lock();
try {
final TLAtoPCalMapping oldMapping = spec2mappings.put(filename, mapping);
// Check if old and new mapping are identical to avoid disk flush.
// This requires proper equals/hashcode in TLAtoPCalMapping and nested.
if (!mapping.equals(oldMapping)) {
// Use a submonitor to show progress as well as failure
final SubProgressMonitor subProgressMonitor = new SubProgressMonitor(monitor, 1);
subProgressMonitor.setTaskName("Writing TLA+ to PCal mapping for " + filename);
// Eagerly flush mapping to its persistent disk storage (overwriting
// any previous mapping stored on disk). This is relatively cheap
// compared to how often a mapping is re-generated, but has the
// advantage that the mapping doesn't get lost if the Toolbox decides to
// not shut down gracefully.
try {
Assert.isTrue(ResourceHelper.writeTLAtoPCalMapping(project,
filename, mapping, subProgressMonitor));
} finally {
subProgressMonitor.done();
}
}
return oldMapping;
} finally {
lock.unlock();
}
}
@SuppressWarnings("serial")
private static class NullTLAtoPCalMapping extends TLAtoPCalMapping {}
}
|
package es.tid.cosmos.platform.injection.server;
import java.io.IOException;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.sshd.server.FileSystemView;
import org.apache.sshd.server.SshFile;
import es.tid.cosmos.base.util.Logger;
/**
* HadoopFileSystemView
*
* @author logc
* @since CTP 2
*/
public class HadoopFileSystemView implements FileSystemView {
private static final org.apache.log4j.Logger LOG =
Logger.get(HadoopFileSystemView.class);
private String homePath;
private FileSystem hadoopFS;
private final String userName;
public HadoopFileSystemView(String userName, Configuration configuration)
throws IOException, InterruptedException {
this.userName = userName;
try {
this.hadoopFS = FileSystem.get(
URI.create(configuration.get("fs.default.name")),
configuration, this.userName);
this.homePath = this.hadoopFS.getHomeDirectory().toString()
.replaceFirst(this.hadoopFS.getUri().toString(), "");
} catch (IOException e) {
LOG.error(e.getMessage(), e);
throw e;
} catch (InterruptedException e) {
LOG.error(e.getMessage(), e);
throw e;
}
}
@Override
public HadoopSshFile getFile(String file) {
try {
return this.getFile("", file);
} catch (IOException e) {
LOG.error(e.getMessage(), e);
} catch (InterruptedException e) {
LOG.error(e.getMessage(), e);
}
return null;
}
@Override
public HadoopSshFile getFile(SshFile baseDir, String file) {
try {
return this.getFile(baseDir.getAbsolutePath(), file);
} catch (IOException e) {
LOG.error(e.getMessage(), e);
} catch (InterruptedException e) {
LOG.error(e.getMessage(), e);
}
return null;
}
private HadoopSshFile getFile(String baseDir, String file)
throws IOException, InterruptedException {
String requestedDir = baseDir;
String requestedFile = file;
if (requestedDir.isEmpty()){
if (requestedFile.isEmpty()) {
throw new IllegalArgumentException("filesystem view impossible" +
" for empty dir and filename!");
} else if (requestedFile.equals(Path.CUR_DIR)) {
requestedDir = this.homePath;
requestedFile = "";
LOG.debug("redirecting to home path: " + this.homePath);
}
}
String wholePath = requestedDir + requestedFile;
if (!requestedDir.endsWith(Path.SEPARATOR) &&
!requestedFile.startsWith(Path.SEPARATOR)) {
wholePath = requestedDir + Path.SEPARATOR + requestedFile;
}
return new HadoopSshFile(wholePath, this.userName, this.hadoopFS);
}
}
|
package com.jme.widget.font;
import java.io.DataInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.logging.Level;
import com.jme.image.Image;
import com.jme.image.Texture;
import com.jme.math.Vector2f;
import com.jme.renderer.ColorRGBA;
import com.jme.util.LoggingSystem;
/**
* @author Gregg Patton
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public abstract class WidgetFontAbstract implements WidgetFont {
private static String FONT_DIRECTORY = "data/Font/";
private static String FONT_EXT = "glf";
protected WidgetFontHeader header;
protected Texture texture;
private String name;
public WidgetFontAbstract(String name) {
this.name = name;
String filename = FONT_DIRECTORY + name + "." + FONT_EXT;
create(filename);
}
public void create(String filename) {
URL url = null;
url = WidgetFontAbstract.class.getClassLoader().getResource(FONT_DIRECTORY+name+"."+FONT_EXT);
if(url != null) {
create(url);
} else {
try {
url = new URL("file:"+filename);
create(url);
} catch (MalformedURLException e){
LoggingSystem.getLogger().log(Level.WARNING, "Could not load: "+filename);
}
}
}
public void create(URL filename) {
try {
int numChars, numTexBytes, cnt;
WidgetFontChar fontChar;
header = new WidgetFontHeader();
texture = new Texture();
InputStream is = filename.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] data = new byte[dis.available()];
dis.readFully(data);
ByteBuffer buf = ByteBuffer.allocateDirect(data.length);
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.rewind();
buf.put(data);
buf.rewind();
header.setTex(buf.getInt());
header.setTexWidth(buf.getInt());
header.setTexHeight(buf.getInt());
header.setStartChar(buf.getInt());
header.setEndChar(buf.getInt());
//header.chars
buf.getInt();
float newHeight = 0;
float height = 0;
numChars = header.getEndChar() - header.getStartChar() + 1;
for (cnt = 0; cnt < numChars; cnt++) {
fontChar = new WidgetFontChar();
fontChar.setDx(buf.getFloat());
fontChar.setDy(buf.getFloat());
fontChar.setTx1(buf.getFloat());
fontChar.setTy1(buf.getFloat());
fontChar.setTx2(buf.getFloat());
fontChar.setTy2(buf.getFloat());
header.addChar(fontChar);
newHeight = fontChar.getDy() * header.getTexHeight();
if (newHeight > height)
height = newHeight;
}
Image textureImage = new Image();
textureImage.setType(Image.RA88);
textureImage.setWidth(header.getTexWidth());
textureImage.setHeight(header.getTexHeight());
textureImage.setData(buf);
texture.setBlendColor(new ColorRGBA(1, 1, 1, 1));
texture.setFilter(Texture.MM_NEAREST);
texture.setImage(textureImage);
texture.setMipmapState(Texture.MM_NONE);
texture.setWrap(Texture.WM_CLAMP_S_CLAMP_T);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//Calculate size of a string
public Vector2f getStringSize(String text) {
Vector2f ret = new Vector2f();
int i;
char c;
WidgetFontChar fontChar;
float width = 0, height = 0; //, newHeight = 0;
fontChar = header.getChar(header.getStartChar());
ret.y = fontChar.getDy() * header.getTexHeight();
//Calculate width of string
width = 0;
for (i = 0; i < text.length(); i++) {
//Make sure character is in range
c = text.charAt(i);
if (c < header.getStartChar() || c > header.getEndChar())
continue;
//Get pointer to glFont character
fontChar = header.getChar(c - header.getStartChar());
//Get width and height
width += fontChar.getDx() * header.getTexWidth();
}
ret.x = width;
return ret;
}
public Texture getTexture() {
return texture;
}
public String getName() {
return name;
}
public abstract void renderString(
String text,
float x,
float y,
float scalar,
ColorRGBA topColor,
ColorRGBA bottomColor);
public String toString() {
return "[" + name + "]";
}
}
|
package com.intellij.psi.impl.source.resolve.reference;
import com.intellij.ant.impl.dom.impl.RegisterInPsi;
import com.intellij.lang.properties.PropertiesReferenceProvider;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.*;
import com.intellij.psi.jsp.el.ELLiteralExpression;
import com.intellij.psi.filters.*;
import com.intellij.psi.filters.position.NamespaceFilter;
import com.intellij.psi.filters.position.ParentElementFilter;
import com.intellij.psi.filters.position.TokenTypeFilter;
import com.intellij.psi.impl.meta.MetaRegistry;
import com.intellij.psi.impl.source.jsp.jspJava.JspDirective;
import com.intellij.psi.impl.source.jsp.el.impl.ELLiteralManipulator;
import com.intellij.psi.impl.source.resolve.ResolveUtil;
import com.intellij.psi.impl.source.resolve.reference.impl.manipulators.*;
import com.intellij.psi.impl.source.resolve.reference.impl.providers.*;
import com.intellij.psi.xml.*;
import com.intellij.xml.util.HtmlReferenceProvider;
import com.intellij.xml.util.XmlUtil;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.codeInsight.daemon.impl.analysis.XmlEncodingReferenceProvider;
import com.intellij.codeInsight.i18n.I18nUtil;
import com.intellij.util.Function;
import com.intellij.javaee.web.WebUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ReferenceProvidersRegistry implements ProjectComponent {
private final List<Class> myTempScopes = new ArrayList<Class>();
private final Map<Class,ProviderBinding> myBindingsMap = new HashMap<Class,ProviderBinding>();
private final List<Pair<Class<?>, ElementManipulator<?>>> myManipulators = new ArrayList<Pair<Class<?>, ElementManipulator<?>>>();
private final Map<ReferenceProviderType,PsiReferenceProvider> myReferenceTypeToProviderMap = new HashMap<ReferenceProviderType, PsiReferenceProvider>(5);
private static final Logger LOG = Logger.getInstance("ReferenceProvidersRegistry");
static public class ReferenceProviderType {
private String myId;
public ReferenceProviderType(@NonNls String id) { myId = id; }
public String toString() { return myId; }
}
public static ReferenceProviderType PROPERTIES_FILE_KEY_PROVIDER = new ReferenceProviderType("Properties File Key Provider");
public static ReferenceProviderType CLASS_REFERENCE_PROVIDER = new ReferenceProviderType("Class Reference Provider");
public static ReferenceProviderType PATH_REFERENCES_PROVIDER = new ReferenceProviderType("Path References Provider");
public static ReferenceProviderType DYNAMIC_PATH_REFERENCES_PROVIDER = new ReferenceProviderType("Dynamic Path References Provider");
public static ReferenceProviderType CSS_CLASS_OR_ID_KEY_PROVIDER = new ReferenceProviderType("Css Class or ID Provider");
public static ReferenceProviderType URI_PROVIDER = new ReferenceProviderType("Uri references provider");
public static ReferenceProviderType SCHEMA_PROVIDER = new ReferenceProviderType("Schema references provider");
public static ReferenceProvidersRegistry getInstance(@NotNull Project project) {
return project.getComponent(ReferenceProvidersRegistry.class);
}
public void registerTypeWithProvider(@NotNull ReferenceProviderType type, @NotNull PsiReferenceProvider provider) {
myReferenceTypeToProviderMap.put(type, provider);
}
private ReferenceProvidersRegistry() {
// Temp scopes declarations
myTempScopes.add(PsiIdentifier.class);
// Manipulators mapping
registerManipulator(XmlAttributeValue.class, new XmlAttributeValueManipulator());
registerManipulator(PsiPlainTextFile.class, new PlainFileManipulator());
registerManipulator(XmlToken.class, new XmlTokenManipulator());
registerManipulator(PsiLiteralExpression.class, new StringLiteralManipulator());
registerManipulator(XmlTag.class, new XmlTagValueManipulator());
registerManipulator(ELLiteralExpression.class, new ELLiteralManipulator());
// Binding declarations
myReferenceTypeToProviderMap.put(CLASS_REFERENCE_PROVIDER, new JavaClassReferenceProvider());
myReferenceTypeToProviderMap.put(PATH_REFERENCES_PROVIDER, new JspxIncludePathReferenceProvider());
myReferenceTypeToProviderMap.put(DYNAMIC_PATH_REFERENCES_PROVIDER, new JspxDynamicPathReferenceProvider());
myReferenceTypeToProviderMap.put(PROPERTIES_FILE_KEY_PROVIDER, new PropertiesReferenceProvider());
registerXmlAttributeValueReferenceProvider(
new String[]{"class", "type"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new TextFilter("useBean"),
new NamespaceFilter(XmlUtil.JSP_URI)
), 2
)
), getProviderByType(CLASS_REFERENCE_PROVIDER)
);
RegisterInPsi.referenceProviders(this);
registerXmlAttributeValueReferenceProvider(
new String[]{"extends"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new OrFilter(
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("directive.page")
),
new AndFilter(
new ClassFilter(JspDirective.class),
new TextFilter("page")
)
),
new NamespaceFilter(XmlUtil.JSP_URI)
),
2
)
), getProviderByType(CLASS_REFERENCE_PROVIDER)
);
final CustomizableReferenceProvider classReferenceProvider = (CustomizableReferenceProvider)getProviderByType(CLASS_REFERENCE_PROVIDER);
final CustomizingReferenceProvider qualifiedClassReferenceProvider = new CustomizingReferenceProvider(classReferenceProvider);
qualifiedClassReferenceProvider.addCustomization(JavaClassReferenceProvider.RESOLVE_QUALIFIED_CLASS_NAME, true);
registerXmlAttributeValueReferenceProvider(
new String[]{"type"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new OrFilter(
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("directive.attribute")
),
new AndFilter(
new ClassFilter(JspDirective.class),
new TextFilter("attribute")
)
),
new NamespaceFilter(XmlUtil.JSP_URI)
),
2
)
),
qualifiedClassReferenceProvider
);
registerXmlAttributeValueReferenceProvider(
new String[]{"variable-class"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new OrFilter(
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("directive.variable")
),
new AndFilter(
new ClassFilter(JspDirective.class),
new TextFilter("variable")
)
),
new NamespaceFilter(XmlUtil.JSP_URI)
),
2
)
),
qualifiedClassReferenceProvider
);
registerXmlAttributeValueReferenceProvider(
new String[] { "import" },
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new OrFilter(
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("directive.page")
),
new AndFilter(
new ClassFilter(JspDirective.class),
new TextFilter("page")
)
),
new NamespaceFilter(XmlUtil.JSP_URI)
),
2
)
),
new JspImportListReferenceProvider()
);
registerXmlAttributeValueReferenceProvider(
new String[]{"errorPage"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.JSP_URI),
new OrFilter(
new AndFilter(
new ClassFilter(JspDirective.class),
new TextFilter("page")
),
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("directive.page")
))
), 2
)
), getProviderByType(PATH_REFERENCES_PROVIDER)
);
registerXmlAttributeValueReferenceProvider(
new String[]{"file"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.JSP_URI),
new OrFilter(
new AndFilter(
new ClassFilter(JspDirective.class),
new TextFilter("include")
),
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("directive.include")
))
), 2
)
), getProviderByType(PATH_REFERENCES_PROVIDER)
);
final CustomizableReferenceProvider dynamicPathReferenceProvider = (CustomizableReferenceProvider)getProviderByType(DYNAMIC_PATH_REFERENCES_PROVIDER);
final CustomizingReferenceProvider dynamicPathReferenceProviderNoEmptyFileReferencesAtEnd = new CustomizingReferenceProvider(dynamicPathReferenceProvider);
dynamicPathReferenceProviderNoEmptyFileReferencesAtEnd.addCustomization(
JspxDynamicPathReferenceProvider.ALLOW_REFERENCING_DIR_WITH_END_SLASH,
true
);
registerXmlAttributeValueReferenceProvider(
new String[]{"value"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.JSTL_CORE_URIS),
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("url")
)
), 2
)
), dynamicPathReferenceProviderNoEmptyFileReferencesAtEnd
);
registerXmlAttributeValueReferenceProvider(
new String[]{"url"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.JSTL_CORE_URIS),
new AndFilter(
new ClassFilter(XmlTag.class),
new OrFilter(
new TextFilter("import"),
new TextFilter("redirect")
)
)
), 2
)
), dynamicPathReferenceProviderNoEmptyFileReferencesAtEnd
);
PsiReferenceProvider propertiesReferenceProvider = getProviderByType(PROPERTIES_FILE_KEY_PROVIDER);
registerXmlAttributeValueReferenceProvider(
new String[]{"key"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new OrFilter(
new NamespaceFilter(XmlUtil.JSTL_FORMAT_URIS),
new NamespaceFilter(XmlUtil.STRUTS_BEAN_URI)
),
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("message")
)
), 2
)
), propertiesReferenceProvider
);
registerXmlAttributeValueReferenceProvider(
new String[]{"altKey","titleKey","pageKey","srcKey"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.STRUTS_HTML_URI),
new ClassFilter(XmlTag.class)
), 2
)
), propertiesReferenceProvider
);
registerXmlAttributeValueReferenceProvider(
new String[]{"code"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.SPRING_URI),
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("message", "theme")
)
), 2
)
), propertiesReferenceProvider
);
registerXmlAttributeValueReferenceProvider(
new String[]{"page"},
new ScopeFilter(
new ParentElementFilter(
new OrFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.JSP_URI),
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("include","forward")
)
),
new AndFilter(
new NamespaceFilter(XmlUtil.STRUTS_HTML_URI),
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("rewrite")
)
)
), 2
)
), getProviderByType(DYNAMIC_PATH_REFERENCES_PROVIDER)
);
final PsiReferenceProvider pathReferenceProvider = getProviderByType(PATH_REFERENCES_PROVIDER);
final CustomizingReferenceProvider webXmlPathReferenceProvider = new CustomizingReferenceProvider(
(CustomizableReferenceProvider)pathReferenceProvider
);
webXmlPathReferenceProvider.addCustomization(
FileReferenceSet.DEFAULT_PATH_EVALUATOR_OPTION,
new Function<PsiFile, PsiElement>() {
public PsiElement fun(final PsiFile file) {
return FileReferenceSet.getAbsoluteTopLevelDirLocation(
WebUtil.getWebModuleProperties(file),
file.getProject(),
file
);
}
}
);
registerXmlTagReferenceProvider(
new String[]{"welcome-file","location","taglib-location"},
new NamespaceFilter(XmlUtil.WEB_XML_URIS),
true,
webXmlPathReferenceProvider
);
registerXmlAttributeValueReferenceProvider(
new String[]{"tagdir"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.JSP_URI),
new AndFilter(
new ClassFilter(JspDirective.class),
new TextFilter("taglib")
)
), 2
)
), getProviderByType(PATH_REFERENCES_PROVIDER)
);
registerXmlAttributeValueReferenceProvider(
new String[] { "uri" },
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(XmlUtil.JSP_URI),
new AndFilter(
new ClassFilter(JspDirective.class),
new TextFilter("taglib")
)
), 2
)
),
new JspUriReferenceProvider()
);
final JavaClassListReferenceProvider classListProvider = new JavaClassListReferenceProvider();
registerXmlAttributeValueReferenceProvider(null,
new AndFilter(
new NotFilter(
new ParentElementFilter(
new NamespaceFilter(XmlUtil.ANT_URI), 2)),
new NotFilter(
new ScopeFilter(new ParentElementFilter(
new AndFilter(
new OrFilter(
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("directive.page")),
new AndFilter(
new ClassFilter(JspDirective.class),
new TextFilter("page"))),
new NamespaceFilter(XmlUtil.JSP_URI)), 2)))), classListProvider);
registerReferenceProvider(new TokenTypeFilter(XmlTokenType.XML_DATA_CHARACTERS), XmlToken.class,
classListProvider);
registerXmlTagReferenceProvider(
new String[] {
"function-class", "tag-class", "tei-class", "variable-class", "type", "path",
"function-signature", "name", "name-given"
},
new NamespaceFilter(MetaRegistry.TAGLIB_URIS),
true,
new TaglibReferenceProvider( getProviderByType(CLASS_REFERENCE_PROVIDER) )
);
final NamespaceFilter jsfNsFilter = new NamespaceFilter(XmlUtil.JSF_URIS);
registerXmlTagReferenceProvider(
new String[] {
"render-kit-class","renderer-class","managed-bean-class","attribute-class","component-class",
"converter-for-class", "converter-class", "key-class", "value-class",
"referenced-bean-class", "validator-class", "application-factory", "faces-context-factory",
"render-kit-factory", "lifecycle-factory", "view-handler", "variable-resolver", "phase-listener",
"property-resolver", "state-manager", "action-listener", "navigation-handler"
},
jsfNsFilter,
true,
getProviderByType(CLASS_REFERENCE_PROVIDER)
);
final JSFReferencesProvider jsfProvider = new JSFReferencesProvider(getProviderByType(DYNAMIC_PATH_REFERENCES_PROVIDER));
registerXmlTagReferenceProvider(
jsfProvider.getTagNames(),
jsfNsFilter,
true,
jsfProvider
);
registerXmlAttributeValueReferenceProvider(
jsfProvider.getAttributeNames(),
new ParentElementFilter( new NamespaceFilter(XmlUtil.JSF_HTML_URI), 2),
true,
jsfProvider
);
final DtdReferencesProvider dtdReferencesProvider = new DtdReferencesProvider();
//registerReferenceProvider(null, XmlEntityDecl.class,dtdReferencesProvider);
registerReferenceProvider(null, XmlEntityRef.class,dtdReferencesProvider);
registerReferenceProvider(null, XmlDoctype.class,dtdReferencesProvider);
registerReferenceProvider(null, XmlElementDecl.class,dtdReferencesProvider);
registerReferenceProvider(null, XmlAttlistDecl.class,dtdReferencesProvider);
registerReferenceProvider(null, XmlElementContentSpec.class,dtdReferencesProvider);
registerReferenceProvider(null, XmlToken.class,dtdReferencesProvider);
URIReferenceProvider uriProvider = new URIReferenceProvider();
registerTypeWithProvider(URI_PROVIDER,uriProvider);
registerXmlAttributeValueReferenceProvider(
null,
dtdReferencesProvider.getSystemReferenceFilter(),
uriProvider
);
//registerReferenceProvider(PsiPlainTextFile.class, new JavaClassListReferenceProvider());
HtmlReferenceProvider provider = new HtmlReferenceProvider();
registerXmlAttributeValueReferenceProvider(
new String[] {
"src", "href", "action", "background", "width", "height", "type", "bgcolor", "color", "vlink", "link", "alink", "text", "name"
},
provider.getFilter(),
false,
provider
);
final PsiReferenceProvider filePathReferenceProvider = new FilePathReferenceProvider();
registerReferenceProvider(
new ElementFilter() {
public boolean isAcceptable(Object element, PsiElement context) {
if (context instanceof PsiLiteralExpression) {
PsiLiteralExpression literalExpression = (PsiLiteralExpression) context;
final Map<String, Object> annotationParams = new HashMap<String, Object>();
annotationParams.put(AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER, null);
if (I18nUtil.mustBePropertyKey(literalExpression, annotationParams)) {
return false;
}
}
return true;
}
public boolean isClassAcceptable(Class hintClass) {
return true;
}
}, PsiLiteralExpression.class, filePathReferenceProvider);
final SchemaReferencesProvider schemaReferencesProvider = new SchemaReferencesProvider();
registerTypeWithProvider(SCHEMA_PROVIDER, schemaReferencesProvider);
registerXmlAttributeValueReferenceProvider(
new String[] {"ref","type","base","name","substitutionGroup","memberTypes","value"},
new ScopeFilter(
new ParentElementFilter(
new NamespaceFilter(MetaRegistry.SCHEMA_URIS), 2
)
),
schemaReferencesProvider
);
registerXmlAttributeValueReferenceProvider(
new String[] {"xsi:type"},
null,
schemaReferencesProvider
);
registerXmlAttributeValueReferenceProvider(
new String[] {"xsi:noNamespaceSchemaLocation"},
null,
uriProvider
);
registerXmlAttributeValueReferenceProvider(
new String[] {"schemaLocation"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new NamespaceFilter(MetaRegistry.SCHEMA_URIS),
new AndFilter(
new ClassFilter(XmlTag.class),
new TextFilter("import","include")
)
), 2
)
),
uriProvider
);
registerXmlAttributeValueReferenceProvider(
null,
uriProvider.getNamespaceAttributeFilter(),
uriProvider
);
final JspReferencesProvider jspReferencesProvider = new JspReferencesProvider();
registerXmlAttributeValueReferenceProvider(
new String[] {"fragment","name","property","id","name-given","dynamic-attributes","name-from-attribute"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new ClassFilter(XmlTag.class),
new NamespaceFilter(
new String[] {
XmlUtil.JSP_URI,
XmlUtil.STRUTS_BEAN_URI,
XmlUtil.STRUTS_LOGIC_URI
}
)
), 2
)
),
jspReferencesProvider
);
registerXmlAttributeValueReferenceProvider(
new String[] {"var"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new ClassFilter(XmlTag.class),
new NamespaceFilter(XmlUtil.JSTL_CORE_URIS)
), 2
)
),
jspReferencesProvider
);
registerXmlAttributeValueReferenceProvider(
new String[] {"scope"},
null,
jspReferencesProvider
);
registerXmlAttributeValueReferenceProvider(
new String[] {"name"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new ClassFilter(XmlTag.class),
new AndFilter(
new TextFilter("property"),
new NamespaceFilter(XmlUtil.SPRING_CORE_URIS)
)
), 2
)
),
new SpringReferencesProvider()
);
registerXmlAttributeValueReferenceProvider(
new String[] {"name"},
new ScopeFilter(
new ParentElementFilter(
new AndFilter(
new ClassFilter(XmlTag.class),
new AndFilter(
new NamespaceFilter(XmlUtil.HIBERNATE_URIS),
new TextFilter(new String[] { "property","list","map","set", "array", "bag", "idbag", "primitive-array", "many-to-one", "one-to-one"} )
)
), 2
)
),
new HibernateReferencesProvider()
);
registerXmlAttributeValueReferenceProvider(
new String[] {"encoding"},
new ScopeFilter(new ParentElementFilter(new ClassFilter(XmlProcessingInstruction.class))),
new XmlEncodingReferenceProvider()
);
}
public void registerReferenceProvider(@Nullable ElementFilter elementFilter, @NotNull Class scope, @NotNull PsiReferenceProvider provider) {
if (scope == XmlAttributeValue.class) {
registerXmlAttributeValueReferenceProvider(null, elementFilter, provider);
return;
} else if (scope == XmlTag.class) {
registerXmlTagReferenceProvider(null, elementFilter, false, provider);
return;
}
final ProviderBinding providerBinding = myBindingsMap.get(scope);
if (providerBinding != null) {
((SimpleProviderBinding)providerBinding).registerProvider(provider, elementFilter);
return;
}
final SimpleProviderBinding binding = new SimpleProviderBinding(scope);
binding.registerProvider(provider,elementFilter);
myBindingsMap.put(scope,binding);
}
public void registerXmlTagReferenceProvider(@NonNls String[] names, @Nullable ElementFilter elementFilter,
boolean caseSensitive, @NotNull PsiReferenceProvider provider) {
registerNamedReferenceProvider(names, elementFilter, XmlTagProviderBinding.class,XmlTag.class,caseSensitive, provider);
}
private void registerNamedReferenceProvider(
@Nullable @NonNls String[] names,
@Nullable ElementFilter elementFilter,
@NotNull Class<? extends NamedObjectProviderBinding> bindingClass,
@NotNull Class scopeClass,
boolean caseSensitive,
@NotNull PsiReferenceProvider provider
) {
NamedObjectProviderBinding providerBinding = (NamedObjectProviderBinding)myBindingsMap.get(scopeClass);
if (providerBinding == null) {
try {
providerBinding = bindingClass.newInstance();
myBindingsMap.put(scopeClass, providerBinding);
}
catch (Exception e) {
LOG.error(e);
return;
}
}
providerBinding.registerProvider(
names,
elementFilter,
caseSensitive,
provider
);
}
public void registerXmlAttributeValueReferenceProvider(@Nullable @NonNls String[] attributeNames,
@Nullable ElementFilter elementFilter,
boolean caseSensitive,
@NotNull PsiReferenceProvider provider) {
registerNamedReferenceProvider(
attributeNames,
elementFilter,
XmlAttributeValueProviderBinding.class,
XmlAttributeValue.class,
caseSensitive,
provider
);
}
public void registerXmlAttributeValueReferenceProvider(@Nullable @NonNls String[] attributeNames,
@Nullable ElementFilter elementFilter,
@NotNull PsiReferenceProvider provider) {
registerXmlAttributeValueReferenceProvider(attributeNames, elementFilter, true, provider);
}
public @NotNull PsiReferenceProvider getProviderByType(@NotNull ReferenceProviderType type) {
return myReferenceTypeToProviderMap.get(type);
}
public void registerReferenceProvider(@NotNull Class scope, @NotNull PsiReferenceProvider provider) {
registerReferenceProvider(null, scope, provider);
}
public @NotNull PsiReferenceProvider[] getProvidersByElement(@NotNull PsiElement element, @NotNull Class clazz) {
assert clazz.isInstance(element);
List<PsiReferenceProvider> ret = new ArrayList<PsiReferenceProvider>(1);
PsiElement current;
do {
current = element;
final ProviderBinding providerBinding = myBindingsMap.get(clazz);
if (providerBinding != null) providerBinding.addAcceptableReferenceProviders(current, ret);
element = ResolveUtil.getContext(element);
}
while (!isScopeFinal(current.getClass()));
return ret.size() > 0 ? ret.toArray(new PsiReferenceProvider[ret.size()]) : PsiReferenceProvider.EMPTY_ARRAY;
}
public @Nullable <T extends PsiElement> ElementManipulator<T> getManipulator(@NotNull T element) {
for (final Pair<Class<?>,ElementManipulator<?>> pair : myManipulators) {
if (pair.getFirst().isAssignableFrom(element.getClass())) {
return (ElementManipulator<T>)pair.getSecond();
}
}
return null;
}
public <T extends PsiElement> void registerManipulator(@NotNull Class<T> elementClass, @NotNull ElementManipulator<T> manipulator) {
myManipulators.add(new Pair<Class<?>, ElementManipulator<?>>(elementClass, manipulator));
}
private boolean isScopeFinal(Class scopeClass) {
for (final Class aClass : myTempScopes) {
if (aClass.isAssignableFrom(scopeClass)) {
return false;
}
}
return true;
}
public void projectOpened() {}
public void projectClosed() {}
public String getComponentName() {
return "Reference providers registry";
}
public void initComponent() {}
public void disposeComponent() {}
}
|
package org.metaborg.runtime.task;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.spoofax.interpreter.terms.IStrategoInt;
import org.spoofax.interpreter.terms.IStrategoList;
import org.spoofax.interpreter.terms.IStrategoString;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.IStrategoTuple;
import org.spoofax.interpreter.terms.ITermFactory;
import static com.google.common.collect.Sets.filter;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
public class Tasks {
private final ITermFactory factory;
private final ManyToManyMap<IStrategoInt, IStrategoString> toPartition = ManyToManyMap.create();
private final ManyToManyMap<IStrategoInt, IStrategoTerm> toDependency = ManyToManyMap.create();
private final Map<IStrategoInt, IStrategoTerm> toInstruction = new ConcurrentHashMap<IStrategoInt, IStrategoTerm>();
private final Map<IStrategoInt, IStrategoList> toResult = new ConcurrentHashMap<IStrategoInt, IStrategoList>();
private final Set<IStrategoInt> addedTasks = new HashSet<IStrategoInt>();
private final Set<IStrategoInt> removedTasks = new HashSet<IStrategoInt>();
private final Set<IStrategoInt> tasks = toInstruction.keySet();
private final Set<IStrategoInt> garbage = filter(tasks, not(in(toPartition.keys())));
private final Set<IStrategoInt> solved = toResult.keySet();
private final Set<IStrategoInt> stalled = toDependency.keySet();
// private final Set<IStrategoInt> solvable = filter(tasks, not(or(in(solved), in(stalled))));
public Tasks(ITermFactory factory) {
this.factory = factory;
}
public IStrategoInt addTask(IStrategoString partition, IStrategoList dependencies, IStrategoTerm instruction) {
IStrategoInt taskID = factory.makeInt(instruction.hashCode());
if(toInstruction.put(taskID, instruction) == null)
addedTasks.add(taskID);
removedTasks.remove(taskID);
toPartition.put(taskID, partition);
for (IStrategoTerm dep : dependencies.getAllSubterms())
toDependency.put(taskID, dep);
return taskID;
}
public void addResult(IStrategoInt taskID, IStrategoTerm result) {
toResult.put(taskID, factory.makeListCons(result, factory.makeList()));
}
public void addResult(IStrategoInt taskID, IStrategoList resultList) {
toResult.put(taskID, resultList);
}
public IStrategoList getResult(IStrategoInt taskID) {
return toResult.get(taskID);
}
public void startCollection(IStrategoString partition) {
addedTasks.clear();
removedTasks.clear();
removedTasks.addAll(toPartition.getInverse(partition));
}
public IStrategoTuple stopCollection(IStrategoString partition) {
for(IStrategoInt removed : removedTasks)
toPartition.remove(removed, partition);
collectGarbage();
return factory.makeTuple(factory.makeList(addedTasks), factory.makeList(removedTasks));
}
// private void removeTask(IStrategoInt taskID, IStrategoString partition) {
// toPartition.remove(taskID, partition);
// if(!toPartition.containsKey(taskID)) {
// toDependency.removeAll(taskID);
// toInstruction.remove(taskID);
// toResult.remove(taskID);
private void collectGarbage() {
tasks.removeAll(garbage);
solved.removeAll(garbage);
stalled.removeAll(garbage);
}
}
|
// This source code is available under agreement available at
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
package org.talend.dataprep.transformation.api.action.metadata.text;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static org.talend.dataprep.api.dataset.ColumnMetadata.Builder.column;
import static org.talend.dataprep.transformation.api.action.metadata.ActionMetadataTestUtils.getColumn;
import static org.talend.dataprep.transformation.api.action.metadata.ActionMetadataTestUtils.getRow;
import java.io.IOException;
import java.util.*;
import org.apache.commons.lang.StringUtils;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.talend.dataprep.api.dataset.ColumnMetadata;
import org.talend.dataprep.api.dataset.DataSetRow;
import org.talend.dataprep.api.dataset.Quality;
import org.talend.dataprep.api.dataset.RowMetadata;
import org.talend.dataprep.api.dataset.location.SemanticDomain;
import org.talend.dataprep.api.dataset.statistics.Statistics;
import org.talend.dataprep.api.preparation.Action;
import org.talend.dataprep.api.type.Type;
import org.talend.dataprep.transformation.api.action.ActionTestWorkbench;
import org.talend.dataprep.transformation.api.action.metadata.AbstractMetadataBaseTest;
import org.talend.dataprep.transformation.api.action.metadata.ActionMetadataTestUtils;
import org.talend.dataprep.transformation.api.action.metadata.category.ActionCategory;
import org.talend.dataprep.transformation.api.action.parameters.Parameter;
/**
* Test class for Split action. Creates one consumer, and test it.
*
* @see Split
*/
public class SplitTest extends AbstractMetadataBaseTest {
/**
* The action to test.
*/
@Autowired
private Split action;
/** The action parameters. */
private Map<String, String> parameters;
@Before
public void init() throws IOException {
parameters = ActionMetadataTestUtils.parseParameters(SplitTest.class.getResourceAsStream("splitAction.json"));
}
@Test
public void testName() throws Exception {
assertEquals("split", action.getName());
}
@Test
public void testParameters() throws Exception {
final List<Parameter> parameters = action.getParameters();
assertEquals(6, parameters.size());
assertEquals(1L, parameters.stream().filter(p -> StringUtils.equals(Split.LIMIT, p.getName())).count());
final Optional<Parameter> separatorParameter = parameters.stream()
.filter(p -> StringUtils.equals(Split.SEPARATOR_PARAMETER, p.getName()))
.findFirst();
assertTrue(separatorParameter.isPresent());
}
@Test
public void testAdapt() throws Exception {
assertThat(action.adapt((ColumnMetadata) null), is(action));
ColumnMetadata column = column().name("myColumn").id(0).type(Type.STRING).build();
assertThat(action.adapt(column), is(action));
}
@Test
public void testCategory() throws Exception {
assertThat(action.getCategory(), is(ActionCategory.SPLIT.getDisplayName()));
}
/**
* @see Split#create(Map)
*/
@Test
public void should_split_row() {
// given
final DataSetRow row = getRow("lorem bacon", "Bacon ipsum dolor amet swine leberkas pork belly", "01/01/2015");
final Map<String, String> expectedValues = new HashMap<>();
expectedValues.put("0000", "lorem bacon");
expectedValues.put("0001", "Bacon ipsum dolor amet swine leberkas pork belly");
expectedValues.put("0003", "Bacon");
expectedValues.put("0004", "ipsum dolor amet swine leberkas pork belly");
expectedValues.put("0002", "01/01/2015");
// when
ActionTestWorkbench.test(row, action.create(parameters).getRowAction());
// then
assertEquals(expectedValues, row.values());
}
@Test
public void should_split_semicolon() {
// given
final DataSetRow row = getRow("lorem bacon", "Bacon;ipsum", "01/01/2015");
parameters.put(Split.SEPARATOR_PARAMETER, ";");
final Map<String, String> expectedValues = new HashMap<>();
expectedValues.put("0000", "lorem bacon");
expectedValues.put("0001", "Bacon;ipsum");
expectedValues.put("0003", "Bacon");
expectedValues.put("0004", "ipsum");
expectedValues.put("0002", "01/01/2015");
// when
ActionTestWorkbench.test(row, action.create(parameters).getRowAction());
// then
assertEquals(expectedValues, row.values());
}
@Test
public void should_split_underscore() {
// given
final DataSetRow row = getRow("lorem bacon", "Bacon_ipsum", "01/01/2015");
parameters.put(Split.SEPARATOR_PARAMETER, "other (string)");
parameters.put(Split.MANUAL_SEPARATOR_PARAMETER_STRING, "_");
final Map<String, String> expectedValues = new HashMap<>();
expectedValues.put("0000", "lorem bacon");
expectedValues.put("0001", "Bacon_ipsum");
expectedValues.put("0003", "Bacon");
expectedValues.put("0004", "ipsum");
expectedValues.put("0002", "01/01/2015");
// when
ActionTestWorkbench.test(row, action.create(parameters).getRowAction());
// then
assertEquals(expectedValues, row.values());
}
@Test
public void should_split_tab() {
// given
final DataSetRow row = getRow("lorem bacon", "Bacon\tipsum", "01/01/2015");
parameters.put(Split.SEPARATOR_PARAMETER, "other (string)");
parameters.put(Split.MANUAL_SEPARATOR_PARAMETER_STRING, "\t");
final Map<String, String> expectedValues = new HashMap<>();
expectedValues.put("0000", "lorem bacon");
expectedValues.put("0001", "Bacon\tipsum");
expectedValues.put("0003", "Bacon");
expectedValues.put("0004", "ipsum");
expectedValues.put("0002", "01/01/2015");
// when
ActionTestWorkbench.test(row, action.create(parameters).getRowAction());
// then
assertEquals(expectedValues, row.values());
}
@Test
public void test_TDP_786_empty_pattern() {
// given
final Map<String, String> values = new HashMap<>();
values.put("0000", "lorem bacon");
values.put("0001", "Je vais bien (tout va bien)");
values.put("0002", "01/01/2015");
final DataSetRow row = new DataSetRow(values);
parameters.put(Split.SEPARATOR_PARAMETER, "other (string)");
parameters.put(Split.MANUAL_SEPARATOR_PARAMETER_STRING, "");
// when
ActionTestWorkbench.test(row, action.create(parameters).getRowAction());
// then
assertEquals(values, row.values());
}
@Test
public void test_TDP_831_invalid_pattern() {
// given
final Map<String, String> values = new HashMap<>();
values.put("0000", "lorem bacon");
values.put("0001", "Je vais bien (tout va bien)");
values.put("0002", "01/01/2015");
final DataSetRow row = new DataSetRow(values);
parameters.put(Split.SEPARATOR_PARAMETER, "other (regex)");
parameters.put(Split.MANUAL_SEPARATOR_PARAMETER_STRING, "(");
// when
ActionTestWorkbench.test(row, action.create(parameters).getRowAction());
// then
assertEquals(values, row.values());
}
@Test
public void test_string_that_looks_like_a_regex() {
// given
final DataSetRow row = getRow("lorem bacon", "Je vais bien (tout va bien)", "01/01/2015");
parameters.put(Split.SEPARATOR_PARAMETER, "other (string)");
parameters.put(Split.MANUAL_SEPARATOR_PARAMETER_STRING, "(");
final Map<String, String> expectedValues = new HashMap<>();
expectedValues.put("0000", "lorem bacon");
expectedValues.put("0001", "Je vais bien (tout va bien)");
expectedValues.put("0002", "01/01/2015");
expectedValues.put("0003", "Je vais bien ");
expectedValues.put("0004", "tout va bien)");
// when
ActionTestWorkbench.test(row, action.create(parameters).getRowAction());
// then
assertEquals(expectedValues, row.values());
}
@Test
public void test_split_on_regex() {
// given
final DataSetRow row = getRow("lorem bacon", "Je vais bien (tout va bien)", "01/01/2015");
parameters.put(Split.SEPARATOR_PARAMETER, "other (regex)");
parameters.put(Split.MANUAL_SEPARATOR_PARAMETER_REGEX, "bien");
final Map<String, String> expectedValues = new HashMap<>();
expectedValues.put("0000", "lorem bacon");
expectedValues.put("0001", "Je vais bien (tout va bien)");
expectedValues.put("0003", "Je vais ");
expectedValues.put("0004", " (tout va bien)");
expectedValues.put("0002", "01/01/2015");
// when
ActionTestWorkbench.test(row, action.create(parameters).getRowAction());
// then
assertEquals(expectedValues, row.values());
}
@Test
public void test_split_on_regex2() {
// given
final DataSetRow row = getRow("lorem bacon", "Je vais bien (tout va bien)", "01/01/2015");
parameters.put(Split.SEPARATOR_PARAMETER, "other (regex)");
parameters.put(Split.MANUAL_SEPARATOR_PARAMETER_REGEX, "bien|fff");
final Map<String, String> expectedValues = new HashMap<>();
expectedValues.put("0000", "lorem bacon");
expectedValues.put("0001", "Je vais bien (tout va bien)");
expectedValues.put("0003", "Je vais ");
expectedValues.put("0004", " (tout va bien)");
expectedValues.put("0002", "01/01/2015");
// when
ActionTestWorkbench.test(row, action.create(parameters).getRowAction());
// then
assertEquals(expectedValues, row.values());
}
@Test
/**
* @see SplitTest#should_split_row()
*/
public void test_TDP_876() {
// given
final Map<String, String> values = new HashMap<>();
values.put("0000", "lorem bacon");
values.put("0001", "Bacon ipsum dolor amet swine leberkas pork belly");
values.put("0002", "01/01/2015");
final DataSetRow row = new DataSetRow(values);
Statistics originalStats = row.getRowMetadata().getById("0001").getStatistics();
Quality originalQuality = row.getRowMetadata().getById("0001").getQuality();
List<SemanticDomain> originalDomains = row.getRowMetadata().getById("0001").getSemanticDomains();
// when
ActionTestWorkbench.test(row, action.create(parameters).getRowAction());
// then
assertTrue(originalStats == row.getRowMetadata().getById("0001").getStatistics());
assertTrue(originalQuality == row.getRowMetadata().getById("0001").getQuality());
assertTrue(originalDomains == row.getRowMetadata().getById("0001").getSemanticDomains());
assertTrue(originalStats != row.getRowMetadata().getById("0003").getStatistics());
assertTrue(originalQuality != row.getRowMetadata().getById("0003").getQuality());
assertTrue(originalDomains == Collections.<SemanticDomain> emptyList()
|| originalDomains != row.getRowMetadata().getById("0003").getSemanticDomains());
assertTrue(originalStats != row.getRowMetadata().getById("0004").getStatistics());
assertTrue(originalQuality != row.getRowMetadata().getById("0004").getQuality());
assertTrue(originalDomains == Collections.<SemanticDomain> emptyList()
|| originalDomains != row.getRowMetadata().getById("0004").getSemanticDomains());
}
/**
* @see Split#create(Map)
*/
@Test
public void should_split_row_twice() {
// given
final DataSetRow row = getRow("lorem bacon", "Bacon ipsum dolor amet swine leberkas pork belly", "01/01/2015");
final Map<String, String> expectedValues = new HashMap<>();
expectedValues.put("0000", "lorem bacon");
expectedValues.put("0001", "Bacon ipsum dolor amet swine leberkas pork belly");
expectedValues.put("0005", "Bacon");
expectedValues.put("0006", "ipsum dolor amet swine leberkas pork belly");
expectedValues.put("0003", "Bacon");
expectedValues.put("0004", "ipsum dolor amet swine leberkas pork belly");
expectedValues.put("0002", "01/01/2015");
// when
ActionTestWorkbench.test(row, action.create(parameters).getRowAction(), action.create(parameters).getRowAction());
// then
assertEquals(expectedValues, row.values());
}
/**
* @see Action#getRowAction()
*/
@Test
public void should_split_row_with_separator_at_the_end() {
// given
final DataSetRow row = getRow("lorem bacon", "Bacon ", "01/01/2015");
final Map<String, String> expectedValues = new HashMap<>();
expectedValues.put("0000", "lorem bacon");
expectedValues.put("0001", "Bacon ");
expectedValues.put("0003", "Bacon");
expectedValues.put("0004", "");
expectedValues.put("0002", "01/01/2015");
// when
ActionTestWorkbench.test(row, action.create(parameters).getRowAction());
// then
assertEquals(expectedValues, row.values());
}
/**
* @see Action#getRowAction()
*/
@Test
public void should_split_row_no_separator() {
// given
final DataSetRow row = getRow("lorem bacon", "Bacon", "01/01/2015");
final Map<String, String> expectedValues = new HashMap<>();
expectedValues.put("0000", "lorem bacon");
expectedValues.put("0001", "Bacon");
expectedValues.put("0003", "Bacon");
expectedValues.put("0004", "");
expectedValues.put("0002", "01/01/2015");
// when
ActionTestWorkbench.test(row, action.create(parameters).getRowAction());
// then
assertEquals(expectedValues, row.values());
}
/**
* @see Action#getRowAction()
*/
@Test
public void should_update_metadata() {
// given
final List<ColumnMetadata> input = new ArrayList<>();
input.add(createMetadata("0000", "recipe"));
input.add(createMetadata("0001", "steps"));
input.add(createMetadata("0002", "last update"));
final RowMetadata rowMetadata = new RowMetadata(input);
final List<ColumnMetadata> expected = new ArrayList<>();
expected.add(createMetadata("0000", "recipe"));
expected.add(createMetadata("0001", "steps"));
expected.add(createMetadata("0003", "steps_split"));
expected.add(createMetadata("0004", "steps_split"));
expected.add(createMetadata("0002", "last update"));
// when
ActionTestWorkbench.test(rowMetadata, action.create(parameters).getRowAction());
// then
assertEquals(expected, rowMetadata.getColumns());
}
/**
* @see Action#getRowAction()
*/
@Test
public void should_update_metadata_twice() {
// given
final List<ColumnMetadata> input = new ArrayList<>();
input.add(createMetadata("0000", "recipe"));
input.add(createMetadata("0001", "steps"));
input.add(createMetadata("0002", "last update"));
final RowMetadata rowMetadata = new RowMetadata(input);
final List<ColumnMetadata> expected = new ArrayList<>();
expected.add(createMetadata("0000", "recipe"));
expected.add(createMetadata("0001", "steps"));
expected.add(createMetadata("0005", "steps_split"));
expected.add(createMetadata("0006", "steps_split"));
expected.add(createMetadata("0003", "steps_split"));
expected.add(createMetadata("0004", "steps_split"));
expected.add(createMetadata("0002", "last update"));
// when
ActionTestWorkbench.test(rowMetadata, action.create(parameters).getRowAction(), action.create(parameters).getRowAction());
assertEquals(expected, rowMetadata.getColumns());
}
@Test
public void should_not_split_separator_not_found() throws IOException {
// given
final DataSetRow row = getRow("lorem bacon", "Bacon ipsum dolor amet swine leberkas pork belly", "01/01/2015");
parameters.put(Split.SEPARATOR_PARAMETER, "-");
parameters.put(Split.LIMIT, "4");
// when
ActionTestWorkbench.test(row, action.create(parameters).getRowAction());
// then
final Map<String, String> expectedValues = new HashMap<>();
expectedValues.put("0000", "lorem bacon");
expectedValues.put("0001", "Bacon ipsum dolor amet swine leberkas pork belly");
expectedValues.put("0003", "Bacon ipsum dolor amet swine leberkas pork belly");
expectedValues.put("0004", "");
expectedValues.put("0005", "");
expectedValues.put("0006", "");
expectedValues.put("0002", "01/01/2015");
assertEquals(expectedValues, row.values());
}
@Test
public void should_not_split_because_null_separator() throws IOException {
// given
final Map<String, String> values = new HashMap<>();
values.put("0000", "lorem bacon");
values.put("0001", "Bacon ipsum dolor amet swine leberkas pork belly");
values.put("0002", "01/01/2015");
final DataSetRow row = new DataSetRow(values);
parameters.put(Split.SEPARATOR_PARAMETER, "");
// when
ActionTestWorkbench.test(row, action.create(parameters).getRowAction());
// then
assertEquals(values, row.values());
}
public void should_not_update_metadata_because_null_separator() throws IOException {
// given
final List<ColumnMetadata> input = new ArrayList<>();
input.add(createMetadata("0000", "recipe"));
input.add(createMetadata("0001", "steps"));
input.add(createMetadata("0002", "last update"));
final RowMetadata rowMetadata = new RowMetadata(input);
parameters.put(Split.SEPARATOR_PARAMETER, "");
// when
ActionTestWorkbench.test(rowMetadata, action.create(parameters).getRowAction());
// then
assertEquals(input, rowMetadata.getColumns());
}
@Test
public void should_accept_column() {
assertTrue(action.acceptColumn(getColumn(Type.STRING)));
}
@Test
public void should_not_accept_column() {
assertFalse(action.acceptColumn(getColumn(Type.NUMERIC)));
assertFalse(action.acceptColumn(getColumn(Type.FLOAT)));
assertFalse(action.acceptColumn(getColumn(Type.DATE)));
assertFalse(action.acceptColumn(getColumn(Type.BOOLEAN)));
}
@Test
public void should_have_separator_that_could_be_blank() {
Optional<Parameter> parameter = new Split().getParameters().stream()
.filter(p -> StringUtils.equals(p.getName(), Split.SEPARATOR_PARAMETER)).findFirst();
if (parameter.isPresent()) {
assertTrue(parameter.get().isCanBeBlank());
} else {
fail();
}
}
/**
* @param name name of the column metadata to create.
* @return a new column metadata
*/
private ColumnMetadata createMetadata(String id, String name) {
return ColumnMetadata.Builder.column().computedId(id).name(name).type(Type.STRING).headerSize(12).empty(0).invalid(2)
.valid(5).build();
}
}
|
package com.li_tianyang.android3d;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ToggleButton;
public class MainActivity extends ActionBarActivity {
private static final String TAG = "MainActivity";
private Camera mCamera;
private static int mCameraID;
private CameraPreview mPreview;
private boolean recording;
private SensorManager mSensorManager;
private Sensor accel;
private Sensor gyro;
public static enum RawDatumType {
GYRO, /* gyroscope */
ACCEL, /* accelerator */
CAM, /* camera */
FIN, /* data collection finished, continue processing */
STOP, /* data collection stopped, forget about processing */
}
public class RawDatum {
RawDatumType mType;
byte[] mCam;
float[] mSensorVal;
public RawDatum() {
mCam = null;
mSensorVal = null;
}
};
LinkedBlockingQueue<RawDatum> mRawData;
private SensorEventListener mSensorEventListener = new SensorEventListener() {
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
if (recording) {
RawDatum rawData = new RawDatum();
rawData.mSensorVal = Arrays.copyOf(event.values,
event.values.length);
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
rawData.mType = RawDatumType.ACCEL;
break;
case Sensor.TYPE_GYROSCOPE:
rawData.mType = RawDatumType.GYRO;
break;
}
}
}
};
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance() {
Camera c = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
int cameraCount = 0;
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
try {
c = Camera.open(camIdx);
mCameraID = camIdx;
} catch (RuntimeException e) {
Log.d(TAG,
"Camera is not available (in use or does not exist)"
+ e.getMessage());
}
}
}
c.setDisplayOrientation(90);
return c; // returns null if camera is unavailable
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCamera = getCameraInstance();
mPreview = new CameraPreview(this, mCamera);
FrameLayout fL = (FrameLayout) findViewById(R.id.camera_preview);
fL.addView(mPreview);
ToggleButton cB = (ToggleButton) findViewById(R.id.control_button);
cB.bringToFront();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accel = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
gyro = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
mRawData = new LinkedBlockingQueue<RawDatum>();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void openAbout() {
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.action_about:
openAbout();
return true;
}
return super.onOptionsItemSelected(item);
}
public void control(View view) {
recording = ((ToggleButton) findViewById(R.id.control_button))
.isChecked();
if (recording) {
new Thread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "processing thread started");
boolean loop = true;
RawDatum rawDatum = null;
try {
while (loop) {
rawDatum = mRawData.take();
switch (rawDatum.mType) {
case GYRO:
break;
case ACCEL:
break;
case CAM:
break;
case FIN:
loop = false;
break;
case STOP:
loop = false;
break;
}
}
switch (rawDatum.mType) {
case FIN:
break;
case STOP:
break;
default:
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(TAG, "processing thread ended");
}
}).start();
} else {
RawDatum rawDatum = new RawDatum();
rawDatum.mType = RawDatumType.FIN;
try {
mRawData.put(rawDatum);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback, Camera.PreviewCallback {
private SurfaceHolder mHolder;
private Camera c;
public CameraPreview(Context context, Camera camera) {
super(context);
c = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
@Override
public void onLayout(boolean changed, int left, int top, int right,
int bottom) {
if (changed) {
Size s = goodPreviewSize();
View par = (View) getParent();
final int w = par.getWidth();
final int h = par.getHeight();
int l = (w - s.height) / 2;
int t = (h - s.width) / 2;
(this).layout(l, t, l + s.height, t + s.width);
}
}
private void fitPreview() {
Size s = goodPreviewSize();
Camera.Parameters p = c.getParameters();
p.setPreviewSize(s.width, s.height);
c.setParameters(p);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw
// the preview.
try {
c.setPreviewDisplay(holder);
fitPreview();
c.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your
// activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w,
int h) {
// If your preview can change or rotate, take care of those events
// here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
c.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
c.setPreviewDisplay(mHolder);
fitPreview();
c.setPreviewCallback(this);
c.startPreview();
} catch (Exception e) {
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
public void setCamera(Camera cam) {
c = cam;
}
private Size goodPreviewSize() {
Camera.Parameters p = mCamera.getParameters();
List<Size> sizes = p.getSupportedPreviewSizes();
Size goodSize = null;
View par = (View) getParent();
final int w = par.getWidth();
final int h = par.getHeight();
double area = (double) (w * h);
double partial = 0;
for (Size s : sizes) {
if (s.width <= h && s.height <= w) {
if (goodSize == null) {
goodSize = s;
partial = (double) (s.width * s.height) / area;
} else {
double tmpPartial = (double) (s.width * s.height)
/ area;
if (tmpPartial > partial) {
partial = tmpPartial;
goodSize = s;
}
}
}
}
return goodSize;
}
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
if (recording && data != null) {
RawDatum rawDatum = new RawDatum();
rawDatum.mType = RawDatumType.CAM;
rawDatum.mCam = Arrays.copyOf(data, data.length);
try {
mRawData.put(rawDatum);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
protected void onPause() {
super.onPause();
releaseCamera(); // release the camera immediately on pause event
mSensorManager.unregisterListener(mSensorEventListener);
RawDatum rawDatum = new RawDatum();
rawDatum.mType = RawDatumType.STOP;
try {
mRawData.put(rawDatum);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
@Override
protected void onResume() {
super.onResume();
if (mCamera == null) {
mCamera = Camera.open(mCameraID);
mCamera.setDisplayOrientation(90);
mPreview.setCamera(mCamera);
}
if (accel != null) {
mSensorManager.registerListener(mSensorEventListener, accel,
SensorManager.SENSOR_DELAY_NORMAL);
Log.d(TAG, "Good: ACCELEROMETER Sensor");
} else {
Log.d(TAG, "Bad: ACCELEROMETER Sensor");
}
if (gyro != null) {
mSensorManager.registerListener(mSensorEventListener, gyro,
SensorManager.SENSOR_DELAY_NORMAL);
Log.d(TAG, "Good: GYROSCOPE Sensor");
} else {
Log.d(TAG, "Bad: GYROSCOPE Sensor");
}
ToggleButton cB = (ToggleButton) findViewById(R.id.control_button);
cB.setChecked(false);
recording = false;
}
}
|
package org.elasticsearch.marvel.agent.resolver.cluster;
import org.apache.lucene.util.LuceneTestCase;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.marvel.MarvelSettings;
import org.elasticsearch.marvel.agent.collector.cluster.ClusterStateCollector;
import org.elasticsearch.marvel.agent.resolver.MonitoringIndexNameResolver;
import org.elasticsearch.marvel.test.MarvelIntegTestCase;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope;
import org.junit.After;
import org.junit.Before;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
import static org.elasticsearch.marvel.MonitoredSystem.ES;
import static org.elasticsearch.marvel.agent.exporter.MarvelTemplateUtils.TEMPLATE_VERSION;
import static org.elasticsearch.marvel.agent.resolver.MonitoringIndexNameResolver.Fields.SOURCE_NODE;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.core.Is.is;
//test is just too slow, please fix it to not be sleep-based
@LuceneTestCase.BadApple(bugUrl = "https://github.com/elastic/x-plugins/issues/1007")
@ClusterScope(scope = Scope.TEST)
public class ClusterStateTests extends MarvelIntegTestCase {
private int randomInt = randomInt();
@Override
protected Settings nodeSettings(int nodeOrdinal) {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put(MarvelSettings.INTERVAL.getKey(), "-1")
.put(MarvelSettings.COLLECTORS.getKey(), ClusterStateCollector.NAME)
.put("xpack.monitoring.agent.exporters.default_local.type", "local")
.put("node.custom", randomInt)
.build();
}
@Before
public void init() throws Exception {
updateMarvelInterval(3L, TimeUnit.SECONDS);
waitForMarvelIndices();
}
@After
public void cleanup() throws Exception {
updateMarvelInterval(-1, TimeUnit.SECONDS);
wipeMarvelIndices();
}
public void testClusterState() throws Exception {
logger.debug("--> waiting for documents to be collected");
awaitMarvelDocsCount(greaterThan(0L), ClusterStateResolver.TYPE);
logger.debug("--> searching for monitoring documents of type [{}]", ClusterStateResolver.TYPE);
SearchResponse response = client().prepareSearch().setTypes(ClusterStateResolver.TYPE).get();
assertThat(response.getHits().getTotalHits(), greaterThan(0L));
logger.debug("--> checking that every document contains the expected fields");
String[] filters = ClusterStateResolver.FILTERS;
for (SearchHit searchHit : response.getHits().getHits()) {
Map<String, Object> fields = searchHit.sourceAsMap();
for (String filter : filters) {
assertContains(filter, fields);
}
}
logger.debug("--> cluster state successfully collected");
}
/**
* This test should fail if the mapping for the 'nodes' attribute
* in the 'cluster_state' document is NOT set to 'enable: false'
*/
public void testNoNodesIndexing() throws Exception {
logger.debug("--> waiting for documents to be collected");
awaitMarvelDocsCount(greaterThan(0L), ClusterStateResolver.TYPE);
logger.debug("--> searching for monitoring documents of type [{}]", ClusterStateResolver.TYPE);
SearchResponse response = client().prepareSearch().setTypes(ClusterStateResolver.TYPE).get();
assertThat(response.getHits().getTotalHits(), greaterThan(0L));
DiscoveryNodes nodes = client().admin().cluster().prepareState().clear().setNodes(true).get().getState().nodes();
logger.debug("--> ensure that the 'nodes' attributes of the cluster state document is not indexed");
assertHitCount(client().prepareSearch().setSize(0)
.setTypes(ClusterStateResolver.TYPE)
.setQuery(matchQuery("cluster_state.nodes." + nodes.getMasterNodeId() + ".name",
nodes.getMasterNode().getName())).get(), 0L);
}
public void testClusterStateNodes() throws Exception {
final long nbNodes = internalCluster().size();
MonitoringIndexNameResolver.Timestamped timestampedResolver = new MockTimestampedIndexNameResolver(ES, TEMPLATE_VERSION);
assertNotNull(timestampedResolver);
String timestampedIndex = timestampedResolver.indexPattern();
awaitIndexExists(timestampedIndex);
logger.debug("--> waiting for documents to be collected");
awaitMarvelDocsCount(greaterThanOrEqualTo(nbNodes), ClusterStateNodeResolver.TYPE);
logger.debug("--> searching for monitoring documents of type [{}]", ClusterStateNodeResolver.TYPE);
SearchResponse response = client().prepareSearch(timestampedIndex).setTypes(ClusterStateNodeResolver.TYPE).get();
assertThat(response.getHits().getTotalHits(), greaterThanOrEqualTo(nbNodes));
logger.debug("--> checking that every document contains the expected fields");
String[] filters = {
MonitoringIndexNameResolver.Fields.CLUSTER_UUID.underscore().toString(),
MonitoringIndexNameResolver.Fields.TIMESTAMP.underscore().toString(),
SOURCE_NODE.underscore().toString(),
ClusterStateNodeResolver.Fields.STATE_UUID.underscore().toString(),
ClusterStateNodeResolver.Fields.NODE.underscore().toString(),
ClusterStateNodeResolver.Fields.NODE.underscore().toString() + "."
+ ClusterStateNodeResolver.Fields.ID.underscore().toString(),
};
for (SearchHit searchHit : response.getHits().getHits()) {
Map<String, Object> fields = searchHit.sourceAsMap();
for (String filter : filters) {
assertContains(filter, fields);
}
}
logger.debug("--> check that node attributes are indexed");
assertThat(client().prepareSearch().setSize(0)
.setIndices(timestampedIndex)
.setTypes(ClusterStateNodeResolver.TYPE)
.setQuery(QueryBuilders.matchQuery(SOURCE_NODE.underscore().toString() + ".attributes.custom", randomInt))
.get().getHits().getTotalHits(), greaterThan(0L));
logger.debug("--> cluster state nodes successfully collected");
}
public void testDiscoveryNodes() throws Exception {
final long nbNodes = internalCluster().size();
MonitoringIndexNameResolver.Data dataResolver = new MockDataIndexNameResolver(TEMPLATE_VERSION);
assertNotNull(dataResolver);
String dataIndex = dataResolver.indexPattern();
awaitIndexExists(dataIndex);
logger.debug("--> waiting for documents to be collected");
awaitMarvelDocsCount(greaterThanOrEqualTo(nbNodes), DiscoveryNodeResolver.TYPE);
logger.debug("--> searching for monitoring documents of type [{}]", DiscoveryNodeResolver.TYPE);
SearchResponse response = client().prepareSearch(dataIndex).setTypes(DiscoveryNodeResolver.TYPE).get();
assertThat(response.getHits().getTotalHits(), greaterThanOrEqualTo(nbNodes));
logger.debug("--> checking that every document contains the expected fields");
String[] filters = {
MonitoringIndexNameResolver.Fields.CLUSTER_UUID.underscore().toString(),
MonitoringIndexNameResolver.Fields.TIMESTAMP.underscore().toString(),
MonitoringIndexNameResolver.Fields.SOURCE_NODE.underscore().toString(),
DiscoveryNodeResolver.Fields.NODE.underscore().toString(),
DiscoveryNodeResolver.Fields.NODE.underscore().toString() + "."
+ DiscoveryNodeResolver.Fields.ID.underscore().toString(),
DiscoveryNodeResolver.Fields.NODE.underscore().toString() + "."
+ DiscoveryNodeResolver.Fields.NAME.underscore().toString(),
DiscoveryNodeResolver.Fields.NODE.underscore().toString() + "."
+ DiscoveryNodeResolver.Fields.ATTRIBUTES.underscore().toString(),
DiscoveryNodeResolver.Fields.NODE.underscore().toString() + "."
+ DiscoveryNodeResolver.Fields.TRANSPORT_ADDRESS.underscore().toString(),
};
for (SearchHit searchHit : response.getHits().getHits()) {
Map<String, Object> fields = searchHit.sourceAsMap();
for (String filter : filters) {
assertContains(filter, fields);
}
}
for (final String nodeName : internalCluster().getNodeNames()) {
final String nodeId = internalCluster().clusterService(nodeName).localNode().getId();
logger.debug("--> getting monitoring document for node id [{}]", nodeId);
assertThat(client().prepareGet(dataIndex, DiscoveryNodeResolver.TYPE, nodeId).get().isExists(), is(true));
// checks that document is not indexed
assertHitCount(client().prepareSearch(dataIndex).setSize(0)
.setTypes(DiscoveryNodeResolver.TYPE)
.setQuery(QueryBuilders.boolQuery()
.should(matchQuery("node.id", nodeId))
.should(matchQuery("node.name", nodeName))).get(), 0);
}
logger.debug("--> cluster state nodes successfully collected");
}
}
|
package com.maddyhome.idea.vim.ui;
import com.intellij.ide.ui.LafManager;
import com.intellij.ide.ui.LafManagerListener;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollingModel;
import com.intellij.ui.DocumentAdapter;
import com.intellij.util.IJSwingUtilities;
import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.ex.CommandParser;
import com.maddyhome.idea.vim.ex.ExCommand;
import com.maddyhome.idea.vim.ex.ranges.LineRange;
import com.maddyhome.idea.vim.group.MotionGroup;
import com.maddyhome.idea.vim.helper.UiHelper;
import com.maddyhome.idea.vim.option.OptionsManager;
import com.maddyhome.idea.vim.regexp.CharPointer;
import com.maddyhome.idea.vim.regexp.RegExp;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
/**
* This is used to enter ex commands such as searches and "colon" commands
*/
public class ExEntryPanel extends JPanel implements LafManagerListener {
private static ExEntryPanel instance;
private static ExEntryPanel instanceWithoutShortcuts;
private ExEntryPanel(boolean enableShortcuts) {
label = new JLabel(" ");
entry = new ExTextField();
GridBagLayout layout = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(layout);
gbc.gridx = 0;
layout.setConstraints(this.label, gbc);
add(this.label);
gbc.gridx = 1;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
layout.setConstraints(entry, gbc);
add(entry);
if (enableShortcuts) {
// This does not need to be unregistered, it's registered as a custom UI property on this
new ExShortcutKeyAction(this).registerCustomShortcutSet();
}
// [VERSION UPDATE] 193+
//noinspection deprecation
LafManager.getInstance().addLafManagerListener(this);
updateUI();
}
public static ExEntryPanel getInstance() {
if (instance == null) {
instance = new ExEntryPanel(true);
}
return instance;
}
public static ExEntryPanel getInstanceWithoutShortcuts() {
if (instanceWithoutShortcuts == null) {
instanceWithoutShortcuts = new ExEntryPanel(false);
}
return instanceWithoutShortcuts;
}
public static void fullReset() {
if (instance != null) {
instance.reset();
instance = null;
}
if (instanceWithoutShortcuts != null) {
instanceWithoutShortcuts.reset();
instanceWithoutShortcuts = null;
}
}
/**
* Turns on the ex entry field for the given editor
*
* @param editor The editor to use for display
* @param context The data context
* @param label The label for the ex entry (i.e. :, /, or ?)
* @param initText The initial text for the entry
* @param count A holder for the ex entry count
*/
public void activate(@NotNull Editor editor, DataContext context, @NotNull String label, String initText, int count) {
this.label.setText(label);
this.label.setFont(UiHelper.selectFont(label));
this.count = count;
entry.reset();
entry.setEditor(editor, context);
entry.setText(initText);
entry.setFont(UiHelper.selectFont(initText));
entry.setType(label);
parent = editor.getContentComponent();
entry.getDocument().addDocumentListener(fontListener);
if (isIncSearchEnabled()) {
entry.getDocument().addDocumentListener(incSearchDocumentListener);
caretOffset = editor.getCaretModel().getOffset();
verticalOffset = editor.getScrollingModel().getVerticalScrollOffset();
horizontalOffset = editor.getScrollingModel().getHorizontalScrollOffset();
}
if (!ApplicationManager.getApplication().isUnitTestMode()) {
JRootPane root = SwingUtilities.getRootPane(parent);
if (root == null) return;
oldGlass = (JComponent)root.getGlassPane();
oldLayout = oldGlass.getLayout();
wasOpaque = oldGlass.isOpaque();
oldGlass.setLayout(null);
oldGlass.setOpaque(false);
oldGlass.add(this);
oldGlass.addComponentListener(resizePanelListener);
positionPanel();
oldGlass.setVisible(true);
entry.requestFocusInWindow();
}
active = true;
}
public static void deactivateAll() {
if (instance != null && instance.active) {
instance.deactivate(false);
}
if (instanceWithoutShortcuts != null && instanceWithoutShortcuts.active) {
instanceWithoutShortcuts.deactivate(false);
}
}
public void deactivate(boolean refocusOwningEditor) {
deactivate(refocusOwningEditor, true);
}
/**
* Turns off the ex entry field and optionally puts the focus back to the original component
*/
public void deactivate(boolean refocusOwningEditor, boolean resetCaret) {
logger.info("Deactivate ex entry panel");
if (!active) return;
active = false;
try {
entry.getDocument().removeDocumentListener(fontListener);
// incsearch won't change in the lifetime of this activation
if (isIncSearchEnabled()) {
entry.getDocument().removeDocumentListener(incSearchDocumentListener);
// TODO: Reduce the amount of unnecessary work here
// If incsearch and hlsearch are enabled, and if this is a search panel, we'll have all of the results correctly
// highlighted. But because we don't know why we're being closed, and what handler is being called next, we need
// to reset state. This will remove all highlights and reset back to the last accepted search results. This is
// fine for <Esc>. But if we hit <Enter>, the search handler will remove the highlights again, perform the same
// search that we did for incsearch and add highlights back. The `:nohlsearch` command, even if bound to a
// shortcut, is still processed by the ex entry panel, so deactivating will force update remove, search and add
// of the current search results before the `NoHLSearchHandler` will remove all highlights again
final Editor editor = entry.getEditor();
if (!editor.isDisposed() && resetCaret) {
resetCaretOffset(editor);
}
VimPlugin.getSearch().resetIncsearchHighlights();
}
entry.deactivate();
}
finally {
// Make sure we hide the UI, especially if something goes wrong
if (!ApplicationManager.getApplication().isUnitTestMode()) {
if (refocusOwningEditor && parent != null) {
UiHelper.requestFocus(parent);
}
oldGlass.removeComponentListener(resizePanelListener);
oldGlass.setVisible(false);
oldGlass.remove(this);
oldGlass.setOpaque(wasOpaque);
oldGlass.setLayout(oldLayout);
}
parent = null;
}
}
private void reset() {
deactivate(false);
LafManager.getInstance().removeLafManagerListener(this);
}
private void resetCaretOffset(@NotNull Editor editor) {
// Reset the original caret, with original scroll offsets
final Caret primaryCaret = editor.getCaretModel().getPrimaryCaret();
if (primaryCaret.getOffset() != caretOffset) {
MotionGroup.moveCaret(editor, primaryCaret, caretOffset);
}
final ScrollingModel scrollingModel = editor.getScrollingModel();
if (scrollingModel.getHorizontalScrollOffset() != horizontalOffset ||
scrollingModel.getVerticalScrollOffset() != verticalOffset) {
scrollingModel.scroll(horizontalOffset, verticalOffset);
}
}
private final @NotNull DocumentListener fontListener = new DocumentAdapter() {
@Override
protected void textChanged(@NotNull DocumentEvent e) {
String text = entry.getActualText();
Font newFont = UiHelper.selectFont(text);
if (newFont != entry.getFont()) {
entry.setFont(newFont);
}
}
};
private final @NotNull DocumentListener incSearchDocumentListener = new DocumentAdapter() {
@Override
protected void textChanged(@NotNull DocumentEvent e) {
final Editor editor = entry.getEditor();
boolean searchCommand = false;
LineRange searchRange = null;
char separator = label.getText().charAt(0);
String searchText = entry.getActualText();
if (label.getText().equals(":")) {
if (searchText.isEmpty()) return;
final ExCommand command = getIncsearchCommand(searchText);
if (command == null) {
return;
}
searchCommand = true;
searchText = "";
final String argument = command.getArgument();
if (argument.length() > 1) { // E.g. skip '/' in `:%s/`. `%` is range, `s` is command, `/` is argument
separator = argument.charAt(0);
searchText = argument.substring(1);
}
if (searchText.length() == 0) {
VimPlugin.getSearch().resetIncsearchHighlights();
return;
}
searchRange = command.getLineRange(editor);
}
final String labelText = label.getText();
if (labelText.equals("/") || labelText.equals("?") || searchCommand) {
final boolean forwards = !labelText.equals("?"); // :s, :g, :v are treated as forwards
final String pattern;
final CharPointer p = new CharPointer(searchText);
final CharPointer end = RegExp.skip_regexp(new CharPointer(searchText), separator, true);
pattern = p.substring(end.pointer() - p.pointer());
VimPlugin.getEditor().closeEditorSearchSession(editor);
final int matchOffset = VimPlugin.getSearch().updateIncsearchHighlights(editor, pattern, forwards, caretOffset, searchRange);
if (matchOffset != -1) {
MotionGroup.moveCaret(editor, editor.getCaretModel().getPrimaryCaret(), matchOffset);
}
else {
resetCaretOffset(editor);
}
}
}
@Contract("null -> null")
private @Nullable ExCommand getIncsearchCommand(@Nullable String commandText) {
if (commandText == null) return null;
try {
final ExCommand exCommand = CommandParser.getInstance().parse(commandText);
final String command = exCommand.getCommand();
// TODO: Add global, vglobal, smagic and snomagic here when the commands are supported
if ("substitute".startsWith(command)) {
return exCommand;
}
}
catch(Exception e) {
logger.warn("Cannot parse command for incsearch", e);
}
return null;
}
};
/**
* Gets the label for the ex entry. This should be one of ":", "/", or "?"
*
* @return The ex entry label
*/
public String getLabel() {
return label.getText();
}
/**
* Gets the count given during activation
*
* @return The count
*/
public int getCount() {
return count;
}
/**
* Checks if the ex entry panel is currently active
*
* @return true if active, false if not
*/
public boolean isActive() {
return active;
}
/**
* Gets the text entered by the user. This includes any initial text but does not include the label
*
* @return The user entered text
*/
public @NotNull String getText() {
return entry.getActualText();
}
public @NotNull ExTextField getEntry() {
return entry;
}
/**
* Pass the keystroke on to the text edit for handling
*
* @param stroke The keystroke
*/
public void handleKey(@NotNull KeyStroke stroke) {
entry.handleKey(stroke);
}
@Override
public void lookAndFeelChanged(@NotNull LafManager source) {
// Calls updateUI on this and child components
IJSwingUtilities.updateComponentTreeUI(this);
}
// Called automatically when the LAF is changed and the component is visible, and manually by the LAF listener handler
@Override
public void updateUI() {
super.updateUI();
setBorder(new ExPanelBorder());
// Can be null when called from base constructor
//noinspection ConstantConditions
if (entry != null && label != null) {
setFontForElements();
// Label background is automatically picked up
label.setForeground(entry.getForeground());
}
}
// Entry can be null if getForeground is called during base class initialisation
@SuppressWarnings("ConstantConditions")
@Override
public Color getForeground() {
return entry != null ? entry.getForeground() : super.getForeground();
}
@SuppressWarnings("ConstantConditions")
@Override
public Color getBackground() {
return entry != null ? entry.getBackground() : super.getBackground();
}
private void setFontForElements() {
label.setFont(UiHelper.selectFont(label.getText()));
entry.setFont(UiHelper.selectFont(entry.getActualText()));
}
private void positionPanel() {
if (parent == null) return;
Container scroll = SwingUtilities.getAncestorOfClass(JScrollPane.class, parent);
int height = (int)getPreferredSize().getHeight();
if (scroll != null) {
Rectangle bounds = scroll.getBounds();
bounds.translate(0, scroll.getHeight() - height);
bounds.height = height;
Point pos = SwingUtilities.convertPoint(scroll.getParent(), bounds.getLocation(), oldGlass);
bounds.setLocation(pos);
setBounds(bounds);
repaint();
}
}
private boolean isIncSearchEnabled() {
return OptionsManager.INSTANCE.getIncsearch().isSet();
}
private boolean active;
private int count;
// UI stuff
private @Nullable JComponent parent;
private final @NotNull JLabel label;
private final @NotNull ExTextField entry;
private JComponent oldGlass;
private LayoutManager oldLayout;
private boolean wasOpaque;
// incsearch stuff
private int verticalOffset;
private int horizontalOffset;
private int caretOffset;
private final @NotNull ComponentListener resizePanelListener = new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
positionPanel();
}
};
private static final Logger logger = Logger.getInstance(ExEntryPanel.class.getName());
}
|
package com.maddyhome.idea.vim.ui;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.maddyhome.idea.vim.helper.UiHelper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
/**
* This is used to enter ex commands such as searches and "colon" commands
*/
public class ExEntryPanel extends JPanel {
public static ExEntryPanel getInstance() {
if (instance == null) {
instance = new ExEntryPanel();
}
return instance;
}
private ExEntryPanel() {
setBorder(BorderFactory.createEtchedBorder());
label = new JLabel(" ");
entry = new ExTextField();
entry.setBorder(null);
setFontForElements();
setForeground(entry.getForeground());
setBackground(entry.getBackground());
label.setForeground(entry.getForeground());
label.setBackground(entry.getBackground());
GridBagLayout layout = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(layout);
gbc.gridx = 0;
layout.setConstraints(this.label, gbc);
add(this.label);
gbc.gridx = 1;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
layout.setConstraints(entry, gbc);
add(entry);
setBorder(BorderFactory.createEtchedBorder());
adapter = new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
positionPanel();
}
};
}
private void setFontForElements() {
final Font font = UiHelper.getEditorFont();
label.setFont(font);
entry.setFont(font);
}
/**
* Turns on the ex entry field for the given editor
*
* @param editor The editor to use for dislay
* @param context The data context
* @param label The label for the ex entry (i.e. :, /, or ?)
* @param initText The initial text for the entry
* @param count A holder for the ex entry count
*/
public void activate(@NotNull Editor editor, DataContext context, @NotNull String label, String initText, int count) {
entry.setEditor(editor, context);
this.label.setText(label);
this.count = count;
setFontForElements();
entry.setDocument(entry.createDefaultModel());
entry.setText(initText);
entry.setType(label);
parent = editor.getContentComponent();
if (!ApplicationManager.getApplication().isUnitTestMode()) {
JRootPane root = SwingUtilities.getRootPane(parent);
oldGlass = (JComponent)root.getGlassPane();
oldLayout = oldGlass.getLayout();
wasOpaque = oldGlass.isOpaque();
oldGlass.setLayout(null);
oldGlass.setOpaque(false);
oldGlass.add(this);
oldGlass.addComponentListener(adapter);
positionPanel();
oldGlass.setVisible(true);
entry.requestFocusInWindow();
}
active = true;
}
/**
* Gets the label for the ex entry. This should be one of ":", "/", or "?"
*
* @return The ex entry label
*/
public String getLabel() {
return label.getText();
}
/**
* Gets the count given during activation
*
* @return The count
*/
public int getCount() {
return count;
}
/**
* Pass the keystroke on to the text edit for handling
*
* @param stroke The keystroke
*/
public void handleKey(@NotNull KeyStroke stroke) {
entry.handleKey(stroke);
}
public void processKey(KeyEvent event) {
entry.processKeyEvent(event);
}
private void positionPanel() {
if (parent == null) return;
Container scroll = SwingUtilities.getAncestorOfClass(JScrollPane.class, parent);
int height = (int)getPreferredSize().getHeight();
if (scroll != null) {
Rectangle bounds = scroll.getBounds();
bounds.translate(0, scroll.getHeight() - height);
bounds.height = height;
Point pos = SwingUtilities.convertPoint(scroll.getParent(), bounds.getLocation(), oldGlass);
bounds.setLocation(pos);
setBounds(bounds);
repaint();
}
}
/**
* Gets the text entered by the user. This includes any initial text but does not include the label
*
* @return The user entered text
*/
public String getText() {
return entry.getText();
}
@NotNull
public ExTextField getEntry() {
return entry;
}
/**
* Turns off the ex entry field and optionally puts the focus back to the original component
*/
public void deactivate(boolean refocusOwningEditor) {
logger.info("deactivate");
if (!active) return;
active = false;
if (!ApplicationManager.getApplication().isUnitTestMode()) {
if (refocusOwningEditor && parent != null) {
parent.requestFocus();
}
oldGlass.removeComponentListener(adapter);
oldGlass.setVisible(false);
oldGlass.remove(this);
oldGlass.setOpaque(wasOpaque);
oldGlass.setLayout(oldLayout);
}
parent = null;
}
/**
* Checks if the ex entry panel is currently active
*
* @return true if active, false if not
*/
public boolean isActive() {
return active;
}
@Nullable private JComponent parent;
@NotNull private final JLabel label;
@NotNull private final ExTextField entry;
private JComponent oldGlass;
private LayoutManager oldLayout;
private boolean wasOpaque;
@NotNull private final ComponentAdapter adapter;
private int count;
private boolean active;
private static ExEntryPanel instance;
private static final Logger logger = Logger.getInstance(ExEntryPanel.class.getName());
}
|
package org.opennms.features.vaadin.nodemaps.gwt.client;
import org.opennms.features.vaadin.nodemaps.gwt.client.openlayers.FeatureCollection;
import org.opennms.features.vaadin.nodemaps.gwt.client.openlayers.OnmsOpenLayersMap;
import org.opennms.features.vaadin.nodemaps.gwt.client.openlayers.VectorLayer;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.VConsole;
public class GWTOpenlayersWidget extends Widget {
private final DivElement m_div;
private OnmsOpenLayersMap m_map;
private VectorLayer m_vectorLayer;
private FeatureCollection m_features;
public GWTOpenlayersWidget() {
super();
m_div = Document.get().createDivElement();
m_div.setId("gwt-map");
setElement(m_div);
}
@Override
protected void onLoad() {
super.onLoad();
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
createMap(m_div.getId());
}
});
}
@Override
protected void onUnload() {
destroyMap();
super.onUnload();
}
private String getNodesGml() {
return GWT.getModuleBaseURL() + "nodes.gml";
}
private void createMap(final String divId) {
m_map = OnmsOpenLayersMap.newInstance(divId);
initializeMap(m_map);
}
private final native void initializeMap(final OnmsOpenLayersMap map) /*-{
var displayAllNodes = true;
var nodeFillColors = {
Critical: "#F5CDCD",
Major: "#FFD7CD",
Minor: "#FFEBCD",
Warning: "#FFF5CD",
Normal: "#D7E100" // was #D7E1CD
};
var nodeStrokeColors = {
Critical: "#CC0000",
Major: "#FF3300",
Minor: "#FF9900",
Warning: "#FFCC00",
Normal: "#336600"
};
var nodeStyles = new $wnd.OpenLayers.Style({
pointRadius: "${radius}",
graphicName: "${shape}",
label: "${label}",
display: "${display}",
fillColor: "${fillColor}",
fillOpacity: 0.8,
strokeColor: "${strokeColor}",
strokeOpacity: 0.8,
strokeWidth: 3,
fontFamily: "'Lucida Grande', Verdana, sans-serif",
fontSize: 10
}, {
context: {
// The Shape will change if the cluster contain several nodes or not.
shape: function(feature) {
return feature.cluster && feature.cluster.length > 1 ? "circle" : "square";
},
// The Radius will change according with the amount of nodes on the cluster.
radius: function(feature) {
return feature.cluster ? Math.min(feature.attributes.count, 7) + 5 : 5;
},
// The label will display the amount of nodes only for clusters.
label: function(feature) {
return feature.cluster && feature.cluster.length > 1 ? feature.cluster.length : "";
},
display: function(feature) {
if (displayAllNodes) {
return 'display';
}
// Display only nodes with availability < 100
return getHighestSeverity(feature) == 'Normal' ? 'none' : 'display';
},
// It depends on the calculated severity
strokeColor: function(feature) {
return nodeStrokeColors[getNodeSeverity(feature)];
},
// It depends on the calculated severity
fillColor: function(feature) {
return nodeFillColors[getNodeSeverity(feature)];
}
}
});
// Nodes Layer
var nodesLayer = new $wnd.OpenLayers.Layer.Vector("All Nodes", {
strategies: [
new $wnd.OpenLayers.Strategy.Cluster()
],
styleMap: new $wnd.OpenLayers.StyleMap({
'default': nodeStyles,
'select': {
fillColor: "#8aeeef",
strokeColor: "#32a8a9"
}
})
});
// Selection Features
var select = new $wnd.OpenLayers.Control.SelectFeature(
nodesLayer, {hover: false} // The user must click on the cluster to see the details of it.
);
map.addControl(select);
select.activate();
nodesLayer.events.on({
'featureselected': onFeatureSelect,
'featureunselected': onFeatureUnselect
});
// It is important to add the layer to the map before populate it with the nodes.
map.addLayer(nodesLayer);
// Updating Nodes Layer
this.@org.opennms.features.vaadin.nodemaps.gwt.client.GWTOpenlayersWidget::m_vectorLayer = nodesLayer;
this.@org.opennms.features.vaadin.nodemaps.gwt.client.GWTOpenlayersWidget::updateFeatureLayer()();
map.zoomToExtent(nodesLayer.getDataExtent());
function getAvailability(feature) {
if (!feature.cluster) return 100;
var count = 0;
for (var i=0; i<feature.cluster.length; i++) {
var n = feature.cluster[i].attributes;
if (n.nodeStatus == 'Down') count++;
}
return ((1 - count/feature.cluster.length) * 100).toFixed(2);
}
function getNodeSeverity(feature) {
return getHighestSeverity(feature);
}
function onPopupClose(evt) {
select.unselect(this.feature);
}
function onFeatureSelect(evt) {
feature = evt.feature;
var msg = "";
if (feature.cluster.length > 1) {
var nodes = [];
for (var i=0; i<feature.cluster.length; i++) {
var n = feature.cluster[i].attributes;
nodes.push(n.nodeLabel + "(" + n.ipAddress + ") : " + n.nodeStatus);
}
msg = "<h2># of nodes: " + feature.cluster.length + " (" + getNumUnacked(feature) + " Unacknowledged Alarms)</h2><ul><li>" + nodes.join("</li><li>") + "</li></ul>";
} else {
var n = feature.cluster[0].attributes;
msg = "<h2>Node " + n.nodeLabel + "</h2>" +
"<p>Node ID: " + n.nodeId + "</br>" +
"Foreign Source: " + n.foreignSource + "</br>" +
"Foreign ID: " + n.foreignId + "</br>" +
"IP Address: " + n.ipAddress + "</br>" +
"Status: " + n.nodeStatus + "</br></p>";
}
popup = new $wnd.OpenLayers.Popup.FramedCloud("nodePopup",
feature.geometry.getBounds().getCenterLonLat(),
new $wnd.OpenLayers.Size(100,100), msg, null, false, onPopupClose);
feature.popup = popup;
popup.feature = feature;
map.addPopup(popup);
}
function getHighestSeverity(feature) {
if (!feature.cluster) return "Normal";
var severity = 0;
var severityLabel = "Normal";
for (var i=0; i<feature.cluster.length; i++) {
var n = feature.cluster[i].attributes;
if (n.severity && n.severity > severity) {
severity = n.severity;
severityLabel = n.severityLabel;
}
if (severity == 7) {
break;
}
}
}
function getNumUnacked(feature) {
if (!feature.cluster) return 0;
var count = 0;
for (var i=0; i<feature.cluster.length; i++) {
var n = feature.cluster[i].attributes;
if (n.unackedCount) count += n.unackedCount;
}
return count;
}
function onFeatureUnselect(evt) {
feature = evt.feature;
if (feature.popup) {
popup.feature = null;
map.removePopup(feature.popup);
feature.popup.destroy();
feature.popup = null;
}
}
function applyFilters(btn) {
btn.value = displayAllNodes ? 'Show All Nodes' : 'Show Down Nodes';
displayAllNodes = !displayAllNodes;
nodesLayer.redraw();
}
}-*/;
public void updateFeatureLayer() {
if (m_features == null) {
VConsole.log("features not initialized yet, skipping update");
return;
}
if (m_vectorLayer == null) {
VConsole.log("vector layer not initialized yet, skipping update");
return;
}
VConsole.log("adding features to the node layer");
m_vectorLayer.replaceFeatureCollection(m_features);
VConsole.log("finished adding features");
}
public FeatureCollection getFeatureCollection() {
return m_features;
}
public void setFeatureCollection(final FeatureCollection collection) {
m_features = collection;
}
private final native void destroyMap() /*-{
map.destroy();
}-*/;
}
|
package com.powerblock.timesheets;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.powerblock.timesheets.signatures.SignatureActivity;
import com.powerblock.timesheets.signatures.SignatureView;
public class ExcelHandler {
public static final String workingTemplateTempFileName = "output.xls";
private File workingTemplateFile;
private File workingTemplateTemp;
private static final String root = Environment.getExternalStorageDirectory().toString();
private static File custSig = new File(root, SignatureView.custSigLoc);
private static File empSig = new File(root, SignatureView.empSigLoc);
private Workbook mOriginalWorkingTemplate;
private static File[] fSigFiles = {custSig, empSig};
//Section constants
public static final String EXCEL_SECTION_JOB_SETUP = "JobSetup";
public static final String EXCEL_SECTION_EQUIPMENT = "Equipment";
public static final String EXCEL_SECTION_MATERIALS = "Materials";
public static final String EXCEL_SECTION_TESTING = "Testing";
public static final String EXCEL_SECTION_TIME = "Time";
public static final String EXCEL_SECTION_MATERIALS_LIGHTING = "Lighting";
public static final String EXCEL_SECTION_MATERIALS_POWER = "Power";
//Cell coordinates
private final static int[] cJobType = {1,1};
private final static int[] cSiteName = {1,2};
private final static int[] cSiteAddress = {1,3};
private final static int[] cPIC = {1,4};
private final static int[] cAPersonnel = {1,5};
private final static int[][] cJobSetupCells = {cJobType,cSiteName,cSiteAddress, cPIC, cAPersonnel};
private final static int[] rJobSetupIds = {R.id.job_setup_job_types,
R.id.job_setup_site_name, R.id.job_setup_site_address, R.id.job_setup_PIC,
R.id.job_setup_personnel};
private final static int[][] cEquipmentCells =
{{1,7},{1,11},{1,12},{1,13},{1,8},{1,9}};
private final static int[] rEquipmentIds =
{R.id.equipment_drills,
R.id.equipment_test_1, R.id.equipment_test_2, R.id.equipment_equipment,
R.id.equipment_leads, R.id.equipment_access};
private final static int[][] cMaterialsLighting = {
{0,20},{0,21},
{1,21},{1,22},{1,23},{1,24},
{2,21},{2,22},{2,23},{2,24},
{3,21},{3,22},{3,23},{3,24}};
private final static int[] rMaterialsLighting = {
R.id.materials_cell_lighting_store, R.id.materials_cell_lighting_docket,
R.id.materials_cell_lighting_quantity_1,R.id.materials_cell_lighting_quantity_2,
R.id.materials_cell_lighting_quantity_3,R.id.materials_cell_lighting_quantity_4,
R.id.materials_cell_lighting_material_1,R.id.materials_cell_lighting_material_2,
R.id.materials_cell_lighting_material_3,R.id.materials_cell_lighting_material_4,
R.id.materials_cell_lighting_size_1,R.id.materials_cell_lighting_size_2,
R.id.materials_cell_lighting_size_3,R.id.materials_cell_lighting_size_4};
private final static int[][] cMaterialsPower = {
{0,26},{0,27},
{1,27},{1,28},{1,29},{1,30},
{2,27},{2,28},{2,29},{2,30},
{3,27},{3,28},{3,29},{3,30}
};
private final static int[] rMaterialsPower = {
R.id.materials_power_store, R.id.materials_power_docket,
R.id.materials_cell_power_quantity_1,R.id.materials_cell_power_quantity_2,
R.id.materials_cell_power_quantity_3,R.id.materials_cell_power_quantity_4,
R.id.materials_cell_power_material_1,R.id.materials_cell_power_material_2,
R.id.materials_cell_power_material_3,R.id.materials_cell_power_material_4,
R.id.materials_cell_power_size_1,R.id.materials_cell_power_size_2,
R.id.materials_cell_power_size_3,R.id.materials_cell_power_size_4
};
private final static int[][] cMaterialsData = {
{1,33},{1,34},{1,35},{1,36},
{2,33},{2,34},{2,35},{2,36},
{3,33},{3,34},{3,35},{3,36}};
private final static int[] rMaterialsData = {
R.id.materials_cell_data_quantity_1,R.id.materials_cell_data_quantity_2,
R.id.materials_cell_data_quantity_3,R.id.materials_cell_data_quantity_4,
R.id.materials_cell_data_material_1,R.id.materials_cell_data_material_2,
R.id.materials_cell_data_material_3,R.id.materials_cell_data_material_4,
R.id.materials_cell_data_size_1,R.id.materials_cell_data_size_2,
R.id.materials_cell_data_size_3,R.id.materials_cell_data_size_4};
private final static int[][] cMaterialsContainment = {
{1,39},{1,40},{1,41},{1,42},
{2,39},{2,40},{2,41},{2,42},
{3,39},{3,40},{3,41},{3,42}
};
private final static int[] rMaterialsContainment = {
R.id.materials_cell_containment_quantity_1,R.id.materials_cell_containment_quantity_3,
R.id.materials_cell_containment_quantity_3,R.id.materials_cell_containment_quantity_4,
R.id.materials_cell_containment_material_1,R.id.materials_cell_containment_material_2,
R.id.materials_cell_containment_material_3,R.id.materials_cell_containment_material_4,
R.id.materials_cell_containment_size_1,R.id.materials_cell_containment_size_3,
R.id.materials_cell_containment_size_3,R.id.materials_cell_containment_size_4
};
private final static int[] cSigImage = {1,2};
public ExcelHandler(){
File myDir = new File(root + MainActivity.workingTemplateDir);
workingTemplateFile = new File(myDir, MainActivity.workingTemplateFileName);
workingTemplateTemp = new File(myDir, workingTemplateTempFileName);
}
public ArrayList<int[][]> getCells(String section){
int[][] cells;
int[][] ids = new int[1][];
List<int[][]> list = new ArrayList<int[][]>();
if(section.equalsIgnoreCase(EXCEL_SECTION_JOB_SETUP)){
cells = cJobSetupCells;
ids[0] = rJobSetupIds;
} else if(section.equalsIgnoreCase(EXCEL_SECTION_EQUIPMENT)){
cells = cEquipmentCells;
ids[0] = rEquipmentIds;
} else if(section.equalsIgnoreCase(EXCEL_SECTION_MATERIALS_CONTAINMENT)){
cells = cMaterialsContainment;
ids[0] = rMaterialsContainment;
} else if(section.equalsIgnoreCase(EXCEL_SECTION_MATERIALS_LIGHTING)){
cells = cMaterialsLighting;
ids[0] = rMaterialsLighting;
} else if(section.equalsIgnoreCase(EXCEL_SECTION_MATERIALS_POWER)){
cells = cMaterialsPower;
ids[0] = rMaterialsPower;
} else if(section.equalsIgnoreCase(EXCEL_SECTION_MATERIALS_DATA)){
cells = cMaterialsData;
ids[0] = rMaterialsData;
} else {
return null;
}
list.add(cells);
list.add(ids);
return (ArrayList<int[][]>) list;
}
public void write(String section, View givenView){
ArrayList<int[][]> list = getCells(section);
int[][] cells = list.get(0);
int[] ids = list.get(1)[0];
try{
WritableWorkbook w = getWritableWorkbook();
WritableSheet s = w.getSheet(0);
WritableCell cell = null;
PBSpinner spinner = null;
for(int i = 0; i < cells.length; i ++){
cell = s.getWritableCell(cells[i][0], cells[i][1]);
spinner = (PBSpinner) givenView.findViewById(ids[i]);
if(isLabel(cell)){
Label l = (Label) cell;
l.setString(spinner.getString());
} else {
Label l = new Label(cells[i][0], cells[i][1],spinner.getString());
s.addCell(l);
}
}
saveWritableWorkbook(w);
} catch(RowsExceededException e){
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
/*public View readJobSetup(LayoutInflater inflater, ViewGroup container){
Workbook w = getWorkbook();
Sheet s = w.getSheet(0);
View v = inflater.inflate(R.layout.job_setup_fragment, container, false);
Cell cell = null;
CustomSpinner spinner = null;
int columns = s.getColumns();
Log.v("Test","Columns = " + String.valueOf(columns));
if(columns > 1){
for(int i = 0; i < cJobSetupCells.length; i ++){
cell = s.getCell(cJobSetupCells[i][0], cJobSetupCells[i][1]);
spinner = (CustomSpinner) v.findViewById(rJobSetupIds[i]);
if(isLabel(cell)){
spinner.select(cell.getContents());
}
}
}
return v;
}*/
public View read(LayoutInflater inflater, ViewGroup container, int layout, String section){
ArrayList<int[][]> list = getCells(section);
int[][] cells = list.get(0);
int[] ids = list.get(1)[0];
Workbook w = getWorkbook();
Sheet s = w.getSheet(0);
View v = inflater.inflate(layout, container, false);
Cell cell = null;
PBSpinner spinner = null;
int columns = s.getColumns();
Log.v("Test","Columns = " + String.valueOf(columns));
if(columns > 1){
for(int i = 0; i < cells.length; i ++){
cell = s.getCell(cells[i][0], cells[i][1]);
spinner = (PBSpinner) v.findViewById(ids[i]);
if(isLabel(cell)){
spinner.select(cell.getContents());
}
}
}
return v;
}
private boolean isLabel(Cell cell){
if(cell.getType() == CellType.LABEL){
return true;
} else {
return false;
}
}
private WritableWorkbook getWritableWorkbook(){
WritableWorkbook w = null;
try{
mOriginalWorkingTemplate = Workbook.getWorkbook(workingTemplateFile);
w = Workbook.createWorkbook(workingTemplateTemp, mOriginalWorkingTemplate);
mOriginalWorkingTemplate.close();
mOriginalWorkingTemplate = null;
} catch(Exception e){
e.printStackTrace();
}
return w;
}
private Workbook getWorkbook(){
Workbook w = null;
try{
w = Workbook.getWorkbook(workingTemplateFile);
} catch(Exception e){
}
return w;
}
private void saveWritableWorkbook(WritableWorkbook w){
File myDir = new File(root + MainActivity.workingTemplateDir);
workingTemplateFile = new File(myDir, MainActivity.workingTemplateFileName);
workingTemplateTemp = new File(myDir, workingTemplateTempFileName);
try{
w.write();
w.close();
workingTemplateFile.delete();
InputStream in = new FileInputStream(workingTemplateTemp);
OutputStream out = new FileOutputStream(workingTemplateFile);
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != - 1){
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
workingTemplateTemp.delete();
}catch(Exception e){
e.printStackTrace();
}
}
public void saveSignature(String fileLoc, String type){
Log.v("Test","Saving");
int iType = 0;
if(type.equalsIgnoreCase(SignatureActivity.SIG_IDENTIFIER_CUST)){
Log.v("Test","iType = 1");
iType = 1;
} else if(type.equalsIgnoreCase(SignatureActivity.SIG_IDENTIFIER_EMP)){
Log.v("Test","iType = 2");
iType = 2;
}
WritableWorkbook w = getWritableWorkbook();
WritableSheet s = w.getSheet(iType);
Log.v("Test","Image = " + fSigFiles[iType - 1].toString());
WritableImage i = new WritableImage(cSigImage[0], cSigImage[1], 6, 6, fSigFiles[iType - 1]);
s.addImage(i);
saveWritableWorkbook(w);
}
}
|
package com.skht777.chatwork.impl;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import org.json.JSONObject;
import com.skht777.chatwork.NumberedRoomClient;
import com.skht777.chatwork.api.Contact;
import com.skht777.chatwork.api.File;
import com.skht777.chatwork.api.Me;
import com.skht777.chatwork.api.Member;
import com.skht777.chatwork.api.Message;
import com.skht777.chatwork.api.MyStatus;
import com.skht777.chatwork.api.MyTask;
import com.skht777.chatwork.api.NumberedRoom;
import com.skht777.chatwork.api.RoomAccount;
import com.skht777.chatwork.api.Task;
import com.skht777.chatwork.api.UserAccount;
import com.skht777.chatwork.parameter.Role;
import com.skht777.chatwork.parameter.Status;
import com.skht777.chatwork.parameter.Type;
/**
* @author skht777
*
*/
class ResponseImpl implements Message, Task, MyTask, File, NumberedRoom, MyStatus, Member, Me {
private enum ResponseList {
ACCOUNT,
ACCOUNT_ID,
ADMIN,
ASSIGNED_BY_ACCOUNT,
AVATAR_IMAGE_URL,
BODY,
CHATWORK_ID,
DEPARTMENT,
DESCRIPTION,
DOWNLOAD_URL,
FACEBOOK,
FILE_ID,
FILE_NUM,
FILENAME,
FILESIZE,
ICON_PATH,
INTRODUCTION,
LAST_UPDATE_TIME,
LIMIT_TIME,
MAIL,
MEMBER,
MENTION_NUM,
MENTION_ROOM_NUM,
MESSAGE_ID,
MESSAGE_NUM,
MYTASK_NUM,
MYTASK_ROOM_NUM,
NAME,
ORGANIZATION_ID,
ORGANIZATION_NAME,
READONLY,
ROLE,
ROOM,
ROOM_ID,
SEND_TIME,
SKYPE,
STATUS,
STICKY,
TASK_ID,
TASK_IDS,
TASK_NUM,
TEL_EXTENSION,
TEL_MOBILE,
TEL_ORGANIZATION,
TITLE,
TWITTER,
TYPE,
UNREAD_NUM,
UNREAD_ROOM_NUM,
UPDATE_TIME,
UPLOAD_TIME,
URL;
public String toString() {
return super.toString().toLowerCase();
}
}
private int messageId;
private UserAccount account;
private String body;
private int taskId;
private LocalDate limitDate;
private Status status;
private UserAccount assignedByAccount;
private RoomAccount room;
private int fileId;
private String fileName;
private int fileSize;
private LocalDateTime uploadTime;
private Type type;
private boolean sticky;
private int messageNum;
private int fileNum;
private int taskNum;
private LocalDateTime lastUpdateTime;
private URL iconPath;
private int roomId;
private String name;
private int unreadNum;
private int mentionNum;
private int mytaskNum;
private Role role;
private int chatworkId;
private int organizationId;
private int organizationName;
private String department;
private int accountId;
private URL avatarImageUrl;
private String title;
private URL url;
private String introduction;
private String mail;
private String telOrganization;
private String telExtension;
private String telMobile;
private String skype;
private String facebook;
private String twitter;
private int unreadRoomNum;
private int mentionRoomNum;
private int mytaskRoomNum;
private String description;
private URL downloadUrl;
private LocalDateTime sendTime;
private LocalDateTime updateTime;
private JSONObject element;
private ResponseImpl(JSONObject element) {
this.element = element;
}
private static UserAccount getUserAccount(JSONObject element) {
ResponseImpl account = new ResponseImpl(element.getJSONObject(ResponseList.ACCOUNT.toString()));
account.setAccountId();
account.setName();
account.setAvatarImageUrl();
return account;
}
private static RoomAccount getRoomAccount(JSONObject element) {
ResponseImpl account = new ResponseImpl(element.getJSONObject(ResponseList.ACCOUNT.toString()));
account.setRoomId();
account.setName();
account.setIconPath();
return account;
}
static Me getMyAccount(String response) {
return null;
}
static List<MyTask> getMyTasks(String response) {
return null;
}
static MyStatus getMyStatus(String response) {
return null;
}
static List<Contact> getContacts(String response) {
return null;
}
static List<NumberedRoom> getRooms(String response) {
return null;
}
static NumberedRoomClient createRoom(String response) {
return null;
}
static NumberedRoom getNumberdRoom(String response) {
return null;
}
static void editRoom(String response) {
}
static void deleteRoom(String response) {
}
static Map<Role, List<Integer>> editMembers(String response) {
return null;
}
static List<Member> getMembers(String response) {
return null;
}
static Message createMessage(String response) {
return null;
}
static List<Message> getMessages(String response) {
return null;
}
static Message getMessage(String response) {
return null;
}
static List<Task> getTasks(String response) {
return null;
}
static Task createTask(String response) {
return null;
}
static Task getTask(String response) {
return null;
}
static File getFile(String response) {
return null;
}
static List<File> getFiles(String response) {
return null;
}
private void setMessageId() {
this.messageId = messageId;
}
private void setAccount() {
this.account = ResponseImpl.getUserAccount(element);
}
private void setBody() {
this.body = body;
}
private void setTaskId() {
this.taskId = taskId;
}
private void setLimitDate() {
this.limitDate = limitDate;
}
private void setStatus() {
this.status = status;
}
private void setAssignedByAccount() {
this.assignedByAccount = assignedByAccount;
}
private void setRoom() {
this.room = ResponseImpl.getRoomAccount(element);
}
private void setFileId() {
this.fileId = fileId;
}
private void setFileName() {
this.fileName = fileName;
}
private void setFileSize() {
this.fileSize = fileSize;
}
private void setUploadTime() {
this.uploadTime = uploadTime;
}
private void setType() {
this.type = type;
}
private void setSticky() {
this.sticky = sticky;
}
private void setMessageNum() {
this.messageNum = messageNum;
}
private void setFileNum() {
this.fileNum = fileNum;
}
private void setTaskNum() {
this.taskNum = taskNum;
}
private void setLastUpdateTime() {
this.lastUpdateTime = lastUpdateTime;
}
private void setIconPath() {
this.iconPath = iconPath;
}
private void setRoomId() {
this.roomId = roomId;
}
private void setName() {
this.name = name;
}
private void setUnreadNum() {
this.unreadNum = unreadNum;
}
private void setMentionNum() {
this.mentionNum = mentionNum;
}
private void setMytaskNum() {
this.mytaskNum = mytaskNum;
}
private void setRole() {
this.role = role;
}
private void setChatworkId() {
this.chatworkId = chatworkId;
}
private void setOrganizationId() {
this.organizationId = organizationId;
}
private void setOrganizationName() {
this.organizationName = organizationName;
}
private void setDepartment() {
this.department = department;
}
private void setAccountId() {
this.accountId = accountId;
}
private void setAvatarImageUrl() {
this.avatarImageUrl = avatarImageUrl;
}
private void setTitle() {
this.title = title;
}
private void setUrl() {
this.url = url;
}
private void setIntroduction() {
this.introduction = introduction;
}
private void setMail() {
this.mail = mail;
}
private void setTelOrganization() {
this.telOrganization = telOrganization;
}
private void setTelExtension() {
this.telExtension = telExtension;
}
private void setTelMobile() {
this.telMobile = telMobile;
}
private void setSkype() {
this.skype = skype;
}
private void setFacebook() {
this.facebook = facebook;
}
private void setTwitter() {
this.twitter = twitter;
}
private void setUnreadRoomNum() {
this.unreadRoomNum = unreadRoomNum;
}
private void setMentionRoomNum() {
this.mentionRoomNum = mentionRoomNum;
}
private void setMytaskRoomNum() {
this.mytaskRoomNum = mytaskRoomNum;
}
private void setDescription() {
this.description = description;
}
private void setDownloadUrl() {
this.downloadUrl = downloadUrl;
}
private void setSendTime() {
this.sendTime = sendTime;
}
private void setUpdateTime() {
this.updateTime = updateTime;
}
@Override
public int getMessageId() {
return messageId;
}
@Override
public UserAccount getAccount() {
return account;
}
@Override
public String getBody() {
return body;
}
@Override
public int getTaskId() {
return taskId;
}
@Override
public LocalDate getLimitDate() {
return limitDate;
}
@Override
public Status getStatus() {
return status;
}
@Override
public UserAccount getAssignedByAccount() {
return assignedByAccount;
}
@Override
public RoomAccount getRoom() {
return room;
}
@Override
public int getFileId() {
return fileId;
}
@Override
public String getFileName() {
return fileName;
}
@Override
public int getFileSize() {
return fileSize;
}
@Override
public LocalDateTime getUploadTime() {
return uploadTime;
}
@Override
public Type getType() {
return type;
}
@Override
public boolean getSticky() {
return sticky;
}
@Override
public int getMessageNum() {
return messageNum;
}
@Override
public int getFileNum() {
return fileNum;
}
@Override
public int getTaskNum() {
return taskNum;
}
@Override
public LocalDateTime getLastUpdateTime() {
return lastUpdateTime;
}
@Override
public URL getIconPath() {
return iconPath;
}
@Override
public int getRoomId() {
return roomId;
}
@Override
public String getName() {
return name;
}
@Override
public int getUnreadNum() {
return unreadNum;
}
@Override
public int getMentionNum() {
return mentionNum;
}
@Override
public int getMytaskNum() {
return mytaskNum;
}
@Override
public Role getRole() {
return role;
}
@Override
public int getChatworkId() {
return chatworkId;
}
@Override
public int getOrganizationId() {
return organizationId;
}
@Override
public int getOrganizationName() {
return organizationName;
}
@Override
public String getDepartment() {
return department;
}
@Override
public int getAccountId() {
return accountId;
}
@Override
public URL getAvatarImageUrl() {
return avatarImageUrl;
}
@Override
public String getTitle() {
return title;
}
@Override
public URL getUrl() {
return url;
}
@Override
public String getIntroduction() {
return introduction;
}
@Override
public String getMail() {
return mail;
}
@Override
public String getTelOrganization() {
return telOrganization;
}
@Override
public String getTelExtension() {
return telExtension;
}
@Override
public String getTelMobile() {
return telMobile;
}
@Override
public String getSkype() {
return skype;
}
@Override
public String getFacebook() {
return facebook;
}
@Override
public String getTwitter() {
return twitter;
}
@Override
public int getUnreadRoomNum() {
return unreadRoomNum;
}
@Override
public int getMentionRoomNum() {
return mentionRoomNum;
}
@Override
public int getMytaskRoomNum() {
return mytaskRoomNum;
}
@Override
public String getDescription() {
return description;
}
@Override
public URL getDownloadUrl() {
return downloadUrl;
}
@Override
public LocalDateTime getSendTime() {
return sendTime;
}
@Override
public LocalDateTime getUpdateTime() {
return updateTime;
}
}
|
package com.wenyu.Utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.ImageView;
public class RoundedCornerImageView extends ImageView {
private final float density = getContext().getResources()
.getDisplayMetrics().density;
private float roundness;
public RoundedCornerImageView(Context context) {
super(context);
init();
}
public RoundedCornerImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public RoundedCornerImageView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
init();
}
@Override
public void draw(Canvas canvas) {
final Bitmap composedBitmap;
final Bitmap originalBitmap;
final Canvas composedCanvas;
final Canvas originalCanvas;
final Paint paint;
final int height;
final int width;
width = getWidth();
height = getHeight();
composedBitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
originalBitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
composedCanvas = new Canvas(composedBitmap);
originalCanvas = new Canvas(originalBitmap);
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
super.draw(originalCanvas);
composedCanvas.drawARGB(0, 0, 0, 0);
composedCanvas.drawRoundRect(new RectF(5, 5, width-5, height-5),
this.roundness, this.roundness, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
composedCanvas.drawBitmap(originalBitmap, 0, 0, paint);
Paint temppaint = new Paint();
temppaint.setStyle(Style.STROKE);
temppaint.setStrokeWidth(2);
temppaint.setColor(Color.BLACK);
int circle = width < height ? width : height;
circle = circle / 2;
composedCanvas.drawCircle(width/2, height/2, circle - 3, temppaint);
canvas.drawBitmap(composedBitmap, 0, 0, new Paint());
}
public float getRoundness() {
return this.roundness / this.density;
}
public void setRoundness(float roundness) {
this.roundness = roundness * this.density;
}
private void init() {
// 100? 15?
setRoundness(100);
}
}
|
package eu.mikroskeem.shuriken.instrumentation.methodreflector;
import eu.mikroskeem.shuriken.common.Ensure;
import eu.mikroskeem.shuriken.reflect.ClassWrapper;
import eu.mikroskeem.shuriken.reflect.Reflect;
import eu.mikroskeem.shuriken.reflect.wrappers.TypeWrapper;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Type;
import org.objectweb.asm.util.CheckClassAdapter;
import org.objectweb.asm.util.TraceClassVisitor;
import java.io.PrintWriter;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import static eu.mikroskeem.shuriken.instrumentation.ClassTools.unqualifyName;
import static eu.mikroskeem.shuriken.instrumentation.methodreflector.MethodGenerator.*;
import static org.objectweb.asm.Opcodes.*;
/**
* Package-private Method reflector factory, used to generate proxy classes
*
* @author Mark Vainomaa
*/
final class MethodReflectorFactory {
private static final Map<Class<?>, AtomicInteger> COUNTER = new WeakHashMap<>();
private final GeneratedClassLoader GCL = new GeneratedClassLoader(MethodReflectorFactory.class.getClassLoader());
private final MethodHandles.Lookup mhLookup = MethodHandles.lookup();
/* Error messages */
private final static String NO_CLASS_INSTANCE_PRESET = "Interface targets instance methods, but class instance " +
"is not present in ClassWrapper!";
private final static String ANNOTATION_ERROR = "Interface method can only have one target or field annotation! ";
private final static String FIELD_NAME_IS_NULL = "Field name shouldn't be null or empty!";
private final static String FAILED_TO_UNREFLECT = "Failed to unreflect target: ";
private final static String FAILED_TO_FIND_FIELD = "Could not find target field for interface method: ";
private final static String FAILED_TO_FIND_METHOD = "Could not find target method for interface method: ";
private final static String FAILED_TO_FIND_CTOR = "Could not find target constructor for interface method: ";
private final static String SETTER_WRONG_RETURN_TYPE = "Setters can only return void type! ";
private final static String SETTER_WRONG_PARAM_COUNT = "Setters can only take one argument! ";
private final static String GETTER_WRONG_RETURN_TYPE = "Getters can't return void type! ";
private final static String GETTER_WRONG_PARAM_COUNT = "Getters can't take any arguments! ";
private final static String CTOR_INVOKER_WRONG_RETURN_TYPE = "Constructor invoker's return type must match interface " +
"method's return type or return java.lang.Object! ";
private final static String CTOR_TO_USE_OBJECT_PLEASE_OVERRIDE = "Please override constructor descriptor in " +
"annotation, or change method return type: ";
@SuppressWarnings("unchecked")
@Contract("null, null, null -> fail")
<T> T generateReflector(ClassWrapper<?> target, Class<T> intf, Map<String, String> r) {
Ensure.notNull(target, "Target class must not be null!");
Ensure.notNull(intf, "Interface must not be null!");
List<MethodHandle> methodHandles = new ArrayList<>();
boolean isTargetPublic = Modifier.isPublic(target.getWrappedClass().getModifiers());
boolean classMustUseInstance = false;
boolean classMustUseMH = false;
/* Proxy class info */
String proxyClassName = generateName(target, intf);
Type proxyClassType = Type.getObjectType(unqualifyName(proxyClassName));
/* Interface class info */
Type interfaceClassType = Type.getType(intf);
/* Target class info */
Class<?> targetClass = target.getWrappedClass();
Type targetClassType = Type.getType(targetClass);
/* Set up class writer */
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
ClassVisitor classWriter = cw;
if(MethodReflector.DEBUG) {
classWriter = new CheckClassAdapter(new TraceClassVisitor(classWriter, new PrintWriter(System.out)), false);
}
/* Start generating new class */
classWriter.visit(V1_8, ACC_PUBLIC + ACC_SUPER,
proxyClassType.getInternalName(),
null,
OBJECT.getInternalName(),
new String[]{interfaceClassType.getInternalName()}
);
/* Iterate through interface methods */
for(Method interfaceMethod: intf.getMethods()) {
/* Gather proxy method info */
boolean interfaceHasDefault = interfaceMethod.isDefault();
Type[] interfaceParameters = Type.getArgumentTypes(interfaceMethod);
Type interfaceReturnType = Type.getReturnType(interfaceMethod);
/* Gather proxy method annotations */
boolean hasAnnotation = false;
TargetFieldGetter fieldGetterInfo = interfaceMethod.getAnnotation(TargetFieldGetter.class);
TargetFieldSetter fieldSetterInfo = interfaceMethod.getAnnotation(TargetFieldSetter.class);
TargetMethod targetMethodInfo = interfaceMethod.getAnnotation(TargetMethod.class);
TargetConstructor targetConstructorInfo = interfaceMethod.getAnnotation(TargetConstructor.class);
if(fieldGetterInfo != null) { Ensure.ensureCondition(!hasAnnotation, ANNOTATION_ERROR + interfaceMethod); hasAnnotation = true; }
if(fieldSetterInfo != null) { Ensure.ensureCondition(!hasAnnotation, ANNOTATION_ERROR + interfaceMethod); hasAnnotation = true; }
if(targetMethodInfo != null) { Ensure.ensureCondition(!hasAnnotation, ANNOTATION_ERROR + interfaceMethod); hasAnnotation = true; }
if(targetConstructorInfo != null) { Ensure.ensureCondition(!hasAnnotation, ANNOTATION_ERROR + interfaceMethod); hasAnnotation = true; }
/* Check if annotation is present and create method with custom target */
if(hasAnnotation && targetMethodInfo == null) {
/* Field getter/setter */
if(fieldGetterInfo != null || fieldSetterInfo != null) {
String fieldName = r(Ensure.notNull(either(fieldGetterInfo, fieldSetterInfo, "value"),
FIELD_NAME_IS_NULL), r);
String annotationFieldType = r(either(fieldGetterInfo, fieldSetterInfo, "type"), r);
boolean isSetter = fieldSetterInfo != null;
Type fieldType;
/*
* Force setters to return void and take only one parameter,
* force getters to return type and take no parameters
*/
if(isSetter) {
Ensure.ensureCondition(interfaceReturnType.equals(Type.VOID_TYPE),
SETTER_WRONG_RETURN_TYPE + interfaceMethod);
Ensure.ensureCondition(interfaceParameters.length == 1,
SETTER_WRONG_PARAM_COUNT + interfaceMethod);
fieldType = Optional.ofNullable(annotationFieldType).map(Type::getType)
.orElse(interfaceParameters[0]);
} else {
Ensure.ensureCondition(!interfaceReturnType.equals(Type.VOID_TYPE),
GETTER_WRONG_RETURN_TYPE + interfaceMethod);
Ensure.ensureCondition(interfaceParameters.length == 0,
GETTER_WRONG_PARAM_COUNT + interfaceMethod);
fieldType = Optional.ofNullable(annotationFieldType).map(Type::getType)
.orElse(interfaceReturnType);
}
/* Try to find field */
if(MethodReflector.DEBUG)
System.out.format("Trying to find field with name '%s', type '%s' from class '%s'%n",
fieldName, fieldType, targetClass);
Field targetField = findDeclaredField(targetClass, fieldName, fieldType);
/* Ensure target field is present */
if(targetField == null && interfaceHasDefault) {
/* Use interface's default method */
if(MethodReflector.DEBUG)
System.out.format(
"Target for '%s' was not found, but default is present, so using interface default%n",
interfaceMethod
);
continue;
}
Ensure.notNull(targetField, FAILED_TO_FIND_FIELD + interfaceMethod);
/* Get needed target field info */
boolean useInstance = false;
boolean useMH = false;
if(!Modifier.isStatic(targetField.getModifiers())) {
/* Proxy class must use target class instance */
if(!classMustUseInstance) classMustUseInstance = true;
if(MethodReflector.DEBUG)
System.out.format("Field '%s' is not static, proxy class must use target class instance%n", targetField);
useInstance = true;
}
if(!isTargetPublic) {
/* Must use MethodHandle */
if(!classMustUseMH) classMustUseMH = true;
if(MethodReflector.DEBUG)
System.out.format("Field '%s' declarer class is not public, proxy class must use method handle%n", targetField);
useMH = true;
}
if(!Modifier.isPublic(targetField.getModifiers())) {
/* Proxy class must use method handles */
if(!classMustUseMH) classMustUseMH = true;
if(MethodReflector.DEBUG)
System.out.format("Field '%s' is not public, proxy class must use method handle%n", targetField);
useMH = true;
}
if(!Modifier.isPublic(targetField.getType().getModifiers())) {
/* Must use MethodHandle, again */
if(!classMustUseMH) classMustUseMH = true;
fieldType = OBJECT;
if(MethodReflector.DEBUG)
System.out.format("Field '%s' type is not public, proxy class must use method handle%n", targetField);
useMH = true;
}
if(Modifier.isFinal(targetField.getModifiers())) {
/* Proxy class must use method handles */
if(!classMustUseMH) classMustUseMH = true;
useMH = true;
/* Remove final modifier */
int modifiers = targetField.getModifiers();
Reflect.wrapInstance(targetField).getField("modifiers", int.class)
.ifPresent(fw -> fw.write(modifiers & ~Modifier.FINAL));
if(MethodReflector.DEBUG)
System.out.format("Field '%s' is final, proxy class must use method handle%n", targetField);
}
/* Generate proxy method */
try {
int mhIndex = -1;
if(useMH) {
/* Try to look up method handle */
if(!targetField.isAccessible()) targetField.setAccessible(true);
MethodHandle methodHandle = isSetter? mhLookup.unreflectSetter(targetField) :
mhLookup.unreflectGetter(targetField);
/* Add MethodHandle into MethodHandles array */
methodHandles.add(methodHandle);
/* Set up mhIndex */
mhIndex = methodHandles.size() - 1;
}
if(isSetter) {
/* Generate setter */
generateFieldWriteMethod(classWriter, interfaceMethod,
proxyClassType, targetClassType, fieldType, fieldName,
isTargetPublic, useInstance, useMH, mhIndex);
} else {
/* Generate getter */
generateFieldReadMethod(classWriter, interfaceMethod,
proxyClassType, targetClassType, fieldType, fieldName,
isTargetPublic, useInstance, useMH, mhIndex);
}
} catch (IllegalStateException e) {
generateFailedMethod(classWriter, interfaceMethod, e.getMessage());
} catch (IllegalAccessException e) {
generateFailedMethod(classWriter, interfaceMethod, FAILED_TO_UNREFLECT + targetField);
}
continue;
}
/* ** Constructor invoker */
/* Ensure interface method returns given class type or Object */
Ensure.ensureCondition(
interfaceReturnType.equals(targetClassType) ||
interfaceReturnType.equals(OBJECT),
CTOR_INVOKER_WRONG_RETURN_TYPE + interfaceMethod
);
Type[] targetParameters = interfaceParameters;
Type targetReturnType = interfaceReturnType;
/* Read custom descriptor, if present */
if(!targetConstructorInfo.desc().isEmpty()) {
targetParameters = Type.getArgumentTypes(r(targetConstructorInfo.desc(), r));
targetReturnType = Type.getReturnType(r(targetConstructorInfo.desc(), r));
}
/* Constructor return type cannot be Object anymore */
Ensure.ensureCondition(!targetReturnType.equals(OBJECT) &&
targetClass != Object.class, /* People like to do weird stuff */
CTOR_TO_USE_OBJECT_PLEASE_OVERRIDE + interfaceMethod);
/* Try to find target constructor */
if(MethodReflector.DEBUG)
System.out.format("Trying to find constructor with parameters '%s' from class '%s'%n",
Arrays.toString(targetParameters), targetClass);
Constructor<?> targetConstructor = findDeclaredConstructor(targetClass, targetParameters);
if(targetConstructor == null && interfaceHasDefault) {
/* Use interface's default method */
if(MethodReflector.DEBUG)
System.out.format(
"Target for '%s' was not found, but default is present, so using interface default%n",
interfaceMethod
);
continue;
}
Ensure.notNull(targetConstructor, FAILED_TO_FIND_CTOR + interfaceMethod);
/* Get needed target constructor info */
boolean useMH = false;
if(!Modifier.isPublic(targetConstructor.getModifiers())) {
/* Proxy class must use method handles */
if(!classMustUseMH) classMustUseMH = true;
if(MethodReflector.DEBUG)
System.out.format(
"Constructor '%s' is not public, proxy class must use method handle%n", targetConstructor
);
useMH = true;
}
if(!isTargetPublic) {
/* Must use MethodHandle */
if(!classMustUseMH) classMustUseMH = true;
if(MethodReflector.DEBUG)
System.out.format(
"Constructor '%s' type is not public, proxy class must use method handle%n", targetConstructor
);
useMH = true;
}
/* Generate proxy method */
try {
int mhIndex = -1;
if(useMH) {
if(!targetConstructor.isAccessible()) targetConstructor.setAccessible(true);
MethodHandle methodHandle = mhLookup.unreflectConstructor(targetConstructor);
/* Add MethodHandle into MethodHandles array */
methodHandles.add(methodHandle);
/* Set up mhIndex */
mhIndex = methodHandles.size() - 1;
}
/* Generate method */
generateConstructorProxy(classWriter, interfaceMethod,
proxyClassType, targetClassType, targetParameters,
isTargetPublic, useMH, mhIndex);
} catch (IllegalStateException e) {
generateFailedMethod(classWriter, interfaceMethod, e.getMessage());
} catch (IllegalAccessException e) {
generateFailedMethod(classWriter, interfaceMethod, FAILED_TO_UNREFLECT + targetConstructor);
}
continue;
}
/* ** Proceed creating proxy method */
/* Gather required method parameter/return type info */
String methodName = targetMethodInfo != null && !targetMethodInfo.value().isEmpty()?
r(targetMethodInfo.value(), r)
:
interfaceMethod.getName();
Type[] targetParameters = targetMethodInfo != null && !targetMethodInfo.desc().isEmpty()?
Type.getArgumentTypes(r(targetMethodInfo.desc(), r))
:
Type.getArgumentTypes(interfaceMethod);
Type targetReturnType = targetMethodInfo != null && !targetMethodInfo.desc().isEmpty()?
Type.getReturnType(r(targetMethodInfo.desc(), r))
:
Type.getReturnType(interfaceMethod);
/* Try to find target method */
if(MethodReflector.DEBUG)
System.out.format("Trying to find method with name '%s', with parameters '%s' " +
"and return type '%s' from class '%s'%n",
methodName, Arrays.toString(targetParameters), targetReturnType, targetClass);
Method targetMethod = findDeclaredMethod(targetClass, methodName, targetParameters, targetReturnType);
/* Ensure target method is present */
if(targetMethod == null && interfaceHasDefault) {
/* Use interface's default method */
if(MethodReflector.DEBUG)
System.out.format(
"Target for '%s' was not found, but default is present, so using interface default%n",
interfaceMethod
);
continue;
}
Ensure.notNull(targetMethod, FAILED_TO_FIND_METHOD + interfaceMethod);
/* Get needed target method info */
boolean useInterface = false;
boolean useInstance = false;
boolean useMH = false;
if(targetMethod.getDeclaringClass().isInterface()) {
/* INVOKEINTERFACE it is */
if(MethodReflector.DEBUG)
System.out.format(
"Method '%s' overrides interface, so using INVOKEINTERFACE%n", targetMethod
);
useInterface = true;
}
if(!Modifier.isStatic(targetMethod.getModifiers())) {
/* Proxy class must use target class instance */
if(!classMustUseInstance) classMustUseInstance = true;
if(MethodReflector.DEBUG)
System.out.format("Method '%s' is not static, proxy class must use target class instance%n", targetMethod);
useInstance = true;
}
if(!isTargetPublic) {
/* Must use MethodHandle */
if(!classMustUseMH) classMustUseMH = true;
if(MethodReflector.DEBUG)
System.out.format("Method '%s' declarer class is not public, proxy class must use method handle%n", targetMethod);
useMH = true;
}
if(!Modifier.isPublic(targetMethod.getReturnType().getModifiers())) {
/* Must use MethodHandle, again */
if(!classMustUseMH) classMustUseMH = true;
targetReturnType = OBJECT;
if(MethodReflector.DEBUG)
System.out.format("Method '%s' return type is not public, proxy class must use method handle%n", targetMethod);
useMH = true;
}
if(!Modifier.isPublic(targetMethod.getModifiers())) {
/* Proxy class must use method handles */
if(!classMustUseMH) classMustUseMH = true;
if(MethodReflector.DEBUG)
System.out.format("Method '%s' is not public, proxy class must use method handle%n", targetMethod);
useMH = true;
}
try {
int mhIndex = -1;
if(useMH) {
/* Try to look up method handle */
if(!targetMethod.isAccessible()) targetMethod.setAccessible(true);
MethodHandle methodHandle = mhLookup.unreflect(targetMethod);
/* Add MethodHandle into MethodHandles array */
methodHandles.add(methodHandle);
/* Set up mhIndex */
mhIndex = methodHandles.size() - 1;
}
/* Generate method */
generateMethodProxy(classWriter, interfaceMethod, proxyClassType, targetClassType,
useInterface? Type.getType(targetMethod.getDeclaringClass()) : null,
methodName, targetParameters, targetReturnType,
isTargetPublic, useInstance,
useInterface, useMH, mhIndex);
} catch (IllegalStateException e) {
/* Something failed, whoops */
generateFailedMethod(classWriter, interfaceMethod, e.getMessage());
} catch (IllegalAccessException e) {
generateFailedMethod(classWriter, interfaceMethod, FAILED_TO_UNREFLECT + targetMethod);
}
}
/* Check if we have class instance in ClassWrapper */
if(classMustUseInstance) {
Ensure.ensureCondition(target.getClassInstance() != null, NO_CLASS_INSTANCE_PRESET);
}
/* Generate class base (constructor, fields) */
generateClassBase(classWriter, classMustUseInstance, classMustUseMH,
isTargetPublic, proxyClassType, targetClassType);
/* End class writing */
classWriter.visitEnd();
/* Load accessor */
byte[] classData = cw.toByteArray();
ClassWrapper<?> accessor = Reflect.wrapClass(GCL.defineClass(proxyClassName, classData));
/* Construct accessor */
List<TypeWrapper> ctorParams = new ArrayList<>();
if(classMustUseInstance) ctorParams.add(TypeWrapper.of(
isTargetPublic?targetClass:Object.class, target.getClassInstance()));
if(classMustUseMH) ctorParams.add(TypeWrapper.of(MethodHandle[].class,
methodHandles.toArray(new MethodHandle[methodHandles.size()])));
return (T) accessor.construct(ctorParams.toArray(new TypeWrapper[ctorParams.size()])).getClassInstance();
}
@NotNull
private String generateName(ClassWrapper<?> target, Class<?> intf) {
StringBuilder classNameBuilder = new StringBuilder();
classNameBuilder.append(MethodReflector.class.getPackage().getName());
classNameBuilder.append(".");
classNameBuilder.append("Target$");
classNameBuilder.append(getClassName(target.getWrappedClass().getName()));
classNameBuilder.append("$");
classNameBuilder.append(getClassName(intf.getName()));
classNameBuilder.append("$");
classNameBuilder.append(COUNTER.computeIfAbsent(intf, k -> new AtomicInteger(0)).getAndIncrement());
return classNameBuilder.toString();
}
@NotNull
private String getClassName(String name) {
return name.substring(name.lastIndexOf('.') + 1, name.length());
}
/* Finds declared method by name, parameters and return type. Probably inefficient as fuck */
@Nullable
private Method findDeclaredMethod(Class<?> clazz, String methodName, Type[] params, Type returnType) {
Class<?> scanClass = clazz;
Method method;
/* Scan superclasses */
do {
method = Arrays.stream(scanClass.getDeclaredMethods())
.filter(m ->
methodName.equals(m.getName()) &&
Arrays.equals(Type.getArgumentTypes(m), params) &&
Type.getType(m.getReturnType()).equals(returnType)
)
.findFirst().orElse(null);
} while (method == null && (scanClass = scanClass.getSuperclass()) != null);
if(method != null) return method;
/* No interfaces to scan :( */
if(clazz.getInterfaces().length == 0) return null;
/* Scan interfaces */
int i = 0;
scanClass = clazz.getInterfaces()[i];
do {
method = Arrays.stream(scanClass.getDeclaredMethods())
.filter(m ->
methodName.equals(m.getName()) &&
Arrays.equals(m.getParameterTypes(), params) &&
Type.getType(m.getReturnType()).equals(returnType) &&
(m.isDefault() || Modifier.isStatic(m.getModifiers()))
)
.findFirst().orElse(null);
i++;
} while(method == null && i < scanClass.getInterfaces().length &&
(scanClass = scanClass.getInterfaces()[i]) != null);
return method;
}
/* Finds field */
private Field findDeclaredField(Class<?> clazz, String fieldName, Type fieldType) {
return Arrays.stream(clazz.getDeclaredFields()).filter(field ->
field.getName().equals(fieldName) &&
Type.getType(field.getType()).equals(fieldType))
.findFirst()
.orElse(null);
}
/* Finds constructor */
private Constructor<?> findDeclaredConstructor(Class<?> clazz, Type[] parameters) {
return Arrays.stream(clazz.getDeclaredConstructors())
.filter(c -> Arrays.equals(Type.getType(c).getArgumentTypes(), parameters))
.findFirst()
.orElse(null);
}
/* Gets either of value from annotations */
@Nullable
private static <A, B> String either(A one, B two, String value) {
String val = null;
if(one != null) val = Reflect.wrapInstance(one).invokeMethod(value, String.class);
if((val == null || val.isEmpty()) && two != null) val = Reflect.wrapInstance(two).invokeMethod(value, String.class);
return val != null && !val.isEmpty() ? val : null;
}
/* Replace placeholders in string. Sorry for short name, but this method isn't public anyway :) */
@Nullable
@Contract("_, null -> fail")
private String r(String source, Map<String, String> replacements) {
Ensure.notNull(replacements, "Replacements map shouldn't be null!");
if(source == null) return null;
/* Find placeholders */
List<String> foundPlaceholders = new ArrayList<>();
StringBuilder lastPlaceholder = null;
for(char c: source.toCharArray()) {
if(c == '{' && lastPlaceholder == null) {
lastPlaceholder = new StringBuilder();
} else if(lastPlaceholder != null && c != '}') {
lastPlaceholder.append(c);
} else if(lastPlaceholder != null) {
foundPlaceholders.add(lastPlaceholder.toString());
lastPlaceholder = null;
}
}
/* Amazing hack, wow */
String[] a = new String[] { source };
/* Replace placeholders */
for(String placeholder: foundPlaceholders) {
replacements.computeIfPresent(placeholder, (k, value) -> {
a[0] = a[0].replace("{" + k + "}", value);
return value;
});
}
/* Debug gogogogogo */
if(MethodReflector.DEBUG)
System.out.format("Replaced placeholders: '%s' -> '%s'%n", source, a[0]);
return a[0];
}
}
|
package com.controlgroup.coffeesystem.processors;
public class GoogleAppEngineCoffeeStatusProcessorTest extends AbstractPostingCoffeeStatusProcessorTest {
@Override
public AbstractPostingCoffeeStatusProcessor getCoffeeStatusProcessor() {
setHttpResponseCode(204);
return new GoogleAppEngineCoffeeStatusProcessor(mockTypeSafePropertyFetcher, mockHttpClientFactory, mockMessageSigner);
}
}
|
package org.eclipse.persistence.testing.tests.jpa.advanced;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Collection;
import java.util.Map;
import java.util.Vector;
import java.util.Iterator;
import java.sql.Date;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.FlushModeType;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnitUtil;
import javax.persistence.PessimisticLockScope;
import javax.persistence.Query;
import javax.persistence.TemporalType;
import javax.persistence.TransactionRequiredException;
import javax.persistence.LockModeType;
import javax.persistence.PersistenceException;
import javax.persistence.OptimisticLockException;
import javax.persistence.RollbackException;
import javax.persistence.spi.LoadState;
import javax.persistence.spi.ProviderUtil;
import junit.framework.*;
import org.eclipse.persistence.annotations.IdValidation;
import org.eclipse.persistence.config.EntityManagerProperties;
import org.eclipse.persistence.config.ExclusiveConnectionMode;
import org.eclipse.persistence.indirection.IndirectList;
import org.eclipse.persistence.internal.indirection.BatchValueHolder;
import org.eclipse.persistence.internal.jpa.EJBQueryImpl;
import org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl;
import org.eclipse.persistence.internal.helper.Helper;
import org.eclipse.persistence.queries.CursoredStreamPolicy;
import org.eclipse.persistence.queries.DataModifyQuery;
import org.eclipse.persistence.queries.DatabaseQuery;
import org.eclipse.persistence.queries.FetchGroup;
import org.eclipse.persistence.queries.InMemoryQueryIndirectionPolicy;
import org.eclipse.persistence.queries.ObjectLevelReadQuery;
import org.eclipse.persistence.queries.ReadAllQuery;
import org.eclipse.persistence.queries.ReadObjectQuery;
import org.eclipse.persistence.queries.ReportQuery;
import org.eclipse.persistence.queries.SQLCall;
import org.eclipse.persistence.queries.ScrollableCursorPolicy;
import org.eclipse.persistence.queries.ValueReadQuery;
import org.eclipse.persistence.sequencing.NativeSequence;
import org.eclipse.persistence.sequencing.Sequence;
import org.eclipse.persistence.sessions.server.ClientSession;
import org.eclipse.persistence.sessions.server.ConnectionPolicy;
import org.eclipse.persistence.sessions.server.ConnectionPool;
import org.eclipse.persistence.sessions.server.ReadConnectionPool;
import org.eclipse.persistence.sessions.server.ServerSession;
import org.eclipse.persistence.exceptions.EclipseLinkException;
import org.eclipse.persistence.exceptions.IntegrityException;
import org.eclipse.persistence.exceptions.ValidationException;
import org.eclipse.persistence.tools.schemaframework.SequenceObjectDefinition;
import org.eclipse.persistence.jpa.JpaHelper;
import org.eclipse.persistence.jpa.JpaQuery;
import org.eclipse.persistence.jpa.PersistenceProvider;
import org.eclipse.persistence.exceptions.QueryException;
import org.eclipse.persistence.expressions.Expression;
import org.eclipse.persistence.expressions.ExpressionBuilder;
import org.eclipse.persistence.sessions.Connector;
import org.eclipse.persistence.sessions.DatasourceLogin;
import org.eclipse.persistence.sessions.DefaultConnector;
import org.eclipse.persistence.sessions.JNDIConnector;
import org.eclipse.persistence.sessions.Session;
import org.eclipse.persistence.sessions.SessionEvent;
import org.eclipse.persistence.sessions.SessionEventAdapter;
import org.eclipse.persistence.sessions.UnitOfWork;
import org.eclipse.persistence.jpa.JpaEntityManager;
import org.eclipse.persistence.logging.SessionLog;
import org.eclipse.persistence.config.CacheUsage;
import org.eclipse.persistence.config.CacheUsageIndirectionPolicy;
import org.eclipse.persistence.config.CascadePolicy;
import org.eclipse.persistence.config.QueryHints;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.eclipse.persistence.config.PessimisticLock;
import org.eclipse.persistence.config.QueryType;
import org.eclipse.persistence.config.ResultSetConcurrency;
import org.eclipse.persistence.config.ResultSetType;
import org.eclipse.persistence.config.ResultType;
import org.eclipse.persistence.config.SessionCustomizer;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.descriptors.DescriptorQueryManager;
import org.eclipse.persistence.descriptors.InheritancePolicy;
import org.eclipse.persistence.descriptors.changetracking.ChangeTracker;
import org.eclipse.persistence.internal.databaseaccess.Accessor;
import org.eclipse.persistence.internal.descriptors.PersistenceEntity;
import org.eclipse.persistence.internal.jpa.EntityManagerImpl;
import org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork;
import org.eclipse.persistence.internal.sessions.UnitOfWorkImpl;
import org.eclipse.persistence.internal.weaving.PersistenceWeaved;
import org.eclipse.persistence.internal.weaving.PersistenceWeavedLazy;
import org.eclipse.persistence.queries.FetchGroupTracker;
import org.eclipse.persistence.testing.framework.DriverWrapper;
import org.eclipse.persistence.testing.framework.junit.JUnitTestCase;
import org.eclipse.persistence.testing.framework.junit.JUnitTestCaseHelper;
import org.eclipse.persistence.testing.framework.TestProblemException;
import org.eclipse.persistence.testing.models.jpa.advanced.*;
import org.eclipse.persistence.testing.models.jpa.relationships.CustomerCollection;
/**
* Test the EntityManager API using the advanced model.
*/
public class EntityManagerJUnitTestSuite extends JUnitTestCase {
/** The field length for the firstname */
public static final int MAX_FIRST_NAME_FIELD_LENGTH = 255;
public EntityManagerJUnitTestSuite() {
super();
}
public EntityManagerJUnitTestSuite(String name) {
super(name);
}
public static Test suite() {
TestSuite suite = new TestSuite();
suite.setName("EntityManagerJUnitTestSuite");
suite.addTest(new EntityManagerJUnitTestSuite("testSetup"));
suite.addTest(new EntityManagerJUnitTestSuite("testWeaving"));
suite.addTest(new EntityManagerJUnitTestSuite("testClearEntityManagerWithoutPersistenceContext"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllProjects"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateUsingTempStorage"));
suite.addTest(new EntityManagerJUnitTestSuite("testSequenceObjectDefinition"));
suite.addTest(new EntityManagerJUnitTestSuite("testFindDeleteAllPersist"));
suite.addTest(new EntityManagerJUnitTestSuite("testExtendedPersistenceContext"));
suite.addTest(new EntityManagerJUnitTestSuite("testRemoveFlushFind"));
suite.addTest(new EntityManagerJUnitTestSuite("testRemoveFlushPersistContains"));
suite.addTest(new EntityManagerJUnitTestSuite("testTransactionRequired"));
suite.addTest(new EntityManagerJUnitTestSuite("testSubString"));
suite.addTest(new EntityManagerJUnitTestSuite("testFlushModeOnUpdateQuery"));
suite.addTest(new EntityManagerJUnitTestSuite("testAnnotationDefaultLockModeNONEOnUpdateQuery"));
suite.addTest(new EntityManagerJUnitTestSuite("testContainsRemoved"));
suite.addTest(new EntityManagerJUnitTestSuite("testRefreshRemoved"));
suite.addTest(new EntityManagerJUnitTestSuite("testRefreshNotManaged"));
suite.addTest(new EntityManagerJUnitTestSuite("testDoubleMerge"));
suite.addTest(new EntityManagerJUnitTestSuite("testDescriptorNamedQueryForMultipleQueries"));
suite.addTest(new EntityManagerJUnitTestSuite("testDescriptorNamedQuery"));
suite.addTest(new EntityManagerJUnitTestSuite("testClearEntityManagerWithoutPersistenceContextSimulateJTA"));
suite.addTest(new EntityManagerJUnitTestSuite("testMultipleEntityManagerFactories"));
suite.addTest(new EntityManagerJUnitTestSuite("testOneToManyDefaultJoinTableName"));
suite.addTest(new EntityManagerJUnitTestSuite("testClosedEmShouldThrowException"));
suite.addTest(new EntityManagerJUnitTestSuite("testRollbackOnlyOnException"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllProjectsWithNullTeamLeader"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllLargeProjectsWithNullTeamLeader"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllSmallProjectsWithNullTeamLeader"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllProjectsWithName"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllLargeProjectsWithName"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllSmallProjectsWithName"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllLargeProjects"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateAllSmallProjects"));
suite.addTest(new EntityManagerJUnitTestSuite("testUpdateUsingTempStorageWithParameter"));
suite.addTest(new EntityManagerJUnitTestSuite("testDeleteAllLargeProjectsWithNullTeamLeader"));
suite.addTest(new EntityManagerJUnitTestSuite("testDeleteAllSmallProjectsWithNullTeamLeader"));
suite.addTest(new EntityManagerJUnitTestSuite("testDeleteAllProjectsWithNullTeamLeader"));
suite.addTest(new EntityManagerJUnitTestSuite("testDeleteAllPhonesWithNullOwner"));
suite.addTest(new EntityManagerJUnitTestSuite("testSetFieldForPropertyAccessWithNewEM"));
suite.addTest(new EntityManagerJUnitTestSuite("testSetFieldForPropertyAccessWithRefresh"));
suite.addTest(new EntityManagerJUnitTestSuite("testSetFieldForPropertyAccess"));
suite.addTest(new EntityManagerJUnitTestSuite("testInitializeFieldForPropertyAccess"));
suite.addTest(new EntityManagerJUnitTestSuite("testCascadePersistToNonEntitySubclass"));
suite.addTest(new EntityManagerJUnitTestSuite("testCascadeMergeManaged"));
suite.addTest(new EntityManagerJUnitTestSuite("testCascadeMergeDetached"));
suite.addTest(new EntityManagerJUnitTestSuite("testPrimaryKeyUpdatePKFK"));
suite.addTest(new EntityManagerJUnitTestSuite("testPrimaryKeyUpdateSameValue"));
suite.addTest(new EntityManagerJUnitTestSuite("testPrimaryKeyUpdate"));
suite.addTest(new EntityManagerJUnitTestSuite("testRemoveNull"));
suite.addTest(new EntityManagerJUnitTestSuite("testDetachNull"));
suite.addTest(new EntityManagerJUnitTestSuite("testContainsNull"));
suite.addTest(new EntityManagerJUnitTestSuite("testPersistNull"));
suite.addTest(new EntityManagerJUnitTestSuite("testMergeNull"));
suite.addTest(new EntityManagerJUnitTestSuite("testMergeRemovedObject"));
suite.addTest(new EntityManagerJUnitTestSuite("testDetachRemovedObject"));
suite.addTest(new EntityManagerJUnitTestSuite("testMergeDetachedObject"));
suite.addTest(new EntityManagerJUnitTestSuite("testSerializedLazy"));
suite.addTest(new EntityManagerJUnitTestSuite("testCloneable"));
suite.addTest(new EntityManagerJUnitTestSuite("testLeftJoinOneToOneQuery"));
suite.addTest(new EntityManagerJUnitTestSuite("testLockingLeftJoinOneToOneQuery"));
suite.addTest(new EntityManagerJUnitTestSuite("testLockingLeftJoinOneToOneQuery2"));
suite.addTest(new EntityManagerJUnitTestSuite("testNullifyAddressIn"));
suite.addTest(new EntityManagerJUnitTestSuite("testQueryOnClosedEM"));
suite.addTest(new EntityManagerJUnitTestSuite("testIncorrectBatchQueryHint"));
suite.addTest(new EntityManagerJUnitTestSuite("testFetchQueryHint"));
suite.addTest(new EntityManagerJUnitTestSuite("testBatchQueryHint"));
suite.addTest(new EntityManagerJUnitTestSuite("testQueryHints"));
suite.addTest(new EntityManagerJUnitTestSuite("testParallelMultipleFactories"));
suite.addTest(new EntityManagerJUnitTestSuite("testMultipleFactories"));
suite.addTest(new EntityManagerJUnitTestSuite("testPersistenceProperties"));
suite.addTest(new EntityManagerJUnitTestSuite("testGetProperties"));
suite.addTest(new EntityManagerJUnitTestSuite("testBeginTransactionCloseCommitTransaction"));
suite.addTest(new EntityManagerJUnitTestSuite("testBeginTransactionClose"));
suite.addTest(new EntityManagerJUnitTestSuite("testClose"));
suite.addTest(new EntityManagerJUnitTestSuite("testPersistOnNonEntity"));
suite.addTest(new EntityManagerJUnitTestSuite("testDetachNonEntity"));
suite.addTest(new EntityManagerJUnitTestSuite("testWRITELock"));
suite.addTest(new EntityManagerJUnitTestSuite("testOPTIMISTIC_FORCE_INCREMENTLock"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_OriginalInCache_UpdateAll_Refresh_Flush"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_OriginalInCache_UpdateAll_Refresh"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_OriginalInCache_UpdateAll_Flush"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_OriginalInCache_UpdateAll"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_OriginalInCache_CustomUpdate_Refresh_Flush"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_OriginalInCache_CustomUpdate_Refresh"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_OriginalInCache_CustomUpdate_Flush"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_OriginalInCache_CustomUpdate"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_UpdateAll_Refresh_Flush"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_UpdateAll_Refresh"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_UpdateAll_Flush"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_UpdateAll"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_CustomUpdate_Refresh_Flush"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_CustomUpdate_Refresh"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_CustomUpdate_Flush"));
suite.addTest(new EntityManagerJUnitTestSuite("testReadTransactionIsolation_CustomUpdate"));
suite.addTest(new EntityManagerJUnitTestSuite("testClearInTransaction"));
suite.addTest(new EntityManagerJUnitTestSuite("testClearWithFlush"));
suite.addTest(new EntityManagerJUnitTestSuite("testClear"));
suite.addTest(new EntityManagerJUnitTestSuite("testEMFClose"));
suite.addTest(new EntityManagerJUnitTestSuite("testCheckVersionOnMerge"));
suite.addTest(new EntityManagerJUnitTestSuite("testFindWithNullPk"));
suite.addTest(new EntityManagerJUnitTestSuite("testFindWithWrongTypePk"));
suite.addTest(new EntityManagerJUnitTestSuite("testFindWithProperties"));
suite.addTest(new EntityManagerJUnitTestSuite("testPersistManagedNoException"));
suite.addTest(new EntityManagerJUnitTestSuite("testPersistManagedException"));
suite.addTest(new EntityManagerJUnitTestSuite("testDetachManagedObject"));
suite.addTest(new EntityManagerJUnitTestSuite("testDetachNonManagedObject"));
suite.addTest(new EntityManagerJUnitTestSuite("testCascadeDetach"));
suite.addTest(new EntityManagerJUnitTestSuite("testPersistRemoved"));
suite.addTest(new EntityManagerJUnitTestSuite("testREADLock"));
suite.addTest(new EntityManagerJUnitTestSuite("testOPTIMISTICLock"));
suite.addTest(new EntityManagerJUnitTestSuite("testPESSIMISTIC_READLock"));
suite.addTest(new EntityManagerJUnitTestSuite("testPESSIMISTIC_WRITELock"));
suite.addTest(new EntityManagerJUnitTestSuite("testPESSIMISTIC_FORCE_INCREMENTLock"));
suite.addTest(new EntityManagerJUnitTestSuite("testPESSIMISTIC_READLockWithNoChanges"));
suite.addTest(new EntityManagerJUnitTestSuite("testPESSIMISTIC_WRITELockWithNoChanges"));
suite.addTest(new EntityManagerJUnitTestSuite("testPESSIMISTIC_READ_TIMEOUTLock"));
suite.addTest(new EntityManagerJUnitTestSuite("testPESSIMISTIC_WRITE_TIMEOUTLock"));
suite.addTest(new EntityManagerJUnitTestSuite("testPESSIMISTIC_ExtendedScope"));
suite.addTest(new EntityManagerJUnitTestSuite("testRefreshOPTIMISTICLock"));
suite.addTest(new EntityManagerJUnitTestSuite("testRefreshPESSIMISTIC_READLock"));
suite.addTest(new EntityManagerJUnitTestSuite("testRefreshPESSIMISTIC_WRITELock"));
suite.addTest(new EntityManagerJUnitTestSuite("testIgnoreRemovedObjectsOnDatabaseSync"));
suite.addTest(new EntityManagerJUnitTestSuite("testIdentityOutsideTransaction"));
suite.addTest(new EntityManagerJUnitTestSuite("testIdentityInsideTransaction"));
suite.addTest(new EntityManagerJUnitTestSuite("testDatabaseSyncNewObject"));
suite.addTest(new EntityManagerJUnitTestSuite("testSetRollbackOnly"));
suite.addTest(new EntityManagerJUnitTestSuite("testFlushModeEmCommitQueryAuto"));
suite.addTest(new EntityManagerJUnitTestSuite("testFlushModeEmCommit"));
suite.addTest(new EntityManagerJUnitTestSuite("testFlushModeEmCommitQueryCommit"));
suite.addTest(new EntityManagerJUnitTestSuite("testFlushModeEmAutoQueryAuto"));
suite.addTest(new EntityManagerJUnitTestSuite("testFlushModeEmAuto"));
suite.addTest(new EntityManagerJUnitTestSuite("testFlushModeEmAutoQueryCommit"));
suite.addTest(new EntityManagerJUnitTestSuite("testCacheUsage"));
suite.addTest(new EntityManagerJUnitTestSuite("testSequencePreallocationUsingCallbackTest"));
suite.addTest(new EntityManagerJUnitTestSuite("testForceSQLExceptionFor219097"));
suite.addTest(new EntityManagerJUnitTestSuite("testRefreshInvalidateDeletedObject"));
suite.addTest(new EntityManagerJUnitTestSuite("testClearWithFlush2"));
suite.addTest(new EntityManagerJUnitTestSuite("testEMFWrapValidationException"));
suite.addTest(new EntityManagerJUnitTestSuite("testEMDefaultTxType"));
suite.addTest(new EntityManagerJUnitTestSuite("testMergeNewObject"));
suite.addTest(new EntityManagerJUnitTestSuite("testMergeNewObject2"));
suite.addTest(new EntityManagerJUnitTestSuite("testMergeNewObject3_UseSequencing"));
suite.addTest(new EntityManagerJUnitTestSuite("testMergeNewObject3_DontUseSequencing"));
suite.addTest(new EntityManagerJUnitTestSuite("testCreateEntityManagerFactory"));
suite.addTest(new EntityManagerJUnitTestSuite("testCreateEntityManagerFactory2"));
suite.addTest(new EntityManagerJUnitTestSuite("testPessimisticLockHintStartsTransaction"));
suite.addTest(new EntityManagerJUnitTestSuite("testManyToOnePersistCascadeOnFlush"));
suite.addTest(new EntityManagerJUnitTestSuite("testDiscoverNewReferencedObject"));
suite.addTest(new EntityManagerJUnitTestSuite("testBulkDeleteThenMerge"));
suite.addTest(new EntityManagerJUnitTestSuite("testNativeSequences"));
suite.addTest(new EntityManagerJUnitTestSuite("testGetReference"));
suite.addTest(new EntityManagerJUnitTestSuite("testGetLockModeType"));
suite.addTest(new EntityManagerJUnitTestSuite("testGetEntityManagerFactory"));
suite.addTest(new EntityManagerJUnitTestSuite("testGetReferenceUpdate"));
suite.addTest(new EntityManagerJUnitTestSuite("testGetReferenceUsedInUpdate"));
suite.addTest(new EntityManagerJUnitTestSuite("testBadGetReference"));
suite.addTest(new EntityManagerJUnitTestSuite("testClassInstanceConverter"));
suite.addTest(new EntityManagerJUnitTestSuite("test210280EntityManagerFromPUwithSpaceInNameButNotInPath"));
suite.addTest(new EntityManagerJUnitTestSuite("test210280EntityManagerFromPUwithSpaceInPathButNotInName"));
suite.addTest(new EntityManagerJUnitTestSuite("test210280EntityManagerFromPUwithSpaceInNameAndPath"));
suite.addTest(new EntityManagerJUnitTestSuite("testNewObjectNotCascadePersist"));
suite.addTest(new EntityManagerJUnitTestSuite("testConnectionPolicy"));
suite.addTest(new EntityManagerJUnitTestSuite("testConnectionPolicySetProperty"));
suite.addTest(new EntityManagerJUnitTestSuite("testConverterIn"));
suite.addTest(new EntityManagerJUnitTestSuite("testExceptionForPersistNonEntitySubclass"));
suite.addTest(new EntityManagerJUnitTestSuite("testEnabledPersistNonEntitySubclass"));
suite.addTest(new EntityManagerJUnitTestSuite("testCloneEmbeddable"));
suite.addTest(new EntityManagerJUnitTestSuite("testCloseOnCommit"));
suite.addTest(new EntityManagerJUnitTestSuite("testPersistOnCommit"));
suite.addTest(new EntityManagerJUnitTestSuite("testFlushMode"));
suite.addTest(new EntityManagerJUnitTestSuite("testEmbeddedNPE"));
suite.addTest(new EntityManagerJUnitTestSuite("testCollectionAddNewObjectUpdate"));
suite.addTest(new EntityManagerJUnitTestSuite("testUnWrapClass"));
suite.addTest(new EntityManagerJUnitTestSuite("testEMCloseAndOpen"));
suite.addTest(new EntityManagerJUnitTestSuite("testEMFactoryCloseAndOpen"));
suite.addTest(new EntityManagerJUnitTestSuite("testNoPersistOnCommit"));
suite.addTest(new EntityManagerJUnitTestSuite("testNoPersistOnCommitProperties"));
suite.addTest(new EntityManagerJUnitTestSuite("testForUOWInSharedCacheWithBatchQueryHint"));
suite.addTest(new EntityManagerJUnitTestSuite("testNoPersistOnFlushProperties"));
suite.addTest(new EntityManagerJUnitTestSuite("testUOWReferenceInExpressionCache"));
suite.addTest(new EntityManagerJUnitTestSuite("testIsLoaded"));
suite.addTest(new EntityManagerJUnitTestSuite("testIsLoadedAttribute"));
suite.addTest(new EntityManagerJUnitTestSuite("testGetIdentifier"));
suite.addTest(new EntityManagerJUnitTestSuite("testIsLoadedWithReference"));
suite.addTest(new EntityManagerJUnitTestSuite("testIsLoadedWithoutReference"));
suite.addTest(new EntityManagerJUnitTestSuite("testIsLoadedWithoutReferenceAttribute"));
suite.addTest(new EntityManagerJUnitTestSuite("testGetHints"));
suite.addTest(new EntityManagerJUnitTestSuite("testTemporalOnClosedEm"));
suite.addTest(new EntityManagerJUnitTestSuite("testTransientMapping"));
suite.addTest(new EntityManagerJUnitTestSuite("testGenerateSessionNameFromConnectionProperties"));
suite.addTest(new EntityManagerJUnitTestSuite("testPESSIMISTIC_FORCE_INCREMENTLockOnNonVersionedEntity"));
suite.addTest(new EntityManagerJUnitTestSuite("testLockWithJoinedInheritanceStrategy"));
suite.addTest(new EntityManagerJUnitTestSuite("testPreupdateEmbeddable"));
suite.addTest(new EntityManagerJUnitTestSuite("testFindReadOnlyIsolated"));
suite.addTest(new EntityManagerJUnitTestSuite("testInheritanceQuery"));
return suite;
}
public void testSetup() {
new AdvancedTableCreator().replaceTables(JUnitTestCase.getServerSession());
// Force uppercase for Postgres.
if (getServerSession().getPlatform().isPostgreSQL()) {
getServerSession().getLogin().setShouldForceFieldNamesToUpperCase(true);
}
}
/**
* Bug# 219097
* This test would normally pass, but we purposely invoke an SQLException on the firstName field
* so that we can test that an UnsupportedOperationException is not thrown as part of the
* roll-back exception handling code for an SQLException.
*/
public void testForceSQLExceptionFor219097() {
boolean exceptionThrown = false;
// Set an immutable properties Map on the em to test addition of properties to this map in the roll-back exception handler
EntityManager em = createEntityManager(Collections.emptyMap());
beginTransaction(em);
Employee emp = new Employee();
/*
* Provoke an SQL exception by setting a field with a value greater than field length.
* 1 - This test will not throw an exception without the Collections$emptyMap() set on the EntityhManager
* or the exceeded field length set on firstName.
* 2 - This test will throw an UnsupportedOperationException if the map on AbstractSession is not cloned when immutable - bug fix
* 3 - This test will throw an SQLException when operating normally due to the field length exception
*/
StringBuffer firstName = new StringBuffer("firstName_maxfieldLength_");
for(int i=0; i<MAX_FIRST_NAME_FIELD_LENGTH + 100; i++) {
firstName.append("0");
}
emp.setFirstName(firstName.toString());
em.persist(emp);
try {
commitTransaction(em);
} catch (Exception e) {
Throwable cause = e.getCause();
if(cause instanceof UnsupportedOperationException) {
exceptionThrown = true;
fail(cause.getClass() + " Exception was thrown in error instead of expected SQLException.");
} else {
exceptionThrown = true;
}
} finally {
closeEntityManager(em);
}
if(!exceptionThrown) {
fail("An expected SQLException was not thrown.");
}
}
// JUnit framework will automatically execute all methods starting with test...
public void testRefreshNotManaged() {
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("testRefreshNotManaged");
try {
em.refresh(emp);
fail("entityManager.refresh(notManagedObject) didn't throw exception");
} catch (IllegalArgumentException illegalArgumentException) {
// expected behavior
} catch (Exception exception ) {
fail("entityManager.refresh(notManagedObject) threw a wrong exception: " + exception.getMessage());
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testEMFClose() {
// This test tests the bug fix for 260511
// The NPE would be thrown if the EnityManager
// was created through the constructor
String errorMsg = "";
EntityManagerFactory em = new EntityManagerFactoryImpl(JUnitTestCase.getServerSession());
try {
em.close();
} catch (RuntimeException ex) {
errorMsg ="EMFClose: " + ex.getMessage() +";";
}
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
public void testRefreshOPTIMISTICLock(){
// Cannot create parallel entity managers in the server.
if (! isOnServer()) {
EntityManager em = createEntityManager();
beginTransaction(em);
Employee employee = null;
try {
employee = new Employee();
employee.setFirstName("Billy");
employee.setLastName("Madsen");
em.persist(employee);
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
EntityManager em2 = createEntityManager();
Exception optimisticLockException = null;
beginTransaction(em);
try {
em.refresh(employee, LockModeType.OPTIMISTIC);
beginTransaction(em2);
try {
Employee employee2 = em2.find(Employee.class, employee.getId());
employee2.setFirstName("Tilly");
commitTransaction(em2);
} catch (RuntimeException ex) {
if (isTransactionActive(em2)) {
rollbackTransaction(em2);
}
throw ex;
} finally {
closeEntityManager(em2);
}
try {
em.flush();
} catch (PersistenceException exception) {
if (exception instanceof OptimisticLockException){
optimisticLockException = exception;
} else {
throw exception;
}
}
rollbackTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
try {
beginTransaction(em);
employee = em.find(Employee.class, employee.getId());
em.remove(employee);
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
assertFalse("Proper exception not thrown when EntityManager.lock(object, OPTIMISTIC) is used.", optimisticLockException == null);
}
}
public void testRefreshPESSIMISTIC_READLock() {
ServerSession session = JUnitTestCase.getServerSession();
// Cannot create parallel entity managers in the server.
if (! isOnServer() && isSelectForUpateNoWaitSupported()) {
EntityManager em = createEntityManager();
Department dept = null;
try {
beginTransaction(em);
dept = new Department();
dept.setName("Pessimistic Department");
em.persist(dept);
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
Exception pessimisticLockException = null;
try {
beginTransaction(em);
dept = em.find(Department.class, dept.getId());
em.lock(dept, LockModeType.PESSIMISTIC_READ);
dept.setName("New Pessimistic Department");
EntityManager em2 = createEntityManager();
try {
beginTransaction(em2);
Department dept2 = em2.find(Department.class, dept.getId());
HashMap properties = new HashMap();
// According to the spec a 0 indicates a NOWAIT clause.
properties.put(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
em2.refresh(dept2, LockModeType.PESSIMISTIC_READ, properties);
} catch (PersistenceException ex) {
if (ex instanceof javax.persistence.PessimisticLockException) {
pessimisticLockException = ex;
} else {
throw ex;
}
} finally {
closeEntityManager(em2);
}
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
assertFalse("Proper exception not thrown when EntityManager.lock(object, PESSIMISTIC) is used.", pessimisticLockException == null);
}
}
public void testRefreshPESSIMISTIC_WRITELock() {
ServerSession session = JUnitTestCase.getServerSession();
// Cannot create parallel entity managers in the server.
if (! isOnServer() && isSelectForUpateNoWaitSupported()) {
EntityManager em = createEntityManager();
Department dept = null;
try {
beginTransaction(em);
dept = new Department();
dept.setName("Pessimistic Department");
em.persist(dept);
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
Exception pessimisticLockException = null;
try {
beginTransaction(em);
dept = em.find(Department.class, dept.getId());
em.lock(dept, LockModeType.PESSIMISTIC_WRITE);
dept.setName("New Pessimistic Department");
EntityManager em2 = createEntityManager();
try {
beginTransaction(em2);
Department dept2 = em2.find(Department.class, dept.getId());
HashMap properties = new HashMap();
// According to the spec a 0 indicates a NOWAIT clause.
properties.put(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
em2.refresh(dept2, LockModeType.PESSIMISTIC_WRITE, properties);
} catch (PersistenceException ex) {
if (ex instanceof javax.persistence.PessimisticLockException) {
pessimisticLockException = ex;
} else {
throw ex;
}
} finally {
closeEntityManager(em2);
}
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
assertFalse("Proper exception not thrown when EntityManager.lock(object, PESSIMISTIC) is used.", pessimisticLockException == null);
}
}
public void testRefreshRemoved() {
// find an existing or create a new Employee
String firstName = "testRefreshRemoved";
Employee emp;
EntityManager em = createEntityManager();
List result = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = '"+firstName+"'").getResultList();
if(!result.isEmpty()) {
emp = (Employee)result.get(0);
} else {
emp = new Employee();
emp.setFirstName(firstName);
// persist the Employee
try{
beginTransaction(em);
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
}
}
try{
beginTransaction(em);
emp = em.find(Employee.class, emp.getId());
// delete the Employee from the db
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
// refresh the Employee - should fail with EntityNotFoundException
em.refresh(emp);
fail("entityManager.refresh(removedObject) didn't throw exception");
} catch (EntityNotFoundException entityNotFoundException) {
rollbackTransaction(em);
// expected behavior
} catch (Exception exception ) {
rollbackTransaction(em);
fail("entityManager.refresh(removedObject) threw a wrong exception: " + exception.getMessage());
}
}
//Bug5955326, refresh should invalidate the shared cached object that was deleted outside of JPA.
public void testRefreshInvalidateDeletedObject(){
EntityManager em1 = createEntityManager();
EntityManager em2 = createEntityManager();
Address address = new Address();
address.setCity("Kanata");
// persist the Address
try {
//Ensure shared cache being used.
boolean isIsolated = ((EntityManagerImpl)em1).getServerSession().getClassDescriptorForAlias("Address").isIsolated();
if(isIsolated){
throw new Exception("This test should use non-isolated cache setting class descriptor for test.");
}
beginTransaction(em1);
em1.persist(address);
commitTransaction(em1);
//Cache the Address
em1 = createEntityManager();
beginTransaction(em1);
address = em1.find(Address.class, address.getId());
// Delete Address outside of JPA so that the object still stored in the cache.
em2 = createEntityManager();
beginTransaction(em2);
em2.createNativeQuery("DELETE FROM CMP3_ADDRESS where address_id = ?1").setParameter(1, address.getId()).executeUpdate();
commitTransaction(em2);
//Call refresh to invalidate the object
em1.refresh(address);
}catch (Exception e){
//expected exception
} finally{
if (isTransactionActive(em1)) {
rollbackTransaction(em1);
}
}
//Verify
beginTransaction(em1);
address=em1.find(Address.class, address.getId());
commitTransaction(em1);
assertNull("The deleted object is still valid in share cache", address);
}
public void testCacheUsage() {
EntityManager em = createEntityManager();
Employee emp = new Employee();
emp.setFirstName("Mark");
// persist the Employee
try {
beginTransaction(em);
em.persist(emp);
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
}
clearCache();
// Create new entity manager to avoid extended uow of work cache hits.
em = createEntityManager();
beginTransaction(em);
List result = em.createQuery("SELECT OBJECT(e) FROM Employee e").getResultList();
commitTransaction(em);
Object obj = getServerSession().getIdentityMapAccessor().getFromIdentityMap(result.get(0));
assertTrue("Failed to load the object into the shared cache when there were no changes in the UOW", obj != null);
try{
beginTransaction(em);
emp = em.find(Employee.class, emp.getId());
em.remove(emp);
commitTransaction(em);
} catch (RuntimeException exception) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
throw exception;
}
}
public void testContainsRemoved() {
// find an existing or create a new Employee
String firstName = "testContainsRemoved";
Employee emp;
EntityManager em = createEntityManager();
List result = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = '"+firstName+"'").getResultList();
if(!result.isEmpty()) {
emp = (Employee)result.get(0);
} else {
emp = new Employee();
emp.setFirstName(firstName);
// persist the Employee
try{
beginTransaction(em);
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
}
}
boolean containsRemoved = true;
try{
beginTransaction(em);
emp = em.find(Employee.class, emp.getId());
em.remove(emp);
containsRemoved = em.contains(emp);
commitTransaction(em);
}catch (RuntimeException t){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw t;
}
assertFalse("entityManager.contains(removedObject)==true ", containsRemoved);
}
public void testFlushModeEmAutoQueryCommit() {
internalTestFlushMode(FlushModeType.AUTO, FlushModeType.COMMIT);
}
public void testFlushModeEmAuto() {
internalTestFlushMode(FlushModeType.AUTO, null);
}
public void testFlushModeEmAutoQueryAuto() {
internalTestFlushMode(FlushModeType.AUTO, FlushModeType.AUTO);
}
public void testFlushModeEmCommitQueryCommit() {
internalTestFlushMode(FlushModeType.COMMIT, FlushModeType.COMMIT);
}
public void testFlushModeEmCommit() {
internalTestFlushMode(FlushModeType.COMMIT, null);
}
public void testFlushModeEmCommitQueryAuto() {
internalTestFlushMode(FlushModeType.COMMIT, FlushModeType.AUTO);
}
public void internalTestFlushMode(FlushModeType emFlushMode, FlushModeType queryFlushMode) {
// create a new Employee
String firstName = "testFlushMode";
// make sure no Employee with the specified firstName exists.
EntityManager em = createEntityManager();
try{
beginTransaction(em);
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
}
clearCache();
Employee emp;
FlushModeType emFlushModeOriginal = em.getFlushMode();
// create a new Employee
emp = new Employee();
emp.setFirstName(firstName);
boolean flushed = true;
Employee result = null;
try{
beginTransaction(em);
Query query = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName like '"+firstName+"'");
if(queryFlushMode != null) {
query.setFlushMode(queryFlushMode);
}
emFlushModeOriginal = em.getFlushMode();
em.setFlushMode(emFlushMode);
em.persist(emp);
result = (Employee) query.getSingleResult();
result.toString();
} catch (javax.persistence.NoResultException ex) {
// failed to flush to database
flushed = false;
} finally {
rollbackTransaction(em);
em.setFlushMode(emFlushModeOriginal);
}
boolean shouldHaveFlushed;
if(queryFlushMode != null) {
shouldHaveFlushed = queryFlushMode == FlushModeType.AUTO;
} else {
shouldHaveFlushed = emFlushMode == FlushModeType.AUTO;
}
if(shouldHaveFlushed != flushed) {
if(flushed) {
fail("Flushed to database");
} else {
fail("Failed to flush to database");
}
}
}
public void testFlushModeOnUpdateQuery() {
// find an existing or create a new Employee
String firstName = "testFlushModeOnUpdateQuery";
Employee emp;
EntityManager em = createEntityManager();
emp = new Employee();
emp.setFirstName(firstName);
try{
try{
beginTransaction(em);
Query readQuery = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.phoneNumbers IS EMPTY and e.firstName like '"+firstName+"'");
Query updateQuery = em.createQuery("UPDATE Employee e set e.salary = 100 where e.firstName like '" + firstName + "'");
updateQuery.setFlushMode(FlushModeType.AUTO);
em.persist(emp);
updateQuery.executeUpdate();
Employee result = (Employee) readQuery.getSingleResult();
result.toString();
}catch (javax.persistence.EntityNotFoundException ex){
rollbackTransaction(em);
fail("Failed to flush to database");
}
em.refresh(emp);
assertTrue("Failed to flush to Database", emp.getSalary() == 100);
em.remove(emp);
commitTransaction(em);
}catch(RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
}
}
public void testAnnotationDefaultLockModeNONEOnUpdateQuery() {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
em.createNamedQuery("UpdateEmployeeQueryWithLockModeNONE").executeUpdate();
commitTransaction(em);
} catch (Exception e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
fail("Update query failed: " + e.getMessage());
} finally {
closeEntityManager(em);
}
}
public void testSetRollbackOnly(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
Employee emp = new Employee();
emp.setFirstName("Bob");
emp.setLastName("Fisher");
em.persist(emp);
emp = new Employee();
emp.setFirstName("Anthony");
emp.setLastName("Walace");
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
clearCache();
em = createEntityManager();
beginTransaction(em);
List result = em.createQuery("SELECT e FROM Employee e").getResultList();
Employee emp = (Employee)result.get(0);
emp.toString();
Employee emp2 = (Employee)result.get(1);
String newName = ""+System.currentTimeMillis();
emp2.setFirstName(newName);
em.flush();
emp2.setLastName("Whatever");
emp2.setVersion(0);
try{
em.flush();
}catch (Exception ex){
em.clear(); //prevent the flush again
// Query may fail in server as connection marked for rollback.
try {
String eName = (String)em.createQuery("SELECT e.firstName FROM Employee e where e.id = " + emp2.getId()).getSingleResult();
assertTrue("Failed to keep txn open for set RollbackOnly", eName.equals(newName));
} catch (Exception ignore) {}
}
try {
if (isOnServer()) {
assertTrue("Failed to mark txn rollback only", !isTransactionActive(em));
} else {
assertTrue("Failed to mark txn rollback only", em.getTransaction().getRollbackOnly());
}
} finally{
try{
commitTransaction(em);
}catch (RollbackException ex){
return;
}catch (RuntimeException ex){
if (ex.getCause() instanceof javax.transaction.RollbackException) {
return;
}
if (ex.getCause() instanceof javax.persistence.RollbackException) {
return;
}
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
}
}
fail("Failed to throw rollback exception");
}
public void testSubString() {
// find an existing or create a new Employee
String firstName = "testSubString";
Employee emp;
EntityManager em = createEntityManager();
List result = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = '"+firstName+"'").getResultList();
if(!result.isEmpty()) {
emp = (Employee)result.get(0);
} else {
emp = new Employee();
emp.setFirstName(firstName);
// persist the Employee
try{
beginTransaction(em);
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
}
}
int firstIndex = 1;
int lastIndex = firstName.length();
List employees = em.createQuery("SELECT object(e) FROM Employee e where e.firstName = substring(:p1, :p2, :p3)").
setParameter("p1", firstName).
setParameter("p2", new Integer(firstIndex)).
setParameter("p3", new Integer(lastIndex)).
getResultList();
// clean up
try{
beginTransaction(em);
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
}
assertFalse("employees.isEmpty()==true ", employees.isEmpty());
}
public void testNewObjectNotCascadePersist(){
IllegalStateException exception = null;
EntityManager em = createEntityManager();
beginTransaction(em);
Golfer g = new Golfer();
WorldRank wr = new WorldRank();
g.setWorldRank(wr);
em.persist(g);
try{
em.flush();
}catch (IllegalStateException ex){
exception = ex;
}finally{
rollbackTransaction(em);
closeEntityManager(em);
}
assertNotNull("Failed to throw IllegalStateException see bug: 237279 ", exception);
}
public void testDatabaseSyncNewObject() {
EntityManager em = createEntityManager();
beginTransaction(em);
try{
Project project = new LargeProject();
em.persist(project);
project.setName("Blah");
project.setTeamLeader(new Employee());
project.getTeamLeader().addProject(project);
em.flush();
}catch (RuntimeException ex){
rollbackTransaction(em);
if (ex instanceof IllegalStateException)
return;
}
fail("Failed to throw illegal argument when finding unregistered new object cascading on database sync");
}
public void testTransactionRequired() {
String firstName = "testTransactionRequired";
Employee emp = new Employee();
emp.setFirstName(firstName);
String noException = "";
String wrongException = "";
try {
createEntityManager().flush();
noException = noException + " flush;";
} catch (TransactionRequiredException transactionRequiredException) {
// expected behavior
} catch (RuntimeException ex) {
wrongException = wrongException + " flush: " + ex.getMessage() +";";
}
String errorMsg = "";
if(noException.length() > 0) {
errorMsg = "No exception thrown: " + noException;
}
if(wrongException.length() > 0) {
if(errorMsg.length() > 0) {
errorMsg = errorMsg + " ";
}
errorMsg = errorMsg + "Wrong exception thrown: " + wrongException;
}
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
public void testIdentityInsideTransaction() {
EntityManager em = createEntityManager();
beginTransaction(em);
Query query = em.createQuery("SELECT e FROM PhoneNumber e");
List<PhoneNumber> phoneNumbers = query.getResultList();
for (PhoneNumber phoneNumber : phoneNumbers) {
Employee emp = phoneNumber.getOwner();
Collection<PhoneNumber> numbers = emp.getPhoneNumbers();
assertTrue(numbers.contains(phoneNumber));
}
commitTransaction(em);
closeEntityManager(em);
}
public void testIdentityOutsideTransaction() {
EntityManager em = createEntityManager();
Query query = em.createQuery("SELECT e FROM PhoneNumber e");
List<PhoneNumber> phoneNumbers = query.getResultList();
for (PhoneNumber phoneNumber : phoneNumbers) {
Employee emp = phoneNumber.getOwner();
Collection<PhoneNumber> numbers = emp.getPhoneNumbers();
assertTrue(numbers.contains(phoneNumber));
}
closeEntityManager(em);
}
public void testIgnoreRemovedObjectsOnDatabaseSync() {
EntityManager em = createEntityManager();
beginTransaction(em);
Query phoneQuery = em.createQuery("Select p from PhoneNumber p where p.owner.lastName like 'Dow%'");
Query empQuery = em.createQuery("Select e FROM Employee e where e.lastName like 'Dow%'");
//--setup
try{
Employee emp = new Employee();
emp.setLastName("Dowder");
PhoneNumber phone = new PhoneNumber("work", "613", "5555555");
emp.addPhoneNumber(phone);
phone = new PhoneNumber("home", "613", "4444444");
emp.addPhoneNumber(phone);
Address address = new Address("SomeStreet", "somecity", "province", "country", "postalcode");
emp.setAddress(address);
em.persist(emp);
em.flush();
emp = new Employee();
emp.setLastName("Dows");
phone = new PhoneNumber("work", "613", "2222222");
emp.addPhoneNumber(phone);
phone = new PhoneNumber("home", "613", "1111111");
emp.addPhoneNumber(phone);
address = new Address("street1", "city1", "province1", "country1", "postalcode1");
emp.setAddress(address);
em.persist(emp);
em.flush();
//--end setup
List<Employee> emps = empQuery.getResultList();
List phones = phoneQuery.getResultList();
for (Iterator iterator = phones.iterator(); iterator.hasNext();){
em.remove(iterator.next());
}
em.flush();
for (Iterator<Employee> iterator = emps.iterator(); iterator.hasNext();){
em.remove(iterator.next());
}
}catch (RuntimeException ex){
rollbackTransaction(em);
throw ex;
}
try{
em.flush();
}catch (IllegalStateException ex){
rollbackTransaction(em);
closeEntityManager(em);
em = createEntityManager();
beginTransaction(em);
try{
phoneQuery = em.createQuery("Select p from PhoneNumber p where p.owner.lastName like 'Dow%'");
empQuery = em.createQuery("Select e from Employee e where e.lastName like 'Dow%'");
List<Employee> emps = empQuery.getResultList();
List phones = phoneQuery.getResultList();
for (Iterator iterator = phones.iterator(); iterator.hasNext();){
em.remove(iterator.next());
}
for (Iterator<Employee> iterator = emps.iterator(); iterator.hasNext();){
em.remove(iterator.next());
}
commitTransaction(em);
}catch (RuntimeException re){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw re;
}
fail("Failed to ignore the removedobject when cascading on database sync");
}
commitTransaction(em);
}
public void testREADLock(){
// Cannot create parallel entity managers in the server.
if (isOnServer()) {
return;
}
EntityManager em = createEntityManager();
beginTransaction(em);
Employee employee = null;
try {
employee = new Employee();
employee.setFirstName("Mark");
employee.setLastName("Madsen");
em.persist(employee);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
EntityManager em2 = createEntityManager();
Exception optimisticLockException = null;
beginTransaction(em);
try{
employee = em.find(Employee.class, employee.getId());
em.lock(employee, LockModeType.READ);
em2.getTransaction().begin();
try{
Employee employee2 = em2.find(Employee.class, employee.getId());
employee2.setFirstName("Michael");
em2.getTransaction().commit();
em2.close();
}catch (RuntimeException ex){
em2.getTransaction().rollback();
em2.close();
throw ex;
}
try{
em.flush();
} catch (PersistenceException exception) {
if (exception instanceof OptimisticLockException){
optimisticLockException = exception;
}else{
throw exception;
}
}
rollbackTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
beginTransaction(em);
try{
employee = em.find(Employee.class, employee.getId());
em.remove(employee);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
if (optimisticLockException == null){
fail("Proper exception not thrown when EntityManager.lock(object, READ) is used.");
}
}
public void testOPTIMISTIC_FORCE_INCREMENTLock(){
// Cannot create parallel transactions.
if (! isOnServer()) {
EntityManager em = createEntityManager();
Employee employee;
try {
beginTransaction(em);
employee = new Employee();
employee.setFirstName("Philip");
employee.setLastName("Madsen");
em.persist(employee);
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
Exception optimisticLockException = null;
try {
beginTransaction(em);
employee = em.find(Employee.class, employee.getId(), LockModeType.OPTIMISTIC_FORCE_INCREMENT);
EntityManager em2 = createEntityManager();
try {
beginTransaction(em2);
Employee employee2 = em2.find(Employee.class, employee.getId());
employee2.setFirstName("Tulip");
commitTransaction(em2);
} catch (RuntimeException ex) {
if (isTransactionActive(em2)) {
rollbackTransaction(em2);
}
throw ex;
} finally {
closeEntityManager(em2);
}
commitTransaction(em);
} catch (RollbackException exception) {
if (exception.getCause() instanceof OptimisticLockException){
optimisticLockException = exception;
}
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
beginTransaction(em);
try {
employee = em.find(Employee.class, employee.getId());
em.remove(employee);
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
assertFalse("Proper exception not thrown when EntityManager.lock(object, WRITE) is used.", optimisticLockException == null);
}
}
public void testOPTIMISTICLock(){
// Cannot create parallel entity managers in the server.
if (! isOnServer()) {
EntityManager em = createEntityManager();
beginTransaction(em);
Employee employee = null;
try {
employee = new Employee();
employee.setFirstName("Harry");
employee.setLastName("Madsen");
em.persist(employee);
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
EntityManager em2 = createEntityManager();
Exception optimisticLockException = null;
beginTransaction(em);
try {
employee = em.find(Employee.class, employee.getId());
em.lock(employee, LockModeType.OPTIMISTIC);
beginTransaction(em2);
try {
Employee employee2 = em2.find(Employee.class, employee.getId());
employee2.setFirstName("Michael");
commitTransaction(em2);
} catch (RuntimeException ex) {
if (isTransactionActive(em2)) {
rollbackTransaction(em2);
}
throw ex;
} finally {
closeEntityManager(em2);
}
try {
em.flush();
} catch (PersistenceException exception) {
if (exception instanceof OptimisticLockException){
optimisticLockException = exception;
} else {
throw exception;
}
}
rollbackTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
try {
beginTransaction(em);
employee = em.find(Employee.class, employee.getId());
em.remove(employee);
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
assertFalse("Proper exception not thrown when EntityManager.lock(object, OPTIMISTIC) is used.", optimisticLockException == null);
}
}
// This test issues a LOCK and a LOCK NOWAIT.
public void testPESSIMISTIC_READLock() {
ServerSession session = JUnitTestCase.getServerSession();
// Cannot create parallel entity managers in the server.
if (! isOnServer() && isSelectForUpateNoWaitSupported()) {
EntityManager em = createEntityManager();
Department dept = null;
try {
beginTransaction(em);
dept = new Department();
dept.setName("Pessimistic Department");
em.persist(dept);
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
Exception pessimisticLockException = null;
try {
beginTransaction(em);
dept = em.find(Department.class, dept.getId());
em.lock(dept, LockModeType.PESSIMISTIC_READ);
dept.setName("New Pessimistic Department");
EntityManager em2 = createEntityManager();
try {
beginTransaction(em2);
Department dept2 = em2.find(Department.class, dept.getId());
HashMap properties = new HashMap();
// According to the spec a 0 indicates a NOWAIT clause.
properties.put(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
em2.lock(dept2, LockModeType.PESSIMISTIC_READ, properties);
} catch (PersistenceException ex) {
if (ex instanceof javax.persistence.PessimisticLockException) {
pessimisticLockException = ex;
} else {
throw ex;
}
} finally {
rollbackTransaction(em2);
closeEntityManager(em2);
}
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
assertFalse("Proper exception not thrown when EntityManager.lock(object, PESSIMISTIC) is used.", pessimisticLockException == null);
}
}
public void testPESSIMISTIC_WRITELock() {
ServerSession session = JUnitTestCase.getServerSession();
// Cannot create parallel entity managers in the server.
if (! isOnServer() && isSelectForUpateNoWaitSupported()) {
EntityManager em = createEntityManager();
Department dept = null;
try {
beginTransaction(em);
dept = new Department();
dept.setName("Pessimistic Department");
em.persist(dept);
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
Exception pessimisticLockException = null;
try {
beginTransaction(em);
dept = em.find(Department.class, dept.getId());
em.lock(dept, LockModeType.PESSIMISTIC_WRITE);
dept.setName("New Pessimistic Department");
EntityManager em2 = createEntityManager();
try {
beginTransaction(em2);
Department dept2 = em2.find(Department.class, dept.getId());
HashMap properties = new HashMap();
// According to the spec a 0 indicates a NOWAIT clause.
properties.put(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
em2.lock(dept2, LockModeType.PESSIMISTIC_WRITE, properties);
} catch (PersistenceException ex) {
if (ex instanceof javax.persistence.PessimisticLockException) {
pessimisticLockException = ex;
} else {
throw ex;
}
} finally {
rollbackTransaction(em2);
closeEntityManager(em2);
}
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
assertFalse("Proper exception not thrown when EntityManager.lock(object, PESSIMISTIC) is used.", pessimisticLockException == null);
}
}
public void testPESSIMISTIC_FORCE_INCREMENTLock() {
ServerSession session = JUnitTestCase.getServerSession();
// It's JPA2.0 feature.
if (! isJPA10() && isSelectForUpateSupported()) {
Employee employee = null;
Integer version1;
EntityManager em = createEntityManager();
try {
beginTransaction(em);
employee = new Employee();
employee.setFirstName("Guillaume");
employee.setLastName("Aujet");
em.persist(employee);
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
version1 = employee.getVersion();
try {
beginTransaction(em);
employee = em.find(Employee.class, employee.getId(), LockModeType.PESSIMISTIC_FORCE_INCREMENT);
commitTransaction(em);
assertTrue("The version was not updated on the pessimistic lock.", version1.intValue() < employee.getVersion().intValue());
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
}
}
public void testPESSIMISTIC_READLockWithNoChanges() {
ServerSession session = JUnitTestCase.getServerSession();
// Cannot create parallel entity managers in the server.
if (! isOnServer() && isSelectForUpateSupported()) {
Employee employee = null;
Integer version1;
EntityManager em = createEntityManager();
try {
beginTransaction(em);
employee = new Employee();
employee.setFirstName("Black");
employee.setLastName("Crappie");
em.persist(employee);
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
version1 = employee.getVersion();
try {
beginTransaction(em);
employee = em.find(Employee.class, employee.getId(), LockModeType.PESSIMISTIC_READ);
commitTransaction(em);
assertTrue("The version was updated on the pessimistic lock.", version1.intValue() == employee.getVersion().intValue());
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
}
}
public void testPESSIMISTIC_WRITELockWithNoChanges() {
ServerSession session = JUnitTestCase.getServerSession();
// Cannot create parallel entity managers in the server.
if (! isOnServer() && isSelectForUpateSupported()) {
Employee employee = null;
Integer version1;
EntityManager em = createEntityManager();
try {
beginTransaction(em);
employee = new Employee();
employee.setFirstName("Black");
employee.setLastName("Crappie");
em.persist(employee);
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
version1 = employee.getVersion();
try {
beginTransaction(em);
employee = em.find(Employee.class, employee.getId(), LockModeType.PESSIMISTIC_WRITE);
commitTransaction(em);
assertTrue("The version was updated on the pessimistic lock.", version1.intValue() == employee.getVersion().intValue());
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
}
}
public void testPESSIMISTIC_READ_TIMEOUTLock() {
ServerSession session = JUnitTestCase.getServerSession();
// Cannot create parallel entity managers in the server.
// Lock timeout is only supported on Oracle.
if (! isOnServer() && session.getPlatform().isOracle()) {
EntityManager em = createEntityManager();
List result = em.createQuery("Select employee from Employee employee").getResultList();
Employee employee = (Employee) result.get(0);
Exception lockTimeOutException = null;
try {
beginTransaction(em);
employee = em.find(Employee.class, employee.getId(), LockModeType.PESSIMISTIC_READ);
EntityManager em2 = createEntityManager();
try {
beginTransaction(em2);
HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 5);
Employee employee2 = (Employee)em2.find(Employee.class, employee.getId(), LockModeType.PESSIMISTIC_READ, properties);
employee2.setFirstName("Invalid Lock Employee");
commitTransaction(em2);
} catch (PersistenceException ex) {
if (isTransactionActive(em2)) {
rollbackTransaction(em2);
}
if (ex instanceof javax.persistence.LockTimeoutException) {
lockTimeOutException = ex;
} else {
throw ex;
}
} finally {
closeEntityManager(em2);
}
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
assertFalse("Proper exception not thrown when Query with LockModeType.PESSIMISTIC is used.", lockTimeOutException == null);
}
}
public void testPESSIMISTIC_WRITE_TIMEOUTLock() {
ServerSession session = JUnitTestCase.getServerSession();
// Cannot create parallel entity managers in the server.
// Lock timeout is only supported on Oracle.
if (! isOnServer() && session.getPlatform().isOracle()) {
EntityManager em = createEntityManager();
List result = em.createQuery("Select employee from Employee employee").getResultList();
Employee employee = (Employee) result.get(0);
Exception lockTimeOutException = null;
try {
beginTransaction(em);
employee = em.find(Employee.class, employee.getId(), LockModeType.PESSIMISTIC_WRITE);
EntityManager em2 = createEntityManager();
try {
beginTransaction(em2);
HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 5);
Employee employee2 = (Employee)em2.find(Employee.class, employee.getId(), LockModeType.PESSIMISTIC_WRITE, properties);
employee2.setFirstName("Invalid Lock Employee");
commitTransaction(em2);
} catch (PersistenceException ex) {
if (isTransactionActive(em2)) {
rollbackTransaction(em2);
}
if (ex instanceof javax.persistence.LockTimeoutException) {
lockTimeOutException = ex;
} else {
throw ex;
}
} finally {
closeEntityManager(em2);
}
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
assertFalse("Proper exception not thrown when Query with LockModeType.PESSIMISTIC is used.", lockTimeOutException == null);
}
}
public void testPESSIMISTIC_FORCE_INCREMENTLockOnNonVersionedEntity() {
ServerSession session = JUnitTestCase.getServerSession();
// It's a JPA2.0 feature
if (! isJPA10()) {
Department dept = null;
EntityManager em = createEntityManager();
try {
beginTransaction(em);
dept = new Department();
em.persist(dept);
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
try {
beginTransaction(em);
dept = em.find(Department.class, dept.getId(), LockModeType.PESSIMISTIC_FORCE_INCREMENT);
rollbackTransaction(em);
fail("An Expected javax.persistence.PersistenceException was not thrown");
} catch (PersistenceException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
} finally {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
}
}
public void testLockWithJoinedInheritanceStrategy () {
ServerSession session = JUnitTestCase.getServerSession();
// Cannot create parallel entity managers in the server.
if (! isOnServer() && isSelectForUpateSupported()) {
Employee emp = null;
LargeProject largeProject = null;
EntityManager em = createEntityManager();
try {
beginTransaction(em);
emp = new Employee();
largeProject = new LargeProject();
largeProject.setName("Large Project");
largeProject.setBudget(50000);
emp.addProject(largeProject);
em.persist(emp);
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
try {
beginTransaction(em);
emp = em.find(Employee.class, emp.getId());
Project lp1 = emp.getProjects().iterator().next();
em.lock(lp1, LockModeType.PESSIMISTIC_WRITE);
lp1.setName("Lock In Additional Table ");
EntityManager em2 = createEntityManager();
try {
beginTransaction(em2);
LargeProject lp2 = em2.find(LargeProject.class, lp1.getId());
HashMap properties = new HashMap();
// According to the spec a 0 indicates a NOWAIT clause.
properties.put(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
em2.lock(lp2, LockModeType.PESSIMISTIC_WRITE, properties);
} catch (PersistenceException ex) {
if (!(ex instanceof javax.persistence.PessimisticLockException)) {
throw ex;
}
} finally {
rollbackTransaction(em2);
closeEntityManager(em2);
}
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
}
}
/*
* Helper class for testPESSIMISTIC_ExtendedScope.
* Kills transaction that is holding the test for too long.
*/
class TransactionKiller extends Thread {
EntityManager em;
long timeToWait;
boolean shouldKillTransaction = true;
boolean isWaiting;
boolean hasKilledTransaction;
TransactionKiller(EntityManager em, long timeToWait) {
this.em = em;
this.timeToWait = timeToWait;
}
public void run() {
try {
isWaiting = true;
Thread.sleep(timeToWait);
} catch (InterruptedException ex) {
throw new TestProblemException("TestProblem: TransactionKiller.run: wait failed: " + ex);
} finally {
isWaiting = false;
}
if (shouldKillTransaction && isTransactionActive(em)) {
hasKilledTransaction = true;
rollbackTransaction(em);
}
}
}
public void testPESSIMISTIC_ExtendedScope() {
ServerSession session = JUnitTestCase.getServerSession();
// Cannot create parallel entity managers in the server. Uses FOR UPDATE clause which SQLServer doesn't support.
if (isOnServer() || !isSelectForUpateSupported() || !isPessimisticWriteLockSupported()) {
return;
}
ServerSession ss = ((EntityManagerFactoryImpl)getEntityManagerFactory()).getServerSession();
// If FOR UPDATE NOWAIT is not supported then FOR UPDATE is used - and that could lock the test (em2) for a long time (depending on db setting).
boolean shouldSpawnThread = !isSelectForUpateNoWaitSupported();
// To avoid that a separate thread is spawned that - after waiting the specified time -
// completes the locking transaction (em1) and therefore clears the way to em2 go ahead.
long timeToWait = 1000;
String errorMsg = "";
LockModeType lockMode = LockModeType.PESSIMISTIC_WRITE;
// create Employee with Projects and Responsibilities
Employee emp = new Employee();
emp.setFirstName("PESSIMISTIC");
emp.setLastName("ExtendedScope");
emp.addResponsibility("0");
emp.addResponsibility("1");
SmallProject smallProject = new SmallProject();
smallProject.setName("SmallExtendedScope");
emp.addProject(smallProject);
LargeProject largeProject = new LargeProject();
largeProject.setName("LargeExtendedScope");
largeProject.setBudget(5000);
emp.addProject(largeProject);
// persist
EntityManager em = createEntityManager();
try {
beginTransaction(em);
em.persist(emp);
commitTransaction(em);
} finally {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
// cache ids
int id = emp.getId();
int smallProjId = smallProject.getId();
clearCache();
// properties to be passed to find, lock, refresh methods
Map<String, Object> properties = new HashMap();
properties.put(QueryHints.PESSIMISTIC_LOCK_SCOPE, PessimisticLockScope.EXTENDED);
String forUpdateClause = session.getPlatform().getSelectForUpdateString();
if(isSelectForUpateNoWaitSupported()) {
properties.put(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
forUpdateClause = session.getPlatform().getSelectForUpdateNoWaitString();
}
String lockingClauseAfterWhereClause = "";
String lockingClauseBeforeWhereClause = "";
if(session.getPlatform().shouldPrintLockingClauseAfterWhereClause()) {
lockingClauseAfterWhereClause = forUpdateClause;
} else {
lockingClauseBeforeWhereClause = forUpdateClause;
}
// indicates whether the object to be locked is already in cache.
boolean[] isObjectCached = {false, true};
// indicates which method on the first entity manager is used to lock the object.
String[] testModeArray1 = {"query", "find", "lock", "refresh"};
// indicates which method on the second entity manager is used to test the lock.
String[] testModeArray2 = {"query", "find", "update_name", "update_salary", "remove_project", "remove_respons", "update_project", "update_respons", "lock", "refresh"};
/* test runs all combinations of elements of the above three arrays. To limit the number of configuration for debugging override these array, for instance:
boolean[] isObjectCached = {false};
String[] testModeArray1 = {"lock"};
String[] testModeArray2 = {"find"};
*/
// testMode1 loop
for(int i=0; i < testModeArray1.length; i++) {
String testMode1 = testModeArray1[i];
// isObjectCached loop
for(int k=0; k < isObjectCached.length; k++) {
boolean isObjCached = isObjectCached[k];
// testMode2 loop
for(int j=0; j < testModeArray2.length; j++) {
String testMode2 = testModeArray2[j];
boolean isExceptionExpected = !testMode2.equals("update_project");
// lock emp using em1
EntityManager em1= createEntityManager();
// bring object into cache if required
if(isObjCached) {
ss.log(SessionLog.FINEST, SessionLog.QUERY, "testPESSIMISTIC_ExtendedScope: bring object into cache", (Object[])null, null, false);
em1.find(Employee.class, id);
}
Employee emp1;
try {
beginTransaction(em1);
ss.log(SessionLog.FINEST, SessionLog.QUERY, "testPESSIMISTIC_ExtendedScope: testMode1 = " + testMode1, (Object[])null, null, false);
if(testMode1.equals("query")) {
Query query1 = em1.createQuery("SELECT emp FROM Employee emp WHERE emp.id = "+id).setLockMode(lockMode).
setHint(QueryHints.PESSIMISTIC_LOCK_SCOPE, PessimisticLockScope.EXTENDED);
if(isSelectForUpateNoWaitSupported()) {
query1.setHint(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
}
emp1 = (Employee)query1.getSingleResult();
} else if(testMode1.equals("find")) {
emp1 = em1.find(Employee.class, id, lockMode, properties);
} else {
emp1 = em1.find(Employee.class, id);
if(testMode1.equals("lock")) {
em1.lock(emp1, lockMode, properties);
} else if(testMode1.equals("refresh")) {
em1.refresh(emp1, lockMode, properties);
} else {
fail("Unknown testMode1 = " + testMode1);
}
}
TransactionKiller transactionKiller = null;
// try to update emp using em2
EntityManager em2 = createEntityManager();
Employee emp2;
try {
beginTransaction(em2);
ss.log(SessionLog.FINEST, SessionLog.QUERY, "testPESSIMISTIC_ExtendedScope: testMode2 = " + testMode2, (Object[])null, null, false);
if(shouldSpawnThread) {
// after waiting TransactionKiller rollback em1 transaction unlocking way for em2 to proceed.
// the test assumes that em2 waiting for timeToWait means em2 waiting on the lock acquired by em1.
transactionKiller = new TransactionKiller(em1, timeToWait);
transactionKiller.start();
}
if(testMode2.equals("query")) {
Query query2 = em2.createQuery("SELECT emp FROM Employee emp WHERE emp.id = "+id).setLockMode(lockMode).
setHint(QueryHints.PESSIMISTIC_LOCK_SCOPE, PessimisticLockScope.EXTENDED);
if(isSelectForUpateNoWaitSupported()) {
query2.setHint(QueryHints.PESSIMISTIC_LOCK_TIMEOUT, 0);
}
emp2 = (Employee)query2.getSingleResult();
} else if(testMode2.equals("find")) {
emp2 = em2.find(Employee.class, id, lockMode, properties);
} else if(testMode2.equals("update_name")) {
em2.createNativeQuery("SELECT L_NAME FROM CMP3_EMPLOYEE"+lockingClauseBeforeWhereClause+" WHERE EMP_ID = "+id+lockingClauseAfterWhereClause).getSingleResult();
// em2.createNativeQuery("UPDATE CMP3_EMPLOYEE SET L_NAME = 'NEW' WHERE EMP_ID = "+id).executeUpdate();
} else if(testMode2.equals("update_salary")) {
em2.createNativeQuery("SELECT SALARY FROM CMP3_SALARY"+lockingClauseBeforeWhereClause+" WHERE EMP_ID = "+id+lockingClauseAfterWhereClause).getSingleResult();
// em2.createNativeQuery("UPDATE CMP3_SALARY SET SALARY = 1000 WHERE EMP_ID = "+id).executeUpdate();
} else if(testMode2.equals("remove_project")) {
em2.createNativeQuery("SELECT PROJECTS_PROJ_ID FROM CMP3_EMP_PROJ"+lockingClauseBeforeWhereClause+" WHERE EMPLOYEES_EMP_ID = "+id+lockingClauseAfterWhereClause).getResultList();
// em2.createNativeQuery("DELETE FROM CMP3_EMP_PROJ WHERE EMPLOYEES_EMP_ID = "+id).executeUpdate();
} else if(testMode2.equals("remove_respons")) {
em2.createNativeQuery("SELECT EMP_ID FROM CMP3_RESPONS"+lockingClauseBeforeWhereClause+" WHERE EMP_ID = "+id+lockingClauseAfterWhereClause).getResultList();
// em2.createNativeQuery("DELETE FROM CMP3_RESPONS WHERE EMP_ID = "+id).executeUpdate();
} else if(testMode2.equals("update_project")) {
em2.createNativeQuery("SELECT PROJ_NAME FROM CMP3_PROJECT"+lockingClauseBeforeWhereClause+" WHERE PROJ_ID = "+smallProjId+lockingClauseAfterWhereClause).getSingleResult();
// em2.createNativeQuery("UPDATE CMP3_PROJECT SET PROJ_NAME = 'NEW' WHERE PROJ_ID = "+smallProjId).executeUpdate();
} else if(testMode2.equals("update_respons")) {
em2.createNativeQuery("SELECT DESCRIPTION FROM CMP3_RESPONS"+lockingClauseBeforeWhereClause+" WHERE EMP_ID = "+id+lockingClauseAfterWhereClause).getResultList();
// em2.createNativeQuery("UPDATE CMP3_RESPONS SET DESCRIPTION = 'NEW' WHERE EMP_ID = "+id).executeUpdate();
} else {
emp2 = em2.find(Employee.class, id);
if(testMode2.equals("lock")) {
em2.lock(emp2, lockMode, properties);
} else if(testMode2.equals("refresh")) {
em2.refresh(emp2, lockMode, properties);
} else {
fail("Unknown testMode2 = " + testMode2);
}
}
// commitTransaction(em2);
boolean hasKilledTransaction = false;
if(transactionKiller != null) {
transactionKiller.shouldKillTransaction = false;
try {
transactionKiller.join();
} catch(InterruptedException intEx) {
// Ignore
}
hasKilledTransaction = transactionKiller.hasKilledTransaction;
}
// transaction killed by TransactionKiller is treated as PessimisticLockException
if(isExceptionExpected && !hasKilledTransaction) {
String localErrorMsg = testMode1 + (isObjCached ? " cached " : " ") + testMode2 + ": Exception was expected.";
ss.log(SessionLog.FINEST, SessionLog.QUERY, localErrorMsg, (Object[])null, null, false);
errorMsg += '\n' + localErrorMsg;
}
} catch (Exception ex) {
if(transactionKiller != null) {
transactionKiller.shouldKillTransaction = false;
try {
transactionKiller.join();
} catch(InterruptedException intEx) {
// Ignore
}
}
if(!isExceptionExpected) {
String localErrorMsg = testMode1 + (isObjCached ? " cached " : " ") + testMode2 + ": Unexpected exception: " + ex.getMessage();
ss.log(SessionLog.FINEST, SessionLog.QUERY, localErrorMsg, (Object[])null, null, false);
errorMsg += '\n' + localErrorMsg;
}
} finally {
if (isTransactionActive(em2)) {
rollbackTransaction(em2);
}
closeEntityManager(em2);
}
// commitTransaction(em1);
} finally {
if (isTransactionActive(em1)) {
rollbackTransaction(em1);
}
closeEntityManager(em1);
}
clearCache();
} // testModel2 loop
} // isObjectCached loop
} // testMode1 loop
// clean up
em = createEntityManager();
emp = em.find(Employee.class, id);
try {
beginTransaction(em);
Iterator<Project> it = emp.getProjects().iterator();
while(it.hasNext()) {
Project project = it.next();
it.remove();
em.remove(project);
}
em.remove(emp);
commitTransaction(em);
} finally {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
// test for bug 4676587:
// CTS: AFTER A REMOVE THEN A PERSIST ON THE SAME ENTITY, CONTAINS RETURNS FALSE
// The test performs persist, remove, persist sequence on a single object
// in different "flavours":
// doTransaction - the first persist happens in a separate transaction;
// doFirstFlush - perform flush after the first persist;
// doSecondFlush - perform flush after the remove;
// doThirdFlush - perform flush after the second persist;
// doRollback - rollbacks transaction that contains remove and the second persist.
public void testPersistRemoved() {
// create an Employee
String firstName = "testPesistRemoved";
Employee emp = new Employee();
emp.setFirstName(firstName);
// make sure no Employee with the specified firstName exists.
EntityManager em = createEntityManager();
beginTransaction(em);
try{
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
String errorMsg = "";
for (int i=0; i < 32; i++) {
int j = i;
boolean doRollback = j % 2 == 0;
j = j/2;
boolean doThirdFlush = j % 2 == 0;
j = j/2;
boolean doSecondFlush = j % 2 == 0;
j = j/2;
boolean doFirstFlush = j % 2 == 0;
j = j/2;
boolean doTransaction = j % 2 == 0;
if(doTransaction && doFirstFlush) {
continue;
}
String msg = "";
if(doTransaction) {
msg = "Transaction ";
}
if(doFirstFlush) {
msg = msg + "firstFlush ";
}
if(doSecondFlush) {
msg = msg + "secondFlush ";
}
if(doThirdFlush) {
msg = msg + "thirdFlush ";
}
if(doRollback) {
msg = msg + "RolledBack ";
}
String localErrorMsg = msg;
boolean exceptionWasThrown = false;
Integer empId = null;
beginTransaction(em);
try {
emp = new Employee();
emp.setFirstName(firstName);
// persist the Employee
em.persist(emp);
if(doTransaction) {
commitTransaction(em);
empId = emp.getId();
beginTransaction(em);
} else {
if(doFirstFlush) {
em.flush();
}
}
if(doTransaction) {
emp = em.find(Employee.class, empId);
}
// remove the Employee
em.remove(emp);
if(doSecondFlush) {
em.flush();
}
// persist the Employee
em.persist(emp);
if(doThirdFlush) {
em.flush();
}
} catch (RuntimeException ex) {
rollbackTransaction(em);
localErrorMsg = localErrorMsg + " " + ex.getMessage() + ";";
exceptionWasThrown = true;
}
boolean employeeShouldExist = doTransaction || !doRollback;
boolean employeeExists = false;
try{
if(!exceptionWasThrown) {
if(doRollback) {
rollbackTransaction(em);
} else {
commitTransaction(em);
}
if(doTransaction) {
Employee employeeReadFromCache = em.find(Employee.class, empId);
if(employeeReadFromCache == null) {
localErrorMsg = localErrorMsg + " employeeReadFromCache == null;";
}
}
List resultList = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = '"+firstName+"'").getResultList();
employeeExists = resultList.size() > 0;
if(employeeShouldExist) {
if(resultList.size() > 1) {
localErrorMsg = localErrorMsg + " resultList.size() > 1";
}
if(!employeeExists) {
localErrorMsg = localErrorMsg + " employeeReadFromDB == null;";
}
} else {
if(resultList.size() > 0) {
localErrorMsg = localErrorMsg + " employeeReadFromDB != null;";
}
}
}
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
}
// clean up
if(employeeExists || exceptionWasThrown) {
em = createEntityManager();
beginTransaction(em);
try{
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
rollbackTransaction(em);
throw ex;
}
}
if(!msg.equals(localErrorMsg)) {
errorMsg = errorMsg + "i="+Integer.toString(i)+": "+ localErrorMsg + " ";
}
}
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
public void testPersistManagedException(){
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
em.persist(emp);
em.flush();
Integer id = emp.getId();
emp = new Employee();
emp.setId(id);
boolean caughtException = false;
try{
em.persist(emp);
} catch (EntityExistsException e){
caughtException = true;
}
emp = em.find(Employee.class, id);
em.remove(emp);
rollbackTransaction(em);
assertTrue("EntityExistsException was not thrown for an existing Employee.", caughtException);
}
public void testPersistManagedNoException(){
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
em.persist(emp);
em.flush();
Integer id = emp.getId();
Address address = new Address();
emp.setAddress(address);
boolean caughtException = false;
try{
em.persist(emp);
} catch (EntityExistsException e){
caughtException = true;
}
emp = em.find(Employee.class, id);
em.remove(emp);
commitTransaction(em);
assertFalse("EntityExistsException was thrown for a registered Employee.", caughtException);
}
public void testDetachManagedObject() {
// Don't run this test in a JPA 1.0 environment.
if (! isJPA10()) {
EntityManager em = createEntityManager();
// create test data
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("beforePersist");
em.persist(emp);
Integer id = emp.getId();
commitTransaction(em);
// Test that 'detach()' removes 'emp' from the persistence context
beginTransaction(em);
em.detach(emp);
assertFalse("could not detach managed object", em.contains(emp));
// clean up
emp = em.find(Employee.class, id);
em.remove(emp);
commitTransaction(em);
}
}
public void testCascadeDetach() {
// Don't run this test in a JPA 1.0 environment.
if (! isJPA10()) {
EntityManager em = createEntityManager();
Employee emp = (Employee)em.createQuery("Select e from Employee e where e.managedEmployees is not empty").getResultList().get(0);
emp.getManagedEmployees().size();
em.detach(emp);
assertFalse("Did not cascade detach", em.contains(emp.getManagedEmployees().iterator().next()));
}
}
//detaching an non-managed object should not throw any exception.
public void testDetachNonManagedObject() {
// Don't run this test in a JPA 1.0 environment.
if (! isJPA10()) {
EntityManager em = createEntityManager();
// Create test data
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("beforePersist");
boolean caughtException = false;
// detach the object
em.detach(emp);
em.persist(emp);
// Deleting the object
em.remove(emp);
commitTransaction(em);
assertFalse("Cannot_detach_Object Exception was thrown for a non-managed Entity", caughtException);
}
}
// test for bug 4676587:
// CTS: AFTER A REMOVE THEN A PERSIST ON THE SAME ENTITY, CONTAINS RETURNS FALSE
public void testRemoveFlushPersistContains() {
// create an Employee
String firstName = "testRemoveFlushPersistContains";
Employee emp = new Employee();
emp.setFirstName(firstName);
// make sure no Employee with the specified firstName exists.
EntityManager em = createEntityManager();
beginTransaction(em);
try{
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// persist
beginTransaction(em);
try{
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// remove, flush, persist, contains
boolean contains = false;
beginTransaction(em);
try{
emp = em.find(Employee.class, emp.getId());
em.remove(emp);
em.flush();
em.persist(emp);
contains = em.contains(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// clean up
beginTransaction(em);
try{
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
assertTrue("contains==false", contains);
}
// test for bug 4742161:
// CTS: OBJECTS REMOVED AND THEN FLUSHED ARE RETURNED BY QUERIES AFTER THE FLUSH
public void testRemoveFlushFind() {
// create an Employee
String firstName = "testRemoveFlushFind";
Employee emp = new Employee();
emp.setFirstName(firstName);
// make sure no Employee with the specified firstName exists.
EntityManager em = createEntityManager();
beginTransaction(em);
try{
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// persist
beginTransaction(em);
try{
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// remove, flush, persist, contains
boolean foundAfterFlush = true;
boolean foundBeforeFlush = true;
beginTransaction(em);
try{
emp = em.find(Employee.class, emp.getId());
em.remove(emp);
Employee empFound = em.find(Employee.class, emp.getId());
foundBeforeFlush = empFound != null;
em.flush();
empFound = em.find(Employee.class, emp.getId());
foundAfterFlush = empFound != null;
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// clean up
beginTransaction(em);
try{
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
assertFalse("removed object found", foundBeforeFlush);
assertFalse("removed object found after flush", foundAfterFlush);
}
// test for bug 4681287:
// CTS: EXCEPTION EXPECTED ON FIND() IF PK PASSED IN != ATTRIBUTE TYPE
public void testFindWithWrongTypePk() {
EntityManager em = createEntityManager();
try {
em.find(Employee.class, "1");
} catch (IllegalArgumentException ilEx) {
return;
} catch (Exception ex) {
fail("Wrong exception thrown: " + ex.getMessage());
return;
}finally{
closeEntityManager(em);
}
fail("No exception thrown");
}
public void testFindWithNullPk() {
EntityManager em = createEntityManager();
try {
em.find(Employee.class, null);
} catch (IllegalArgumentException iae) {
return;
} catch (Exception e) {
fail("Wrong exception type thrown: " + e.getClass());
}finally{
closeEntityManager(em);
}
fail("No exception thrown when null PK used in find operation.");
}
public void testFindWithProperties(){
// find with properties not supported on 1.0
if (! isJPA10()) {
Employee employee = new Employee();
employee.setFirstName("Marc");
HashMap<String, Object> queryhints=new HashMap<String, Object>();
EntityManager em = createEntityManager();
try {
beginTransaction(em);
em.persist(employee);
commitTransaction(em);
beginTransaction(em);
int empId=employee.getId();
Employee e1=em.find(Employee.class,empId);
e1.setFirstName("testfind");
queryhints.put(QueryHints.REFRESH, "TRUE");
Employee e2= (Employee)em.find(Employee.class,empId ,queryhints);
assertFalse(e2.getFirstName().equals("testfind"));
commitTransaction(em);
} catch (IllegalArgumentException iae) {
return;
} catch (Exception e) {
fail("Wrong exception type thrown: " + e.getClass());
}finally{
closeEntityManager(em);
}
}
}
public void testCheckVersionOnMerge() {
Employee employee = new Employee();
employee.setFirstName("Marc");
EntityManager em = createEntityManager();
try{
beginTransaction(em);
em.persist(employee);
commitTransaction(em);
em.clear();
beginTransaction(em);
Employee empClone = em.find(Employee.class, employee.getId());
empClone.setFirstName("Guy");
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
fail("Exception caught during test setup " + ex);
}
try {
beginTransaction(em);
em.merge(employee);
commitTransaction(em);
} catch (OptimisticLockException e) {
rollbackTransaction(em);
closeEntityManager(em);
return;
} catch (RuntimeException ex) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
fail("Wrong exception thrown: " + ex.getMessage());
}
fail("No exception thrown");
}
public void testClear(){
Employee employee = new Employee();
EntityManager em = createEntityManager();
beginTransaction(em);
try{
em.persist(employee);
commitTransaction(em);
em.clear();
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
boolean cleared = !em.contains(employee);
closeEntityManager(em);
assertTrue("EntityManager not properly cleared", cleared);
}
// Test using PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT option to avoid the resume on commit.
public void testCloseOnCommit() {
// Properties only works in jse.
if (isOnServer()) {
return;
}
Map properties = new HashMap();
properties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT, "true");
EntityManager em = createEntityManager(properties);
beginTransaction(em);
try {
Employee emp = new Employee();
emp.setFirstName("Douglas");
emp.setLastName("McRae");
em.persist(emp);
commitTransaction(em);
verifyObjectInCacheAndDatabase(emp);
closeEntityManager(em);
em = createEntityManager(properties);
beginTransaction(em);
emp = em.find(Employee.class, emp.getId());
emp.setFirstName("Joe");
commitTransaction(em);
verifyObjectInCacheAndDatabase(emp);
em = createEntityManager(properties);
beginTransaction(em);
emp = em.find(Employee.class, emp.getId());
em.remove(emp);
commitTransaction(em);
closeEntityManager(em);
} catch (RuntimeException exception) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw exception;
}
}
// Test using PERSISTENCE_CONTEXT_PERSIST_ON_COMMIT option to avoid the discover on commit.
public void testPersistOnCommit() {
// Properties only works in jse.
if (isOnServer()) {
return;
}
Map properties = new HashMap();
properties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_PERSIST_ON_COMMIT, "false");
EntityManager em = createEntityManager(properties);
beginTransaction(em);
try {
Employee emp = new Employee();
emp.setFirstName("Douglas");
emp.setLastName("McRae");
em.persist(emp);
commitTransaction(em);
verifyObjectInCacheAndDatabase(emp);
closeEntityManager(em);
em = createEntityManager(properties);
beginTransaction(em);
Address address = new Address();
emp = em.find(Employee.class, emp.getId());
emp.setAddress(address);
em.persist(address);
commitTransaction(em);
verifyObjectInCacheAndDatabase(emp);
em = createEntityManager(properties);
beginTransaction(em);
emp = em.find(Employee.class, emp.getId());
em.remove(emp);
commitTransaction(em);
closeEntityManager(em);
} catch (RuntimeException exception) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw exception;
}
}
// Test Not using the persist operation on commit.
public void testNoPersistOnCommit() {
// Properties only works in jse.
if (isOnServer()) {
return;
}
EntityManager em = createEntityManager();
beginTransaction(em);
Employee employee = new Employee();
employee.setLastName("SomeName");
Address addr = new Address();
addr.setCity("Douglas");
try {
em.persist(employee);
commitTransaction(em);
verifyObjectInCacheAndDatabase(employee);
closeEntityManager(em);
em = createEntityManager();
beginTransaction(em);
((RepeatableWriteUnitOfWork)JpaHelper.getEntityManager(em).getUnitOfWork()).setDiscoverUnregisteredNewObjectsWithoutPersist(true);
employee = em.find(Employee.class, employee.getId());
employee.setAddress(addr);
addr.getEmployees().add(employee);
commitTransaction(em);
verifyObjectInCacheAndDatabase(employee);
closeEntityManager(em);
em = createEntityManager();
clearCache();
beginTransaction(em);
((RepeatableWriteUnitOfWork)JpaHelper.getEntityManager(em).getUnitOfWork()).setDiscoverUnregisteredNewObjectsWithoutPersist(true);
employee = em.find(Employee.class, employee.getId());
employee.getAddress().setCountry("country");
employee.getAddress().getEmployees().size();
employee.setAddress((Address)null);
em.remove(employee);
commitTransaction(em);
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, employee.getId());
assertNull("Employee Not Deleted", employee);
commitTransaction(em);
closeEntityManager(em);
} catch (RuntimeException exception) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw exception;
} finally {
try {
em = createEntityManager();
clearCache();
beginTransaction(em);
em.remove(em.find(Address.class, addr.getId()));
commitTransaction(em);
} catch (RuntimeException ex) {
// ignore
}
}
}
// Test Not using the persist operation on commit.
public void testNoPersistOnCommitProperties() {
// Properties only works in jse.
if (isOnServer()) {
return;
}
Map properties = new HashMap();
properties.putAll(JUnitTestCaseHelper.getDatabaseProperties());
properties.put(EntityManagerProperties.PERSISTENCE_CONTEXT_COMMIT_WITHOUT_PERSIST_RULES, "true");
EntityManager em = createEntityManager(properties);
beginTransaction(em);
Employee employee = new Employee();
employee.setLastName("SomeName");
Address addr = new Address();
addr.setCity("Douglas");
try {
em.persist(employee);
commitTransaction(em);
verifyObjectInCacheAndDatabase(employee);
closeEntityManager(em);
em = createEntityManager(properties);
beginTransaction(em);
employee = em.find(Employee.class, employee.getId());
employee.setAddress(addr);
addr.getEmployees().add(employee);
commitTransaction(em);
verifyObjectInCacheAndDatabase(employee);
closeEntityManager(em);
em = createEntityManager(properties);
clearCache();
beginTransaction(em);
employee = em.find(Employee.class, employee.getId());
employee.getAddress().setCountry("country");
employee.getAddress().getEmployees().size();
employee.setAddress((Address)null);
em.remove(employee);
commitTransaction(em);
em = createEntityManager(properties);
beginTransaction(em);
employee = em.find(Employee.class, employee.getId());
assertNull("Employee Not Deleted", employee);
commitTransaction(em);
closeEntityManager(em);
} catch (RuntimeException exception) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw exception;
} finally {
try {
em = createEntityManager();
clearCache();
beginTransaction(em);
em.remove(em.find(Address.class, addr.getId()));
commitTransaction(em);
} catch (RuntimeException ex) {
// ignore
}
}
}
// Test Not using the persist operation on commit.
public void testNoPersistOnFlushProperties() {
// Properties only works in jse.
if (isOnServer()) {
return;
}
Map properties = new HashMap();
properties.putAll(JUnitTestCaseHelper.getDatabaseProperties());
properties.put(EntityManagerProperties.PERSISTENCE_CONTEXT_COMMIT_WITHOUT_PERSIST_RULES, "true");
EntityManager em = createEntityManager(properties);
beginTransaction(em);
Employee employee = new Employee();
employee.setLastName("SomeName");
Address addr = new Address();
addr.setCity("Douglas");
try {
em.persist(employee);
em.flush();
commitTransaction(em);
verifyObjectInCacheAndDatabase(employee);
closeEntityManager(em);
em = createEntityManager(properties);
beginTransaction(em);
employee = em.find(Employee.class, employee.getId());
employee.setAddress(addr);
addr.getEmployees().add(employee);
em.flush();
commitTransaction(em);
verifyObjectInCacheAndDatabase(employee);
closeEntityManager(em);
em = createEntityManager(properties);
clearCache();
beginTransaction(em);
employee = em.find(Employee.class, employee.getId());
employee.getAddress().setCountry("country");
employee.getAddress().getEmployees().size();
employee.setAddress((Address)null);
em.remove(employee);
commitTransaction(em);
em = createEntityManager(properties);
beginTransaction(em);
employee = em.find(Employee.class, employee.getId());
assertNull("Employee Not Deleted", employee);
commitTransaction(em);
closeEntityManager(em);
} catch (RuntimeException exception) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw exception;
} finally {
try {
em = createEntityManager();
clearCache();
beginTransaction(em);
em.remove(em.find(Address.class, addr.getId()));
commitTransaction(em);
} catch (RuntimeException ex) {
// ignore
}
}
}
// Test using PERSISTENCE_CONTEXT_FLUSH_MODE option.
public void testFlushMode() {
// Properties only works in jse.
if (isOnServer()) {
return;
}
Map properties = new HashMap();
properties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_FLUSH_MODE, "COMMIT");
EntityManager em = createEntityManager(properties);
beginTransaction(em);
try {
Employee emp = new Employee();
emp.setFirstName("Douglas");
emp.setLastName("McRae");
em.persist(emp);
Query query = em.createQuery("Select e from Employee e where e.id = " + emp.getId());
if (query.getResultList().size() > 0) {
fail("Query triggered flush.");
}
rollbackTransaction(em);
closeEntityManager(em);
} catch (RuntimeException exception) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw exception;
}
}
public void testClearWithFlush(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
Employee emp = new Employee();
emp.setFirstName("Douglas");
emp.setLastName("McRae");
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
clearCache();
EntityManager localEm = createEntityManager();
beginTransaction(localEm);
Employee emp = null;
String originalName = "";
boolean cleared, updated, reset = false;
try{
Query query = localEm.createQuery("Select e FROM Employee e where e.firstName is not null");
emp = (Employee)query.getResultList().get(0);
originalName = emp.getFirstName();
emp.setFirstName("Bobster");
localEm.flush();
localEm.clear();
//this test is testing the cache not the database
commitTransaction(localEm);
cleared = !localEm.contains(emp);
emp = localEm.find(Employee.class, emp.getId());
updated = emp.getFirstName().equals("Bobster");
closeEntityManager(localEm);
} catch (RuntimeException exception) {
if (isTransactionActive(localEm)) {
rollbackTransaction(localEm);
}
closeEntityManager(localEm);
throw exception;
} finally {
//now clean up
localEm = createEntityManager();
beginTransaction(localEm);
emp = localEm.find(Employee.class, emp.getId());
emp.setFirstName(originalName);
commitTransaction(localEm);
emp = localEm.find(Employee.class, emp.getId());
reset = emp.getFirstName().equals(originalName);
closeEntityManager(localEm);
}
assertTrue("EntityManager not properly cleared", cleared);
assertTrue("flushed data not merged", updated);
assertTrue("unable to reset", reset);
}
// gf3596: transactions never release memory until commit, so JVM eventually crashes
// The test verifies that there's no stale data read after transaction.
// Because there were no TopLinkProperties.FLUSH_CLEAR_CACHE property passed
// while creating either EM or EMF the tested behavior corresponds to
// the default property value FlushClearCache.DropInvalidate.
// Note that the same test would pass with FlushClearCache.Merge
// (in that case all changes are merges into the shared cache after transaction committed),
// but the test would fail with FlushClearCache.Drop - that mode just drops em cache
// without doing any invalidation of the shared cache.
public void testClearWithFlush2() {
String firstName = "testClearWithFlush2";
// setup
// create employee and manager - and then remove them from the shared cache
EntityManager em = createEntityManager();
int employee_1_NotInCache_id = 0;
int employee_2_NotInCache_id = 0;
int manager_NotInCache_id = 0;
beginTransaction(em);
try {
Employee employee_1_NotInCache = new Employee();
employee_1_NotInCache.setFirstName(firstName);
employee_1_NotInCache.setLastName("Employee_1_NotInCache");
Employee employee_2_NotInCache = new Employee();
employee_2_NotInCache.setFirstName(firstName);
employee_2_NotInCache.setLastName("Employee_2_NotInCache");
Employee manager_NotInCache = new Employee();
manager_NotInCache.setFirstName(firstName);
manager_NotInCache.setLastName("Manager_NotInCache");
// employee_1 is manager, employee_2 is not
manager_NotInCache.addManagedEmployee(employee_1_NotInCache);
// persist
em.persist(manager_NotInCache);
em.persist(employee_1_NotInCache);
em.persist(employee_2_NotInCache);
commitTransaction(em);
employee_1_NotInCache_id = employee_1_NotInCache.getId();
employee_2_NotInCache_id = employee_2_NotInCache.getId();
manager_NotInCache_id = manager_NotInCache.getId();
} catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// remove both manager_NotInCache and employee_NotInCache from the shared cache
clearCache();
// setup
// create employee and manager - and keep them in the shared cache
em = createEntityManager();
int employee_1_InCache_id = 0;
int employee_2_InCache_id = 0;
int manager_InCache_id = 0;
beginTransaction(em);
try {
Employee employee_1_InCache = new Employee();
employee_1_InCache.setFirstName(firstName);
employee_1_InCache.setLastName("Employee_1_InCache");
Employee employee_2_InCache = new Employee();
employee_2_InCache.setFirstName(firstName);
employee_2_InCache.setLastName("Employee_2_InCache");
Employee manager_InCache = new Employee();
manager_InCache.setFirstName(firstName);
manager_InCache.setLastName("Manager_InCache");
// employee_1 is manager, employee_2 is not
manager_InCache.addManagedEmployee(employee_1_InCache);
// persist
em.persist(manager_InCache);
em.persist(employee_1_InCache);
em.persist(employee_2_InCache);
commitTransaction(em);
employee_1_InCache_id = employee_1_InCache.getId();
employee_2_InCache_id = employee_2_InCache.getId();
manager_InCache_id = manager_InCache.getId();
} catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// test
// create new employee and manager, change existing ones, flush, clear
em = createEntityManager();
int employee_1_New_id = 0;
int employee_2_New_id = 0;
int employee_3_New_id = 0;
int employee_4_New_id = 0;
int manager_New_id = 0;
beginTransaction(em);
try {
Employee employee_1_New = new Employee();
employee_1_New.setFirstName(firstName);
employee_1_New.setLastName("Employee_1_New");
em.persist(employee_1_New);
employee_1_New_id = employee_1_New.getId();
Employee employee_2_New = new Employee();
employee_2_New.setFirstName(firstName);
employee_2_New.setLastName("Employee_2_New");
em.persist(employee_2_New);
employee_2_New_id = employee_2_New.getId();
Employee employee_3_New = new Employee();
employee_3_New.setFirstName(firstName);
employee_3_New.setLastName("Employee_3_New");
em.persist(employee_3_New);
employee_3_New_id = employee_3_New.getId();
Employee employee_4_New = new Employee();
employee_4_New.setFirstName(firstName);
employee_4_New.setLastName("Employee_4_New");
em.persist(employee_4_New);
employee_4_New_id = employee_4_New.getId();
Employee manager_New = new Employee();
manager_New.setFirstName(firstName);
manager_New.setLastName("Manager_New");
em.persist(manager_New);
manager_New_id = manager_New.getId();
// find and update all objects created during setup
Employee employee_1_NotInCache = em.find(Employee.class, employee_1_NotInCache_id);
employee_1_NotInCache.setLastName(employee_1_NotInCache.getLastName() + "_Updated");
Employee employee_2_NotInCache = em.find(Employee.class, employee_2_NotInCache_id);
employee_2_NotInCache.setLastName(employee_2_NotInCache.getLastName() + "_Updated");
Employee manager_NotInCache = em.find(Employee.class, manager_NotInCache_id);
manager_NotInCache.setLastName(manager_NotInCache.getLastName() + "_Updated");
Employee employee_1_InCache = em.find(Employee.class, employee_1_InCache_id);
employee_1_InCache.setLastName(employee_1_InCache.getLastName() + "_Updated");
Employee employee_2_InCache = em.find(Employee.class, employee_2_InCache_id);
employee_2_InCache.setLastName(employee_2_InCache.getLastName() + "_Updated");
Employee manager_InCache = em.find(Employee.class, manager_InCache_id);
manager_InCache.setLastName(manager_InCache.getLastName() + "_Updated");
manager_NotInCache.addManagedEmployee(employee_1_New);
manager_InCache.addManagedEmployee(employee_2_New);
manager_New.addManagedEmployee(employee_3_New);
manager_New.addManagedEmployee(employee_2_NotInCache);
manager_New.addManagedEmployee(employee_2_InCache);
// flush
em.flush();
// clear and commit
em.clear();
commitTransaction(em);
} catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// verify
String errorMsg = "";
em = createEntityManager();
// find and verify all objects created during setup and test
Employee manager_NotInCache = em.find(Employee.class, manager_NotInCache_id);
if(!manager_NotInCache.getLastName().endsWith("_Updated")) {
errorMsg = errorMsg + "manager_NotInCache lastName NOT updated; ";
}
Iterator it = manager_NotInCache.getManagedEmployees().iterator();
while(it.hasNext()) {
Employee emp = (Employee)it.next();
if(emp.getId() == employee_1_NotInCache_id) {
if(!emp.getLastName().endsWith("_Updated")) {
errorMsg = errorMsg + "employee_1_NotInCache lastName NOT updated; ";
}
} else if(emp.getId() == employee_1_New_id) {
if(!emp.getLastName().endsWith("_New")) {
errorMsg = errorMsg + "employee_1_New lastName wrong; ";
}
} else {
errorMsg = errorMsg + "manager_NotInCache has unexpected employee: lastName = " + emp.getLastName();
}
}
if(manager_NotInCache.getManagedEmployees().size() != 2) {
errorMsg = errorMsg + "manager_NotInCache.getManagedEmployees().size() != 2; size = " + manager_NotInCache.getManagedEmployees().size();
}
Employee manager_InCache = em.find(Employee.class, manager_InCache_id);
if(!manager_InCache.getLastName().endsWith("_Updated")) {
errorMsg = errorMsg + "manager_InCache lastName NOT updated; ";
}
it = manager_InCache.getManagedEmployees().iterator();
while(it.hasNext()) {
Employee emp = (Employee)it.next();
if(emp.getId() == employee_1_InCache_id) {
if(!emp.getLastName().endsWith("_Updated")) {
errorMsg = errorMsg + "employee_1_InCache lastName NOT updated; ";
}
} else if(emp.getId() == employee_2_New_id) {
if(!emp.getLastName().endsWith("_New")) {
errorMsg = errorMsg + "employee_2_New lastName wrong; ";
}
} else {
errorMsg = errorMsg + "manager_InCache has unexpected employee: lastName = " + emp.getLastName();
}
}
if(manager_InCache.getManagedEmployees().size() != 2) {
errorMsg = errorMsg + "manager_InCache.getManagedEmployees().size() != 2; size = " + manager_InCache.getManagedEmployees().size();
}
Employee manager_New = em.find(Employee.class, manager_New_id);
if(!manager_New.getLastName().endsWith("_New")) {
errorMsg = errorMsg + "manager_New lastName wrong; ";
}
it = manager_New.getManagedEmployees().iterator();
while(it.hasNext()) {
Employee emp = (Employee)it.next();
if(emp.getId() == employee_2_NotInCache_id) {
if(!emp.getLastName().endsWith("_Updated")) {
errorMsg = errorMsg + "employee_2_NotInCache_id lastName NOT updated; ";
}
} else if(emp.getId() == employee_2_InCache_id) {
if(!emp.getLastName().endsWith("_Updated")) {
errorMsg = errorMsg + "employee_2_InCache_id lastName NOT updated; ";
}
} else if(emp.getId() == employee_3_New_id) {
if(!emp.getLastName().endsWith("_New")) {
errorMsg = errorMsg + "employee_3_New lastName wrong; ";
}
} else {
errorMsg = errorMsg + "manager_New has unexpected employee: lastName = " + emp.getLastName();
}
}
if(manager_New.getManagedEmployees().size() != 3) {
errorMsg = errorMsg + "manager_InCache.getManagedEmployees().size() != 3; size = " + manager_InCache.getManagedEmployees().size();
}
Employee employee_4_New = em.find(Employee.class, employee_4_New_id);
if(!employee_4_New.getLastName().endsWith("_New")) {
errorMsg = errorMsg + "employee_4_New lastName wrong; ";
}
closeEntityManager(em);
// clean up
// remove all objects created during this test and clear the cache.
em = createEntityManager();
try {
beginTransaction(em);
List<Employee> list = em.createQuery("Select e from Employee e where e.firstName = '"+firstName+"'").getResultList();
Iterator<Employee> i = list.iterator();
while (i.hasNext()){
Employee e = i.next();
if (e.getManager() != null){
e.getManager().removeManagedEmployee(e);
e.setManager(null);
}
em.remove(e);
}
commitTransaction(em);
} catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
// ignore exception in clean up in case there's an error in test
if(errorMsg.length() == 0) {
throw ex;
}
}
clearCache();
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
/** ToDo: move these to a memory test suite.
// gf3596: transactions never release memory until commit, so JVM eventually crashes.
// Attempts to compare memory consumption between the two FlushClearCache modes.
// If the values changed to be big enough (in TopLink I tried nFlashes = 30 , nInsertsPerFlush = 10000)
// internalMassInsertFlushClear(FlushClearCache.Merge, 30, 10000) will run out of memory,
// but internalMassInsertFlushClear(null, 30, 10000) will still be ok.
public void testMassInsertFlushClear() {
int nFlushes = 20;
int nPersistsPerFlush = 50;
long[] defaultFreeMemoryDelta = internalMassInsertFlushClear(null, nFlushes, nPersistsPerFlush);
long[] mergeFreeMemoryDelta = internalMassInsertFlushClear(FlushClearCache.Merge, nFlushes, nPersistsPerFlush);
// disregard the flush if any of the two FreeMemoryDeltas is negative - clearly that's gc artefact.
int nEligibleFlushes = 0;
long diff = 0;
for(int nFlush = 0; nFlush < nFlushes; nFlush++) {
if(defaultFreeMemoryDelta[nFlush] >= 0 && mergeFreeMemoryDelta[nFlush] >= 0) {
nEligibleFlushes++;
diff = diff + mergeFreeMemoryDelta[nFlush] - defaultFreeMemoryDelta[nFlush];
}
}
long lowEstimateOfBytesPerObject = 200;
long diffPerObject = diff / (nEligibleFlushes * nPersistsPerFlush);
if(diffPerObject < lowEstimateOfBytesPerObject) {
fail("difference in freememory per object persisted " + diffPerObject + " is lower than lowEstimateOfBytesPerObject " + lowEstimateOfBytesPerObject);
}
}
// memory usage with different FlushClearCache modes.
protected long[] internalMassInsertFlushClear(String propValue, int nFlushes, int nPersistsPerFlush) {
// set logDebug to true to output the freeMemory values after each flush/clear
boolean logDebug = false;
String firstName = "testMassInsertFlushClear";
EntityManager em;
if(propValue == null) {
// default value FlushClearCache.DropInvalidate will be used
em = createEntityManager();
if(logDebug) {
System.out.println(FlushClearCache.DEFAULT);
}
} else {
HashMap map = new HashMap(1);
map.put(PersistenceUnitProperties.FLUSH_CLEAR_CACHE, propValue);
em = getEntityManagerFactory().createEntityManager(map);
if(logDebug) {
System.out.println(propValue);
}
}
// For enhance accuracy of memory measuring allocate everything first:
// make a first run and completely disregard its results - somehow
// that get freeMemory function to report more accurate results in the second run -
// which is the only one used to calculate results.
if(logDebug) {
System.out.println("The first run is ignored");
}
long freeMemoryOld;
long freeMemoryNew;
long[] freeMemoryDelta = new long[nFlushes];
beginTransaction(em);
try {
// Try to force garbage collection NOW.
System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();
freeMemoryOld = Runtime.getRuntime().freeMemory();
if(logDebug) {
System.out.println("initial freeMemory = " + freeMemoryOld);
}
for(int nFlush = 0; nFlush < nFlushes; nFlush++) {
for(int nPersist = 0; nPersist < nPersistsPerFlush; nPersist++) {
Employee emp = new Employee();
emp.setFirstName(firstName);
int nEmployee = nFlush * nPersistsPerFlush + nPersist;
emp.setLastName("lastName_" + Integer.toString(nEmployee));
em.persist(emp);
}
em.flush();
em.clear();
// Try to force garbage collection NOW.
System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();
freeMemoryNew = Runtime.getRuntime().freeMemory();
freeMemoryDelta[nFlush] = freeMemoryOld - freeMemoryNew;
freeMemoryOld = freeMemoryNew;
if(logDebug) {
System.out.println(nFlush +": after flush/clear freeMemory = " + freeMemoryNew);
}
}
} finally {
rollbackTransaction(em);
em = null;
}
if(logDebug) {
System.out.println("The second run");
}
// now allocate again - with gc and memory measuring
if(propValue == null) {
// default value FlushClearCache.DropInvalidate will be used
em = createEntityManager();
} else {
HashMap map = new HashMap(1);
map.put(PersistenceUnitProperties.FLUSH_CLEAR_CACHE, propValue);
em = getEntityManagerFactory().createEntityManager(map);
}
beginTransaction(em);
try {
// Try to force garbage collection NOW.
System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();
freeMemoryOld = Runtime.getRuntime().freeMemory();
if(logDebug) {
System.out.println("initial freeMemory = " + freeMemoryOld);
}
for(int nFlush = 0; nFlush < nFlushes; nFlush++) {
for(int nPersist = 0; nPersist < nPersistsPerFlush; nPersist++) {
Employee emp = new Employee();
emp.setFirstName(firstName);
int nEmployee = nFlush * nPersistsPerFlush + nPersist;
emp.setLastName("lastName_" + Integer.toString(nEmployee));
em.persist(emp);
}
em.flush();
em.clear();
// Try to force garbage collection NOW.
System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();System.gc();
freeMemoryNew = Runtime.getRuntime().freeMemory();
freeMemoryDelta[nFlush] = freeMemoryOld - freeMemoryNew;
freeMemoryOld = freeMemoryNew;
if(logDebug) {
System.out.println(nFlush +": after flush/clear freeMemory = " + freeMemoryNew);
}
}
return freeMemoryDelta;
} finally {
rollbackTransaction(em);
}
}*/
public void testClearInTransaction(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
Employee emp = new Employee();
emp.setFirstName("Tommy");
emp.setLastName("Marsh");
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
clearCache();
em = createEntityManager();
beginTransaction(em);
Employee emp = null;
String originalName = "";
try {
Query query = em.createQuery("Select e FROM Employee e where e.firstName is not null");
emp = (Employee)query.getResultList().get(0);
originalName = emp.getFirstName();
emp.setFirstName("Bobster");
em.clear();
commitTransaction(em);
} catch (RuntimeException ex) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
boolean cleared = !em.contains(emp);
emp = em.find(Employee.class, emp.getId());
closeEntityManager(em);
assertTrue("EntityManager not properly cleared", cleared);
assertTrue("Employee was updated although EM was cleared", emp.getFirstName().equals(originalName));
}
public void testExtendedPersistenceContext() {
// Extended persistence context are not supported in the server.
// TODO: make this test use an extended entity manager in the server by creating from the factory and joining transaction.
if (isOnServer()) {
return;
}
String firstName = "testExtendedPersistenceContext";
int originalSalary = 0;
Employee empNew = new Employee();
empNew.setFirstName(firstName);
empNew.setLastName("new");
empNew.setSalary(originalSalary);
Employee empToBeRemoved = new Employee();
empToBeRemoved.setFirstName(firstName);
empToBeRemoved.setLastName("toBeRemoved");
empToBeRemoved.setSalary(originalSalary);
Employee empToBeRefreshed = new Employee();
empToBeRefreshed.setFirstName(firstName);
empToBeRefreshed.setLastName("toBeRefreshed");
empToBeRefreshed.setSalary(originalSalary);
Employee empToBeMerged = new Employee();
empToBeMerged.setFirstName(firstName);
empToBeMerged.setLastName("toBeMerged");
empToBeMerged.setSalary(originalSalary);
// setup: make sure no Employee with the specified firstName exists and create the existing employees.
EntityManager em = createEntityManager();
beginTransaction(em);
try{
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
beginTransaction(em);
em.persist(empToBeRemoved);
em.persist(empToBeRefreshed);
em.persist(empToBeMerged);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
closeEntityManager(em);
clearCache();
// create entityManager with extended Persistence Context.
em = createEntityManager();
try {
// first test
// without starting transaction persist, remove, refresh, merge
em.persist(empNew);
Employee empToBeRemovedExtended = em.find(Employee.class, empToBeRemoved.getId());
em.remove(empToBeRemovedExtended);
Employee empToBeRefreshedExtended = em.find(Employee.class, empToBeRefreshed.getId());
int newSalary = 100;
// Use another EntityManager to alter empToBeRefreshed in the db
beginTransaction(em);
empToBeRefreshed = em.find(Employee.class, empToBeRefreshed.getId());
empToBeRefreshed.setSalary(newSalary);
commitTransaction(em);
// now refesh
em.refresh(empToBeRefreshedExtended);
Employee empToBeMergedExtended = em.find(Employee.class, empToBeMerged.getId());
// alter empToBeRefreshed
empToBeMerged.setSalary(newSalary);
// now merge
em.merge(empToBeMerged);
// begin and commit transaction
beginTransaction(em);
commitTransaction(em);
// verify objects are correct in the PersistenceContext after transaction
if(!em.contains(empNew)) {
fail("empNew gone from extended PersistenceContext after transaction committed");
}
if(em.contains(empToBeRemovedExtended)) {
fail("empToBeRemovedExtended still in extended PersistenceContext after transaction committed");
}
if(!em.contains(empToBeRefreshedExtended)) {
fail("empToBeRefreshedExtended gone from extended PersistenceContext after transaction committed");
} else if(empToBeRefreshedExtended.getSalary() != newSalary) {
fail("empToBeRefreshedExtended still has the original salary after transaction committed");
}
if(!em.contains(empToBeMergedExtended)) {
fail("empToBeMergedExtended gone from extended PersistenceContext after transaction committed");
} else if(empToBeMergedExtended.getSalary() != newSalary) {
fail("empToBeMergedExtended still has the original salary after transaction committed");
}
// verify objects are correct in the db after transaction
clearCache();
Employee empNewFound = em.find(Employee.class, empNew.getId());
if(empNewFound == null) {
fail("empNew not in the db after transaction committed");
}
Employee empToBeRemovedFound = em.find(Employee.class, empToBeRemoved.getId());
if(empToBeRemovedFound != null) {
fail("empToBeRemoved is still in the db after transaction committed");
}
Employee empToBeRefreshedFound = em.find(Employee.class, empToBeRefreshed.getId());
if(empToBeRefreshedFound == null) {
fail("empToBeRefreshed not in the db after transaction committed");
} else if(empToBeRefreshedFound.getSalary() != newSalary) {
fail("empToBeRefreshed still has the original salary in the db after transaction committed");
}
Employee empToBeMergedFound = em.find(Employee.class, empToBeMerged.getId());
if(empToBeMergedFound == null) {
fail("empToBeMerged not in the db after transaction committed");
} else if(empToBeMergedFound.getSalary() != newSalary) {
fail("empToBeMerged still has the original salary in the db after transaction committed");
}
// second test
// without starting transaction persist, remove, refresh, merge for the second time:
// now return to the original state of the objects:
// remove empNew, persist empToBeRemoved, set empToBeRefreshed and empToBeMerged the original salary.
em.persist(empToBeRemoved);
em.remove(empNew);
// Use another EntityManager to alter empToBeRefreshed in the db
beginTransaction(em);
empToBeRefreshed = em.find(Employee.class, empToBeRefreshed.getId());
empToBeRefreshed.setSalary(originalSalary);
commitTransaction(em);
// now refesh
em.refresh(empToBeRefreshedExtended);
// alter empToBeRefreshedFound - can't use empToBeRefreshed here because of its older version().
empToBeMergedFound.setSalary(originalSalary);
// now merge
em.merge(empToBeMergedFound);
// begin and commit the second transaction
beginTransaction(em);
commitTransaction(em);
// verify objects are correct in the PersistenceContext
if(em.contains(empNew)) {
fail("empNew not gone from extended PersistenceContext after the second transaction committed");
}
if(!em.contains(empToBeRemoved)) {
fail("empToBeRemoved is not in extended PersistenceContext after the second transaction committed");
}
if(!em.contains(empToBeRefreshedExtended)) {
fail("empToBeRefreshedExtended gone from extended PersistenceContext after the second transaction committed");
} else if(empToBeRefreshedExtended.getSalary() != originalSalary) {
fail("empToBeRefreshedExtended still doesn't have the original salary after the second transaction committed");
}
if(!em.contains(empToBeMergedExtended)) {
fail("empToBeMergedExtended gone from extended PersistenceContext after the second transaction committed");
} else if(empToBeMergedExtended.getSalary() != originalSalary) {
fail("empToBeMergedExtended doesn't have the original salary after the second transaction committed");
}
// verify objects are correct in the db
clearCache();
Employee empNewFound2 = em.find(Employee.class, empNew.getId());
if(empNewFound2 != null) {
fail("empNew still in the db after the second transaction committed");
}
Employee empToBeRemovedFound2 = em.find(Employee.class, empToBeRemoved.getId());
if(empToBeRemovedFound2 == null) {
fail("empToBeRemoved is not in the db after the second transaction committed");
}
Employee empToBeRefreshedFound2 = em.find(Employee.class, empToBeRefreshed.getId());
if(empToBeRefreshedFound2 == null) {
fail("empToBeRefreshed not in the db after the second transaction committed");
} else if(empToBeRefreshedFound2.getSalary() != originalSalary) {
fail("empToBeRefreshed doesn't have the original salary in the db after the second transaction committed");
}
Employee empToBeMergedFound2 = em.find(Employee.class, empToBeMerged.getId());
if(empToBeMergedFound2 == null) {
fail("empToBeMerged not in the db after the second transaction committed");
} else if(empToBeMergedFound2.getSalary() != originalSalary) {
fail("empToBeMerged doesn't have the original salary in the db after the second transaction committed");
}
// third test
// without starting transaction persist, remove, refresh, merge
// The same as the first test - but now we'll rollback.
// The objects should be detached.
beginTransaction(em);
em.persist(empNew);
em.remove(empToBeRemoved);
// Use another EntityManager to alter empToBeRefreshed in the db
EntityManager em2 = createEntityManager();
em2.getTransaction().begin();
try{
empToBeRefreshed = em2.find(Employee.class, empToBeRefreshed.getId());
empToBeRefreshed.setSalary(newSalary);
em2.getTransaction().commit();
}catch (RuntimeException ex){
if (em2.getTransaction().isActive()){
em2.getTransaction().rollback();
}
throw ex;
}finally{
em2.close();
}
// now refesh
em.refresh(empToBeRefreshedExtended);
// alter empToBeRefreshed
empToBeMergedFound2.setSalary(newSalary);
// now merge
em.merge(empToBeMergedFound2);
// flush and ROLLBACK the third transaction
em.flush();
rollbackTransaction(em);
// verify objects are correct in the PersistenceContext after the third transaction rolled back
if(em.contains(empNew)) {
fail("empNew is still in extended PersistenceContext after the third transaction rolled back");
}
if(em.contains(empToBeRemoved)) {
fail("empToBeRemoved is still in extended PersistenceContext after the third transaction rolled back");
}
if(em.contains(empToBeRefreshedExtended)) {
fail("empToBeRefreshedExtended is still in extended PersistenceContext after the third transaction rolled back");
} else if(empToBeRefreshedExtended.getSalary() != newSalary) {
fail("empToBeRefreshedExtended still has the original salary after third transaction rolled back");
}
if(em.contains(empToBeMergedExtended)) {
fail("empToBeMergedExtended is still in extended PersistenceContext after the third transaction rolled back");
} else if(empToBeMergedExtended.getSalary() != newSalary) {
fail("empToBeMergedExtended still has the original salary after third transaction rolled back");
}
// verify objects are correct in the db after the third transaction rolled back
clearCache();
Employee empNewFound3 = em.find(Employee.class, empNew.getId());
if(empNewFound3 != null) {
fail("empNew is in the db after the third transaction rolled back");
}
Employee empToBeRemovedFound3 = em.find(Employee.class, empToBeRemoved.getId());
if(empToBeRemovedFound3 == null) {
fail("empToBeRemoved not in the db after the third transaction rolled back");
}
Employee empToBeRefreshedFound3 = em.find(Employee.class, empToBeRefreshed.getId());
if(empToBeRefreshedFound3 == null) {
fail("empToBeRefreshed not in the db after the third transaction rolled back");
} else if(empToBeRefreshedFound3.getSalary() != newSalary) {
fail("empToBeRefreshed has the original salary in the db after the third transaction rolled back");
}
Employee empToBeMergedFound3 = em.find(Employee.class, empToBeMerged.getId());
if(empToBeMergedFound3 == null) {
fail("empToBeMerged not in the db after the third transaction rolled back");
} else if(empToBeMergedFound3.getSalary() != originalSalary) {
fail("empToBeMerged still doesn't have the original salary in the db after the third transaction rolled back");
}
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
}
public void testReadTransactionIsolation_CustomUpdate() {
internalTestReadTransactionIsolation(false, false, false, false);
}
public void testReadTransactionIsolation_CustomUpdate_Flush() {
internalTestReadTransactionIsolation(false, false, false, true);
}
public void testReadTransactionIsolation_CustomUpdate_Refresh() {
internalTestReadTransactionIsolation(false, false, true, false);
}
public void testReadTransactionIsolation_CustomUpdate_Refresh_Flush() {
internalTestReadTransactionIsolation(false, false, true, true);
}
public void testReadTransactionIsolation_UpdateAll() {
internalTestReadTransactionIsolation(false, true, false, false);
}
public void testReadTransactionIsolation_UpdateAll_Flush() {
internalTestReadTransactionIsolation(false, true, false, true);
}
public void testReadTransactionIsolation_UpdateAll_Refresh() {
internalTestReadTransactionIsolation(false, true, true, false);
}
public void testReadTransactionIsolation_UpdateAll_Refresh_Flush() {
internalTestReadTransactionIsolation(false, true, true, true);
}
public void testReadTransactionIsolation_OriginalInCache_CustomUpdate() {
internalTestReadTransactionIsolation(true, false, false, false);
}
public void testReadTransactionIsolation_OriginalInCache_CustomUpdate_Flush() {
internalTestReadTransactionIsolation(true, false, false, true);
}
public void testReadTransactionIsolation_OriginalInCache_CustomUpdate_Refresh() {
internalTestReadTransactionIsolation(true, false, true, false);
}
public void testReadTransactionIsolation_OriginalInCache_CustomUpdate_Refresh_Flush() {
internalTestReadTransactionIsolation(true, false, true, true);
}
public void testReadTransactionIsolation_OriginalInCache_UpdateAll() {
internalTestReadTransactionIsolation(true, true, false, false);
}
public void testReadTransactionIsolation_OriginalInCache_UpdateAll_Flush() {
internalTestReadTransactionIsolation(true, true, false, true);
}
public void testReadTransactionIsolation_OriginalInCache_UpdateAll_Refresh() {
internalTestReadTransactionIsolation(true, true, true, false);
}
public void testReadTransactionIsolation_OriginalInCache_UpdateAll_Refresh_Flush() {
internalTestReadTransactionIsolation(true, true, true, true);
}
protected void internalTestReadTransactionIsolation(boolean shouldOriginalBeInParentCache, boolean shouldUpdateAll, boolean shouldRefresh, boolean shouldFlush) {
//setup
String firstName = "testReadTransactionIsolation";
// make sure no Employee with the specified firstName exists.
EntityManager em = createEntityManager();
beginTransaction(em);
try{
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
clearCache();
em.clear();
// create and persist the object
String lastNameOriginal = "Original";
int salaryOriginal = 0;
Employee employee = new Employee();
employee.setFirstName(firstName);
employee.setLastName(lastNameOriginal);
employee.setSalary(salaryOriginal);
beginTransaction(em);
try{
em.persist(employee);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
if(!shouldOriginalBeInParentCache) {
clearCache();
}
em.clear();
Employee employeeUOW = null;
int salaryNew = 100;
String lastNameNew = "New";
beginTransaction(em);
Query selectQuery = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = '"+firstName+"'");
try{
if(shouldRefresh) {
String lastNameAlternative = "Alternative";
int salaryAlternative = 50;
employeeUOW = (Employee)selectQuery.getSingleResult();
employeeUOW.setLastName(lastNameAlternative);
employeeUOW.setSalary(salaryAlternative);
}
int nUpdated;
if(shouldUpdateAll) {
nUpdated = em.createQuery("UPDATE Employee e set e.lastName = '" + lastNameNew + "' where e.firstName like '" + firstName + "'").setFlushMode(FlushModeType.AUTO).executeUpdate();
} else {
nUpdated = em.createNativeQuery("UPDATE CMP3_EMPLOYEE SET L_NAME = '" + lastNameNew + "', VERSION = VERSION + 1 WHERE F_NAME LIKE '" + firstName + "'").setFlushMode(FlushModeType.AUTO).executeUpdate();
}
assertTrue("nUpdated=="+ nUpdated +"; 1 was expected", nUpdated == 1);
if(shouldFlush) {
selectQuery.setFlushMode(FlushModeType.AUTO);
} else {
selectQuery.setFlushMode(FlushModeType.COMMIT);
}
if(shouldRefresh) {
selectQuery.setHint("eclipselink.refresh", Boolean.TRUE);
employeeUOW = (Employee)selectQuery.getSingleResult();
selectQuery.setHint("eclipselink.refresh", Boolean.FALSE);
} else {
employeeUOW = (Employee)selectQuery.getSingleResult();
}
assertTrue("employeeUOW.getLastName()=="+ employeeUOW.getLastName() +"; " + lastNameNew + " was expected", employeeUOW.getLastName().equals(lastNameNew));
employeeUOW.setSalary(salaryNew);
employeeUOW = (Employee)selectQuery.getSingleResult();
assertTrue("employeeUOW.getSalary()=="+ employeeUOW.getSalary() +"; " + salaryNew + " was expected", employeeUOW.getSalary() == salaryNew);
commitTransaction(em);
}catch (Throwable ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
if (Error.class.isAssignableFrom(ex.getClass())){
throw (Error)ex;
}else{
throw (RuntimeException)ex;
}
}
Employee employeeFoundAfterTransaction = em.find(Employee.class, employeeUOW.getId());
assertTrue("employeeFoundAfterTransaction().getLastName()=="+ employeeFoundAfterTransaction.getLastName() +"; " + lastNameNew + " was expected", employeeFoundAfterTransaction.getLastName().equals(lastNameNew));
assertTrue("employeeFoundAfterTransaction().getSalary()=="+ employeeFoundAfterTransaction.getSalary() +"; " + salaryNew + " was expected", employeeFoundAfterTransaction.getSalary() == salaryNew);
// The cache should be invalidated because the commit should detect a jump in the version number and invalidate the object.
EntityManager em2 = createEntityManager();
employeeFoundAfterTransaction = em2.find(Employee.class, employeeUOW.getId());
assertTrue("employeeFoundAfterTransaction().getLastName()=="+ employeeFoundAfterTransaction.getLastName() +"; " + lastNameNew + " was expected", employeeFoundAfterTransaction.getLastName().equals(lastNameNew));
assertTrue("employeeFoundAfterTransaction().getSalary()=="+ employeeFoundAfterTransaction.getSalary() +"; " + salaryNew + " was expected", employeeFoundAfterTransaction.getSalary() == salaryNew);
closeEntityManager(em2);
// clean up
beginTransaction(em);
try{
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
clearCache();
closeEntityManager(em);
}
// test for bug 4755392:
// AFTER DELETEALL OBJECT STILL DEEMED EXISTING
public void testFindDeleteAllPersist() {
String firstName = "testFindDeleteAllPersist";
// create Employees
Employee empWithAddress = new Employee();
empWithAddress.setFirstName(firstName);
empWithAddress.setLastName("WithAddress");
empWithAddress.setAddress(new Address());
Employee empWithoutAddress = new Employee();
empWithoutAddress.setFirstName(firstName);
empWithoutAddress.setLastName("WithoutAddress");
EntityManager em = createEntityManager();
// make sure no Employee with the specified firstName exists.
beginTransaction(em);
try{
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// persist
beginTransaction(em);
try{
em.persist(empWithAddress);
em.persist(empWithoutAddress);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// clear cache
clearCache();
em.clear();
// Find both to bring into the cache, delete empWithoutAddress.
// Because the address VH is not triggered both objects should be invalidated.
beginTransaction(em);
try {
Employee empWithAddressFound = em.find(Employee.class, empWithAddress.getId());
empWithAddressFound.toString();
Employee empWithoutAddressFound = em.find(Employee.class, empWithoutAddress.getId());
empWithoutAddressFound.toString();
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"' and e.address IS NULL").executeUpdate();
commitTransaction(em);
} catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// we can no longer rely on the query above to clear the Employee from the persistence context.
// Clearling the context to allow us to proceed.
em.clear();
// persist new empWithoutAddress - the one that has been deleted from the db.
beginTransaction(em);
try{
Employee newEmpWithoutAddress = new Employee();
newEmpWithoutAddress.setFirstName(firstName);
newEmpWithoutAddress.setLastName("newWithoutAddress");
newEmpWithoutAddress.setId(empWithoutAddress.getId());
em.persist(newEmpWithoutAddress);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
// persist new empWithAddress - the one still in the db.
beginTransaction(em);
try{
Employee newEmpWithAddress = new Employee();
newEmpWithAddress.setFirstName(firstName);
newEmpWithAddress.setLastName("newWithAddress");
newEmpWithAddress.setId(empWithAddress.getId());
em.persist(newEmpWithAddress);
fail("EntityExistsException was expected");
} catch (EntityExistsException ex) {
// "cant_persist_detatched_object" - ignore the expected exception
} finally {
rollbackTransaction(em);
}
// clean up
beginTransaction(em);
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
closeEntityManager(em);
}
public void testWRITELock(){
// Cannot create parallel transactions.
if (isOnServer()) {
return;
}
EntityManager em = createEntityManager();
Employee employee = new Employee();
employee.setFirstName("Mark");
employee.setLastName("Madsen");
beginTransaction(em);
try{
em.persist(employee);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
EntityManager em2 = createEntityManager();
Exception optimisticLockException = null;
beginTransaction(em);
try{
employee = em.find(Employee.class, employee.getId());
em.lock(employee, LockModeType.WRITE);
em2.getTransaction().begin();
try{
Employee employee2 = em2.find(Employee.class, employee.getId());
employee2.setFirstName("Michael");
em2.getTransaction().commit();
}catch (RuntimeException ex){
em2.getTransaction().rollback();
em2.close();
throw ex;
}
commitTransaction(em);
} catch (RollbackException exception) {
if (exception.getCause() instanceof OptimisticLockException){
optimisticLockException = exception;
}
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
beginTransaction(em);
try{
employee = em.find(Employee.class, employee.getId());
em.remove(employee);
commitTransaction(em);
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
if (optimisticLockException == null){
fail("Proper exception not thrown when EntityManager.lock(object, WRITE) is used.");
}
}
/*This test case uses the "broken-PU" PU defined in the persistence.xml
located at eclipselink.jpa.test/resource/eclipselink-validation-failed-model/
and included in eclipselink-validation-failed-model.jar */
public void testEMFWrapValidationException()
{
// Comment out because it's not relevant for getDatabaseProperties() when running in server
if (isOnServer()) {
return;
}
EntityManagerFactory factory = null;
try {
factory = Persistence.createEntityManagerFactory("broken-PU", JUnitTestCaseHelper.getDatabaseProperties());
EntityManager em = factory.createEntityManager();
em.close();
} catch (javax.persistence.PersistenceException e) {
ArrayList expectedExceptions = new ArrayList();
expectedExceptions.add(48);
expectedExceptions.add(48);
IntegrityException integrityException = (IntegrityException)e.getCause();
Iterator i = integrityException.getIntegrityChecker().getCaughtExceptions().iterator();
while (i.hasNext()){
expectedExceptions.remove((Object)((EclipseLinkException)i.next()).getErrorCode());
}
if (expectedExceptions.size() > 0){
fail("Not all expected exceptions were caught");
}
} finally {
factory.close();
}
}
/**
* At the time this test case was added, the problem it was designed to test for would cause a failure during deployement
* and therefore this tests case would likely always pass if there is a successful deployment.
* But it is anticipated that that may not always be the case and therefore we are adding a test case
*/
public void testEMDefaultTxType()
{
// Comment out because it's not relevant for getDatabaseProperties() when running in server
if (isOnServer()) {
return;
}
EntityManagerFactory factory = null;
try {
factory = Persistence.createEntityManagerFactory("default1", JUnitTestCaseHelper.getDatabaseProperties());
EntityManager em = factory.createEntityManager();
em.close();
} catch (Exception e) {
fail("Exception caught while creating EM with no \"transaction-type\" specified in persistence.xml");
} finally {
factory.close();
}
Assert.assertTrue(true);
}
public void testPersistOnNonEntity()
{
boolean testPass = false;
Object nonEntity = new Object();
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.persist(nonEntity);
} catch (IllegalArgumentException e) {
testPass = true;
} finally {
rollbackTransaction(em);
}
Assert.assertTrue(testPass);
}
public void testDetachNonEntity() {
// Don't run this test in a JPA 1.0 environment.
if (! isJPA10()) {
boolean testPass = false;
Object nonEntity = new Object();
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.detach(nonEntity);
} catch (IllegalArgumentException e) {
testPass = true;
} finally {
rollbackTransaction(em);
}
Assert.assertTrue(testPass);
}
}
public void testClose() {
// Close is not used on server.
if (isOnServer()) {
return;
}
EntityManager em = createEntityManager();
if(!em.isOpen()) {
fail("Created EntityManager is not open");
}
closeEntityManager(em);
if(em.isOpen()) {
fail("Closed EntityManager is still open");
}
}
public void testBeginTransactionClose() {
// Close is not used on server.
if (isOnServer()) {
return;
}
EntityManager em = createEntityManager();
beginTransaction(em);
try{
closeEntityManager(em);
if(em.isOpen()) {
fail("Closed EntityManager is still open before transaction complete");
}
}catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
if(em.isOpen()) {
closeEntityManager(em);
}
throw ex;
}
rollbackTransaction(em);
if(em.isOpen()) {
fail("Closed EntityManager is still open after transaction rollback");
}
}
public void testBeginTransactionCloseCommitTransaction() {
// EntityManager is always open in server.
if (isOnServer()) {
return;
}
String firstName = "testBeginTrCloseCommitTr";
EntityManager em = createEntityManager();
// make sure there is no employees with this firstName
beginTransaction(em);
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
// create a new Employee
Employee employee = new Employee();
employee.setFirstName(firstName);
// persist the new Employee and close the entity manager
beginTransaction(em);
try{
em.persist(employee);
closeEntityManager(em);
if(em.isOpen()) {
fail("Closed EntityManager is still open before transaction complete");
}
}catch (RuntimeException ex){
rollbackTransaction(em);
if(em.isOpen()) {
closeEntityManager(em);
}
throw ex;
}
commitTransaction(em);
if(em.isOpen()) {
fail("Closed EntityManager is still open after transaction commit");
}
// verify that the employee has been persisted
em = createEntityManager();
RuntimeException exception = null;
try {
Employee persistedEmployee = (Employee)em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = '"+firstName+"'").getSingleResult();
persistedEmployee.toString();
} catch (RuntimeException runtimeException) {
exception = runtimeException;
}
// clean up
beginTransaction(em);
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
if(exception != null) {
if(exception instanceof EntityNotFoundException) {
fail("object has not been persisted");
} else {
// unexpected exception - rethrow.
throw exception;
}
}
}
// The test removed because we moved back to binding literals
// on platforms other than DB2 and Derby
/* public void testDontBindLiteral() {
EntityManager em = createEntityManager();
Query controlQuery = em.createQuery("SELECT OBJECT(p) FROM SmallProject p WHERE p.name = CONCAT(:param1, :param2)");
controlQuery.setParameter("param1", "A").setParameter("param2", "B");
List controlResults = controlQuery.getResultList();
int nControlParams = ((ExpressionQueryMechanism)((EJBQueryImpl)controlQuery).getDatabaseQuery().getQueryMechanism()).getCall().getParameters().size();
if(nControlParams != 2) {
fail("controlQuery has wrong number of parameters = "+nControlParams+"; 2 is expected");
}
Query query = em.createQuery("SELECT OBJECT(p) FROM SmallProject p WHERE p.name = CONCAT('A', 'B')");
List results = query.getResultList();
int nParams = ((ExpressionQueryMechanism)((EJBQueryImpl)query).getDatabaseQuery().getQueryMechanism()).getCall().getParameters().size();
if(nParams > 0) {
fail("Query processed literals as parameters");
}
closeEntityManager(em);
}*/
public void testPersistenceProperties() {
// Different properties are used on the server.
if (isOnServer()) {
return;
}
EntityManager em = createEntityManager();
ServerSession ss = ((org.eclipse.persistence.internal.jpa.EntityManagerImpl)em).getServerSession();
// these properties were set in persistence unit
// and overridden in CMP3TestModel.setup - the values should be overridden.
boolean isReadShared = (ss.getReadConnectionPool() instanceof ReadConnectionPool);
if(isReadShared != Boolean.parseBoolean((String)JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_SHARED))) {
fail("isReadShared is wrong");
}
int writeMin = ss.getDefaultConnectionPool().getMinNumberOfConnections();
if(writeMin != Integer.parseInt((String)JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MIN))) {
fail("writeMin is wrong");
}
int writeInitial = ss.getDefaultConnectionPool().getInitialNumberOfConnections();
if(writeInitial != Integer.parseInt((String)JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_INITIAL))) {
fail("writeInitial is wrong");
}
int writeMax = ss.getDefaultConnectionPool().getMaxNumberOfConnections();
if(writeMax != Integer.parseInt((String)JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MAX))) {
fail("writeMax is wrong");
}
int readMin = ss.getReadConnectionPool().getMinNumberOfConnections();
if(readMin != Integer.parseInt((String)JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MIN))) {
fail("readMin is wrong");
}
int readMax = ss.getReadConnectionPool().getMaxNumberOfConnections();
if(readMax != Integer.parseInt((String)JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MAX))) {
fail("readMax is wrong");
}
int batchSize = ss.getPlatform().getMaxBatchWritingSize();
if (batchSize != Integer.parseInt((String)JUnitTestCaseHelper.propertiesMap.get(PersistenceUnitProperties.BATCH_WRITING_SIZE))) {
fail("batchSize is wrong");
}
// these properties were set in persistence unit - the values should be the same as in persistence.xml
/*
<property name="eclipselink.session-name" value="default-session"/>
<property name="eclipselink.cache.size.default" value="500"/>
<property name="eclipselink.cache.size.Employee" value="550"/>
<property name="eclipselink.cache.size.org.eclipse.persistence.testing.models.jpa.advanced.Address" value="555"/>
<property name="eclipselink.cache.type.default" value="Full"/>
<property name="eclipselink.cache.type.Employee" value="Weak"/>
<property name="eclipselink.cache.type.org.eclipse.persistence.testing.models.jpa.advanced.Address" value="HardWeak"/>
<property name="eclipselink.session.customizer" value="org.eclipse.persistence.testing.models.jpa.advanced.Customizer"/>
<property name="eclipselink.descriptor.customizer.Employee" value="org.eclipse.persistence.testing.models.jpa.advanced.Customizer"/>
<property name="eclipselink.descriptor.customizer.org.eclipse.persistence.testing.models.jpa.advanced.Address" value="org.eclipse.persistence.testing.models.jpa.advanced.Customizer"/>
<property name="eclipselink.descriptor.customizer.Project" value="org.eclipse.persistence.testing.models.jpa.advanced.Customizer"/>
*/
String sessionName = ss.getName();
if(!sessionName.equals("default-session")) {
fail("sessionName is wrong");
}
int defaultCacheSize = ss.getDescriptor(Project.class).getIdentityMapSize();
if(defaultCacheSize != 500) {
fail("defaultCacheSize is wrong");
}
int employeeCacheSize = ss.getDescriptor(Employee.class).getIdentityMapSize();
if(employeeCacheSize != 550) {
fail("employeeCacheSize is wrong");
}
int addressCacheSize = ss.getDescriptor(Address.class).getIdentityMapSize();
if(addressCacheSize != 555) {
fail("addressCacheSize is wrong");
}
// Department cache size specified in @Cache annotation - that should override default property
int departmentCacheSize = ss.getDescriptor(Department.class).getIdentityMapSize();
if(departmentCacheSize != 777) {
fail("departmentCacheSize is wrong");
}
Class defaultCacheType = ss.getDescriptor(Project.class).getIdentityMapClass();
if(! Helper.getShortClassName(defaultCacheType).equals("FullIdentityMap")) {
fail("defaultCacheType is wrong");
}
Class employeeCacheType = ss.getDescriptor(Employee.class).getIdentityMapClass();
if(! Helper.getShortClassName(employeeCacheType).equals("WeakIdentityMap")) {
fail("employeeCacheType is wrong");
}
Class addressCacheType = ss.getDescriptor(Address.class).getIdentityMapClass();
if(! Helper.getShortClassName(addressCacheType).equals("HardCacheWeakIdentityMap")) {
fail("addressCacheType is wrong");
}
// Department cache type specified in @Cache annotation - that should override default property
Class departmentCacheType = ss.getDescriptor(Department.class).getIdentityMapClass();
if(! Helper.getShortClassName(departmentCacheType).equals("SoftCacheWeakIdentityMap")) {
fail("departmentCacheType is wrong");
}
int numSessionCalls = Customizer.getNumberOfCallsForSession(ss.getName());
if(numSessionCalls == 0) {
fail("session customizer hasn't been called");
}
int numProjectCalls = Customizer.getNumberOfCallsForClass(Project.class.getName());
if(numProjectCalls == 0) {
fail("Project customizer hasn't been called");
}
int numEmployeeCalls = Customizer.getNumberOfCallsForClass(Employee.class.getName());
if(numEmployeeCalls == 0) {
fail("Employee customizer hasn't been called");
}
int numAddressCalls = Customizer.getNumberOfCallsForClass(Address.class.getName());
if(numAddressCalls == 0) {
fail("Address customizer hasn't been called");
}
IdValidation employeeIdValidation = ss.getDescriptor(Employee.class).getIdValidation();
if(employeeIdValidation != IdValidation.ZERO) {
fail("employeeIdValidation is wrong, IdValidation.ZERO assigned through PrimaryKey annotation was expected");
}
IdValidation addressIdValidation = ss.getDescriptor(Address.class).getIdValidation();
if(addressIdValidation != IdValidation.NEGATIVE) {
fail("addressIdValidation is wrong, IdValidation.NEGATIVE set as a default value in persistence.xml was expected");
}
closeEntityManager(em);
}
public void testGetLockModeType() {
// getLockModeType not supported on 1.0
if ((! isJPA10()) && isSelectForUpateSupported()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Employee emp = new Employee();
Employee emp1 = new Employee();
Employee emp2 = new Employee();
Employee emp3 = new Employee();
Employee emp4 = new Employee();
Employee emp5 = new Employee();
Employee emp6= new Employee();
Employee emp7= new Employee();
emp.setFirstName("Douglas");
emp.setLastName("McRae");
emp1.setFirstName("kaul");
emp1.setLastName("Jeet");
emp2.setFirstName("Schwatz");
emp2.setLastName("Jonathan");
emp3.setFirstName("Anil");
emp3.setLastName("Gadre");
emp4.setFirstName("Anil");
emp4.setLastName("Gaur");
emp5.setFirstName("Eliot");
emp5.setLastName("Morrison");
emp6.setFirstName("Edward");
emp6.setLastName("Bratt");
emp7.setFirstName("TJ");
emp7.setLastName("Thomas");
em.persist(emp);
em.persist(emp1);
em.persist(emp2);
em.persist(emp3);
em.persist(emp4);
em.persist(emp5);
em.persist(emp6);
em.persist(emp7);
commitTransaction(em);
beginTransaction(em);
emp = em.find(Employee.class, emp.getId());
emp1 = em.find(Employee.class, emp1.getId());
emp2 = em.find(Employee.class, emp2.getId());
emp3 = em.find(Employee.class, emp3.getId());
emp4 = em.find(Employee.class, emp4.getId());
emp5 = em.find(Employee.class, emp5.getId());
emp6 = em.find(Employee.class, emp6.getId());
emp7 = em.find(Employee.class, emp7.getId());
em.lock(emp, LockModeType.OPTIMISTIC);
LockModeType lt = em.getLockMode(emp);
em.lock(emp1, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
LockModeType lt1 = em.getLockMode(emp1);
em.lock(emp2, LockModeType.PESSIMISTIC_READ);
LockModeType lt2 = em.getLockMode(emp2);
em.lock(emp3, LockModeType.PESSIMISTIC_WRITE);
LockModeType lt3 = em.getLockMode(emp3);
em.lock(emp4, LockModeType.PESSIMISTIC_FORCE_INCREMENT);
LockModeType lt4 = em.getLockMode(emp4);
em.lock(emp5, LockModeType.READ);
LockModeType lt5 = em.getLockMode(emp5);
em.lock(emp6, LockModeType.WRITE);
LockModeType lt6 = em.getLockMode(emp6);
em.lock(emp7, LockModeType.NONE);
LockModeType lt7 = em.getLockMode(emp7);
assertEquals("Did not return correct LockModeType", LockModeType.OPTIMISTIC, lt);
assertEquals("Did not return correct LockModeType", LockModeType.OPTIMISTIC_FORCE_INCREMENT, lt1);
// Note: On some databases EclipseLink automatically upgrade LockModeType to PESSIMSITIC_WRITE
assertTrue("Did not return correct LockModeType", lt2 == LockModeType.PESSIMISTIC_WRITE || lt2 == LockModeType.PESSIMISTIC_READ);
assertEquals("Did not return correct LockModeType", LockModeType.PESSIMISTIC_WRITE, lt3);
assertEquals("Did not return correct LockModeType", LockModeType.PESSIMISTIC_FORCE_INCREMENT, lt4);
assertEquals("Did not return correct LockModeType", LockModeType.OPTIMISTIC, lt5);
assertEquals("Did not return correct LockModeType", LockModeType.OPTIMISTIC_FORCE_INCREMENT, lt6);
assertEquals("Did not return correct LockModeType", LockModeType.NONE, lt7);
} catch (UnsupportedOperationException use) {
return;
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
}
//'getProperties()' returns map that throws exception when tried to modify.
public void testGetProperties() {
// getProperties not supported on 1.0
if (! isJPA10()) {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
Map m1 = em.getProperties();
m1.remove("eclipselink.weaving");
} catch (UnsupportedOperationException use) {
return;
} catch (Exception e) {
fail("Wrong exception type thrown: " + e.getClass());
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
fail("No exception thrown when entityManager's properties are attempted to change.");
}
}
public void testUOWReferenceInExpressionCache() {
// Properties only works in jse.
if (isOnServer()) {
return;
}
EntityManager manager = createEntityManager();
((JpaEntityManager)manager).getUnitOfWork().getParent().getIdentityMapAccessor().initializeAllIdentityMaps();
DescriptorQueryManager queryManager = ((JpaEntityManager)manager).getUnitOfWork().getDescriptor(Employee.class).getQueryManager();
queryManager.setExpressionQueryCacheMaxSize(queryManager.getExpressionQueryCacheMaxSize());
ReadAllQuery query = new ReadAllQuery();
query.setIsExecutionClone(true);
query.setReferenceClass(Employee.class);
((JpaEntityManager)manager).getUnitOfWork().executeQuery(query);
closeEntityManager(manager);
assertNull("ExpressionCache has query that references a RWUOW", queryManager.getCachedExpressionQuery(query).getSession());
}
public void testUnWrapClass() {
// unWrap not supported on 1.0
if (! isJPA10()) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
EntityManagerImpl emi = (EntityManagerImpl) em.getDelegate();
ServerSession session = emi.getServerSession();
UnitOfWork uow = emi.getUnitOfWork();
JpaEntityManager jem = emi;
org.eclipse.persistence.sessions.server.ServerSession session1;
session1 = (ServerSession) em.unwrap(org.eclipse.persistence.sessions.Session.class);
assertEquals("Does not return server session", session, session1);
UnitOfWork uow1;
uow1 = em.unwrap(org.eclipse.persistence.sessions.UnitOfWork.class);
assertEquals("Does not return unit of work", uow, uow1);
JpaEntityManager jem1;
jem1 = em.unwrap(org.eclipse.persistence.jpa.JpaEntityManager.class);
assertEquals("Does not return underlying entitymanager", jem, jem1);
// TODO: This should be supported.
/*Connection conn1;
conn1 = em.unwrap(java.sql.Connection.class);
Connection conn = uowImpl.getAccessor().getConnection();
assertEquals("Does not return underlying connection", conn, conn1);*/
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
}
public void testMultipleFactories() {
getEntityManagerFactory();
closeEntityManagerFactory();
boolean isOpen = getEntityManagerFactory().isOpen();
if(!isOpen) {
fail("Close factory 1; open factory 2 - it's not open");
} else {
// Get entity manager just to login back the session, then close em
getEntityManagerFactory().createEntityManager().close();
}
}
public void testParallelMultipleFactories() {
if (isOnServer()) {
// Cannot connect locally on server.
return;
}
EntityManagerFactory factory1 = Persistence.createEntityManagerFactory("default", JUnitTestCaseHelper.getDatabaseProperties());
factory1.createEntityManager();
EntityManagerFactory factory2 = Persistence.createEntityManagerFactory("default", JUnitTestCaseHelper.getDatabaseProperties());
factory2.createEntityManager();
factory1.close();
if(factory1.isOpen()) {
fail("after factory1.close() factory1 is not closed");
}
if(!factory2.isOpen()) {
fail("after factory1.close() factory2 is closed");
}
factory2.close();
if(factory2.isOpen()) {
fail("after factory2.close() factory2 is not closed");
}
EntityManagerFactory factory3 = Persistence.createEntityManagerFactory("default", JUnitTestCaseHelper.getDatabaseProperties());
if(!factory3.isOpen()) {
fail("factory3 is closed");
}
factory3.createEntityManager();
factory3.close();
if(factory3.isOpen()) {
fail("after factory3.close() factory3 is open");
}
}
public void testQueryHints() {
EntityManager em = (EntityManager)getEntityManagerFactory().createEntityManager().getDelegate();
Query query = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = 'testQueryHints'");
// Set a hint first to trigger query clone (because query is accessed before other hints are set).
query.setHint(QueryHints.READ_ONLY, false);
ObjectLevelReadQuery olrQuery = (ObjectLevelReadQuery)((JpaQuery)query).getDatabaseQuery();
// binding
// original state = default state
assertTrue(olrQuery.shouldIgnoreBindAllParameters());
// set boolean true
query.setHint(QueryHints.BIND_PARAMETERS, true);
// Parse cached query may be cloned when hint set, so re-get.
olrQuery = (ObjectLevelReadQuery)((EJBQueryImpl)query).getDatabaseQuery();
assertTrue("Binding not set.", olrQuery.shouldBindAllParameters());
// reset to original state
query.setHint(QueryHints.BIND_PARAMETERS, "");
assertTrue("Binding not set.", olrQuery.shouldIgnoreBindAllParameters());
// set "false"
query.setHint(QueryHints.BIND_PARAMETERS, "false");
assertFalse("Binding not set.", olrQuery.shouldBindAllParameters());
// reset to the original state
query.setHint(QueryHints.BIND_PARAMETERS, "");
assertTrue("Binding not set.", olrQuery.shouldIgnoreBindAllParameters());
// cache usage
query.setHint(QueryHints.CACHE_USAGE, CacheUsage.DoNotCheckCache);
assertTrue("Cache usage not set.", olrQuery.getCacheUsage()==ObjectLevelReadQuery.DoNotCheckCache);
query.setHint(QueryHints.CACHE_USAGE, CacheUsage.CheckCacheOnly);
assertTrue("Cache usage not set.", olrQuery.shouldCheckCacheOnly());
query.setHint(QueryHints.CACHE_USAGE, CacheUsage.ConformResultsInUnitOfWork);
assertTrue("Cache usage not set.", olrQuery.shouldConformResultsInUnitOfWork());
query.setHint(QueryHints.INDIRECTION_POLICY, CacheUsageIndirectionPolicy.Trigger);
assertTrue("INDIRECTION_POLICY not set.", olrQuery.getInMemoryQueryIndirectionPolicyState() == InMemoryQueryIndirectionPolicy.SHOULD_TRIGGER_INDIRECTION);
// reset to the original state
query.setHint(QueryHints.CACHE_USAGE, "");
assertTrue("Cache usage not set.", olrQuery.shouldCheckDescriptorForCacheUsage());
// pessimistic lock
query.setHint(QueryHints.PESSIMISTIC_LOCK, PessimisticLock.Lock);
assertTrue("Lock not set.", olrQuery.getLockMode()==ObjectLevelReadQuery.LOCK);
query.setHint(QueryHints.PESSIMISTIC_LOCK, PessimisticLock.NoLock);
assertTrue("Lock not set.", olrQuery.getLockMode()==ObjectLevelReadQuery.NO_LOCK);
query.setHint(QueryHints.PESSIMISTIC_LOCK, PessimisticLock.LockNoWait);
assertTrue("Lock not set.", olrQuery.getLockMode()==ObjectLevelReadQuery.LOCK_NOWAIT);
// default state
query.setHint(QueryHints.PESSIMISTIC_LOCK, "");
assertTrue("Lock not set.", olrQuery.getLockMode()==ObjectLevelReadQuery.NO_LOCK);
//refresh
// set to original state - don't refresh.
// the previously run LOCK and LOCK_NOWAIT have swithed it to true
query.setHint(QueryHints.REFRESH, false);
assertFalse("Refresh not set.", olrQuery.shouldRefreshIdentityMapResult());
// set boolean true
query.setHint(QueryHints.REFRESH, true);
assertTrue("Refresh not set.", olrQuery.shouldRefreshIdentityMapResult());
assertTrue("CascadeByMapping not set.", olrQuery.shouldCascadeByMapping()); // check if cascade refresh is enabled
// set "false"
query.setHint(QueryHints.REFRESH, "false");
assertFalse("Refresh not set.", olrQuery.shouldRefreshIdentityMapResult());
// set Boolean.TRUE
query.setHint(QueryHints.REFRESH, Boolean.TRUE);
assertTrue("Refresh not set.", olrQuery.shouldRefreshIdentityMapResult());
assertTrue("CascadeByMapping not set.", olrQuery.shouldCascadeByMapping()); // check if cascade refresh is enabled
// reset to original state
query.setHint(QueryHints.REFRESH, "");
assertFalse("Refresh not set.", olrQuery.shouldRefreshIdentityMapResult());
// Read-only
query.setHint(QueryHints.READ_ONLY, "false");
assertFalse("Read-only not set.", olrQuery.isReadOnly());
query.setHint(QueryHints.READ_ONLY, Boolean.TRUE);
assertTrue("Read-only not set.", olrQuery.isReadOnly());
query.setHint(QueryHints.READ_ONLY, Boolean.FALSE);
assertFalse("Read-only not set.", olrQuery.isReadOnly());
// Maintain cache
query.setHint(QueryHints.MAINTAIN_CACHE, true);
assertTrue("MAINTAIN_CACHE set.", olrQuery.shouldMaintainCache());
query.setHint(QueryHints.MAINTAIN_CACHE, "false");
assertFalse("MAINTAIN_CACHE not set.", olrQuery.shouldMaintainCache());
query.setHint(QueryHints.MAINTAIN_CACHE, Boolean.TRUE);
assertTrue("MAINTAIN_CACHE not set.", olrQuery.shouldMaintainCache());
query.setHint(QueryHints.MAINTAIN_CACHE, Boolean.FALSE);
assertFalse("MAINTAIN_CACHE not set.", olrQuery.shouldMaintainCache());
// Prepare
query.setHint(QueryHints.PREPARE, true);
assertTrue("PREPARE set.", olrQuery.shouldPrepare());
query.setHint(QueryHints.PREPARE, "false");
assertFalse("PREPARE not set.", olrQuery.shouldPrepare());
query.setHint(QueryHints.PREPARE, Boolean.TRUE);
assertTrue("PREPARE not set.", olrQuery.shouldPrepare());
query.setHint(QueryHints.PREPARE, Boolean.FALSE);
assertFalse("PREPARE not set.", olrQuery.shouldPrepare());
// Cache statement
query.setHint(QueryHints.CACHE_STATMENT, true);
assertTrue("CACHE_STATMENT set.", olrQuery.shouldCacheStatement());
query.setHint(QueryHints.CACHE_STATMENT, "false");
assertFalse("CACHE_STATMENT not set.", olrQuery.shouldCacheStatement());
query.setHint(QueryHints.CACHE_STATMENT, Boolean.TRUE);
assertTrue("CACHE_STATMENT not set.", olrQuery.shouldCacheStatement());
query.setHint(QueryHints.CACHE_STATMENT, Boolean.FALSE);
assertFalse("CACHE_STATMENT not set.", olrQuery.shouldCacheStatement());
// Flush
query.setHint(QueryHints.FLUSH, true);
assertTrue("FLUSH set.", olrQuery.getFlushOnExecute());
query.setHint(QueryHints.FLUSH, "false");
assertFalse("FLUSH not set.", olrQuery.getFlushOnExecute());
query.setHint(QueryHints.FLUSH, Boolean.TRUE);
assertTrue("FLUSH not set.", olrQuery.getFlushOnExecute());
query.setHint(QueryHints.FLUSH, Boolean.FALSE);
assertFalse("FLUSH not set.", olrQuery.getFlushOnExecute());
// Native connection
query.setHint(QueryHints.NATIVE_CONNECTION, true);
assertTrue("NATIVE_CONNECTION set.", olrQuery.isNativeConnectionRequired());
query.setHint(QueryHints.NATIVE_CONNECTION, "false");
assertFalse("NATIVE_CONNECTION not set.", olrQuery.isNativeConnectionRequired());
query.setHint(QueryHints.NATIVE_CONNECTION, Boolean.TRUE);
assertTrue("NATIVE_CONNECTION not set.", olrQuery.isNativeConnectionRequired());
query.setHint(QueryHints.NATIVE_CONNECTION, Boolean.FALSE);
assertFalse("NATIVE_CONNECTION not set.", olrQuery.isNativeConnectionRequired());
// Hint
query.setHint(QueryHints.HINT, "/* use the index man */");
assertTrue("HINT not set.", olrQuery.getHintString().equals("/* use the index man */"));
// Cursor
query.setHint(QueryHints.CURSOR, Boolean.TRUE);
assertTrue("CURSOR not set.", ((ReadAllQuery)olrQuery).getContainerPolicy().isCursoredStreamPolicy());
query.setHint(QueryHints.CURSOR, Boolean.FALSE);
assertFalse("CURSOR set.", ((ReadAllQuery)olrQuery).getContainerPolicy().isCursoredStreamPolicy());
query.setHint(QueryHints.CURSOR_INITIAL_SIZE, "100");
assertTrue("CURSOR not set.", ((ReadAllQuery)olrQuery).getContainerPolicy().isCursoredStreamPolicy());
assertTrue("CURSOR_INITIAL_SIZE not set.", ((CursoredStreamPolicy)((ReadAllQuery)olrQuery).getContainerPolicy()).getInitialReadSize() == 100);
query.setHint(QueryHints.CURSOR_INITIAL_SIZE, 200);
assertTrue("CURSOR_INITIAL_SIZE not set.", ((CursoredStreamPolicy)((ReadAllQuery)olrQuery).getContainerPolicy()).getInitialReadSize() == 200);
query.setHint(QueryHints.CURSOR, Boolean.FALSE);
query.setHint(QueryHints.CURSOR_PAGE_SIZE, "100");
assertTrue("CURSOR not set.", ((ReadAllQuery)olrQuery).getContainerPolicy().isCursoredStreamPolicy());
assertTrue("CURSOR_PAGE_SIZE not set.", ((CursoredStreamPolicy)((ReadAllQuery)olrQuery).getContainerPolicy()).getPageSize() == 100);
query.setHint(QueryHints.CURSOR_PAGE_SIZE, 200);
assertTrue("CURSOR_PAGE_SIZE not set.", ((CursoredStreamPolicy)((ReadAllQuery)olrQuery).getContainerPolicy()).getPageSize() == 200);
query.setHint(QueryHints.CURSOR, Boolean.FALSE);
query.setHint(QueryHints.CURSOR_SIZE, "Select Count(*) from Employee");
assertTrue("CURSOR_SIZE not set.", ((CursoredStreamPolicy)((ReadAllQuery)olrQuery).getContainerPolicy()).getSizeQuery().getSQLString().equals("Select Count(*) from Employee"));
// Scrollable cursor
query.setHint(QueryHints.SCROLLABLE_CURSOR, Boolean.TRUE);
assertTrue("SCROLLABLE_CURSOR not set.", ((ReadAllQuery)olrQuery).getContainerPolicy().isScrollableCursorPolicy());
query.setHint(QueryHints.SCROLLABLE_CURSOR, Boolean.FALSE);
assertFalse("SCROLLABLE_CURSOR set.", ((ReadAllQuery)olrQuery).getContainerPolicy().isScrollableCursorPolicy());
query.setHint(QueryHints.RESULT_SET_TYPE, ResultSetType.Reverse);
assertTrue("RESULT_SET_TYPE not set.", ((ScrollableCursorPolicy)((ReadAllQuery)olrQuery).getContainerPolicy()).getResultSetType() == ScrollableCursorPolicy.FETCH_REVERSE);
query.setHint(QueryHints.RESULT_SET_CONCURRENCY, ResultSetConcurrency.Updatable);
assertTrue("RESULT_SET_CONCURRENCY not set.", ((ScrollableCursorPolicy)((ReadAllQuery)olrQuery).getContainerPolicy()).getResultSetConcurrency() == ScrollableCursorPolicy.CONCUR_UPDATABLE);
// Exclusive connection
query.setHint(QueryHints.EXCLUSIVE_CONNECTION, Boolean.TRUE);
assertTrue("EXCLUSIVE_CONNECTION not set.", olrQuery.shouldUseExclusiveConnection());
// Inheritance
query.setHint(QueryHints.INHERITANCE_OUTER_JOIN, Boolean.TRUE);
assertTrue("INHERITANCE_OUTER_JOIN not set.", olrQuery.shouldOuterJoinSubclasses());
// History
query.setHint(QueryHints.AS_OF, "1973/10/11 12:00:00");
assertTrue("AS_OF not set.", olrQuery.getAsOfClause() != null);
query.setHint(QueryHints.AS_OF_SCN, "12345");
assertTrue("AS_OF_SCN not set.", ((Number)olrQuery.getAsOfClause().getValue()).intValue() == 12345);
// Fetch groups
query.setHint(QueryHints.FETCH_GROUP_DEFAULT, Boolean.FALSE);
assertFalse("FETCH_GROUP_DEFAULT not set.", olrQuery.shouldUseDefaultFetchGroup());
query.setHint(QueryHints.FETCH_GROUP_NAME, "nameAndCity");
assertTrue("FETCH_GROUP_NAME not set.", olrQuery.getFetchGroupName().equals("nameAndCity"));
query.setHint(QueryHints.FETCH_GROUP_ATTRIBUTE, "firstName");
query.setHint(QueryHints.FETCH_GROUP_ATTRIBUTE, "lastName");
assertTrue("FETCH_GROUP_ATTRIBUTE not set.", olrQuery.getFetchGroup().containsAttribute("firstName"));
assertTrue("FETCH_GROUP_ATTRIBUTE not set.", olrQuery.getFetchGroup().containsAttribute("lastName"));
FetchGroup fetchGroup = new FetchGroup();
fetchGroup.addAttribute("id");
query.setHint(QueryHints.FETCH_GROUP, fetchGroup);
assertTrue("FETCH_GROUP not set.", olrQuery.getFetchGroup() == fetchGroup);
// Timeout
query.setHint(QueryHints.JDBC_TIMEOUT, new Integer(100));
assertTrue("Timeout not set.", olrQuery.getQueryTimeout() == 100);
// JDBC
query.setHint(QueryHints.JDBC_FETCH_SIZE, new Integer(101));
assertTrue("Fetch-size not set.", olrQuery.getFetchSize() == 101);
query.setHint(QueryHints.JDBC_MAX_ROWS, new Integer(103));
assertTrue("Max-rows not set.", olrQuery.getMaxRows() == 103);
query.setHint(QueryHints.JDBC_FIRST_RESULT, new Integer(123));
assertTrue("JDBC_FIRST_RESULT not set.", olrQuery.getFirstResult() == 123);
// Refresh
query.setHint(QueryHints.REFRESH_CASCADE, CascadePolicy.NoCascading);
assertTrue(olrQuery.getCascadePolicy()==DatabaseQuery.NoCascading);
query.setHint(QueryHints.REFRESH_CASCADE, CascadePolicy.CascadeByMapping);
assertTrue(olrQuery.getCascadePolicy()==DatabaseQuery.CascadeByMapping);
query.setHint(QueryHints.REFRESH_CASCADE, CascadePolicy.CascadeAllParts);
assertTrue(olrQuery.getCascadePolicy()==DatabaseQuery.CascadeAllParts);
query.setHint(QueryHints.REFRESH_CASCADE, CascadePolicy.CascadePrivateParts);
assertTrue(olrQuery.getCascadePolicy()==DatabaseQuery.CascadePrivateParts);
// reset to the original state
query.setHint(QueryHints.REFRESH_CASCADE, "");
assertTrue(olrQuery.getCascadePolicy()==DatabaseQuery.CascadeByMapping);
// Result collection
query.setHint(QueryHints.RESULT_COLLECTION_TYPE, java.util.ArrayList.class);
assertTrue("ArrayList not set.", ((ReadAllQuery)olrQuery).getContainerPolicy().getContainerClass().equals(java.util.ArrayList.class));
query.setHint(QueryHints.RESULT_COLLECTION_TYPE, "java.util.Vector");
assertTrue("Vector not set.", ((ReadAllQuery)olrQuery).getContainerPolicy().getContainerClass().equals(java.util.Vector.class));
query.setHint(QueryHints.RESULT_COLLECTION_TYPE, "org.eclipse.persistence.testing.models.jpa.relationships.CustomerCollection");
assertTrue("CustomerCollection not set.", ((ReadAllQuery)olrQuery).getContainerPolicy().getContainerClass().equals(CustomerCollection.class));
// Query type
query.setHint(QueryHints.QUERY_TYPE, QueryType.ReadObject);
assertTrue("QUERY_TYPE not set.", ((JpaQuery)query).getDatabaseQuery().getClass().equals(ReadObjectQuery.class));
query.setHint(QueryHints.QUERY_TYPE, QueryType.Report);
assertTrue("QUERY_TYPE not set.", ((JpaQuery)query).getDatabaseQuery().getClass().equals(ReportQuery.class));
query.setHint(QueryHints.QUERY_TYPE, QueryType.DataModify);
assertTrue("QUERY_TYPE not set.", ((JpaQuery)query).getDatabaseQuery().getClass().equals(DataModifyQuery.class));
query.setHint(QueryHints.QUERY_TYPE, "org.eclipse.persistence.queries.ValueReadQuery");
assertTrue("QUERY_TYPE not set.", ((JpaQuery)query).getDatabaseQuery().getClass().equals(ValueReadQuery.class));
query.setHint(QueryHints.QUERY_TYPE, QueryType.ReadAll);
assertTrue("QUERY_TYPE not set.", ((JpaQuery)query).getDatabaseQuery().getClass().equals(ReadAllQuery.class));
// Result type
query.setHint(QueryHints.QUERY_TYPE, QueryType.Report);
query.setHint(QueryHints.RESULT_TYPE, ResultType.Map);
assertTrue("RESULT_TYPE not set.", ((ReportQuery)((JpaQuery)query).getDatabaseQuery()).getReturnType() == ReportQuery.ShouldReturnReportResult);
query.setHint(QueryHints.RESULT_TYPE, ResultType.Array);
assertTrue("RESULT_TYPE not set.", ((ReportQuery)((JpaQuery)query).getDatabaseQuery()).getReturnType() == ReportQuery.ShouldReturnArray);
query.setHint(QueryHints.RESULT_TYPE, ResultType.Value);
assertTrue("RESULT_TYPE not set.", ((ReportQuery)((JpaQuery)query).getDatabaseQuery()).getReturnType() == ReportQuery.ShouldReturnSingleValue);
query.setHint(QueryHints.QUERY_TYPE, QueryType.DataRead);
query.setHint(QueryHints.RESULT_TYPE, ResultType.Map);
query.setHint(QueryHints.RESULT_TYPE, ResultType.Array);
query.setHint(QueryHints.RESULT_TYPE, ResultType.Value);
closeEntityManager(em);
}
/**
* This test ensures that the eclipselink.batch query hint works.
* It tests two things.
*
* 1. That the batch read attribute is properly added to the queyr
* 2. That the query will execute
*
* It does not do any verification that the batch reading feature actually works. That is
* left for the batch reading testing to do.
*/
public void testBatchQueryHint(){
int id1 = 0;
EntityManager em = createEntityManager();
beginTransaction(em);
Employee manager = new Employee();
manager.setFirstName("Marvin");
manager.setLastName("Malone");
PhoneNumber number = new PhoneNumber("cell", "613", "888-8888");
manager.addPhoneNumber(number);
number = new PhoneNumber("home", "613", "888-8880");
manager.addPhoneNumber(number);
em.persist(manager);
id1 = manager.getId();
Employee emp = new Employee();
emp.setFirstName("Melvin");
emp.setLastName("Malone");
emp.setManager(manager);
manager.addManagedEmployee(emp);
number = new PhoneNumber("cell", "613", "888-9888");
emp.addPhoneNumber(number);
number = new PhoneNumber("home", "613", "888-0880");
emp.addPhoneNumber(number);
em.persist(emp);
emp = new Employee();
emp.setFirstName("David");
emp.setLastName("Malone");
emp.setManager(manager);
manager.addManagedEmployee(emp);
number = new PhoneNumber("cell", "613", "888-9988");
emp.addPhoneNumber(number);
number = new PhoneNumber("home", "613", "888-0980");
emp.addPhoneNumber(number);
em.persist(emp);
commitTransaction(em);
em.clear();
//org.eclipse.persistence.jpa.JpaQuery query = (org.eclipse.persistence.jpa.JpaQuery)em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
org.eclipse.persistence.jpa.JpaQuery query = (org.eclipse.persistence.jpa.JpaQuery)getEntityManagerFactory().createEntityManager().createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
query.setHint(QueryHints.BATCH, "e.phoneNumbers");
query.setHint(QueryHints.BATCH, "e.manager.phoneNumbers");
ReadAllQuery raq = (ReadAllQuery)query.getDatabaseQuery();
List expressions = raq.getBatchReadAttributeExpressions();
assertTrue(expressions.size() == 2);
Expression exp = (Expression)expressions.get(0);
assertTrue(exp.isQueryKeyExpression());
assertTrue(exp.getName().equals("phoneNumbers"));
exp = (Expression)expressions.get(1);
assertTrue(exp.isQueryKeyExpression());
assertTrue(exp.getName().equals("phoneNumbers"));
List resultList = query.getResultList();
emp = (Employee)resultList.get(0);
emp.getPhoneNumbers().hashCode();
emp.getManager().getPhoneNumbers().hashCode();
emp = (Employee)resultList.get(1);
emp.getPhoneNumbers().hashCode();
beginTransaction(em);
emp = em.find(Employee.class, id1);
Iterator it = emp.getManagedEmployees().iterator();
while (it.hasNext()){
Employee managedEmp = (Employee)it.next();
it.remove();
managedEmp.setManager(null);
em.remove(managedEmp);
}
em.remove(emp);
commitTransaction(em);
}
/**
* This test ensures that the eclipselink.fetch query hint works.
* It tests two things.
*
* 1. That the joined attribute is properly added to the query
* 2. That the query will execute
*
* It does not do any verification that the joining feature actually works. That is
* left for the joining testing to do.
*/
public void testFetchQueryHint(){
int id1 = 0;
EntityManager em = createEntityManager();
beginTransaction(em);
Employee manager = new Employee();
manager.setFirstName("Marvin");
manager.setLastName("Malone");
PhoneNumber number = new PhoneNumber("cell", "613", "888-8888");
manager.addPhoneNumber(number);
number = new PhoneNumber("home", "613", "888-8880");
manager.addPhoneNumber(number);
em.persist(manager);
id1 = manager.getId();
Employee emp = new Employee();
emp.setFirstName("Melvin");
emp.setLastName("Malone");
emp.setManager(manager);
manager.addManagedEmployee(emp);
number = new PhoneNumber("cell", "613", "888-9888");
emp.addPhoneNumber(number);
number = new PhoneNumber("home", "613", "888-0880");
emp.addPhoneNumber(number);
em.persist(emp);
emp = new Employee();
emp.setFirstName("David");
emp.setLastName("Malone");
emp.setManager(manager);
manager.addManagedEmployee(emp);
number = new PhoneNumber("cell", "613", "888-9988");
emp.addPhoneNumber(number);
number = new PhoneNumber("home", "613", "888-0980");
emp.addPhoneNumber(number);
em.persist(emp);
commitTransaction(em);
em.clear();
//org.eclipse.persistence.jpa.JpaQuery query = (org.eclipse.persistence.jpa.JpaQuery)em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
org.eclipse.persistence.jpa.JpaQuery query = (org.eclipse.persistence.jpa.JpaQuery)getEntityManagerFactory().createEntityManager().createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
query.setHint(QueryHints.LEFT_FETCH, "e.manager");
ReadAllQuery raq = (ReadAllQuery)query.getDatabaseQuery();
List expressions = raq.getJoinedAttributeExpressions();
assertTrue(expressions.size() == 1);
Expression exp = (Expression)expressions.get(0);
assertTrue(exp.getName().equals("manager"));
query.setHint(QueryHints.FETCH, "e.manager.phoneNumbers");
assertTrue(expressions.size() == 2);
List resultList = query.getResultList();
emp = (Employee)resultList.get(0);
beginTransaction(em);
emp = em.find(Employee.class, id1);
Iterator it = emp.getManagedEmployees().iterator();
while (it.hasNext()){
Employee managedEmp = (Employee)it.next();
it.remove();
managedEmp.setManager(null);
em.remove(managedEmp);
}
em.remove(emp);
commitTransaction(em);
}
/**
* Test that the proper exception is thrown when an incorrect batch or fetch query hint is set on the queyr.
*/
public void testIncorrectBatchQueryHint(){
EntityManager em = createEntityManager();
QueryException exception = null;
try{
Query query = em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
query.setHint(QueryHints.BATCH, "e");
query.getResultList();
} catch (QueryException exc){
exception = exc;
}
assertNotNull("No exception was thrown on an incorrect BATCH query hint.", exception);
assertTrue("Incorrect Exception thrown", exception.getErrorCode() == QueryException.QUERY_HINT_DID_NOT_CONTAIN_ENOUGH_TOKENS);
exception = null;
try{
Query query = em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
query.setHint(QueryHints.BATCH, "e.abcdef");
query.getResultList();
} catch (QueryException exc){
exception = exc;
}
assertNotNull("No exception was thrown on an incorrect BATCH query hint.", exception);
assertTrue("Incorrect Exception thrown", exception.getErrorCode() == QueryException.QUERY_HINT_NAVIGATED_NON_EXISTANT_RELATIONSHIP);
exception = null;
try{
Query query = em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
query.setHint(QueryHints.BATCH, "e.firstName");
query.getResultList();
} catch (QueryException exc){
exception = exc;
}
assertNotNull("No exception was thrown when an incorrect relationship was navigated in a BATCH query hint.", exception);
assertTrue("Incorrect Exception thrown", exception.getErrorCode() == QueryException.QUERY_HINT_NAVIGATED_ILLEGAL_RELATIONSHIP);
exception = null;
try{
Query query = em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
query.setHint(QueryHints.FETCH, "e");
query.getResultList();
} catch (QueryException exc){
exception = exc;
}
assertNotNull("No exception was thrown on an incorrect FETCH query hint.", exception);
assertTrue("Incorrect Exception thrown", exception.getErrorCode() == QueryException.QUERY_HINT_DID_NOT_CONTAIN_ENOUGH_TOKENS);
exception = null;
try{
Query query = em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
query.setHint(QueryHints.FETCH, "e.abcdef");
query.getResultList();
} catch (QueryException exc){
exception = exc;
}
assertNotNull("No exception was thrown on an incorrect FETCH query hint.", exception);
assertTrue("Incorrect Exception thrown", exception.getErrorCode() == QueryException.QUERY_HINT_NAVIGATED_NON_EXISTANT_RELATIONSHIP);
exception = null;
try{
Query query = em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
query.setHint(QueryHints.FETCH, "e.firstName");
query.getResultList();
} catch (QueryException exc){
exception = exc;
}
assertNotNull("No exception was thrown when an incorrect relationship was navigated in a FETCH query hint.", exception);
assertTrue("Incorrect Exception thrown", exception.getErrorCode() == QueryException.QUERY_HINT_NAVIGATED_ILLEGAL_RELATIONSHIP);
}
public void testQueryOnClosedEM() {
// Server entity managers are not closed.
if (isOnServer()) {
return;
}
boolean exceptionWasThrown = false;
EntityManager em = createEntityManager();
Query q = em.createQuery("SELECT e FROM Employee e ");
closeEntityManager(em);
if(em.isOpen()) {
fail("Closed EntityManager is still open");
}
try{
q.getResultList();
}catch(java.lang.IllegalStateException e){
exceptionWasThrown=true;
}
if (!exceptionWasThrown){
fail("Query on Closed EntityManager did not throw an exception");
}
}
public void testNullifyAddressIn() {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.createQuery("UPDATE Employee e SET e.address = null WHERE e.address.country IN ('Canada', 'US')").executeUpdate();
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
//test for bug 5234283: WRONG =* SQL FOR LEFT JOIN ON DERBY AND DB2 PLATFORMS
public void testLeftJoinOneToOneQuery() {
EntityManager em = createEntityManager();
List results = em.createQuery("SELECT a FROM Employee e LEFT JOIN e.address a").getResultList();
results.toString();
closeEntityManager(em);
}
// Test multiple items from a report query. Will verify the version on
// only one of the results.
public void testLockingLeftJoinOneToOneQuery() {
// OPTIMISTIC_FORCE_INCREMENT lock not supported on 1.0
if (! isJPA10()) {
// Grab a copy of the results that we will lock then verify.
List<Object[]> results = createEntityManager().createQuery("SELECT m, e FROM Employee e LEFT JOIN e.manager m").getResultList();
if (! results.isEmpty()) {
// Issuing the force increment locking query.
EntityManager em = createEntityManager();
beginTransaction(em);
em.createQuery("SELECT m, e FROM Employee e LEFT JOIN e.manager m").setLockMode(LockModeType.OPTIMISTIC_FORCE_INCREMENT).getResultList();
commitTransaction(em);
// Verify the items of the result list all had a version increment.
beginTransaction(em);
try{
for (Object[] result : results) {
Employee managerBefore = (Employee) result[0];
if (managerBefore != null) {
int managerVersionBefore = managerBefore.getVersion();
Employee managerAfter = em.find(Employee.class, managerBefore.getId());
int managerVersionAfter = managerAfter.getVersion();
assertTrue("The manager version was not updated on the locking query.", (managerVersionAfter - managerVersionBefore) == 1);
}
Employee employeeBefore = (Employee) result[1];
if (employeeBefore != null) {
int employeeVersionBefore = employeeBefore.getVersion();
Employee employeeAfter = em.find(Employee.class, employeeBefore.getId());
int employeeVersionAfter = employeeAfter.getVersion();
assertTrue("The manager version was not updated on the locking query.", (employeeVersionAfter - employeeVersionBefore) == 1);
}
}
} finally {
if(this.isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
}
}
}
// Test single item from a report query.
public void testLockingLeftJoinOneToOneQuery2() {
// OPTIMISTIC_FORCE_INCREMENT lock not supported on 1.0
if (! isJPA10()) {
// Grab a copy of the results that we will lock then verify.
List<Address> results = createEntityManager().createQuery("SELECT a FROM Employee e LEFT JOIN e.address a").getResultList();
if (results != null) {
// Issuing the force increment locking query.
EntityManager em = createEntityManager();
beginTransaction(em);
em.createQuery("SELECT a FROM Employee e LEFT JOIN e.address a").setLockMode(LockModeType.OPTIMISTIC_FORCE_INCREMENT).getResultList();
commitTransaction(em);
// Verify the items of the result list all had a version increment.
beginTransaction(em);
try{
for (Address address : results) {
if (address != null) {
int versionBefore = address.getVersion();
Address addressAfter = em.find(Address.class, address.getId());
int versionAfter = addressAfter.getVersion();
assertTrue("The version on an address was not updated on the locking query.", (versionAfter - versionBefore) == 1);
}
}
} finally {
if(this.isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
}
}
}
// Test the clone method works correctly with lazy attributes.
public void testCloneable() {
EntityManager em = createEntityManager();
beginTransaction(em);
Employee employee = new Employee();
employee.setFirstName("Owen");
employee.setLastName("Hargreaves");
employee.getAddress();
Employee clone = employee.clone();
Address address = new Address();
address.setCity("Munich");
clone.setAddress(address);
clone.getAddress();
em.persist(clone);
if (employee.getAddress() == clone.getAddress()) {
fail("Changing clone address changed original.");
}
commitTransaction(em);
clearCache();
closeEntityManager(em);
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, clone.getId());
clone = employee.clone();
address = new Address();
address.setCity("Not Munich");
clone.setAddress(address);
clone.getAddress();
if (employee.getAddress() == clone.getAddress()) {
fail("Changing clone address changed original.");
}
if (employee.getAddress() == null) {
fail("Changing clone address reset original to null.");
}
if (clone.getAddress() != address) {
fail("Changing clone did not work.");
}
commitTransaction(em);
closeEntityManager(em);
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, clone.getId());
clone = employee.clone();
clone.setId(null);
em.persist(clone);
commitTransaction(em);
if (clone.getId() == null) {
fail("Clone was not persisted.");
}
beginTransaction(em);
employee = em.find(Employee.class, clone.getId());
em.remove(employee);
commitTransaction(em);
closeEntityManager(em);
}
// test for GlassFish bug 711 - throw a descriptive exception when an uninstantiated valueholder is serialized and then accessed
public void testSerializedLazy(){
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("Owen");
emp.setLastName("Hargreaves");
emp.setId(40);
Address address = new Address();
address.setCity("Munich");
emp.setAddress(address);
em.persist(emp);
em.flush();
commitTransaction(em);
closeEntityManager(em);
clearCache();
em = createEntityManager();
String ejbqlString = "SELECT e FROM Employee e WHERE e.firstName = 'Owen' and e.lastName = 'Hargreaves'";
List result = em.createQuery(ejbqlString).getResultList();
emp = (Employee)result.get(0);
Exception exception = null;
try {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ObjectOutputStream stream = new ObjectOutputStream(byteStream);
stream.writeObject(emp);
stream.flush();
byte arr[] = byteStream.toByteArray();
ByteArrayInputStream inByteStream = new ByteArrayInputStream(arr);
ObjectInputStream inObjStream = new ObjectInputStream(inByteStream);
emp = (Employee) inObjStream.readObject();
emp.getAddress();
} catch (ValidationException e) {
if (e.getErrorCode() == ValidationException.INSTANTIATING_VALUEHOLDER_WITH_NULL_SESSION){
exception = e;
} else {
fail("An unexpected exception was thrown while testing serialization of ValueHolders: " + e.toString());
}
} catch (Exception e){
fail("An unexpected exception was thrown while testing serialization of ValueHolders: " + e.toString());
}
// Only throw error if weaving was used.
if (isWeavingEnabled()) {
assertNotNull("The correct exception was not thrown while traversing an uninstantiated lazy relationship on a serialized object: " + exception, exception);
}
beginTransaction(em);
emp = em.find(Employee.class, emp.getId());
em.remove(emp);
commitTransaction(em);
}
//test for bug 5170395: GET THE SEQUENCING EXCEPTION WHEN RUNNING FOR THE FIRST TIME ON A CLEAR SCHEMA
public void testSequenceObjectDefinition() {
EntityManager em = createEntityManager();
ServerSession ss = getServerSession();
if(!ss.getLogin().getPlatform().supportsSequenceObjects() || isOnServer()) {
// platform that supports sequence objects is required for this test
// this test not work on server since the bug: 262251
closeEntityManager(em);
return;
}
String seqName = "testSequenceObjectDefinition";
try {
// first param is preallocationSize, second is startValue
// both should be positive
internalTestSequenceObjectDefinition(10, 1, seqName, em, ss);
internalTestSequenceObjectDefinition(10, 5, seqName, em, ss);
internalTestSequenceObjectDefinition(10, 15, seqName, em, ss);
} finally {
closeEntityManager(em);
}
}
protected void internalTestSequenceObjectDefinition(int preallocationSize, int startValue, String seqName, EntityManager em, ServerSession ss) {
NativeSequence sequence = new NativeSequence(seqName, preallocationSize, startValue, false);
sequence.onConnect(ss.getPlatform());
SequenceObjectDefinition def = new SequenceObjectDefinition(sequence);
// create sequence
String createStr = def.buildCreationWriter(ss, new StringWriter()).toString();
beginTransaction(em);
em.createNativeQuery(createStr).executeUpdate();
commitTransaction(em);
try {
// sequence value preallocated
Vector seqValues = sequence.getGeneratedVector(null, ss);
int firstSequenceValue = ((Number)seqValues.elementAt(0)).intValue();
if(firstSequenceValue != startValue) {
fail(seqName + " sequence with preallocationSize = "+preallocationSize+" and startValue = " + startValue + " produced wrong firstSequenceValue =" + firstSequenceValue);
}
} finally {
sequence.onDisconnect(ss.getPlatform());
// drop sequence
String dropStr = def.buildDeletionWriter(ss, new StringWriter()).toString();
beginTransaction(em);
em.createNativeQuery(dropStr).executeUpdate();
commitTransaction(em);
}
}
public void testMergeDetachedObject() {
// Step 1 - read a department and clear the cache.
clearCache();
EntityManager em = createEntityManager();
Query query = em.createNamedQuery("findAllSQLDepartments");
Collection departments = query.getResultList();
Department detachedDepartment;
// This test seems to get called twice. Once with departments populated
// and a second time with the department table empty.
if (departments.isEmpty()) {
beginTransaction(em);
detachedDepartment = new Department();
detachedDepartment.setName("Department X");
em.persist(detachedDepartment);
commitTransaction(em);
} else {
detachedDepartment = (Department) departments.iterator().next();
}
closeEntityManager(em);
clearCache();
// Step 2 - create a new em, create a new employee with the
// detached department and then query the departments again.
em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("Crazy");
emp.setLastName("Kid");
emp.setId(41);
emp.setDepartment(detachedDepartment);
em.persist(emp);
commitTransaction(em);
try {
em.createNamedQuery("findAllSQLDepartments").getResultList();
} catch (NullPointerException e) {
assertTrue("The detached department caused a null pointer on the query execution.", false);
}
closeEntityManager(em);
}
public void testMergeRemovedObject() {
//create an Employee
Employee emp = new Employee();
emp.setFirstName("testMergeRemovedObjectEmployee");
emp.setId(42);
//persist the Employee
EntityManager em = createEntityManager();
try{
beginTransaction(em);
em.persist(emp);
commitTransaction(em);
}catch (RuntimeException re){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw re;
}
beginTransaction(em);
em.remove(em.find(Employee.class, emp.getId())); //attempt to remove the Employee
try{
em.merge(emp); //then attempt to merge the Employee
fail("No exception thrown when merging a removed entity is attempted.");
}catch (IllegalArgumentException iae){
//expected
}catch (Exception e) {
fail("Wrong exception type thrown: " + e.getClass());
}finally {
rollbackTransaction(em);
//clean up - ensure removal of employee
beginTransaction(em);
em.remove(em.find(Employee.class, emp.getId()));
commitTransaction(em);
closeEntityManager(em);
}
}
//detach(object) on a removed object does not throw exception. This test only
//checks whether an removed object is completely deleted from the
//getDeletedObject()Map after 'detach(removedobject)' is invoked
public void testDetachRemovedObject() {
// Don't run this test in a JPA 1.0 environment.
if (! isJPA10()) {
//create an Employee
Employee emp = new Employee();
emp.setFirstName("testDetachRemovedObjectEmployee");
emp.setId(71);
//persist the Employee
EntityManager em = createEntityManager();
try {
beginTransaction(em);
em.persist(emp);
commitTransaction(em);
} catch (RuntimeException re){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw re;
}
beginTransaction(em);
em.remove(em.find(Employee.class, emp.getId())); //attempt to remove the Employee
commitTransaction(em);
beginTransaction(em);
EntityManagerImpl em1 = (EntityManagerImpl)em.getDelegate();
try {
em.detach(emp); //attempt to detach the Employee
UnitOfWork uow = em1.getUnitOfWork();
UnitOfWorkImpl uowImpl = (UnitOfWorkImpl)uow;
boolean afterClear = uowImpl.getDeletedObjects().containsKey(emp);
assertFalse("exception thrown when detaching a removed entity is attempted.", afterClear);
} catch (IllegalArgumentException iae){
return;
} finally {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
}
}
}
//bug6167431: tests calling merge on a new object puts it in the cache, and that all new objects in the tree get IDs generated
public void testMergeNewObject() {
//create an Employee
Employee emp = new Employee();
emp.setFirstName("testMergeNewObjectEmployee");
emp.setAddress(new Address("45 O'Connor", "Ottawa", "Ont", "Canada", "K1P1A4"));
//persist the Employee
EntityManager em = createEntityManager();
try{
beginTransaction(em);
Employee managedEmp = em.merge(emp);
this.assertNotNull("merged Employee doesn't have its ID generated", managedEmp.getId());
this.assertNotNull("merged Employee cannot be found using find", em.find(Employee.class, managedEmp.getId()));
//this won't work till bug:6193761 is fixed
//this.assertTrue("referenced Address doesn't have its ID generated", managedEmp.getAddress().getId()!=0);
}finally {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
}
}
//bug6180972: Tests calling merge on a new Entity that uses int as its ID, verifying it is set and cached correctly
public void testMergeNewObject2() {
//create an Equipment
Equipment equip = new Equipment();
equip.setDescription("New Equipment");
EntityManager em = createEntityManager();
try{
beginTransaction(em);
Equipment managedEquip = em.merge(equip);
this.assertTrue("merged Equipment doesn't have its ID generated", managedEquip.getId()!=0);
this.assertNotNull("merged Equipment cannot be found using find", em.find(Equipment.class, managedEquip.getId()));
}finally {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
}
}
//bug6342382: NEW OBJECT MERGE THROWS OPTIMISTICLOCKEXCEPTION
public void testMergeNewObject3_UseSequencing() {
internalTestMergeNewObject3(true);
}
//bug6342382: NEW OBJECT MERGE THROWS OPTIMISTICLOCKEXCEPTION
public void testMergeNewObject3_DontUseSequencing() {
internalTestMergeNewObject3(false);
}
// shouldUseSequencing == false indicates that PKs should be explicitly assigned to the objects
// rather than generated by sequencing.
protected void internalTestMergeNewObject3(boolean shouldUseSequencing) {
int id = 0;
if(!shouldUseSequencing) {
// obtain the last used sequence number
Employee emp = new Employee();
EntityManager em = createEntityManager();
beginTransaction(em);
em.persist(emp);
commitTransaction(em);
id = emp.getId();
beginTransaction(em);
emp = em.find(Employee.class, emp.getId());
em.remove(emp);
commitTransaction(em);
closeEntityManager(em);
}
//create two Employees:
String firstName = "testMergeNewObjectEmployee3";
Employee manager = new Employee();
manager.setFirstName(firstName);
manager.setLastName("Manager");
if(!shouldUseSequencing) {
manager.setId(id++);
}
Employee employee = new Employee();
employee.setFirstName(firstName);
employee.setLastName("Employee");
if(!shouldUseSequencing) {
employee.setId(id++);
}
manager.addManagedEmployee(employee);
//persist the Employee
EntityManager em = createEntityManager();
try {
beginTransaction(em);
Employee managedEmp = em.merge(manager);
managedEmp.toString();
} finally {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
}
}
public void testMergeNull(){
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.merge(null);
}catch (IllegalArgumentException iae){
return;
}catch (Exception e) {
fail("Wrong exception type thrown: " + e.getClass());
}finally {
rollbackTransaction(em);
closeEntityManager(em);
}
fail("No exception thrown when entityManager.merge(null) attempted.");
}
public void testPersistNull(){
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.persist(null);
}catch (IllegalArgumentException iae){
return;
}catch (Exception e) {
fail("Wrong exception type thrown: " + e.getClass());
}finally {
rollbackTransaction(em);
closeEntityManager(em);
}
fail("No exception thrown when entityManager.persist(null) attempted.");
}
public void testContainsNull(){
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.contains(null);
}catch (IllegalArgumentException iae){
return;
}catch (Exception e) {
fail("Wrong exception type thrown: " + e.getClass());
}finally {
rollbackTransaction(em);
closeEntityManager(em);
}
fail("No exception thrown when entityManager.contains(null) attempted.");
}
public void testDetachNull() {
// Don't run this test in a JPA 1.0 environment.
if (! isJPA10()) {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.detach(null);
} catch (IllegalArgumentException iae) {
return;
} catch (Exception e) {
fail("Wrong exception type thrown: " + e.getClass());
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
fail("No exception thrown when entityManager.detach(null) attempted.");
}
}
public void testRemoveNull(){
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.remove(null);
}catch (IllegalArgumentException iae){
return;
}catch (Exception e) {
fail("Wrong exception type thrown: " + e.getClass());
}finally {
rollbackTransaction(em);
closeEntityManager(em);
}
fail("No exception thrown when entityManager.remove(null) attempted.");
}
/**
* GlassFish Bug854, originally calling with null caused a null-pointer exception.
*/
public void testCreateEntityManagerFactory() {
if (isOnServer() && JUnitTestCase.isWeavingEnabled()) {
// Bug 297628 - jpa.advanced.EntityManagerJUnitTestSuite.testCreateEntityManagerFactory failed on WLS for only dynamic weaving
// Dynamic weaving for Persistence.createEntityManagerFactory can't be done on app. server.
return;
}
EntityManagerFactory factory = null;
try {
// First call with correct properties, to ensure test does not corrupt factory.
Persistence.createEntityManagerFactory("default", JUnitTestCaseHelper.getDatabaseProperties());
factory = Persistence.createEntityManagerFactory("default", null);
factory = Persistence.createEntityManagerFactory("default");
} finally {
if (factory != null) {
factory.close();
}
}
}
//GlassFish Bug854 PU name doesn't exist or PU with the wrong name
public void testCreateEntityManagerFactory2() {
EntityManagerFactory emf = null;
PersistenceProvider provider = new PersistenceProvider();
try{
try {
emf = provider.createEntityManagerFactory("default123", null);
} catch (Exception e) {
fail("Exception is not expected, but thrown:" + e);
}
assertNull(emf);
try {
emf = Persistence.createEntityManagerFactory("default123");
fail("PersistenceException is expected");
} catch (Exception e) {
assertTrue("The exception should be a PersistenceException", e instanceof PersistenceException);
}
} finally{
if (emf != null) {
emf.close();
}
}
}
//Glassfish bug 702 - prevent primary key updates
public void testPrimaryKeyUpdate() {
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("Groucho");
emp.setLastName("Marx");
em.persist(emp);
Integer id = emp.getId();
commitTransaction(em);
beginTransaction(em);
emp = em.merge(emp);
emp.setId(id + 1);
try {
commitTransaction(em);
} catch (Exception exception) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
Throwable persistenceException = exception;
// Remove an wrapping exceptions such as rollback, runtime, etc.
while (persistenceException != null && !(persistenceException instanceof ValidationException)) {
// In the server this is always a rollback exception, need to get nested exception.
persistenceException = persistenceException.getCause();
}
if (persistenceException instanceof ValidationException) {
ValidationException ve = (ValidationException) persistenceException;
if (ve.getErrorCode() == ValidationException.PRIMARY_KEY_UPDATE_DISALLOWED) {
return;
} else {
AssertionFailedError failure = new AssertionFailedError("Wrong error code for ValidationException: " + ve.getErrorCode());
failure.initCause(ve);
throw failure;
}
} else {
AssertionFailedError failure = new AssertionFailedError("ValiationException expected, thrown: " + exception);
failure.initCause(exception);
throw failure;
}
} finally {
closeEntityManager(em);
}
fail("No exception thrown when primary key update attempted.");
}
//Glassfish bug 702 - prevent primary key updates, same value is ok
public void testPrimaryKeyUpdateSameValue() {
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("Harpo");
emp.setLastName("Marx");
em.persist(emp);
Integer id = emp.getId();
commitTransaction(em);
beginTransaction(em);
emp.setId(id);
try {
commitTransaction(em);
} catch (Exception e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
fail("Unexpected exception thrown: " + e.getClass());
} finally {
closeEntityManager(em);
}
}
//Glassfish bug 702 - prevent primary key updates, overlapping PK/FK
public void testPrimaryKeyUpdatePKFK() {
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("Groucho");
emp.setLastName("Marx");
em.persist(emp);
Employee emp2 = new Employee();
emp2.setFirstName("Harpo");
emp2.setLastName("Marx");
em.persist(emp2);
PhoneNumber phone = new PhoneNumber("home", "415", "0007");
phone.setOwner(emp);
em.persist(phone);
commitTransaction(em);
beginTransaction(em);
phone = em.merge(phone);
emp2 = em.merge(emp2);
phone.setOwner(emp2);
try {
commitTransaction(em);
} catch (Exception exception) {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
Throwable persistenceException = exception;
// Remove an wrapping exceptions such as rollback, runtime, etc.
while (persistenceException != null && !(persistenceException instanceof ValidationException)) {
// In the server this is always a rollback exception, need to get nested exception.
persistenceException = persistenceException.getCause();
}
if (persistenceException instanceof ValidationException) {
ValidationException ve = (ValidationException) persistenceException;
if (ve.getErrorCode() == ValidationException.PRIMARY_KEY_UPDATE_DISALLOWED) {
return;
} else {
AssertionFailedError failure = new AssertionFailedError("Wrong error code for ValidationException: " + ve.getErrorCode());
failure.initCause(ve);
throw failure;
}
} else {
AssertionFailedError failure = new AssertionFailedError("ValiationException expected, thrown: " + exception);
failure.initCause(exception);
throw failure;
}
} finally {
closeEntityManager(em);
}
fail("No exception thrown when primary key update attempted.");
}
// Test cascade merge on a detached entity
public void testCascadeMergeDetached() {
// setup
Project p1 = new Project();
p1.setName("Project1");
Project p2 = new Project();
p1.setName("Project2");
Employee e1 = new Employee();
e1.setFirstName("Employee1");
Employee e2 = new Employee();
e2.setFirstName("Employee2");
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.persist(p1);
em.persist(p2);
em.persist(e1);
em.persist(e2);
commitTransaction(em);
} catch (RuntimeException re){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw re;
}
closeEntityManager(em);
// end of setup
//p1,p2,e1,e2 are detached
// associate relationships
//p1 -> e1 (one-to-one)
p1.setTeamLeader(e1);
//e1 -> e2 (one-to-many)
e1.addManagedEmployee(e2);
//e2 -> p2 (many-to-many)
e2.addProject(p2);
p2.addTeamMember(e2);
em = createEntityManager();
beginTransaction(em);
try {
Project mp1 = em.merge(p1); // cascade merge
assertTrue(em.contains(mp1));
assertTrue("Managed instance and detached instance must not be same", mp1 != p1);
Employee me1 = mp1.getTeamLeader();
assertTrue("Cascade merge failed", em.contains(me1));
assertTrue("Managed instance and detached instance must not be same", me1 != e1);
Employee me2 = me1.getManagedEmployees().iterator().next();
assertTrue("Cascade merge failed", em.contains(me2));
assertTrue("Managed instance and detached instance must not be same", me2 != e2);
Project mp2 = me2.getProjects().iterator().next();
assertTrue("Cascade merge failed", em.contains(mp2));
assertTrue("Managed instance and detached instance must not be same", mp2 != p2);
commitTransaction(em);
} catch (RuntimeException re){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw re;
}
closeEntityManager(em);
}
// Test cascade merge on a managed entity
// Test for GF#1139 - Cascade doesn't work when merging managed entity
public void testCascadeMergeManaged() {
// setup
Project p1 = new Project();
p1.setName("Project1");
Project p2 = new Project();
p1.setName("Project2");
Employee e1 = new Employee();
e1.setFirstName("Employee1");
Employee e2 = new Employee();
e2.setFirstName("Employee2");
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.persist(p1);
em.persist(p2);
em.persist(e1);
em.persist(e2);
commitTransaction(em);
} catch (RuntimeException re){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw re;
}
closeEntityManager(em);
// end of setup
//p1,p2,e1,e2 are detached
em = createEntityManager();
beginTransaction(em);
try {
Project mp1 = em.merge(p1);
assertTrue(em.contains(mp1));
assertTrue("Managed instance and detached instance must not be same", mp1 != p1);
//p1 -> e1 (one-to-one)
mp1.setTeamLeader(e1);
mp1 = em.merge(mp1); // merge again - trigger cascade merge
Employee me1 = mp1.getTeamLeader();
assertTrue("Cascade merge failed", em.contains(me1));
assertTrue("Managed instance and detached instance must not be same", me1 != e1);
//e1 -> e2 (one-to-many)
me1.addManagedEmployee(e2);
me1 = em.merge(me1); // merge again - trigger cascade merge
Employee me2 = me1.getManagedEmployees().iterator().next();
assertTrue("Cascade merge failed", em.contains(me2));
assertTrue("Managed instance and detached instance must not be same", me2 != e2);
//e2 -> p2 (many-to-many)
me2.addProject(p2);
p2.addTeamMember(me2);
me2 = em.merge(me2); // merge again - trigger cascade merge
Project mp2 = me2.getProjects().iterator().next();
assertTrue("Cascade merge failed", em.contains(mp2));
assertTrue("Managed instance and detached instance must not be same", mp2 != p2);
commitTransaction(em);
} catch (RuntimeException re){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw re;
}
closeEntityManager(em);
}
//Glassfish bug 1021 - allow cascading persist operation to non-entities
public void testCascadePersistToNonEntitySubclass() {
EntityManager em = createEntityManager();
// added new setting for bug 237281
InheritancePolicy ip = getServerSession().getDescriptor(Project.class).getInheritancePolicy();
boolean describesNonPersistentSubclasses = ip.getDescribesNonPersistentSubclasses();
ip.setDescribesNonPersistentSubclasses(true);
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("Albert");
emp.setLastName("Einstein");
SuperLargeProject s1 = new SuperLargeProject("Super 1");
Collection projects = new ArrayList();
projects.add(s1);
emp.setProjects(projects);
em.persist(emp);
try {
commitTransaction(em);
} catch (Exception e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
fail("Persist operation was not cascaded to related non-entity, thrown: " + e);
} finally {
ip.setDescribesNonPersistentSubclasses(describesNonPersistentSubclasses);
closeEntityManager(em);
}
}
/**
* Bug 801
* Test to ensure when property access is used and the underlying variable is changed the change
* is correctly reflected in the database
*
* In this test we test making the change before the object is managed
*/
public void testInitializeFieldForPropertyAccess(){
Employee employee = new Employee();
employee.setFirstName("Andy");
employee.setLastName("Dufresne");
Address address = new Address();
address.setCity("Shawshank");
employee.setAddressField(address);
EntityManager em = createEntityManager();
beginTransaction(em);
em.persist(employee);
try{
commitTransaction(em);
} catch (RuntimeException e){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
}
int id = employee.getId();
clearCache();
em = createEntityManager();
beginTransaction(em);
try {
employee = em.find(Employee.class, new Integer(id));
address = employee.getAddress();
assertTrue("The address was not persisted.", employee.getAddress() != null);
assertTrue("The address was not correctly persisted.", employee.getAddress().getCity().equals("Shawshank"));
} finally {
employee.setAddress((Address)null);
em.remove(address);
em.remove(employee);
commitTransaction(em);
}
}
/**
* Bug 801
* Test to ensure when property access is used and the underlying variable is changed the change
* is correctly reflected in the database
*
* In this test we test making the change after the object is managed
*/
public void testSetFieldForPropertyAccess(){
EntityManager em = createEntityManager();
Employee employee = new Employee();
employee.setFirstName("Andy");
employee.setLastName("Dufresne");
Address address = new Address();
address.setCity("Shawshank");
employee.setAddress(address);
Employee manager = new Employee();
manager.setFirstName("Bobby");
manager.setLastName("Dufresne");
employee.setManager(manager);
beginTransaction(em);
em.persist(employee);
commitTransaction(em);
int id = employee.getId();
int addressId = address.getId();
int managerId = manager.getId();
beginTransaction(em);
employee = em.find(Employee.class, new Integer(id));
employee.getAddress();
address = new Address();
address.setCity("Metropolis");
employee.setAddress(address);
manager = new Employee();
manager.setFirstName("Metro");
manager.setLastName("Dufresne");
employee.setManagerField(manager);
try {
commitTransaction(em);
} catch (RuntimeException e){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
}
clearCache();
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, new Integer(id));
address = employee.getAddress();
manager = employee.getManager();
assertTrue("The address was not persisted.", employee.getAddress() != null);
assertTrue("The address was not correctly persisted.", employee.getAddress().getCity().equals("Metropolis"));
assertTrue("The manager was not persisted.", employee.getManager() != null);
assertTrue("The manager was not correctly persisted.", employee.getManager().getFirstName().equals("Metro"));
Address initialAddress = em.find(Address.class, new Integer(addressId));
Employee initialManager = em.find(Employee.class, new Integer(managerId));
employee.setAddress((Address)null);
employee.setManager((Employee)null);
em.remove(address);
em.remove(employee);
em.remove(manager);
em.remove(initialAddress);
em.remove(initialManager);
commitTransaction(em);
}
/**
* Bug 801
* Test to ensure when property access is used and the underlying variable is changed the change
* is correctly reflected in the database
*
* In this test we test making the change after the object is refreshed
*/
public void testSetFieldForPropertyAccessWithRefresh(){
EntityManager em = createEntityManager();
Employee employee = new Employee();
employee.setFirstName("Andy");
employee.setLastName("Dufresne");
Address address = new Address();
address.setCity("Shawshank");
employee.setAddress(address);
Employee manager = new Employee();
manager.setFirstName("Bobby");
manager.setLastName("Dufresne");
employee.setManager(manager);
beginTransaction(em);
em.persist(employee);
commitTransaction(em);
int id = employee.getId();
int addressId = address.getId();
int managerId = manager.getId();
beginTransaction(em);
employee = em.getReference(Employee.class, employee.getId());
em.refresh(employee);
employee.getAddress();
address = new Address();
address.setCity("Metropolis");
employee.setAddress(address);
manager = new Employee();
manager.setFirstName("Metro");
manager.setLastName("Dufresne");
employee.setManagerField(manager);
try{
commitTransaction(em);
} catch (RuntimeException e){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
}
clearCache();
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, new Integer(id));
address = employee.getAddress();
manager = employee.getManager();
assertTrue("The address was not persisted.", employee.getAddress() != null);
assertTrue("The address was not correctly persisted.", employee.getAddress().getCity().equals("Metropolis"));
assertTrue("The manager was not persisted.", employee.getManager() != null);
assertTrue("The manager was not correctly persisted.", employee.getManager().getFirstName().equals("Metro"));
Address initialAddress = em.find(Address.class, new Integer(addressId));
Employee initialManager = em.find(Employee.class, new Integer(managerId));
employee.setAddress((Address)null);
employee.setManager((Employee)null);
em.remove(address);
em.remove(employee);
em.remove(manager);
em.remove(initialAddress);
em.remove(initialManager);
commitTransaction(em);
}
/**
* Bug 801
* Test to ensure when property access is used and the underlying variable is changed the change
* is correctly reflected in the database
*
* In this test we test making the change when an existing object is read into a new EM
*/
public void testSetFieldForPropertyAccessWithNewEM(){
EntityManager em = createEntityManager();
Employee employee = new Employee();
employee.setFirstName("Andy");
employee.setLastName("Dufresne");
Employee manager = new Employee();
manager.setFirstName("Bobby");
manager.setLastName("Dufresne");
employee.setManager(manager);
Address address = new Address();
address.setCity("Shawshank");
employee.setAddress(address);
beginTransaction(em);
em.persist(employee);
commitTransaction(em);
int id = employee.getId();
int addressId = address.getId();
int managerId = manager.getId();
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, new Integer(id));
employee.getAddress();
employee.getManager();
address = new Address();
address.setCity("Metropolis");
employee.setAddress(address);
manager = new Employee();
manager.setFirstName("Metro");
manager.setLastName("Dufresne");
employee.setManagerField(manager);
try {
commitTransaction(em);
} catch (RuntimeException e){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
}
clearCache();
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, new Integer(id));
address = employee.getAddress();
manager = employee.getManager();
assertTrue("The address was not persisted.", employee.getAddress() != null);
assertTrue("The address was not correctly persisted.", employee.getAddress().getCity().equals("Metropolis"));
assertTrue("The manager was not persisted.", employee.getManager() != null);
assertTrue("The manager was not correctly persisted.", employee.getManager().getFirstName().equals("Metro"));
Address initialAddress = em.find(Address.class, new Integer(addressId));
Employee initialManager = em.find(Employee.class, new Integer(managerId));
employee.setAddress((Address)null);
employee.setManager((Employee)null);
em.remove(address);
em.remove(employee);
em.remove(manager);
em.remove(initialAddress);
em.remove(initialManager);
commitTransaction(em);
}
//bug gf674 - EJBQL delete query with IS NULL in WHERE clause produces wrong sql
public void testDeleteAllPhonesWithNullOwner() {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.createQuery("DELETE FROM PhoneNumber ph WHERE ph.owner IS NULL").executeUpdate();
} catch (Exception e) {
fail("Exception thrown: " + e.getClass());
} finally {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
}
}
public void testDeleteAllProjectsWithNullTeamLeader() {
internalDeleteAllProjectsWithNullTeamLeader("Project");
}
public void testDeleteAllSmallProjectsWithNullTeamLeader() {
internalDeleteAllProjectsWithNullTeamLeader("SmallProject");
}
public void testDeleteAllLargeProjectsWithNullTeamLeader() {
internalDeleteAllProjectsWithNullTeamLeader("LargeProject");
}
protected void internalDeleteAllProjectsWithNullTeamLeader(String className) {
String name = "testDeleteAllProjectsWithNull";
// setup
SmallProject sp = new SmallProject();
sp.setName(name);
LargeProject lp = new LargeProject();
lp.setName(name);
EntityManager em = createEntityManager();
try {
beginTransaction(em);
// make sure there are no pre-existing objects with this name
em.createQuery("DELETE FROM "+className+" p WHERE p.name = '"+name+"'").executeUpdate();
em.persist(sp);
em.persist(lp);
commitTransaction(em);
} catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
// test
em = createEntityManager();
beginTransaction(em);
try {
em.createQuery("DELETE FROM "+className+" p WHERE p.name = '"+name+"' AND p.teamLeader IS NULL").executeUpdate();
commitTransaction(em);
} catch (RuntimeException e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw e;
} finally {
closeEntityManager(em);
}
// verify
String error = null;
em = createEntityManager();
List result = em.createQuery("SELECT OBJECT(p) FROM Project p WHERE p.name = '"+name+"'").getResultList();
if(result.isEmpty()) {
if(!className.equals("Project")) {
error = "Target Class " + className +": no objects left";
}
} else {
if(result.size() > 1) {
error = "Target Class " + className +": too many objects left: " + result.size();
} else {
Project p = (Project)result.get(0);
if(p.getClass().getName().endsWith(className)) {
error = "Target Class " + className +": object of wrong type left: " + p.getClass().getName();
}
}
}
// clean up
try {
beginTransaction(em);
// make sure there are no pre-existing objects with this name
em.createQuery("DELETE FROM "+className+" p WHERE p.name = '"+name+"'").executeUpdate();
commitTransaction(em);
} catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
if(error != null) {
fail(error);
}
}
// gf1408: DeleteAll and UpdateAll queries broken on some db platforms;
// gf1451: Complex updates to null using temporary storage do not work on Derby;
// gf1860: TopLink provides too few values.
// The tests forces the use of temporary storage to test null assignment to an integer field
// on all platforms.
public void testUpdateUsingTempStorage() {
internalUpdateUsingTempStorage(false);
}
public void testUpdateUsingTempStorageWithParameter() {
internalUpdateUsingTempStorage(true);
}
protected void internalUpdateUsingTempStorage(boolean useParameter) {
String firstName = "testUpdateUsingTempStorage";
int n = 3;
// setup
EntityManager em = createEntityManager();
try {
beginTransaction(em);
// make sure there are no pre-existing objects with this name
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
em.createQuery("DELETE FROM Address a WHERE a.country = '"+firstName+"'").executeUpdate();
// populate Employees
for(int i=1; i<=n; i++) {
Employee emp = new Employee();
emp.setFirstName(firstName);
emp.setLastName(Integer.toString(i));
emp.setSalary(i*100);
emp.setRoomNumber(i);
Address address = new Address();
address.setCountry(firstName);
address.setCity(Integer.toString(i));
emp.setAddress(address);
em.persist(emp);
}
commitTransaction(em);
} catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
// test
em = createEntityManager();
beginTransaction(em);
int nUpdated = 0;
try {
if(useParameter) {
nUpdated = em.createQuery("UPDATE Employee e set e.salary = e.roomNumber, e.roomNumber = e.salary, e.address = :address where e.firstName = '" + firstName + "'").setParameter("address", null).executeUpdate();
} else {
nUpdated = em.createQuery("UPDATE Employee e set e.salary = e.roomNumber, e.roomNumber = e.salary, e.address = null where e.firstName = '" + firstName + "'").executeUpdate();
}
commitTransaction(em);
} finally {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
}
// verify
String error = null;
em = createEntityManager();
List result = em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.firstName = '"+firstName+"'").getResultList();
closeEntityManager(em);
int nReadBack = result.size();
if(n != nUpdated) {
error = "n = "+n+", but nUpdated ="+nUpdated+";";
}
if(n != nReadBack) {
error = " n = "+n+", but nReadBack ="+nReadBack+";";
}
for(int i=0; i<nReadBack; i++) {
Employee emp = (Employee)result.get(i);
if(emp.getAddress() != null) {
error = " Employee "+emp.getLastName()+" still has address;";
}
int ind = Integer.valueOf(emp.getLastName()).intValue();
if(emp.getSalary() != ind) {
error = " Employee "+emp.getLastName()+" has wrong salary "+emp.getSalary()+";";
}
if(emp.getRoomNumber() != ind*100) {
error = " Employee "+emp.getLastName()+" has wrong roomNumber "+emp.getRoomNumber()+";";
}
}
// clean up
em = createEntityManager();
try {
beginTransaction(em);
// make sure there are no objects left with this name
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
em.createQuery("DELETE FROM Address a WHERE a.country = '"+firstName+"'").executeUpdate();
commitTransaction(em);
} catch (RuntimeException ex){
if (isTransactionActive(em)){
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
if(error != null) {
fail(error);
}
}
protected void createProjectsWithName(String name, Employee teamLeader) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
SmallProject sp = new SmallProject();
sp.setName(name);
LargeProject lp = new LargeProject();
lp.setName(name);
em.persist(sp);
em.persist(lp);
if(teamLeader != null) {
SmallProject sp2 = new SmallProject();
sp2.setName(name);
sp2.setTeamLeader(teamLeader);
LargeProject lp2 = new LargeProject();
lp2.setName(name);
lp2.setTeamLeader(teamLeader);
em.persist(sp2);
em.persist(lp2);
}
commitTransaction(em);
} catch (RuntimeException ex) {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
}
protected void deleteProjectsWithName(String name) {
EntityManager em = createEntityManager();
try {
beginTransaction(em);
em.createQuery("DELETE FROM Project p WHERE p.name = '"+name+"'").executeUpdate();
commitTransaction(em);
} catch (RuntimeException ex) {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
}
public void testUpdateAllSmallProjects() {
internalTestUpdateAllProjects(SmallProject.class);
}
public void testUpdateAllLargeProjects() {
internalTestUpdateAllProjects(LargeProject.class);
}
public void testUpdateAllProjects() {
internalTestUpdateAllProjects(Project.class);
}
protected void internalTestUpdateAllProjects(Class cls) {
String className = Helper.getShortClassName(cls);
String name = "testUpdateAllProjects";
String newName = "testUpdateAllProjectsNEW";
HashMap map = null;
boolean ok = false;
try {
// setup
// populate Projects - necessary only if no SmallProject and/or LargeProject objects already exist.
createProjectsWithName(name, null);
// save the original names of projects: will set them back in cleanup
// to restore the original state.
EntityManager em = createEntityManager();
List projects = em.createQuery("SELECT OBJECT(p) FROM Project p").getResultList();
map = new HashMap(projects.size());
for(int i=0; i<projects.size(); i++) {
Project p = (Project)projects.get(i);
map.put(p.getId(), p.getName());
}
// test
beginTransaction(em);
try {
em.createQuery("UPDATE "+className+" p set p.name = '"+newName+"'").executeUpdate();
commitTransaction(em);
} catch (RuntimeException ex) {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
// verify
em = createEntityManager();
String errorMsg = "";
projects = em.createQuery("SELECT OBJECT(p) FROM Project p").getResultList();
for(int i=0; i<projects.size(); i++) {
Project p = (Project)projects.get(i);
String readName = p.getName();
if(cls.isInstance(p)) {
if(!newName.equals(readName)) {
errorMsg = errorMsg + "haven't updated name: " + p + "; ";
}
} else {
if(newName.equals(readName)) {
errorMsg = errorMsg + "have updated name: " + p + "; ";
}
}
}
closeEntityManager(em);
if(errorMsg.length() > 0) {
fail(errorMsg);
} else {
ok = true;
}
} finally {
// clean-up
try {
if(map != null) {
EntityManager em = createEntityManager();
beginTransaction(em);
List projects = em.createQuery("SELECT OBJECT(p) FROM Project p").getResultList();
try {
for(int i=0; i<projects.size(); i++) {
Project p = (Project)projects.get(i);
String oldName = (String)map.get(((Project)projects.get(i)).getId());
p.setName(oldName);
}
commitTransaction(em);
} catch (RuntimeException ex) {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
}
// delete projects that createProjectsWithName has created in setup
deleteProjectsWithName(name);
} catch (RuntimeException ex) {
// eat clean-up exception in case the test failed
if(ok) {
throw ex;
}
}
}
}
public void testUpdateAllSmallProjectsWithName() {
internalTestUpdateAllProjectsWithName(SmallProject.class);
}
public void testUpdateAllLargeProjectsWithName() {
internalTestUpdateAllProjectsWithName(LargeProject.class);
}
public void testUpdateAllProjectsWithName() {
internalTestUpdateAllProjectsWithName(Project.class);
}
protected void internalTestUpdateAllProjectsWithName(Class cls) {
String className = Helper.getShortClassName(cls);
String name = "testUpdateAllProjects";
String newName = "testUpdateAllProjectsNEW";
boolean ok = false;
try {
// setup
// make sure no projects with the specified names exist
deleteProjectsWithName(name);
deleteProjectsWithName(newName);
// populate Projects
createProjectsWithName(name, null);
// test
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.createQuery("UPDATE "+className+" p set p.name = '"+newName+"' WHERE p.name = '"+name+"'").executeUpdate();
commitTransaction(em);
} catch (RuntimeException ex) {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
// verify
em = createEntityManager();
String errorMsg = "";
List projects = em.createQuery("SELECT OBJECT(p) FROM Project p WHERE p.name = '"+newName+"' OR p.name = '"+name+"'").getResultList();
for(int i=0; i<projects.size(); i++) {
Project p = (Project)projects.get(i);
String readName = p.getName();
if(cls.isInstance(p)) {
if(!readName.equals(newName)) {
errorMsg = errorMsg + "haven't updated name: " + p + "; ";
}
} else {
if(readName.equals(newName)) {
errorMsg = errorMsg + "have updated name: " + p + "; ";
}
}
}
closeEntityManager(em);
if(errorMsg.length() > 0) {
fail(errorMsg);
} else {
ok = true;
}
} finally {
// clean-up
// make sure no projects with the specified names left
try {
deleteProjectsWithName(name);
deleteProjectsWithName(newName);
} catch (RuntimeException ex) {
// eat clean-up exception in case the test failed
if(ok) {
throw ex;
}
}
}
}
public void testUpdateAllSmallProjectsWithNullTeamLeader() {
internalTestUpdateAllProjectsWithNullTeamLeader(SmallProject.class);
}
public void testUpdateAllLargeProjectsWithNullTeamLeader() {
internalTestUpdateAllProjectsWithNullTeamLeader(LargeProject.class);
}
public void testUpdateAllProjectsWithNullTeamLeader() {
internalTestUpdateAllProjectsWithNullTeamLeader(Project.class);
}
protected void internalTestUpdateAllProjectsWithNullTeamLeader(Class cls) {
String className = Helper.getShortClassName(cls);
String name = "testUpdateAllProjects";
String newName = "testUpdateAllProjectsNEW";
Employee empTemp = null;
boolean ok = false;
try {
// setup
// make sure no projects with the specified names exist
deleteProjectsWithName(name);
deleteProjectsWithName(newName);
EntityManager em = createEntityManager();
Employee emp = null;
List employees = em.createQuery("SELECT OBJECT(e) FROM Employee e").getResultList();
if(employees.size() > 0) {
emp = (Employee)employees.get(0);
} else {
beginTransaction(em);
try {
emp = new Employee();
emp.setFirstName(name);
emp.setLastName("TeamLeader");
em.persist(emp);
commitTransaction(em);
empTemp = emp;
} catch (RuntimeException ex) {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
throw ex;
}
}
closeEntityManager(em);
// populate Projects
createProjectsWithName(name, emp);
// test
em = createEntityManager();
beginTransaction(em);
try {
em.createQuery("UPDATE "+className+" p set p.name = '"+newName+"' WHERE p.name = '"+name+"' AND p.teamLeader IS NULL").executeUpdate();
commitTransaction(em);
} catch (RuntimeException ex) {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
// verify
em = createEntityManager();
String errorMsg = "";
List projects = em.createQuery("SELECT OBJECT(p) FROM Project p WHERE p.name = '"+newName+"' OR p.name = '"+name+"'").getResultList();
for(int i=0; i<projects.size(); i++) {
Project p = (Project)projects.get(i);
String readName = p.getName();
if(cls.isInstance(p) && p.getTeamLeader()==null) {
if(!readName.equals(newName)) {
errorMsg = errorMsg + "haven't updated name: " + p + "; ";
}
} else {
if(readName.equals(newName)) {
errorMsg = errorMsg + "have updated name: " + p + "; ";
}
}
}
closeEntityManager(em);
if(errorMsg.length() > 0) {
fail(errorMsg);
} else {
ok = true;
}
} finally {
// clean-up
// make sure no projects with the specified names exist
try {
deleteProjectsWithName(name);
deleteProjectsWithName(newName);
if(empTemp != null) {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.createQuery("DELETE FROM Employee e WHERE e.id = '"+empTemp.getId()+"'").executeUpdate();
commitTransaction(em);
} catch (RuntimeException ex) {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
throw ex;
} finally {
closeEntityManager(em);
}
}
} catch (RuntimeException ex) {
// eat clean-up exception in case the test failed
if(ok) {
throw ex;
}
}
}
}
public void testRollbackOnlyOnException() {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
Employee emp = em.find(Employee.class, "");
emp.toString();
fail("IllegalArgumentException has not been thrown");
} catch(IllegalArgumentException ex) {
if (isOnServer()) {
assertTrue("Transaction is not roll back only", getRollbackOnly(em));
} else {
assertTrue("Transaction is not roll back only", em.getTransaction().getRollbackOnly());
}
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
}
public void testClosedEmShouldThrowException() {
// Close is not used on server.
if (isOnServer()) {
return;
}
EntityManager em = createEntityManager();
closeEntityManager(em);
String errorMsg = "";
try {
em.clear();
errorMsg = errorMsg + "; em.clear() didn't throw exception";
} catch(IllegalStateException ise) {
// expected
} catch(RuntimeException ex) {
errorMsg = errorMsg + "; em.clear() threw wrong exception: " + ex.getMessage();
}
try {
closeEntityManager(em);
errorMsg = errorMsg + "; closeEntityManager(em) didn't throw exception";
} catch(IllegalStateException ise) {
// expected
} catch(RuntimeException ex) {
errorMsg = errorMsg + "; closeEntityManager(em) threw wrong exception: " + ex.getMessage();
}
try {
em.contains(null);
errorMsg = errorMsg + "; em.contains() didn't throw exception";
} catch(IllegalStateException ise) {
// expected
} catch(RuntimeException ex) {
errorMsg = errorMsg + "; em.contains threw() wrong exception: " + ex.getMessage();
}
try {
em.getDelegate();
errorMsg = errorMsg + "; em.getDelegate() didn't throw exception";
} catch(IllegalStateException ise) {
// expected
} catch(RuntimeException ex) {
errorMsg = errorMsg + "; em.getDelegate() threw wrong exception: " + ex.getMessage();
}
try {
em.getReference(Employee.class, new Integer(1));
errorMsg = errorMsg + "; em.getReference() didn't throw exception";
} catch(IllegalStateException ise) {
// expected
} catch(RuntimeException ex) {
errorMsg = errorMsg + "; em.getReference() threw wrong exception: " + ex.getMessage();
}
try {
em.joinTransaction();
errorMsg = errorMsg + "; em.joinTransaction() didn't throw exception";
} catch(IllegalStateException ise) {
// expected
} catch(RuntimeException ex) {
errorMsg = errorMsg + "; em.joinTransaction() threw wrong exception: " + ex.getMessage();
}
try {
em.lock(null, null);
errorMsg = errorMsg + "; em.lock() didn't throw exception";
} catch(IllegalStateException ise) {
// expected
} catch(RuntimeException ex) {
errorMsg = errorMsg + "; em.lock() threw wrong exception: " + ex.getMessage();
}
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
//gf 1217 - Ensure join table defaults correctly when 'mappedby' not specified
public void testOneToManyDefaultJoinTableName() {
Department dept = new Department();
Employee manager = new Employee();
dept.addManager(manager);
EntityManager em = createEntityManager();
try {
beginTransaction(em);
em.persist(dept);
commitTransaction(em);
}catch (RuntimeException e) {
throw e;
}finally {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
}
}
// gf1732
public void testMultipleEntityManagerFactories() {
// TODO: This does not work on the server but should.
if (isOnServer()) {
return;
}
// close the original factory
closeEntityManagerFactory();
// create the new one - not yet deployed
EntityManagerFactory factory1 = getEntityManagerFactory();
// create the second one
EntityManagerFactory factory2 = Persistence.createEntityManagerFactory("default", JUnitTestCaseHelper.getDatabaseProperties());
// deploy
factory2.createEntityManager();
// close
factory2.close();
try {
// now try to getEM from the first one - this used to throw exception
factory1.createEntityManager();
// don't close factory1 if all is well
} catch (PersistenceException ex) {
fail("factory1.createEM threw exception: " + ex.getMessage());
factory1.close();
}
}
// gf2074: EM.clear throws NPE
public void testClearEntityManagerWithoutPersistenceContext() {
EntityManager em = createEntityManager();
try {
em.clear();
}finally {
closeEntityManager(em);
}
}
// Used by testClearEntityManagerWithoutPersistenceContextSimulateJTA().
// At first tried to use JTATransactionController class, but that introduced dependencies
// on javax.transaction package (and therefore failed in gf entity persistence tests).
static class DummyExternalTransactionController extends org.eclipse.persistence.transaction.AbstractTransactionController {
public boolean isRolledBack_impl(Object status){return false;}
protected void registerSynchronization_impl(org.eclipse.persistence.transaction.AbstractSynchronizationListener listener, Object txn) throws Exception{}
protected Object getTransaction_impl() throws Exception {return null;}
protected Object getTransactionKey_impl(Object transaction) throws Exception {return null;}
protected Object getTransactionStatus_impl() throws Exception {return null;}
protected void beginTransaction_impl() throws Exception{}
protected void commitTransaction_impl() throws Exception{}
protected void rollbackTransaction_impl() throws Exception{}
protected void markTransactionForRollback_impl() throws Exception{}
protected boolean canBeginTransaction_impl(Object status){return false;}
protected boolean canCommitTransaction_impl(Object status){return false;}
protected boolean canRollbackTransaction_impl(Object status){return false;}
protected boolean canIssueSQLToDatabase_impl(Object status){return false;}
protected boolean canMergeUnitOfWork_impl(Object status){return false;}
protected String statusToString_impl(Object status){return "";}
}
// gf2074: EM.clear throws NPE (JTA case)
public void testClearEntityManagerWithoutPersistenceContextSimulateJTA() {
EntityManager em = createEntityManager();
ServerSession ss = getServerSession();
closeEntityManager(em);
// in non-JTA case session doesn't have external transaction controller
boolean hasExternalTransactionController = ss.hasExternalTransactionController();
if(!hasExternalTransactionController) {
// simulate JTA case
ss.setExternalTransactionController(new DummyExternalTransactionController());
}
try {
testClearEntityManagerWithoutPersistenceContext();
}finally {
if(!hasExternalTransactionController) {
// remove the temporary set TransactionController
ss.setExternalTransactionController(null);
}
}
}
public void testDescriptorNamedQuery(){
ReadAllQuery query = new ReadAllQuery(Employee.class);
ExpressionBuilder builder = new ExpressionBuilder();
Expression exp = builder.get("firstName").equal(builder.getParameter("fName"));
exp = exp.and(builder.get("lastName").equal(builder.getParameter("lName")));
query.setSelectionCriteria(exp);
query.addArgument("fName", String.class);
query.addArgument("lName", String.class);
EntityManager em = createEntityManager();
Session session = getServerSession();
ClassDescriptor descriptor = session.getDescriptor(Employee.class);
descriptor.getQueryManager().addQuery("findByFNameLName", query);
beginTransaction(em);
try {
Employee emp = new Employee();
emp.setFirstName("Melvin");
emp.setLastName("Malone");
em.persist(emp);
em.flush();
Query ejbQuery = ((org.eclipse.persistence.jpa.JpaEntityManager)em.getDelegate()).createDescriptorNamedQuery("findByFNameLName", Employee.class);
List results = ejbQuery.setParameter("fName", "Melvin").setParameter("lName", "Malone").getResultList();
assertTrue(results.size() == 1);
emp = (Employee)results.get(0);
assertTrue(emp.getFirstName().equals("Melvin"));
assertTrue(emp.getLastName().equals("Malone"));
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
descriptor.getQueryManager().removeQuery("findByFNameLName");
}
public void testDescriptorNamedQueryForMultipleQueries(){
ReadAllQuery query = new ReadAllQuery(Employee.class);
ExpressionBuilder builder = new ExpressionBuilder();
Expression exp = builder.get("firstName").equal(builder.getParameter("fName"));
exp = exp.and(builder.get("lastName").equal(builder.getParameter("lName")));
query.setSelectionCriteria(exp);
query.addArgument("fName", String.class);
query.addArgument("lName", String.class);
ReadAllQuery query2 = new ReadAllQuery(Employee.class);
EntityManager em = createEntityManager();
Session session = getServerSession();
ClassDescriptor descriptor = session.getDescriptor(Employee.class);
descriptor.getQueryManager().addQuery("findEmployees", query);
descriptor.getQueryManager().addQuery("findEmployees", query2);
beginTransaction(em);
try {
Employee emp = new Employee();
emp.setFirstName("Melvin");
emp.setLastName("Malone");
em.persist(emp);
em.flush();
Vector args = new Vector(2);
args.addElement(String.class);
args.addElement(String.class);
Query ejbQuery = ((org.eclipse.persistence.jpa.JpaEntityManager)em.getDelegate()).createDescriptorNamedQuery("findEmployees", Employee.class, args);
List results = ejbQuery.setParameter("fName", "Melvin").setParameter("lName", "Malone").getResultList();
assertTrue(results.size() == 1);
emp = (Employee)results.get(0);
assertTrue(emp.getFirstName().equals("Melvin"));
assertTrue(emp.getLastName().equals("Malone"));
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
descriptor.getQueryManager().removeQuery("findEmployees");
}
// GF 2621
public void testDoubleMerge(){
EntityManager em = createEntityManager();
Employee employee = new Employee();
employee.setId(44);
employee.setVersion(0);
employee.setFirstName("Alfie");
Employee employee2 = new Employee();
employee2.setId(44);
employee2.setVersion(0);
employee2.setFirstName("Phillip");
Employee result = null;
try {
beginTransaction(em);
result = em.merge(employee);
result = em.merge(employee2);
assertTrue("The firstName was not merged properly", result.getFirstName().equals(employee2.getFirstName()));
em.flush();
} catch (PersistenceException e){
fail("A double merge of an object with the same key, caused two inserts instead of one.");
} finally {
rollbackTransaction(em);
}
}
// gf 3032
public void testPessimisticLockHintStartsTransaction(){
if (isOnServer()) {
// Extended persistence context are not supported in the server.
return;
}
if (!isSelectForUpateSupported()) {
return;
}
EntityManagerImpl em = (EntityManagerImpl)createEntityManager();
beginTransaction(em);
Query query = em.createNamedQuery("findAllEmployeesByFirstName");
query.setHint("eclipselink.pessimistic-lock", PessimisticLock.Lock);
query.setParameter("firstname", "Sarah");
List results = query.getResultList();
results.toString();
assertTrue("The extended persistence context is not in a transaction after a pessmimistic lock query", em.getActivePersistenceContext(em.getTransaction()).getParent().isInTransaction());
rollbackTransaction(em);
}
/**
* Test that all of the classes in the advanced model were weaved as expected.
*/
public void testWeaving() {
// Only test if weaving was on, test runs without weaving must set this system property.
if (JUnitTestCase.isWeavingEnabled()) {
internalTestWeaving(new Employee(), true, true);
internalTestWeaving(new FormerEmployment(), true, false);
internalTestWeaving(new Address(), true, false);
internalTestWeaving(new PhoneNumber(), true, false);
internalTestWeaving(new EmploymentPeriod(), true, false);
internalTestWeaving(new Buyer(), false, false); // field-locking
internalTestWeaving(new GoldBuyer(), false, false); // field-locking
internalTestWeaving(new PlatinumBuyer(), false, false); // field-locking
internalTestWeaving(new Department(), true, false); // eager 1-m
internalTestWeaving(new Golfer(), true, false);
internalTestWeaving(new GolferPK(), true, false);
internalTestWeaving(new SmallProject(), true, false);
internalTestWeaving(new LargeProject(), true, false);
internalTestWeaving(new Man(), true, false);
internalTestWeaving(new Woman(), true, false);
internalTestWeaving(new Vegetable(), false, false); // serialized
internalTestWeaving(new VegetablePK(), false, false);
internalTestWeaving(new WorldRank(), true, false);
internalTestWeaving(new Equipment(), true, false);
internalTestWeaving(new EquipmentCode(), true, false);
internalTestWeaving(new PartnerLink(), true, false);
}
}
/**
* Test that the object was weaved.
*/
public void internalTestWeaving(Object object, boolean changeTracking, boolean indirection) {
if (!(object instanceof PersistenceWeaved)) {
fail("Object not weaved:" + object);
}
if (indirection && (!(object instanceof PersistenceWeavedLazy))) {
fail("Object not weaved for indirection:" + object);
}
if (changeTracking && (!(object instanceof ChangeTracker))) {
fail("Object not weaved for ChangeTracker:" + object);
}
ClassDescriptor descriptor = getServerSession().getDescriptor(object);
if (!descriptor.isAggregateDescriptor()) {
if (changeTracking != descriptor.getObjectChangePolicy().isAttributeChangeTrackingPolicy()) {
fail("Descriptor not set to use change tracking policy correctly:" + object);
}
if (!(object instanceof PersistenceEntity)) {
fail("Object not weaved for PersistenceEntity:" + object);
}
if (!(object instanceof FetchGroupTracker)) {
fail("Object not weaved for FetchGroupTracker:" + object);
}
}
}
// this test was failing after transaction ailitche_main_6333458_070821
public void testManyToOnePersistCascadeOnFlush() {
boolean pass = false;
EntityManager em = createEntityManager();
beginTransaction(em);
try {
String firstName = "testManyToOneContains";
Address address = new Address();
address.setCountry(firstName);
Employee employee = new Employee();
employee.setFirstName(firstName);
em.persist(employee);
employee.setAddress(address);
em.flush();
pass = em.contains(address);
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
if(!pass) {
fail("em.contains(address) returned false");
}
}
// This test weaving works with over-writing methods in subclasses, and overloading methods.
public void testOverwrittingAndOverLoadingMethods() {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
Address address = new Address();
address.setCity("Ottawa");
Employee employee = new Employee();
employee.setAddress(address);
LargeProject project = new LargeProject();
project.setTeamLeader(employee);
em.persist(employee);
em.persist(project);
commitTransaction(em);
closeEntityManager(em);
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, employee.getId());
project = em.find(LargeProject.class, project.getId());
if ((employee.getAddress("Home") == null) || (!employee.getAddress("Home").getCity().equals("Ottawa"))) {
fail("Get address did not work.");
}
employee.setAddress("Toronto");
if (!employee.getAddress().getCity().equals("Toronto")) {
fail("Set address did not work.");
}
if (project.getTeamLeader() != employee) {
fail("Get team leader did not work, team is: " + project.getTeamLeader() + " but should be:" + employee);
}
em.remove(employee.getAddress());
em.remove(employee);
em.remove(project);
} finally {
if (isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
}
// This tests that new objects referenced by new objects are found on commit.
public void testDiscoverNewReferencedObject() {
String firstName = "testDiscoverNewReferencedObject";
// setup: create and persist Employee
EntityManager em = createEntityManager();
int employeeId = 0;
beginTransaction(em);
try {
Employee employee = new Employee();
employee.setFirstName(firstName);
employee.setLastName("Employee");
em.persist(employee);
commitTransaction(em);
employeeId = employee.getId();
} finally {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
// test: add to the exsisting Employee a new Manager with new Phones
em = createEntityManager();
int managerId = 0;
beginTransaction(em);
try {
Employee manager = new Employee();
manager.setFirstName(firstName);
manager.setLastName("Manager");
PhoneNumber phoneNumber1 = new PhoneNumber("home", "613", "1111111");
manager.addPhoneNumber(phoneNumber1);
PhoneNumber phoneNumber2 = new PhoneNumber("work", "613", "2222222");
manager.addPhoneNumber(phoneNumber2);
Employee employee = em.find(Employee.class, employeeId);
manager.addManagedEmployee(employee);
commitTransaction(em);
managerId = manager.getId();
} finally {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
// verify: were all the new objects written to the data base?
String errorMsg = "";
em = createEntityManager();
try {
Employee manager = (Employee)em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.id = "+managerId).setHint("eclipselink.refresh", "true").getSingleResult();
if(manager == null) {
errorMsg = "Manager hasn't been written into the db";
} else {
if(manager.getPhoneNumbers().size() != 2) {
errorMsg = "Manager has a wrong number of Phones = "+manager.getPhoneNumbers().size()+"; should be 2";
}
}
} finally {
closeEntityManager(em);
}
// clean up: delete Manager - all other object will be cascade deleted.
em = createEntityManager();
beginTransaction(em);
try {
if(managerId != 0) {
Employee manager = em.find(Employee.class, managerId);
em.remove(manager);
} else if(employeeId != 0) {
// if Manager hasn't been created - delete Employee
Employee employee = em.find(Employee.class, employeeId);
em.remove(employee);
}
} finally {
if(isTransactionActive(em)) {
rollbackTransaction(em);
}
closeEntityManager(em);
}
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
// bug 6006423: BULK DELETE QUERY FOLLOWED BY A MERGE RETURNS DELETED OBJECT
public void testBulkDeleteThenMerge() {
if (isOnServer()) {
// Got transaction timeout on server.
return;
}
String firstName = "testBulkDeleteThenMerge";
// setup - create Employee
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName(firstName);
emp.setLastName("Original");
em.persist(emp);
commitTransaction(em);
closeEntityManager(em);
int id = emp.getId();
// test
// delete the Employee using bulk delete
em = createEntityManager();
beginTransaction(em);
em.createQuery("DELETE FROM Employee e WHERE e.firstName = '"+firstName+"'").executeUpdate();
commitTransaction(em);
closeEntityManager(em);
// then re-create and merge the Employee using the same pk
em = createEntityManager();
beginTransaction(em);
emp = new Employee();
emp.setId(id);
emp.setFirstName(firstName);
emp.setLastName("New");
em.merge(emp);
try {
commitTransaction(em);
} finally {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
}
// verify
String errorMsg = "";
em = createEntityManager();
// is the right Employee in the cache?
emp = (Employee)em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.id = " + id).getSingleResult();
if(emp == null) {
errorMsg = "Cache: Employee is not found; ";
} else {
if(!emp.getLastName().equals("New")) {
errorMsg = "Cache: wrong lastName = "+emp.getLastName()+"; should be New; ";
}
}
// is the right Employee in the db?
emp = (Employee)em.createQuery("SELECT OBJECT(e) FROM Employee e WHERE e.id = " + id).setHint("eclipselink.refresh", Boolean.TRUE).getSingleResult();
if(emp == null) {
errorMsg = errorMsg + "DB: Employee is not found";
} else {
if(!emp.getLastName().equals("New")) {
errorMsg = "DB: wrong lastName = "+emp.getLastName()+"; should be New";
}
// clean up in case the employee is in the db
beginTransaction(em);
em.remove(emp);
commitTransaction(em);
}
closeEntityManager(em);
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
public void testNativeSequences() {
ServerSession ss = JUnitTestCase.getServerSession();
boolean doesPlatformSupportIdentity = ss.getPlatform().supportsIdentity();
boolean doesPlatformSupportSequenceObjects = ss.getPlatform().supportsSequenceObjects();
String errorMsg = "";
// SEQ_GEN_IDENTITY sequence defined by
// @GeneratedValue(strategy=IDENTITY)
boolean isIdentity = ss.getPlatform().getSequence("SEQ_GEN_IDENTITY").shouldAcquireValueAfterInsert();
if(doesPlatformSupportIdentity != isIdentity) {
errorMsg = "SEQ_GEN_IDENTITY: doesPlatformSupportIdentity = " + doesPlatformSupportIdentity +", but isIdentity = " + isIdentity +"; ";
}
// ADDRESS_SEQ sequence defined by
// @GeneratedValue(generator="ADDRESS_SEQ")
// @SequenceGenerator(name="ADDRESS_SEQ", allocationSize=25)
boolean isSequenceObject = !ss.getPlatform().getSequence("ADDRESS_SEQ").shouldAcquireValueAfterInsert();
if(doesPlatformSupportSequenceObjects != isSequenceObject) {
errorMsg = errorMsg +"ADDRESS_SEQ: doesPlatformSupportSequenceObjects = " + doesPlatformSupportSequenceObjects +", but isSequenceObject = " + isSequenceObject;
}
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
/**
* Test that sequence numbers allocated but unused in the transaction
* kept after transaction commits
* in case SequencingCallback used (that happens if TableSequence is used without
* using sequencing connection pool).
*/
public void testSequencePreallocationUsingCallbackTest() {
// setup
ServerSession ss = getServerSession();
// make sure the sequence has both preallocation and callback
// (the latter means not using sequencing connection pool,
// acquiring values before insert and requiring transaction).
//if(ss.getSequencingControl().shouldUseSeparateConnection()) {
// fail("setup failure: the test requires serverSession.getSequencingControl().shouldUseSeparateConnection()==false");
String seqName = ss.getDescriptor(Employee.class).getSequenceNumberName();
Sequence sequence = getServerSession().getLogin().getSequence(seqName);
if(sequence.getPreallocationSize() < 2) {
fail("setup failure: the test requires sequence preallocation size greater than 1");
}
if(sequence.shouldAcquireValueAfterInsert()) {
fail("setup failure: the test requires sequence that acquires value before insert, like TableSequence");
}
if(!sequence.shouldUseTransaction()) {
fail("setup failure: the test requires sequence that uses transaction, like TableSequence");
}
// clear all already allocated sequencing values for seqName
getServerSession().getSequencingControl().initializePreallocated(seqName);
// test
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp1 = new Employee();
emp1.setFirstName("testSequencePreallocation");
emp1.setLastName("1");
em.persist(emp1);
int assignedSequenceNumber = emp1.getId();
commitTransaction(em);
// verify
em = createEntityManager();
beginTransaction(em);
Employee emp2 = new Employee();
emp2.setFirstName("testSequencePreallocation");
emp2.setLastName("2");
em.persist(emp2);
int nextSequenceNumber = emp2.getId();
// only need nextSequenceNumber, no need to commit
rollbackTransaction(em);
// cleanup
// remove the object that has been created in setup
em = createEntityManager();
beginTransaction(em);
emp1 = em.find(Employee.class, assignedSequenceNumber);
em.remove(emp1);
commitTransaction(em);
// report result
if(assignedSequenceNumber + 1 != nextSequenceNumber) {
fail("Transaction that assigned sequence number committed, assignedSequenceNumber = " + assignedSequenceNumber +", but nextSequenceNumber = "+ nextSequenceNumber +"("+Integer.toString(assignedSequenceNumber+1)+" was expected)");
}
}
/**
* Create a test employee.
*/
protected Employee createEmployee(String name) {
EntityManager em = createEntityManager();
beginTransaction(em);
Employee employee = new Employee();
employee.setFirstName(name);
em.persist(employee);
commitTransaction(em);
return employee;
}
public void testGetEntityManagerFactory() {
// getEntityManagerFactory not supported on 1.0
if (! isJPA10()) {
Employee emp = new Employee();
EntityManager em = createEntityManager();
try {
beginTransaction(em);
emp.setFirstName("test");
em.persist(emp);
commitTransaction(em);
EntityManagerFactory emf = em.getEntityManagerFactory();
if (emf == null) {
fail("Factory is null.");
}
} finally {
closeEntityManager(em);
}
}
}
/**
* Test getReference() API.
*/
public void testGetReference() {
Employee employee = createEmployee("testGetReference");
int id = employee.getId();
int version = employee.getVersion();
EntityManager em = createEntityManager();
beginTransaction(em);
employee = em.getReference(Employee.class, id);
if (!employee.getFirstName().equals("testGetReference")) {
fail("getReference returned the wrong object");
}
commitTransaction(em);
if (employee.getVersion() != version) {
fail("fetched object was updated");
}
clearCache();
em = createEntityManager();
beginTransaction(em);
employee = em.getReference(Employee.class, id);
if (employee instanceof FetchGroupTracker) {
if (((FetchGroupTracker)employee)._persistence_isAttributeFetched("firstName")) {
fail("getReference fetched object.");
}
}
if (!employee.getFirstName().equals("testGetReference")) {
fail("getReference returned the wrong object");
}
commitTransaction(em);
if (employee.getVersion() != version) {
fail("fetched object was updated");
}
clearCache();
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, id);
if (!employee.getFirstName().equals("testGetReference")) {
fail("find returned the wrong object");
}
commitTransaction(em);
clearCache();
List key = new ArrayList();
key.add(id);
em = createEntityManager();
beginTransaction(em);
employee = em.getReference(Employee.class, key);
if (!employee.getFirstName().equals("testGetReference")) {
fail("getReference returned the wrong object");
}
commitTransaction(em);
clearCache();
em = createEntityManager();
beginTransaction(em);
employee = em.find(Employee.class, key);
if (!employee.getFirstName().equals("testGetReference")) {
fail("find returned the wrong object");
}
commitTransaction(em);
}
/**
* Test getReference() with update.
*/
public void testGetReferenceUpdate() {
int id = createEmployee("testGetReference").getId();
clearCache();
EntityManager em = createEntityManager();
beginTransaction(em);
Employee employee = em.getReference(Employee.class, id);
employee.setFirstName("changed");
commitTransaction(em);
verifyObjectInCacheAndDatabase(employee);
}
/**
* Test adding a new object to a collection.
*/
public void testCollectionAddNewObjectUpdate() {
int id = createEmployee("testCollectionAddNew").getId();
clearCache();
EntityManager em = createEntityManager();
beginTransaction(em);
Employee employee = em.find(Employee.class, id);
SmallProject project = new SmallProject();
employee.getProjects().add(project);
project.getTeamMembers().add(employee);
commitTransaction(em);
// 264768: Certain application servers like WebSphere 7 will call em.clear() during commit()
// in order that the entityManager is cleared before returning the em to their server pool.
// We will want to verify that the entity is managed before accessing its properties and causing
// the object to be rebuilt with any non-direct fields uninstantiated.
// Note: even in this case the entity should still be in the shared cache and database below
if(em.contains(employee)) {
verifyObject(project);
verifyObject(employee);
}
clearCache();
if(em.contains(employee)) {
verifyObject(project);
verifyObject(employee);
}
}
/**
* Test getReference() with bad id.
*/
public void testBadGetReference() {
clearCache();
EntityManager em = createEntityManager();
Exception caught = null;
try {
Employee employee = em.getReference(Employee.class, -123);
employee.getFirstName();
} catch (EntityNotFoundException exception) {
caught = exception;
}
if (caught == null) {
fail("getReference did not throw an error for a bad id");
}
}
/**
* Test getReference() used in update.
*/
public void testGetReferenceUsedInUpdate() {
Employee employee = createEmployee("testGetReference");
int id = employee.getId();
int version = employee.getVersion();
clearCache();
EntityManager em = createEntityManager();
beginTransaction(em);
employee = em.getReference(Employee.class, id);
if (employee instanceof FetchGroupTracker) {
if (((FetchGroupTracker)employee)._persistence_isAttributeFetched("firstName")) {
fail("getReference fetched object.");
}
}
Employee newEmployee = new Employee();
newEmployee.setFirstName("new");
newEmployee.setManager(employee);
em.persist(newEmployee);
commitTransaction(em);
if (employee instanceof FetchGroupTracker) {
if (((FetchGroupTracker)employee)._persistence_isAttributeFetched("firstName")) {
fail("commit fetched object.");
}
}
// 264768: Certain application servers like WebSphere 7 will call em.clear() during commit()
// in order that the entityManager is cleared before returning the em to their server pool.
// We will want to verify that the entity is managed before accessing its properties and causing
// the object to be rebuilt with any non-direct fields uninstantiated.
// Note: even in this case the entity should still be in the shared cache and database below
if(em.contains(employee)) {
if (employee.getVersion() != version) {
fail("un-fetched object was updated");
}
}
verifyObjectInCacheAndDatabase(newEmployee);
}
public void testClassInstanceConverter(){
EntityManager em = createEntityManager();
beginTransaction(em);
Address add = new Address();
add.setCity("St. Louis");
add.setType(new Bungalow());
em.persist(add);
commitTransaction(em);
int assignedSequenceNumber = add.getId();
em.clear();
getServerSession().getIdentityMapAccessor().initializeAllIdentityMaps();
add = em.find(Address.class, assignedSequenceNumber);
assertTrue("Did not correctly persist a mapping using a class-instance converter", (add.getType() instanceof Bungalow));
beginTransaction(em);
add = em.find(Address.class, assignedSequenceNumber);
em.remove(add);
commitTransaction(em);
}
/**
* See bug# 210280: verify that the URL encoding for spaces and multibyte chars is handled properly in the EMSetup map lookup
* UC1 - EM has no spaces or multi-byte chars in name or path
* UC2 - EM has spaces hex(20) in EM name but not in path
* UC3/4 are fixed by 210280 - the other UC tests are for regression
* UC3 - EM has spaces in path but not in the EM name
* UC4 - EM has spaces in path and EM name
* UC5 - EM has multi-byte hex(C3A1) chars in EM name but not in path
* Keep resource with spaces and multibyte chars separate
* UC6 - EM has multi-byte chars in path but not EM name
* UC7 - EM has multi-byte chars in path and EM name
* UC8 - EM has spaces and multi-byte chars in EM name but not in path
* UC9 - EM has spaces and multi-byte chars in path and EM name
*/
// UC2 - EM has spaces in EM name but not in path
public void test210280EntityManagerFromPUwithSpaceInNameButNotInPath() {
// This EM is defined in a persistence.xml that is off eclipselink-advanced-properties (no URL encoded chars in path)
privateTest210280EntityManagerWithPossibleSpacesInPathOrName(
"A JPAADVProperties pu with spaces in the name",
"with a name containing spaces was not found.");
}
// UC3 - EM has spaces in path but not in the EM name
public void test210280EntityManagerFromPUwithSpaceInPathButNotInName() {
// This EM is defined in a persistence.xml that is off [eclipselink-pu with spaces] (with URL encoded chars in path)
privateTest210280EntityManagerWithPossibleSpacesInPathOrName(
"eclipselink-pu-with-spaces-in-the-path-but-not-the-name",
"with a path containing spaces was not found.");
}
// UC4 - EM has spaces in the path and name
public void test210280EntityManagerFromPUwithSpaceInNameAndPath() {
// This EM is defined in a persistence.xml that is off [eclipselink-pu with spaces] (with URL encoded chars in path)
privateTest210280EntityManagerWithPossibleSpacesInPathOrName(
"eclipselink-pu with spaces in the path and name",
"with a path and name both containing spaces was not found.");
}
private void privateTest210280EntityManagerWithPossibleSpacesInPathOrName(String puName, String failureMessagePostScript) {
EntityManager em = null;
try {
em = createEntityManager(puName);
} catch (Exception exception) {
throw new RuntimeException("A Persistence Unit [" + puName + "] " + failureMessagePostScript, exception);
} finally {
if (null != em) {
closeEntityManager(em);
}
}
}
public void testConnectionPolicy() {
internalTestConnectionPolicy(false);
}
public void testConnectionPolicySetProperty() {
// Don't run this test in a JPA 1.0 environment.
if (! isJPA10()) {
internalTestConnectionPolicy(true);
}
}
public void internalTestConnectionPolicy(boolean useSetProperty) {
// setup
String errorMsg = "";
HashMap properties = null;
if(!useSetProperty) {
properties = new HashMap();
properties.put(EntityManagerProperties.JDBC_USER, "em_user");
properties.put(EntityManagerProperties.JDBC_PASSWORD, "em_password");
properties.put(EntityManagerProperties.JTA_DATASOURCE, "em_jta_datasource");
properties.put(EntityManagerProperties.NON_JTA_DATASOURCE, "em_nonjta_datasource");
properties.put(EntityManagerProperties.EXCLUSIVE_CONNECTION_MODE, ExclusiveConnectionMode.Always);
}
// test
EntityManager em = null;
boolean isInTransaction = false;
try {
// assume that if JTA is used on server then EntityManager is always injected.
boolean isEmInjected = isOnServer() && getServerSession().getLogin().shouldUseExternalTransactionController();
if (isEmInjected) {
em = createEntityManager();
// In server jta case need a transaction - otherwise the wrapped EntityManagerImpl is not kept.
beginTransaction(em);
isInTransaction = true;
((EntityManagerImpl)em.getDelegate()).setProperties(properties);
} else {
EntityManagerFactory emFactory = getEntityManagerFactory();
em = emFactory.createEntityManager(properties);
}
if(useSetProperty) {
em.setProperty(EntityManagerProperties.JDBC_USER, "em_user");
em.setProperty(EntityManagerProperties.JDBC_PASSWORD, "em_password");
em.setProperty(EntityManagerProperties.JTA_DATASOURCE, "em_jta_datasource");
em.setProperty(EntityManagerProperties.NON_JTA_DATASOURCE, "em_nonjta_datasource");
em.setProperty(EntityManagerProperties.EXCLUSIVE_CONNECTION_MODE, ExclusiveConnectionMode.Always);
}
// verify
ClientSession clientSession;
if (isOnServer()) {
clientSession = (ClientSession)((EntityManagerImpl)em.getDelegate()).getActivePersistenceContext(null).getParent();
} else {
clientSession = (ClientSession)((EntityManagerImpl)em).getActivePersistenceContext(null).getParent();
}
if(!clientSession.isExclusiveIsolatedClientSession()) {
errorMsg += "ExclusiveIsolatedClientSession was expected\n";
}
ConnectionPolicy policy = clientSession.getConnectionPolicy();
if(policy.isPooled()) {
errorMsg += "NOT pooled policy was expected\n";
}
String user = (String)policy.getLogin().getProperty("user");
if(!user.equals("em_user")) {
errorMsg += "em_user was expected\n";
}
String password = (String)policy.getLogin().getProperty("password");
if(!password.equals("em_password")) {
errorMsg += "em_password was expected\n";
}
if(! (((DatasourceLogin)policy.getLogin()).getConnector() instanceof JNDIConnector)) {
errorMsg += "JNDIConnector was expected\n";
} else {
JNDIConnector jndiConnector = (JNDIConnector)((DatasourceLogin)policy.getLogin()).getConnector();
String dataSourceName = jndiConnector.getName();
if(dataSourceName == null) {
errorMsg += "NON null dataSourceName was expected\n";
} else {
if(clientSession.getParent().getLogin().shouldUseExternalTransactionController()) {
if(dataSourceName.equals("em_nonjta_datasource")) {
errorMsg += "em_jta_datasource was expected\n";
}
} else {
if(dataSourceName.equals("em_jta_datasource")) {
errorMsg += "em_nonjta_datasource was expected\n";
}
}
}
}
} finally {
// clean-up
if (isInTransaction) {
rollbackTransaction(em);
}
if(em != null) {
closeEntityManager(em);
}
}
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
/*
* Added for bug 235340 - parameters in named query are not transformed when IN is used.
* Before the fix this used to throw exception.
*/
public void testConverterIn() {
EntityManager em = createEntityManager();
List<Employee> emps = em.createQuery("SELECT e FROM Employee e WHERE e.gender IN (:GENDER1, :GENDER2)").
setParameter("GENDER1", Employee.Gender.Male).
setParameter("GENDER2", Employee.Gender.Female).
getResultList();
emps.toString();
closeEntityManager(em);
}
// Bug 237281 - ensure we throw the correct exception when trying to persist a non-entity subclass of an entity
public void testExceptionForPersistNonEntitySubclass(){
EntityManager em = createEntityManager();
Exception caughtException = null;
try{
beginTransaction(em);
em.persist(new SuperLargeProject());
} catch (IllegalArgumentException e){
caughtException = e;
} finally {
rollbackTransaction(em);
closeEntityManager(em);
}
if (caughtException == null){
fail("Caught an incorrect exception when persisting a non entity.");
}
}
// bug 237281 - ensure seeting InheritancePolicy to allow non-entity subclasses to be persisted as their
// superclass works
public void testEnabledPersistNonEntitySubclass() {
EntityManager em = createEntityManager();
InheritancePolicy ip = getServerSession().getDescriptor(Project.class).getInheritancePolicy();
boolean describesNonPersistentSubclasses = ip.getDescribesNonPersistentSubclasses();
ip.setDescribesNonPersistentSubclasses(true);
beginTransaction(em);
SuperLargeProject s1 = new SuperLargeProject("Super 1");
try {
em.persist(s1);
} catch (Exception e) {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
fail("Persist operation was not cascaded to related non-entity, thrown: " + e);
} finally {
rollbackTransaction(em);
ip.setDescribesNonPersistentSubclasses(describesNonPersistentSubclasses);
closeEntityManager(em);
}
}
// bug 239505 - Ensure our Embeddables succeed a call to clone
public void testCloneEmbeddable(){
EmployeePopulator populator = new EmployeePopulator();
EmploymentPeriod period = populator.employmentPeriodExample1();
try {
period.clone();
} catch (Exception e){
fail("Exception thrown when trying to clone an Embeddable: " + e.toString());
}
}
// bug 232555 - NPE setting embedded attributes after persist in woven classes
public void testEmbeddedNPE() {
if (isOnServer()) {
// Close is not used on server.
return;
}
// setup
// create and persist an Employee
Employee emp = new Employee();
emp.setFirstName("testEmbeddedNPE");
EntityManager em = createEntityManager();
beginTransaction(em);
em.persist(emp);
commitTransaction(em);
// test
// add an embedded to the persisted Employee
EmploymentPeriod period = new EmploymentPeriod(Date.valueOf("2007-01-01"), Date.valueOf("2007-12-31"));
try {
// that used to cause NPE
emp.setPeriod(period);
} catch (NullPointerException npe) {
// clean-up
beginTransaction(em);
em.remove(emp);
commitTransaction(em);
em.close();
throw npe;
}
// update the Employee in the db
beginTransaction(em);
em.merge(emp);
commitTransaction(em);
// verify
// make sure that the Employee has been written into the db correctly:
// clear both em and shared cache
em.clear();
clearCache();
// and re-read it
Employee readEmp = em.find(Employee.class, emp.getId());
// should be the same as the original one
boolean equal = getServerSession().compareObjects(emp, readEmp);
// clean-up
if(readEmp != null) {
beginTransaction(em);
//readEmp = em.find(Employee.class, emp.getId());
em.remove(readEmp);
commitTransaction(em);
}
em.close();
if(!equal) {
fail("The Employee wasn't updated correctly in the db");
}
}
// Bug 256296: Reconnect fails when session loses connectivity
static class AcquireReleaseListener extends SessionEventAdapter {
HashSet<Accessor> acquiredReadConnections = new HashSet();
HashSet<Accessor> acquiredWriteConnections = new HashSet();
public void postAcquireConnection(SessionEvent event) {
Accessor accessor = (Accessor)event.getResult();
Session session = event.getSession();
if(session.isServerSession()) {
acquiredReadConnections.add(accessor);
((ServerSession)session).log(SessionLog.FINEST, SessionLog.CONNECTION, "AcquireReleaseListener.acquireReadConnection: " + nAcquredReadConnections(), (Object[])null, accessor, false);
} else {
acquiredWriteConnections.add(accessor);
((ClientSession)session).log(SessionLog.FINEST, SessionLog.CONNECTION, "AcquireReleaseListener.acquireWriteConnection: " + nAcquredWriteConnections(), (Object[])null, accessor, false);
}
}
public void preReleaseConnection(SessionEvent event) {
Accessor accessor = (Accessor)event.getResult();
Session session = event.getSession();
if(session.isServerSession()) {
acquiredReadConnections.remove(accessor);
((ServerSession)session).log(SessionLog.FINEST, SessionLog.CONNECTION, "AcquireReleaseListener.releaseReadConnection: " + nAcquredReadConnections(), (Object[])null, accessor, false);
} else {
acquiredWriteConnections.remove(accessor);
((ClientSession)session).log(SessionLog.FINEST, SessionLog.CONNECTION, "AcquireReleaseListener.releaseWriteConnection: " + nAcquredWriteConnections(), (Object[])null, accessor, false);
}
}
int nAcquredReadConnections() {
return acquiredReadConnections.size();
}
int nAcquredWriteConnections() {
return acquiredWriteConnections.size();
}
void clear() {
acquiredReadConnections.clear();
acquiredWriteConnections.clear();
}
}
public void testEMCloseAndOpen(){
Assert.assertFalse("Warning Sybase Driver does not work with DriverWrapper, testEMCloseAndOpen can't run on this platform.", JUnitTestCase.getServerSession().getPlatform().isSybase());
if (isOnServer()) {
// Uses DefaultConnector.
return;
}
// normally false; set to true for debug output for just this single test
boolean shouldForceFinest = false;
int originalLogLevel = -1;
ServerSession ss = ((EntityManagerFactoryImpl)getEntityManagerFactory()).getServerSession();
// make sure the id hasn't been already used - it will be assigned to a new object (in case sequencing is not used).
int id = (ss.getNextSequenceNumberValue(Employee.class)).intValue();
// cache the original driver name and connection string.
String originalDriverName = ss.getLogin().getDriverClassName();
String originalConnectionString = ss.getLogin().getConnectionString();
// the new driver name and connection string to be used by the test
String newDriverName = DriverWrapper.class.getName();
String newConnectionString = DriverWrapper.codeUrl(originalConnectionString);
// setup the wrapper driver
DriverWrapper.initialize(originalDriverName);
// The test need to connect with the new driver and connection string.
// That could be done in JPA:
// // close the existing emf
// closeEntityManagerFactory();
// HashMap properties = new HashMap(JUnitTestCaseHelper.getDatabaseProperties());
// properties.put(PersistenceUnitProperties.JDBC_DRIVER, newDriverName);
// properties.put(PersistenceUnitProperties.JDBC_URL, newConnectionString);
// emf = getEntityManagerFactory(properties);
// However this only works in case closeEntityManagerFactory disconnects the original ServerSession,
// which requires the factory to be the only one using the persistence unit.
// Alternative - and faster - approach is to disconnect the original session directly
// and then reconnected it with the new driver and connection string.
ss.logout();
ss.getLogin().setDriverClassName(newDriverName);
ss.getLogin().setConnectionString(newConnectionString);
AcquireReleaseListener listener = new AcquireReleaseListener();
ss.getEventManager().addListener(listener);
if(shouldForceFinest) {
if(ss.getLogLevel() != SessionLog.FINEST) {
originalLogLevel = ss.getLogLevel();
ss.setLogLevel(SessionLog.FINEST);
}
}
ss.login();
String errorMsg = "";
// test several configurations:
// all exclusive connection modes
String[] exclusiveConnectionModeArray = new String[]{ExclusiveConnectionMode.Transactional, ExclusiveConnectionMode.Isolated, ExclusiveConnectionMode.Always};
try {
for(int i=0; i<3; i++) {
String exclusiveConnectionMode = exclusiveConnectionModeArray[i];
for(int j=0; j<2; j++) {
// either using or not using sequencing
boolean useSequencing = (j==0);
ss.log(SessionLog.FINEST, SessionLog.CONNECTION, "testEMCloseAndOpen: " + (useSequencing ? "sequencing" : "no sequencing"), (Object[])null, null, false);
HashMap emProperties = new HashMap(1);
emProperties.put(EntityManagerProperties.EXCLUSIVE_CONNECTION_MODE, exclusiveConnectionMode);
EntityManager em = createEntityManager(emProperties);
em.find(Employee.class, 1);
Employee emp = null;
boolean hasUnexpectedlyCommitted = false;
try{
em.getTransaction().begin();
// imitate disconnecting from network:
// driver's connect method and any method on any connection will throw SQLException
ss.log(SessionLog.FINEST, SessionLog.CONNECTION, "testEMCloseAndOpen: DriverWrapper.breakDriver(); DriverWrapper.breakOldConnections();", (Object[])null, null, false);
DriverWrapper.breakDriver();
DriverWrapper.breakOldConnections();
emp = new Employee();
if(!useSequencing) {
emp.setId(id);
}
em.persist(emp);
em.getTransaction().commit();
// should never get here - all connections should be broken.
hasUnexpectedlyCommitted = true;
errorMsg += "useSequencing = " + useSequencing + "; exclusiveConnectionMode = " + exclusiveConnectionMode + ": Commit has unexpectedly succeeded - should have failed because all connections broken. driver = " + ss.getLogin().getDriverClassName() + "; url = " + ss.getLogin().getConnectionString();
} catch (Exception e){
// expected exception - connection is invalid and cannot be reconnected.
if(em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
}
closeEntityManager(em);
// verify - all connections should be released
String localErrorMsg = "";
if(listener.nAcquredWriteConnections() > 0) {
localErrorMsg += "writeConnection not released; ";
}
if(listener.nAcquredReadConnections() > 0) {
localErrorMsg += "readConnection not released; ";
}
if(localErrorMsg.length() > 0) {
localErrorMsg = exclusiveConnectionMode + " useSequencing="+useSequencing + ": " + localErrorMsg;
errorMsg += localErrorMsg;
listener.clear();
}
// imitate reconnecting to network:
// driver's connect method will now work, all newly acquired connections will work, too;
// however the old connections cached in the connection pools are still invalid.
DriverWrapper.repairDriver();
ss.log(SessionLog.FINEST, SessionLog.CONNECTION, "testEMCloseAndOpen: DriverWrapper.repairDriver();", (Object[])null, null, false);
boolean failed = true;
try {
em = createEntityManager();
em.find(Employee.class, 1);
if(!hasUnexpectedlyCommitted) {
em.getTransaction().begin();
emp = new Employee();
if(!useSequencing) {
emp.setId(id);
}
em.persist(emp);
em.getTransaction().commit();
failed = false;
}
} finally {
if(failed) {
// This should not happen
if(em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
closeEntityManager(em);
if(errorMsg.length() > 0) {
ss.log(SessionLog.FINEST, SessionLog.CONNECTION, "testEMCloseAndOpen: errorMsg: " + "\n" + errorMsg, (Object[])null, null, false);
}
}
}
// clean-up
// remove the inserted object
em.getTransaction().begin();
em.remove(emp);
em.getTransaction().commit();
closeEntityManager(em);
}
}
} finally {
// clear the driver wrapper
DriverWrapper.clear();
// reconnect the session using the original driver and connection string
ss.getEventManager().removeListener(listener);
ss.logout();
if(originalLogLevel >= 0) {
ss.setLogLevel(originalLogLevel);
}
ss.getLogin().setDriverClassName(originalDriverName);
ss.getLogin().setConnectionString(originalConnectionString);
ss.login();
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
}
// Bug 256284: Closing an EMF where the database is unavailable results in deployment exception on redeploy
public void testEMFactoryCloseAndOpen(){
if (isOnServer()) {
// Uses DefaultConnector.
return;
}
Assert.assertFalse("Warning Sybase Driver does not work with DriverWrapper, testEMCloseAndOpen can't run on this platform.", JUnitTestCase.getServerSession().getPlatform().isSybase());
// cache the driver name
String driverName = ((EntityManagerFactoryImpl)getEntityManagerFactory()).getServerSession().getLogin().getDriverClassName();
String originalConnectionString = ((EntityManagerFactoryImpl)getEntityManagerFactory()).getServerSession().getLogin().getConnectionString();
// disconnect the session
closeEntityManagerFactory();
// setup the wrapper driver
DriverWrapper.initialize(driverName);
// connect the session using the wrapper driver
HashMap properties = new HashMap(JUnitTestCaseHelper.getDatabaseProperties());
properties.put(PersistenceUnitProperties.JDBC_DRIVER, DriverWrapper.class.getName());
properties.put(PersistenceUnitProperties.JDBC_URL, DriverWrapper.codeUrl(originalConnectionString));
getEntityManagerFactory(properties);
// this connects the session
EntityManager em = createEntityManager();
// imitate disconnecting from network:
// driver's connect method and any method on any connection will throw SQLException
DriverWrapper.breakDriver();
DriverWrapper.breakOldConnections();
// close factory
try {
closeEntityManagerFactory();
} finally {
// clear the driver wrapper
DriverWrapper.clear();
}
String errorMsg = "";
//reconnect the session
em = createEntityManager();
//verify connections
Iterator<ConnectionPool> itPools = ((EntityManagerImpl)em).getServerSession().getConnectionPools().values().iterator();
while (itPools.hasNext()) {
ConnectionPool pool = itPools.next();
int disconnected = 0;
for (int i=0; i < pool.getConnectionsAvailable().size(); i++) {
if (!(pool.getConnectionsAvailable().get(i)).isConnected()) {
disconnected++;
}
}
if (disconnected > 0) {
errorMsg += pool.getName() + " has " + disconnected + " connections; ";
}
}
if (errorMsg.length() > 0) {
fail(errorMsg);
}
}
/**
* This test ensures that the eclipselink.batch query hint works. It tests
* two things.
*
* 1. That the batch read attribute is properly added to the queyr 2. That
* the query will execute
*
* It does not do any verification that the batch reading feature actually
* works. That is left for the batch reading testing to do.
*/
public void testForUOWInSharedCacheWithBatchQueryHint() {
if (isOnServer()) {
// Can not unwrap on WLS.
return;
}
int id1 = 0;
EntityManager em = createEntityManager();
beginTransaction(em);
Employee manager = new Employee();
manager.setFirstName("Marvin");
manager.setLastName("Malone");
PhoneNumber number = new PhoneNumber("cell", "613", "888-8888");
manager.addPhoneNumber(number);
number = new PhoneNumber("home", "613", "888-8880");
manager.addPhoneNumber(number);
em.persist(manager);
id1 = manager.getId();
Employee emp = new Employee();
emp.setFirstName("Melvin");
emp.setLastName("Malone");
emp.setManager(manager);
manager.addManagedEmployee(emp);
number = new PhoneNumber("cell", "613", "888-9888");
emp.addPhoneNumber(number);
number = new PhoneNumber("home", "613", "888-0880");
emp.addPhoneNumber(number);
em.persist(emp);
emp = new Employee();
emp.setFirstName("David");
emp.setLastName("Malone");
emp.setManager(manager);
manager.addManagedEmployee(emp);
number = new PhoneNumber("cell", "613", "888-9988");
emp.addPhoneNumber(number);
number = new PhoneNumber("home", "613", "888-0980");
emp.addPhoneNumber(number);
em.persist(emp);
commitTransaction(em);
closeEntityManager(em);
clearCache();
// org.eclipse.persistence.jpa.JpaQuery query =
// (org.eclipse.persistence.jpa.JpaQuery)em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
em = createEntityManager();
beginTransaction(em);
org.eclipse.persistence.jpa.JpaQuery query = (org.eclipse.persistence.jpa.JpaQuery) em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone' order by e.firstName");
query.setHint(QueryHints.BATCH, "e.phoneNumbers");
List resultList = query.getResultList();
emp = (Employee) resultList.get(0);
emp.setFirstName("somethingelse" + System.currentTimeMillis());
// execute random other query
em.createQuery("SELECT e FROM Employee e WHERE e.lastName = 'Malone'").getResultList();
((Employee) resultList.get(1)).getPhoneNumbers().hashCode();
commitTransaction(em);
try {
emp = (Employee) JpaHelper.getEntityManager(em).getServerSession().getIdentityMapAccessor().getFromIdentityMap(emp);
assertNotNull("Error, phone numbers is empty. Not Batch Read", emp.getPhoneNumbers());
assertFalse("PhoneNumbers was empty. This should not be the case as the test created phone numbers", emp.getPhoneNumbers().isEmpty());
assertTrue("Phonee numbers was not an indirectList", emp.getPhoneNumbers() instanceof IndirectList);
assertNotNull("valueholder was null in triggered batch attribute", ((IndirectList) emp.getPhoneNumbers()).getValueHolder());
BatchValueHolder bvh = (BatchValueHolder) ((IndirectList) emp.getPhoneNumbers()).getValueHolder();
if (bvh.getQuery() != null && bvh.getQuery().getSession() != null && bvh.getQuery().getSession().isUnitOfWork()) {
fail("In Shared Cache a UOW was set within a BatchValueHolder's query object");
}
closeEntityManager(em);
} finally {
em = createEntityManager();
beginTransaction(em);
emp = em.find(Employee.class, id1);
Iterator it = emp.getManagedEmployees().iterator();
while (it.hasNext()) {
Employee managedEmp = (Employee) it.next();
it.remove();
managedEmp.setManager(null);
em.remove(managedEmp);
}
em.remove(emp);
commitTransaction(em);
}
}
public void testIsLoaded(){
// Don't run this test in a JPA 1.0 environment.
if (! isJPA10()) {
EntityManagerFactory emf = getEntityManagerFactory();
EntityManager em = createEntityManager();
beginTransaction(em);
try{
Employee emp = new Employee();
emp.setFirstName("Abe");
emp.setLastName("Jones");
Address addr = new Address();
addr.setCity("Palo Alto");
emp.setAddress(addr);
PhoneNumber pn = new PhoneNumber();
pn.setNumber("1234456");
pn.setType("Home");
emp.addPhoneNumber(pn);
pn.setOwner(emp);
em.persist(emp);
em.flush();
em.clear();
clearCache();
emp = em.find(Employee.class, emp.getId());
PersistenceUnitUtil util = emf.getPersistenceUnitUtil();
assertTrue("PersistenceUnitUtil says employee is not loaded when it is.", util.isLoaded(emp));
} finally {
rollbackTransaction(em);
}
}
}
public void testIsLoadedAttribute(){
// Don't run this test in a JPA 1.0 environment.
if (! isJPA10()) {
EntityManagerFactory emf = getEntityManagerFactory();
EntityManager em = createEntityManager();
beginTransaction(em);
try{
Employee emp = new Employee();
emp.setFirstName("Abe");
emp.setLastName("Jones");
Address addr = new Address();
addr.setCity("Palo Alto");
emp.setAddress(addr);
PhoneNumber pn = new PhoneNumber();
pn.setNumber("1234456");
pn.setType("Home");
emp.addPhoneNumber(pn);
pn.setOwner(emp);
SmallProject project = new SmallProject();
project.setName("Utility Testing");
project.addTeamMember(emp);
emp.addProject(project);
em.persist(emp);
em.flush();
em.clear();
clearCache();
emp = em.find(Employee.class, emp.getId());
PersistenceUnitUtil util = emf.getPersistenceUnitUtil();
if (emp instanceof PersistenceWeaved){
assertFalse("PersistenceUnitUtil says address is loaded when it is not", util.isLoaded(emp, "address"));
} else {
assertTrue("Non-weaved PersistenceUnitUtil says address is not loaded", util.isLoaded(emp, "address"));
}
assertFalse("PersistenceUnitUtil says projects is loaded when it is not", util.isLoaded(emp, "projects"));
emp.getPhoneNumbers().size();
assertTrue("PersistenceUnitUtil says phoneNumbers is not loaded when it is", util.isLoaded(emp, "phoneNumbers"));
assertTrue("PersistenceUnitUtil says firstName is not loaded when it is", util.isLoaded(emp, "firstName"));
} finally {
rollbackTransaction(em);
}
}
}
public void testGetIdentifier(){
// Don't run this test in a JPA 1.0 environment.
if (! isJPA10()) {
EntityManagerFactory emf = getEntityManagerFactory();
EntityManager em = createEntityManager();
beginTransaction(em);
try{
Employee emp = new Employee();
emp.setFirstName("Abe");
emp.setLastName("Jones");
Address addr = new Address();
addr.setCity("Palo Alto");
emp.setAddress(addr);
PhoneNumber pn = new PhoneNumber();
pn.setNumber("1234456");
pn.setType("Home");
emp.addPhoneNumber(pn);
pn.setOwner(emp);
em.persist(emp);
em.flush();
Integer id = emp.getId();
em.clear();
clearCache();
emp = em.find(Employee.class, emp.getId());
PersistenceUnitUtil util = emf.getPersistenceUnitUtil();
Object retrievedId = util.getIdentifier(emp);
assertTrue("Got an incorrect id from persistenceUtil.getIdentifier()", id.equals(retrievedId));
} finally {
rollbackTransaction(em);
}
}
}
public void testIsLoadedWithReference(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
Employee emp = new Employee();
emp.setFirstName("Abe");
emp.setLastName("Jones");
Address addr = new Address();
addr.setCity("Palo Alto");
emp.setAddress(addr);
PhoneNumber pn = new PhoneNumber();
pn.setNumber("1234456");
pn.setType("Home");
emp.addPhoneNumber(pn);
pn.setOwner(emp);
Employee manager = new Employee();
manager.addManagedEmployee(emp);
emp.setManager(manager);
em.persist(emp);
em.flush();
em.clear();
clearCache();
emp = em.find(Employee.class, emp.getId());
emp.getAddress().getCity();
emp.getPhoneNumbers().size();
ProviderUtil util = (new PersistenceProvider()).getProviderUtil();
assertTrue("ProviderUtil did not return LOADED for isLoaded for address when it should.", util.isLoadedWithReference(emp, "address").equals(LoadState.LOADED));
assertTrue("ProviderUtil did not return LOADED for isLoaded for phoneNumbers when it should.", util.isLoadedWithReference(emp, "phoneNumbers").equals(LoadState.LOADED));
if (emp instanceof PersistenceWeaved){
assertTrue("ProviderUtil did not return NOT_LOADED for isLoaded for manager when it should.", util.isLoadedWithReference(emp, "manager").equals(LoadState.NOT_LOADED));
} else {
assertTrue("(NonWeaved) ProviderUtil did not return LOADED for isLoaded for manager when it should.", util.isLoadedWithReference(emp, "manager").equals(LoadState.LOADED));
}
assertTrue("ProviderUtil did not return NOT_LOADED for isLoaded for projects when it should.", util.isLoadedWithReference(emp, "projects").equals(LoadState.NOT_LOADED));
} finally {
rollbackTransaction(em);
}
}
public void testIsLoadedWithoutReference(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
Employee emp = new Employee();
emp.setFirstName("Abe");
emp.setLastName("Jones");
Address addr = new Address();
addr.setCity("Palo Alto");
emp.setAddress(addr);
PhoneNumber pn = new PhoneNumber();
pn.setNumber("1234456");
pn.setType("Home");
emp.addPhoneNumber(pn);
pn.setOwner(emp);
Employee manager = new Employee();
manager.addManagedEmployee(emp);
emp.setManager(manager);
em.persist(emp);
em.flush();
em.clear();
clearCache();
ProviderUtil util = (new PersistenceProvider()).getProviderUtil();
if (emp instanceof PersistenceWeaved){
assertTrue("ProviderUtil did not return LOADED for isLoaded when it should.", util.isLoaded(emp).equals(LoadState.LOADED));
emp = em.getReference(Employee.class, emp.getId());
assertTrue("ProviderUtil did not return NOT_LOADED for isLoaded when it should.", util.isLoaded(emp).equals(LoadState.NOT_LOADED));
} else {
assertTrue("(NonWeaved) ProviderUtil did not return UNKNOWN for isLoaded when it should.", util.isLoaded(emp).equals(LoadState.UNKNOWN));
emp = em.getReference(Employee.class, emp.getId());
assertTrue("(NonWeaved) ProviderUtil did not return UNKNOWN for isLoaded when it should.", util.isLoaded(emp).equals(LoadState.UNKNOWN));
}
assertTrue("ProviderUtil did not return UNKNOWN for isLoaded when it should.", util.isLoaded(new NonEntity()).equals(LoadState.UNKNOWN));
} finally {
rollbackTransaction(em);
}
}
public void testIsLoadedWithoutReferenceAttribute(){
EntityManager em = createEntityManager();
beginTransaction(em);
try{
Employee emp = new Employee();
emp.setFirstName("Abe");
emp.setLastName("Jones");
Address addr = new Address();
addr.setCity("Palo Alto");
emp.setAddress(addr);
PhoneNumber pn = new PhoneNumber();
pn.setNumber("1234456");
pn.setType("Home");
emp.addPhoneNumber(pn);
pn.setOwner(emp);
Employee manager = new Employee();
manager.addManagedEmployee(emp);
emp.setManager(manager);
em.persist(emp);
em.flush();
em.clear();
clearCache();
emp = em.find(Employee.class, emp.getId());
emp.getAddress().getCity();
emp.getPhoneNumbers().size();
ProviderUtil util = (new PersistenceProvider()).getProviderUtil();
if (emp instanceof PersistenceWeaved){
assertTrue("ProviderUtil did not return LOADED for isLoaded for address when it should.", util.isLoadedWithReference(emp, "address").equals(LoadState.LOADED));
assertTrue("ProviderUtil did not return NOT_LOADED for isLoaded for manager when it should.", util.isLoadedWithReference(emp, "manager").equals(LoadState.NOT_LOADED));
} else {
assertTrue("(Unweaved) ProviderUtil did not return LOADED for isLoaded for address when it should.", util.isLoadedWithReference(emp, "address").equals(LoadState.LOADED));
assertTrue("(Unweaved) ProviderUtil did not return LOADED for isLoaded for manager when it should.", util.isLoadedWithReference(emp, "manager").equals(LoadState.LOADED));
}
assertTrue("ProviderUtil did not return LOADED for isLoaded for phoneNumbers when it should.", util.isLoadedWithReference(emp, "phoneNumbers").equals(LoadState.LOADED));
assertTrue("ProviderUtil did not return NOT_LOADED for isLoaded for projects when it should.", util.isLoadedWithReference(emp, "projects").equals(LoadState.NOT_LOADED));
assertTrue("ProviderUtil did not return UNKNOWN for isLoaded when it should.", util.isLoaded(new NonEntity()).equals(LoadState.UNKNOWN));
} finally {
rollbackTransaction(em);
}
}
public void testGetHints(){
// Don't run this test in a JPA 1.0 environment.
if (! isJPA10()) {
EntityManagerFactory emf = getEntityManagerFactory();
EntityManager em = emf.createEntityManager();
Query query = em.createQuery("Select e from Employee e");
query.setHint(QueryHints.CACHE_USAGE, CacheUsage.DoNotCheckCache);
query.setHint(QueryHints.BIND_PARAMETERS, "");
Map<String, Object> hints = query.getHints();
assertTrue("Incorrect number of hints.", hints.size() == 2);
assertTrue("CacheUsage hint missing.", hints.get(QueryHints.CACHE_USAGE).equals(CacheUsage.DoNotCheckCache));
assertTrue("Bind parameters hint missing.", hints.get(QueryHints.BIND_PARAMETERS) != null);
query = em.createQuery("Select a from Address a");
hints = query.getHints();
assertTrue("Hints is not null when it should be.", hints == null);
}
}
public void testTemporalOnClosedEm(){
if (isOnServer()) {
// Don't run this test on server.
return;
}
EntityManager em = createEntityManager();
Query numericParameterQuery = em.createQuery("Select e from Employee e where e.period.startDate = ?1");
Query namedParameterQuery = em.createQuery("Select e from Employee e where e.period.startDate = :date");
closeEntityManager(em);
Exception caughtException = null;
try{
numericParameterQuery.setParameter(1, new Date(System.currentTimeMillis()), TemporalType.DATE);
} catch (Exception e){
caughtException = e;
}
assertTrue("Wrong Exception was caught when setting a numeric temporal Date parameter on a query with a closed em.", caughtException instanceof IllegalStateException);
try{
numericParameterQuery.setParameter(1, Calendar.getInstance(), TemporalType.DATE);
} catch (Exception e){
caughtException = e;
}
assertTrue("Wrong Exception was caught when setting a numeric temporal Calendar parameter on a query with a closed em.", caughtException instanceof IllegalStateException);
try{
namedParameterQuery.setParameter("date", new Date(System.currentTimeMillis()), TemporalType.DATE);
} catch (Exception e){
caughtException = e;
}
assertTrue("Wrong Exception was caught when setting a named temporal Date parameter on a query with a closed em.", caughtException instanceof IllegalStateException);
try{
namedParameterQuery.setParameter("date", Calendar.getInstance(), TemporalType.DATE);
} catch (Exception e){
caughtException = e;
}
assertTrue("Wrong Exception was caught when setting a named temporal Calendar parameter on a query with a closed em.", caughtException instanceof IllegalStateException);
}
public void testTransientMapping(){
ServerSession session = getServerSession();
ClassDescriptor descriptor = session.getClassDescriptor(Customer.class);
assertTrue("There should not be a mapping for transientField.", descriptor.getMappingForAttributeName("transientField") == null);
}
public static class SessionNameCustomizer implements SessionCustomizer {
static ServerSession ss;
public void customize(Session session) throws Exception {
ss = (ServerSession)session;
}
}
public void testGenerateSessionNameFromConnectionProperties() {
// the test requires passing properties to createEMF or createContainerEMF method.
if (isOnServer()) {
return;
}
String errorMsg = "";
EntityManagerFactory emf;
Map properties;
String puName = "default";
String customizer = "org.eclipse.persistence.testing.tests.jpa.advanced.EntityManagerJUnitTestSuite$SessionNameCustomizer";
String myJtaDS = "myJtaDS";
String myNonJtaDS = "myNonJtaDS";
String myUrl = "myUrl";
String myUser = "myUser";
String myDriver = "myDriver";
String myPassword = "myPassword";
ServerSession originalSession = JUnitTestCase.getServerSession();
String loggingLevel = originalSession.getSessionLog().getLevelString();
SessionNameCustomizer.ss = null;
// 0: The session name specified in persistence.xml is NOT overridden -> the existing session is used by emf.
// If persistence.xml no longer specifies session name then comment out this part of the test.
properties = new HashMap();
// required by the test
properties.put(PersistenceUnitProperties.SESSION_CUSTOMIZER, customizer);
// log on the same level as original session
properties.put(PersistenceUnitProperties.LOGGING_LEVEL, loggingLevel);
properties.put(PersistenceUnitProperties.TRANSACTION_TYPE, "RESOURCE_LOCAL");
// to override data source if one is specified in persistence.xml
properties.put(PersistenceUnitProperties.JTA_DATASOURCE, "");
// to override data source if one is specified in persistence.xml
properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, "");
properties.put(PersistenceUnitProperties.JDBC_URL, myUrl);
properties.put(PersistenceUnitProperties.JDBC_USER, myUser);
properties.put(PersistenceUnitProperties.JDBC_DRIVER, myDriver);
properties.put(PersistenceUnitProperties.JDBC_PASSWORD, myPassword);
emf = Persistence.createEntityManagerFactory(puName, properties);
try {
emf.createEntityManager();
} catch (Exception ex) {
// Ignore exception that probably caused by attempt to connect the session with invalid connection data provided in the properties.
} finally {
emf.close();
if(SessionNameCustomizer.ss != null && SessionNameCustomizer.ss != originalSession) {
errorMsg += "0: Session name NOT overridden by an empty string - original session expected; ";
}
// clear for the next test
SessionNameCustomizer.ss = null;
}
// 1: New session with DefaultConnector with myUrl, myDriver, myUser, myPassword
properties = new HashMap();
// required by the test
properties.put(PersistenceUnitProperties.SESSION_CUSTOMIZER, customizer);
// log on the same level as original session
properties.put(PersistenceUnitProperties.LOGGING_LEVEL, loggingLevel);
// to override SESSION_NAME if one is specified in persistence.xml
properties.put(PersistenceUnitProperties.SESSION_NAME, "");
properties.put(PersistenceUnitProperties.TRANSACTION_TYPE, "RESOURCE_LOCAL");
// to override data source if one is specified in persistence.xml
properties.put(PersistenceUnitProperties.JTA_DATASOURCE, "");
// to override data source if one is specified in persistence.xml
properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, "");
properties.put(PersistenceUnitProperties.JDBC_URL, myUrl);
properties.put(PersistenceUnitProperties.JDBC_USER, myUser);
properties.put(PersistenceUnitProperties.JDBC_DRIVER, myDriver);
properties.put(PersistenceUnitProperties.JDBC_PASSWORD, myPassword);
emf = Persistence.createEntityManagerFactory(puName, properties);
try {
emf.createEntityManager();
} catch (Exception ex) {
// Ignore exception that probably caused by attempt to connect the session with invalid connection data provided in the properties.
} finally {
emf.close();
if(SessionNameCustomizer.ss == null && SessionNameCustomizer.ss == originalSession) {
errorMsg += "1: New session expected; ";
} else {
if(SessionNameCustomizer.ss.getLogin().shouldUseExternalConnectionPooling()) {
errorMsg += "1: internal connection pooling expected; ";
}
if(SessionNameCustomizer.ss.getLogin().shouldUseExternalTransactionController()) {
errorMsg += "1: no externalTransactionController expected; ";
}
if(! myUser.equals(SessionNameCustomizer.ss.getLogin().getUserName())) {
errorMsg += "1: myUser expected; ";
}
Connector connector = SessionNameCustomizer.ss.getLogin().getConnector();
if(connector instanceof DefaultConnector) {
if(! myUrl.equals(((DefaultConnector)connector).getDatabaseURL())) {
errorMsg += "1: myUrl expected; ";
}
if(! myDriver.equals(((DefaultConnector)connector).getDriverClassName())) {
errorMsg += "1: myDriver expected; ";
}
} else {
errorMsg += "1: DefaultConnector expected; ";
}
}
// clear for the next test
SessionNameCustomizer.ss = null;
}
// 2: New session with JNDIConnector with myJtaDs, myNonJtaDs
properties = new HashMap();
// required by the test
properties.put(PersistenceUnitProperties.SESSION_CUSTOMIZER, customizer);
// log on the same level as original session
properties.put(PersistenceUnitProperties.LOGGING_LEVEL, loggingLevel);
// to override SESSION_NAME if one is specified in persistence.xml
properties.put(PersistenceUnitProperties.SESSION_NAME, "");
properties.put(PersistenceUnitProperties.TRANSACTION_TYPE, "JTA");
properties.put(PersistenceUnitProperties.JTA_DATASOURCE, myJtaDS);
properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, myNonJtaDS);
// to override user if one is specified in persistence.xml
properties.put(PersistenceUnitProperties.JDBC_USER, "");
// note that there is no need to override JDBC_URL, JDBC_DRIVER, JDBC_PASSWORD with an empty string, they will be ignored.
// JDBC_URL, JDBC_DRIVER - because data source(s) are specified; JDBC_PASSWORD - because JDBC_USER is not specified
emf = Persistence.createEntityManagerFactory(puName, properties);
try {
emf.createEntityManager();
} catch (Exception ex) {
// Ignore exception that probably caused by attempt to connect the session with invalid connection data provided in the properties.
} finally {
emf.close();
if(SessionNameCustomizer.ss == null && SessionNameCustomizer.ss == originalSession) {
errorMsg += "2: New session expected; ";
} else {
if(! SessionNameCustomizer.ss.getLogin().shouldUseExternalConnectionPooling()) {
errorMsg += "2: external connection pooling expected; ";
}
if(! SessionNameCustomizer.ss.getLogin().shouldUseExternalTransactionController()) {
errorMsg += "2: externalTransactionController expected; ";
}
if(SessionNameCustomizer.ss.getLogin().getUserName().length() > 0) {
errorMsg += "2: empty string user expected; ";
}
Connector connector = SessionNameCustomizer.ss.getLogin().getConnector();
if(connector instanceof JNDIConnector) {
if(! myJtaDS.equals(((JNDIConnector)connector).getName())) {
errorMsg += "2: myJtaDS expected; ";
}
} else {
errorMsg += "2: JNDIConnector expected; ";
}
if(! SessionNameCustomizer.ss.getReadConnectionPool().getLogin().shouldUseExternalConnectionPooling()) {
errorMsg += "2: resding: external connection pooling expected; ";
}
if(SessionNameCustomizer.ss.getReadConnectionPool().getLogin().shouldUseExternalTransactionController()) {
errorMsg += "2: reading no externalTransactionController expected; ";
}
if(SessionNameCustomizer.ss.getReadConnectionPool().getLogin().getUserName().length() > 0) {
errorMsg += "2: reading: empty string user expected; ";
}
Connector readConnector = ((DatasourceLogin)SessionNameCustomizer.ss.getReadConnectionPool().getLogin()).getConnector();
if(readConnector instanceof JNDIConnector) {
if(! myNonJtaDS.equals(((JNDIConnector)readConnector).getName())) {
errorMsg += "2: reading: myNonJtaDS expected; ";
}
} else {
errorMsg += "2: reading: JNDIConnector expected; ";
}
}
// clear for the next test
SessionNameCustomizer.ss = null;
}
if(errorMsg.length() > 0) {
fail(errorMsg);
}
}
public void testPreupdateEmbeddable(){
EntityManager em = createEntityManager();
beginTransaction(em);
Employee emp = new Employee();
emp.setFirstName("testPreupdateEmbeddable");
emp.setLastName("testPreupdateEmbeddable");
EmploymentPeriod period = new EmploymentPeriod();
period.setStartDate(Date.valueOf("2002-01-01"));
emp.setPeriod(period);
em.persist(emp);
commitTransaction(em);
closeEntityManager(em);
clearCache();
em = createEntityManager();
beginTransaction(em);
emp = em.find(Employee.class, emp.getId());
emp.setFirstName("testPreupdateEmbeddable1");
emp = em.merge(emp);
em.flush();
clearCache();
emp = em.find(Employee.class, emp.getId());
assertTrue("The endDate was not updated.", emp.getPeriod().getEndDate().equals(EmployeeListener.UPDATE_DATE));
em.remove(emp);
commitTransaction(em);
}
/**
* Test for Bug 299147 - em.find isolated read-only entity throws exception
*/
public void testFindReadOnlyIsolated() {
EntityManager em = createEntityManager();
beginTransaction(em);
try {
// test query
em.createQuery("SELECT ro FROM ReadOnlyIsolated ro").getResultList();
// test find - this used to throw exception
em.find(ReadOnlyIsolated.class, 1);
} finally {
if (isTransactionActive(em)){
rollbackTransaction(em);
}
closeEntityManager(em);
}
}
// bug 274975
public void testInheritanceQuery(){
EntityManager em = createEntityManager();
beginTransaction(em);
LargeProject project = new LargeProject();
em.persist(project);
commitTransaction(em);
int id = project.getId();
clearCache();
ClassDescriptor descriptor = getServerSession().getClassDescriptor(Project.class);
ReadAllQuery query = new ReadAllQuery(Project.class);
ExpressionBuilder b = query.getExpressionBuilder();
query.addArgument("id", Integer.class); // declare bind variable in (parent) query
ReportQuery subQuery = new ReportQuery();
subQuery.setReferenceClass(Project.class); // use any dummy mapped class...
SQLCall selectIdsCall = new SQLCall();
String subSelect = "select p.PROJ_ID from CMP3_PROJECT p where p.PROJ_ID = #id"; // <= re-use bind variable in child query
selectIdsCall.setSQLString(subSelect);
subQuery.setCall(selectIdsCall);
Expression expr = b.get("id").in(subQuery);
query.setSelectionCriteria(expr);
// Now execute query with bind variable
// (using setShouldBindAllParameters(false) makes it work...
// but this is not good, in particular it prevents use of advanced queries with Oraclearrays as bind-variables!!!)
Vector params = new Vector(1);
params.add(id);
List res = (List) getServerSession().executeQuery(query, params);
assertTrue(res.size() == 1);
}
}
|
package torrent.download.tracker;
import java.util.LinkedList;
import java.util.List;
import org.johnnei.utils.ThreadUtils;
import org.johnnei.utils.config.Config;
import torrent.download.Torrent;
import torrent.download.peer.PeerConnectInfo;
public class PeerConnectorPool {
private List<PeerConnector> connectors;
public PeerConnectorPool(TrackerManager manager) {
connectors = new LinkedList<>();
final int connectorCount = Config.getConfig().getInt("peer-max_concurrent_connecting");
final int peerLimitPerConnector = Config.getConfig().getInt("peer-max_connecting") / connectorCount;
for (int i = 0; i < connectorCount; i++) {
PeerConnector connector = new PeerConnector(manager, peerLimitPerConnector);
connectors.add(connector);
Thread thread = new Thread(connector, String.format("Peer Connector #%d", i));
thread.setDaemon(true);
thread.start();
}
}
/**
* Queues a peer to be connected
* @param p the peer to be connected
*/
public void addPeer(PeerConnectInfo peer) {
PeerConnector connector = connectors.stream().max((a, b) -> a.getFreeCapacity() - b.getFreeCapacity()).get();
if (connector.getFreeCapacity() == 0) {
System.err.println("[PeerConnectorPool] Overflowing in peers. Can't distribute peers!");
// TODO Implement a backlog of peers
return;
}
connector.addPeer(peer);
ThreadUtils.notify(connector.PEER_JOB_NOTIFY);
}
public int getFreeCapacity() {
return connectors.stream().mapToInt(PeerConnector::getFreeCapacity).sum();
}
public int getConnectingCountFor(Torrent torrent) {
return connectors.stream().mapToInt(c -> c.getConnectingCountFor(torrent)).sum();
}
}
|
package org.jasig.portal.channels;
import java.util.*;
import org.xml.sax.DocumentHandler;
import org.jasig.portal.*;
import org.jasig.portal.utils.XSLT;
import org.jasig.portal.services.LogService;
import org.w3c.dom.*;
import org.apache.xalan.xslt.*;
/**
* Error channel (aka null channel) is designed to render in
* place of other channels when something goes wrong.<br/>
* Possible conditions when CError is invoked are:
* <ul>
* <li> Channel has thrown a {@link PortalException} from one of the IChannel or IPrivilegedChannel methods.</li>
* <li> Channel has thrown a Runtime exception from one of the methods.<li>
* <li> Channel has timed out on rendering and was terminated.</li>
* <li> uPortal has rejected a channel for some reason.
* In this case a general message is constructed by the portal.</li>
* </ul>
* @author Peter Kharchenko, pkharchenko@interactivebusiness.com
* @version $Revision$
*/
public class CError extends BaseChannel implements IPrivilegedChannel
{
public static final int GENERAL_ERROR=0;
public static final int RENDER_TIME_EXCEPTION=1;
public static final int SET_STATIC_DATA_EXCEPTION=2;
public static final int SET_RUNTIME_DATA_EXCEPTION=3;
public static final int TIMEOUT_EXCEPTION=4;
public static final int SET_PCS_EXCEPTION=5;
protected Exception channelException=null;
protected String str_channelID=null;
protected String str_message=null;
protected IChannel the_channel=null;
protected int errorID=-1;
private boolean showStackTrace=false;
protected ChannelRuntimeData runtimeData;
private PortalControlStructures portcs;
private String fs=java.io.File.separator;
protected StylesheetSet set;
protected String stylesheetDir = GenericPortalBean.getPortalBaseDir () + "webpages" + fs + "stylesheets" + fs + "org" + fs + "jasig" + fs + "portal" + fs + "channels" + fs + "CError" + fs;
public CError() {
set = new StylesheetSet (stylesheetDir + "CError.ssl");
set.setMediaProps (GenericPortalBean.getPortalBaseDir () + "properties" + fs + "media.properties");
}
public CError(int errorCode, Exception exception, String channelID,IChannel channelInstance) {
this();
str_channelID=channelID;
this.channelException=exception;
this.the_channel=channelInstance;
this.errorID=errorCode;
}
public CError(int errorCode, String message,String channelID,IChannel channelInstance) {
this();
this.str_channelID=channelID;
this.str_message=message;
this.the_channel=channelInstance;
this.errorID=errorCode;
}
public void setMessage(String m) {
this.str_message=m;
}
private void resetCError(int errorCode, Exception exception, String channelID,IChannel channelInstance,String message) {
str_channelID=channelID;
this.channelException=exception;
this.the_channel=channelInstance;
this.errorID=errorCode;
this.str_message=message;
}
public void setRuntimeData (ChannelRuntimeData rd)
{
this.runtimeData=rd;
}
public void setPortalControlStructures(PortalControlStructures pcs) {
this.portcs=pcs;
}
public void renderXML(DocumentHandler out) {
// runtime data processing needs to be done here, otherwise replaced
// channel will get duplicated setRuntimeData() calls
if(str_channelID!=null) {
String chFate=runtimeData.getParameter("action");
if(chFate!=null) {
// a fate has been chosen
if(chFate.equals("retry")) {
LogService.instance().log(LogService.DEBUG,"CError:setRuntimeData() : going for retry");
// clean things up for the channel
ChannelRuntimeData crd = (ChannelRuntimeData) runtimeData.clone();
crd.clear(); // Remove parameters
try {
if(the_channel instanceof IPrivilegedChannel)
((IPrivilegedChannel)the_channel).setPortalControlStructures(portcs);
the_channel.setRuntimeData (crd);
ChannelManager cm=portcs.getChannelManager();
cm.addChannelInstance(this.str_channelID,this.the_channel);
the_channel.renderXML(out);
return;
} catch (Exception e) {
// if any of the above didn't work, fall back to the error channel
resetCError(this.SET_RUNTIME_DATA_EXCEPTION,e,this.str_channelID,this.the_channel,"Channel failed a refresh attempt.");
}
} else if(chFate.equals("restart")) {
LogService.instance().log(LogService.DEBUG,"CError:setRuntimeData() : going for reinstantiation");
ChannelManager cm=portcs.getChannelManager();
ChannelRuntimeData crd = (ChannelRuntimeData) runtimeData.clone();
crd.clear();
try {
if((the_channel=cm.instantiateChannel(str_channelID))==null) {
resetCError(this.GENERAL_ERROR,null,this.str_channelID,null,"Channel failed to reinstantiate!");
} else {
try {
if(the_channel instanceof IPrivilegedChannel)
((IPrivilegedChannel)the_channel).setPortalControlStructures(portcs);
the_channel.setRuntimeData (crd);
the_channel.renderXML(out);
return;
} catch (Exception e) {
// if any of the above didn't work, fall back to the error channel
resetCError(this.SET_RUNTIME_DATA_EXCEPTION,e,this.str_channelID,this.the_channel,"Channel failed a reload attempt.");
cm.addChannelInstance(str_channelID,this);
LogService.instance().log(LogService.ERROR,"CError::setRuntimeData() : an error occurred during channel reinitialization. "+e);
}
}
} catch (Exception e) {
resetCError(this.GENERAL_ERROR,e,this.str_channelID,null,"Channel failed to reinstantiate!");
LogService.instance().log(LogService.ERROR,"CError::setRuntimeData() : an error occurred during channel reinstantiation. "+e);
}
} else if(chFate.equals("toggle_stack_trace")) {
showStackTrace=!showStackTrace;
}
}
}
// if channel's render XML method was to be called, we would've returned by now
localRenderXML(out);
}
private void localRenderXML(DocumentHandler out) {
// note: this method should be made very robust. Optimally, it should
// not rely on XSLT to do the job. That means that mime-type dependent
// output should be generated directly within the method.
// For now, we'll just do it the usual way.
// XML of the following type is generated:
// <error code="$errorID">
// <message>$message</messag>
// <channel>
// <id>$channelID</id>
// <name>$channelName</name>
// </channel>
// <exception code="N">
// <resource><uri/><description/></resource>
// <timeout value="N"/>
// </exception>
// </error>
// Note that only two exceptions have detailed elements associated with them.
// In the future, if the information within exceptions is expanded, it should be
// placed into this XML for the CError UI to give user a proper feedback.
Document doc = new org.apache.xerces.dom.DocumentImpl();
Element errorEl=doc.createElement("error");
errorEl.setAttribute("code",Integer.toString(errorID));
if(str_message!=null) {
Element messageEl=doc.createElement("message");
messageEl.appendChild(doc.createTextNode(str_message));
errorEl.appendChild(messageEl);
}
if(str_channelID!=null) {
Element channelEl=doc.createElement("channel");
Element idEl=doc.createElement("id");
idEl.appendChild(doc.createTextNode(str_channelID));
channelEl.appendChild(idEl);
// determine channel name
if(portcs!=null) {
String chName=(portcs.getUserLayoutManager()).getNodeName(str_channelID);
if(chName!=null) {
Element nameEl=doc.createElement("name");
nameEl.appendChild(doc.createTextNode(chName));
channelEl.appendChild(nameEl);
}
errorEl.appendChild(channelEl);
}
}
// if the exception has been generated
if(channelException!=null) {
Element excEl=doc.createElement("exception");
String m;
if((m=channelException.getMessage())!=null) {
Element emEl=doc.createElement("message");
emEl.appendChild(doc.createTextNode(m));
excEl.appendChild(emEl);
}
Element stEl=doc.createElement("stack");
java.io.StringWriter sw=new java.io.StringWriter();
channelException.printStackTrace(new java.io.PrintWriter(sw));
sw.flush();
stEl.appendChild(doc.createTextNode(sw.toString()));
excEl.appendChild(stEl);
if(channelException instanceof PortalException) {
PortalException pe=(PortalException) channelException;
// the Error channel has been invoked as a result of some other
// channel throwing a PortalException.
// determine which type of an exception is it
excEl.setAttribute("code",Integer.toString(pe.getExceptionCode()));
// now specific cases for exceptions containing additional information
if(pe instanceof ResourceMissingException) {
ResourceMissingException rme=(ResourceMissingException) pe;
Element resourceEl=doc.createElement("resource");
Element uriEl=doc.createElement("uri");
uriEl.appendChild(doc.createTextNode(rme.getResourceURI()));
resourceEl.appendChild(uriEl);
Element descriptionEl=doc.createElement("description");
descriptionEl.appendChild(doc.createTextNode(rme.getResourceDescription()));
resourceEl.appendChild(descriptionEl);
excEl.appendChild(resourceEl);
} else if(pe instanceof InternalTimeoutException) {
Long v=((InternalTimeoutException)pe).getTimeoutValue();
if(v!=null) {
Element timeoutEl=doc.createElement("timeout");
timeoutEl.setAttribute("value",v.toString());
}
}
} else {
// runtime exception generated by the channel
excEl.setAttribute("code","-1");
}
errorEl.appendChild(excEl);
}
doc.appendChild(errorEl);
// figure out if we allow for refresh/reload
String allowRef="true";
String allowRel="true";
if(str_channelID==null) {
allowRel=allowRef="false";
} else {
if(channelException!=null && (channelException instanceof PortalException)) {
if(errorID==SET_STATIC_DATA_EXCEPTION || !((PortalException)channelException).allowRefresh())
allowRef="false";
if(!((PortalException)channelException).allowReinstantiation())
allowRel="false";
}
}
// debug block
try {
java.io.StringWriter outString = new java.io.StringWriter ();
org.apache.xml.serialize.OutputFormat format=new org.apache.xml.serialize.OutputFormat();
format.setOmitXMLDeclaration(true);
format.setIndenting(true);
org.apache.xml.serialize.XMLSerializer xsl = new org.apache.xml.serialize.XMLSerializer (outString,format);
xsl.serialize (doc);
LogService.instance().log(LogService.DEBUG,outString.toString());
} catch (Exception e) {
LogService.instance().log(LogService.DEBUG,e);
}
// end of debug block
try {
XSLTInputSource xmlSource = new XSLTInputSource (doc);
XSLTInputSource xslSource = set.getStylesheet(portcs.getHttpServletRequest());
if(xslSource==null) {
// some meaningful error-tolerant output should be generated here.
LogService.instance().log(LogService.ERROR,"CError::renderXML() : unable to locate a stylesheet");
} else {
XSLTResultTarget xmlResult = new XSLTResultTarget(out);
XSLTProcessor processor = XSLTProcessorFactory.getProcessor (new org.apache.xalan.xpath.xdom.XercesLiaison ());
if(runtimeData!=null) {
processor.setStylesheetParam("baseActionURL", processor.createXString (runtimeData.getBaseActionURL()));
processor.setStylesheetParam("showStackTrace", processor.createXString ((new Boolean(showStackTrace)).toString()));
processor.setStylesheetParam("allowRefresh", processor.createXString (allowRef));
processor.setStylesheetParam("allowReinstantiation", processor.createXString (allowRel));
}
processor.process (xmlSource, xslSource, xmlResult);
}
} catch (Exception e) {
LogService.instance().log(LogService.ERROR,"CError::renderXML() : things are bad. Error channel threw: "+e);
}
}
}
|
package org.kuali.rice.kew.framework.document.lookup;
import java.util.List;
/**
* Defines the contract for an object containing result values that are used to customize document lookup results.
* Defines a set of additional custom values for document lookup results that can be defined and returned by an
* application which is customizing the document lookup for a specific document type.
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public interface DocumentLookupResultValuesContract {
/**
* Returns an unmodifiable list of the result values, one for each customized document.
*
* @return the list of customized document lookup result values, will never be null but may be empty
*/
List<? extends DocumentLookupResultValueContract> getResultValues();
}
|
package com.bkromhout.ruqus;
import android.graphics.PorterDuff;
import android.os.Build;
import android.view.View;
import android.widget.ImageButton;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Static utility methods which don't belong in {@link Ruqus}.
*/
class Util {
/**
* For generating unique view IDs.
*/
private static final AtomicInteger nextGeneratedId = new AtomicInteger(1);
/**
* Formatting for date fields.
*/
static final DateFormat dateFormat = SimpleDateFormat.getDateInstance();
static Calendar calFromString(String dateString) {
Calendar c = Calendar.getInstance();
if (dateString == null || dateString.isEmpty()) return c;
try {
c.setTime(dateFormat.parse(dateString));
return c;
} catch (ParseException e) {
return c;
}
}
static String stringFromDateInts(int year, int monthOfYear, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(year, monthOfYear, dayOfMonth);
return dateFormat.format(c.getTime());
}
/**
* Generate a value suitable for use in {@link View#setId(int)}. This value will not collide with ID values
* generated at build time by aapt for R.id.
* <p/>
* This is literally just a copy of API >= 17's {@link View#generateViewId()}.
* @return a generated ID value
*/
private static int generateViewId() {
for (; ; ) {
final int result = nextGeneratedId.get();
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
int newValue = result + 1;
if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
if (nextGeneratedId.compareAndSet(result, newValue)) return result;
}
}
/**
* Get a unique ID to use for a view. If API level is >= 17, will use {@link View#generateViewId()}, otherwise will
* use {@link #generateViewId()}.
* @return Unique view ID.
*/
static int getUniqueViewId() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) return generateViewId();
else return View.generateViewId();
}
/**
* Tints the color of an image button's icon based on the given {@link RuqusTheme}.
* @param imageButton ImageButton whose icon should be tinted.
* @param theme RuqusTheme.
*/
static void tintImageButtonIcon(ImageButton imageButton, RuqusTheme theme) {
imageButton.getDrawable().setColorFilter(
theme == RuqusTheme.LIGHT ? Ruqus.DARK_TEXT_COLOR : Ruqus.LIGHT_TEXT_COLOR, PorterDuff.Mode.SRC_IN);
}
}
|
package de.ii.ldproxy.wfs3.aroundrelations;
import com.fasterxml.jackson.annotation.JsonMerge;
import com.fasterxml.jackson.annotation.OptBoolean;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.common.collect.ImmutableList;
import de.ii.ldproxy.ogcapi.domain.ExtensionConfiguration;
import org.immutables.value.Value;
import java.util.List;
import java.util.OptionalDouble;
/**
* @author zahnen
*/
@Value.Immutable
@Value.Modifiable
@Value.Style(builder = "new")
@JsonDeserialize(as = ImmutableAroundRelationsConfiguration.class)
public abstract class AroundRelationsConfiguration implements ExtensionConfiguration {
@Value.Default
@Override
public boolean getEnabled() {
return false;
}
@JsonMerge(value = OptBoolean.FALSE)
@Value.Default
public List<Relation> getRelations() { return ImmutableList.of(); };
@Value.Immutable
@Value.Modifiable
@JsonDeserialize(as = ModifiableRelation.class)
public static abstract class Relation {
public abstract String getId();
public abstract String getLabel();
public abstract String getResponseType();
public abstract String getUrlTemplate();
public abstract OptionalDouble getBufferInMeters();
}
@Override
public ExtensionConfiguration mergeDefaults(ExtensionConfiguration extensionConfigurationDefault) {
return new ImmutableAroundRelationsConfiguration.Builder()
.from(extensionConfigurationDefault)
.from(this)
.build();
}
}
|
package org.openwms.tms.service;
import org.openwms.common.domain.LocationGroup;
import org.openwms.common.domain.TransportUnit;
import org.openwms.common.service.EntityService;
/**
* A TransportService.
* <p>
* Extends the {@link EntityService} interface about some useful methods
* regarding the general handling with {@link TransportUnit}s.
* </p>
*
* @author <a href="mailto:openwms@googlemail.com">Heiko Scherrer</a>
* @version $Revision: 877 $
* @since 0.1
* @see EntityService
*/
public interface TransportService extends EntityService<TransportUnit> {
/**
* Returns the actual number of active transports that have the
* <tt>locationGroup</tt> as target {@link LocationGroup}.
*
* @param locationGroup
* - {@link LocationGroup} to count all active transports for
* @return - Number of all active transports that are on the way to this
* {@link LocationGroup}
*/
int getTransportsToLocationGroup(LocationGroup locationGroup);
}
|
package org.pocketcampus.plugin.directory.android;
import org.pocketcampus.R;
import org.pocketcampus.android.platform.sdk.core.PluginController;
import org.pocketcampus.android.platform.sdk.core.PluginView;
import org.pocketcampus.android.platform.sdk.ui.element.InputBarElement;
import org.pocketcampus.android.platform.sdk.ui.element.OnKeyPressedListener;
import org.pocketcampus.android.platform.sdk.ui.layout.StandardTitledLayout;
import org.pocketcampus.android.platform.sdk.ui.list.LabeledListViewElement;
import org.pocketcampus.plugin.directory.android.iface.IDirectoryModel;
import org.pocketcampus.plugin.directory.android.iface.IDirectoryView;
import org.pocketcampus.plugin.directory.android.ui.PersonDetailsDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
public class DirectorySearchView extends PluginView implements IDirectoryView{
private DirectoryController mController;
private IDirectoryModel mModel;
private StandardTitledLayout mLayout;
private InputBarElement mInputBar;
private LabeledListViewElement mListView;
ArrayAdapter<String> mAdapter;
PersonDetailsDialog mDialog;
@Override
protected Class<? extends PluginController> getMainControllerClass() {
return DirectoryController.class;
}
/**
* Called once the view is connected to the controller.
* If you don't implement <code>getMainControllerClass()</code>
* then the controller given here will simply be <code>null</code>.
*/
@Override
protected void onDisplay(Bundle savedInstanceState, PluginController controller) {
// Get and cast the controller and model
mController = (DirectoryController) controller;
mModel = (DirectoryModel) controller.getModel();
displayView();
createSuggestionsList();
// mLayout = new DirectorySearchLayout(this, mController);
// OnClickListener listener = new OnClickListener() {
// @Override
// public void onClick(View v) {
// search();
// // The ActionBar is added automatically when you call setContentView
// setContentView(mLayout);
// Button searchButton = (Button) findViewById(R.id.directory_search_button);
// searchButton.setOnClickListener(listener);
// OnEditorActionListener oeal = new OnEditorActionListener() {
// @Override
// public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// if (actionId == EditorInfo.IME_ACTION_SEARCH) {
// search();
// return true;
// return false;
// mLayout.setOnEditorActionListener(oeal);
// We need to force the display before asking the controller for the data,
// as the controller may take some time to get it.
//displayData();
}
private void displayView() {
/** Layout */
mLayout = new StandardTitledLayout(this);
mLayout.setTitle(getString(R.string.directory_searchView_title));
/** Input bar */
mInputBar = new InputBarElement(this, "",getString(R.string.directory_searchView_hint));
mInputBar.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
mInputBar.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_SEARCH){
String query = mInputBar.getInputText();
search(query);
}
return true;
}
});
mInputBar.setOnButtonClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String query = mInputBar.getInputText();
search(query);
}
});
mInputBar.setOnKeyPressedListener(new OnKeyPressedListener() {
@Override
public void onKeyPressed(String text) {
mController.getAutoCompleted(text);
}
});
mLayout.addFillerView(mInputBar);
setContentView(mLayout);
}
private void createSuggestionsList() {
mListView = new LabeledListViewElement(this);
mInputBar.addView(mListView);
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view, int pos, long id) {
String query = adapter.getItemAtPosition(pos).toString();
if(query.contains(" "))
search(query);
else{
mInputBar.setInputText(query + " ");
mInputBar.setCursorAtEnd();
}
}
});
}
@Override
public void autoCompletedUpdated() {
mAdapter = new ArrayAdapter<String>(this, R.layout.sdk_list_entry, R.id.sdk_list_entry_text, mModel.getAutocompleteSuggestions());
mListView.setAdapter(mAdapter);
mListView.invalidate();
}
@Override
public void networkErrorHappened() {
Toast toast = Toast.makeText(getApplicationContext(), getString(R.string.directory_network_error), Toast.LENGTH_SHORT);
toast.show();
}
@Override
public void resultsUpdated() {
if(mModel.getResults().size() == 1){
mModel.selectPerson(mModel.getResults().get(0));
mController.getProfilePicture(mModel.getResults().get(0).sciper);
mDialog = new PersonDetailsDialog(this, mModel.getSelectedPerson());
mDialog.show();
}else
startActivity(new Intent(getApplicationContext(), DirectoryResultListView.class));
}
@Override
public void tooManyResults(int nb) {
Toast.makeText(this, getString(R.string.directory_too_many_results_warning), Toast.LENGTH_LONG).show();
}
@Override
public void pictureUpdated() {
if(mDialog != null)
mDialog.loadPicture();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_SEARCH){
String query = mInputBar.getInputText();
search(query);
}
return super.onKeyDown(keyCode, event);
}
private void search(String query){
mController.search(query);
}
}
|
package org.zstack.storage.primary.smp;
import org.zstack.header.core.ReturnValueCompletion;
public abstract class BackupStorageKvmUploader {
// When uploading an image from 'psPath' to backup storage, the 'bsPath'
// might be allocated by the backup storage and returned by the completion,
// instead of being known ahead of time.
public abstract void uploadBits(String bsPath, String psPath, ReturnValueCompletion<String> completion);
}
|
package com.google.appengine.eclipse.wtp.facet;
import com.google.appengine.eclipse.core.nature.GaeNature;
import com.google.appengine.eclipse.core.preferences.GaePreferences;
import com.google.appengine.eclipse.core.properties.GaeProjectProperties;
import com.google.appengine.eclipse.core.resources.GaeProjectResources;
import com.google.appengine.eclipse.core.sdk.GaeSdk;
import com.google.appengine.eclipse.wtp.AppEnginePlugin;
import com.google.appengine.eclipse.wtp.building.ProjectChangeNotifier;
import com.google.appengine.eclipse.wtp.classpath.GaeWtpClasspathContainer;
import com.google.appengine.eclipse.wtp.facet.ops.AppEngineXmlCreateOperation;
import com.google.appengine.eclipse.wtp.facet.ops.GaeFileCreateOperation;
import com.google.appengine.eclipse.wtp.facet.ops.SampleServletCreateOperation;
import com.google.appengine.eclipse.wtp.runtime.RuntimeUtils;
import com.google.appengine.eclipse.wtp.utils.ProjectUtils;
import com.google.common.collect.Lists;
import com.google.gdt.eclipse.core.BuilderUtilities;
import com.google.gdt.eclipse.core.StatusUtilities;
import com.google.gdt.eclipse.core.StringUtilities;
import com.google.gdt.eclipse.core.sdk.SdkSet;
import com.google.gdt.eclipse.core.sdk.SdkUtils;
import com.google.gdt.eclipse.managedapis.ManagedApiPlugin;
import com.google.gdt.eclipse.managedapis.ui.ApiImportWizard;
import com.google.gdt.eclipse.managedapis.ui.JavaProjectCheckDialog;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.jst.j2ee.project.JavaEEProjectUtilities;
import org.eclipse.swt.widgets.Display;
import org.eclipse.wst.common.componentcore.datamodel.properties.IFacetDataModelProperties;
import org.eclipse.wst.common.frameworks.datamodel.IDataModel;
import org.eclipse.wst.common.frameworks.datamodel.IDataModelOperation;
import org.eclipse.wst.common.project.facet.core.IDelegate;
import org.eclipse.wst.common.project.facet.core.IFacetedProjectWorkingCopy;
import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion;
import org.eclipse.wst.common.project.facet.core.runtime.IRuntime;
import org.osgi.service.prefs.BackingStoreException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
/**
* Google App Engine Facet delegate for INSTALL action.
*/
public final class GaeFacetInstallDelegate implements IDelegate {
@Override
public void execute(final IProject project, IProjectFacetVersion fv, Object config,
IProgressMonitor monitor) throws CoreException {
IDataModel model = (IDataModel) config;
List<IDataModelOperation> operations = Lists.newArrayList();
IPath sdkLocation = getSdkLocation(model);
GaeSdk sdk = getSdk(sdkLocation);
// if user attempts to install App Engine facet to existing old-style GPE project, then make
// that project 'not using GAE'.
GaeNature.removeNatureFromProject(project);
// do create project contents
if (JavaEEProjectUtilities.isDynamicWebProject(project)) {
// add a special container to be dependency of the Web App (WEB-INF/lib)
ProjectUtils.addWebAppDependencyContainer(project, fv,
GaeWtpClasspathContainer.CONTAINER_PATH);
// add custom builders
if (sdk != null) {
// since 1.8.1 Development server scans and reloads application automatically
if (SdkUtils.compareVersionStrings(sdk.getVersion(),
RuntimeUtils.MIN_SDK_VERSION_USING_AUTORELOAD) < 0) {
BuilderUtilities.addBuilderToProject(project, ProjectChangeNotifier.BUILDER_ID);
}
}
// add "appengine-web.xml" file
operations.add(new AppEngineXmlCreateOperation(model));
// add "logging.properties"
if (sdkLocation != null) {
final File loggingPropertiesFile = sdkLocation.append("config/user/logging.properties").toFile();
if (loggingPropertiesFile.exists()) {
operations.add(new GaeFileCreateOperation(model, new Path("WEB-INF/logging.properties")) {
@Override
protected InputStream getResourceContentsAsStream() throws CoreException {
try {
return new FileInputStream(loggingPropertiesFile);
} catch (FileNotFoundException e) {
throw new CoreException(
StatusUtilities.newErrorStatus(e, AppEnginePlugin.PLUGIN_ID));
}
}
});
}
}
boolean generateSample = model.getBooleanProperty(IGaeFacetConstants.GAE_PROPERTY_CREATE_SAMPLE);
if (generateSample) {
// add "favicon.ico"
operations.add(new GaeFileCreateOperation(model, new Path("favicon.ico")) {
@Override
protected InputStream getResourceContentsAsStream() throws CoreException {
return GaeProjectResources.createFavicon();
}
});
// add sample servlet
final String projectName = project.getName();
String servletClassName = generateServletClassName(projectName);
final String servletPath = generateServletPath(projectName);
operations.add(new SampleServletCreateOperation(model, servletClassName, servletPath));
// add index.html
operations.add(new GaeFileCreateOperation(model, new Path("index.html")) {
@Override
protected InputStream getResourceContentsAsStream() throws CoreException {
String servletName = generateServletName(projectName);
return GaeProjectResources.createWelcomePageSource(servletName, servletPath);
}
});
}
}
// setup deployment options
try {
GaeProjectProperties.setGaeEnableJarSplitting(project,
model.getBooleanProperty(IGaeFacetConstants.GAE_PROPERTY_ENABLE_JAR_SPLITTING));
GaeProjectProperties.setGaeDoJarClasses(project,
model.getBooleanProperty(IGaeFacetConstants.GAE_PROPERTY_DO_JAR_CLASSES));
GaeProjectProperties.setGaeRetaingStagingDir(project,
model.getBooleanProperty(IGaeFacetConstants.GAE_PROPERTY_RETAIN_STAGING_DIR));
} catch (BackingStoreException e) {
AppEnginePlugin.logMessage("Cannot setup deployment option", e);
}
try {
for (IDataModelOperation operation : operations) {
IStatus status = operation.execute(monitor, null);
if (status != null && !status.isOK()) {
throw new CoreException(status);
}
}
} catch (ExecutionException e) {
// TODO(amitin): perform undo?
throw new CoreException(StatusUtilities.newErrorStatus(e, AppEnginePlugin.PLUGIN_ID));
}
// open Import API Wizard if selected
if (model.getBooleanProperty(IGaeFacetConstants.GAE_PROPERTY_OPEN_IMPORT_API_WIZARD)) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
try {
openManagedApisImportWizard(project);
} catch (CoreException e) {
AppEnginePlugin.logMessage(e);
}
}
});
}
}
/**
* Opens Import Managed API Wizard.
*/
protected static void openManagedApisImportWizard(IProject project) throws CoreException {
if (JavaProjectCheckDialog.canAddGoogleApi(project)) {
ApiImportWizard wizard = new ApiImportWizard();
wizard.setProject(project);
wizard.setResources(ManagedApiPlugin.getDefault().getResources());
WizardDialog dialog = new WizardDialog(Display.getDefault().getActiveShell(), wizard);
dialog.setMinimumPageSize(wizard.getPreferredPageSize());
dialog.open();
}
}
/**
* Generates servlet class name basing on project name.
*/
private static String generateServletClassName(String projectName) {
return generateServletName(projectName) + "Servlet";
}
/**
* Generates servlet class name basing on project name.
*/
private static String generateServletName(String projectName) {
return StringUtilities.capitalize(sanitizeProjectName(projectName));
}
/**
* Generates path basing on project name.
*/
private static String generateServletPath(String projectName) {
return generateServletName(projectName).toLowerCase();
}
/**
* @return the {@link GaeSdk} for given {@link IPath} (location in filesystem) or
* <code>null</code> if SDK is not found.
*/
private static GaeSdk getSdk(IPath sdkLocation) {
if (sdkLocation != null) {
SdkSet<GaeSdk> sdks = GaePreferences.getSdkManager().getSdks();
return SdkUtils.findSdkForInstallationPath(sdks, sdkLocation);
}
return null;
}
/**
* Searches runtime components and retrieves runtime location (GAE SDK location). Returns
* <code>null</code>, if cannot be found.
*/
private static IPath getSdkLocation(IDataModel model) {
IFacetedProjectWorkingCopy fpwc = (IFacetedProjectWorkingCopy) model.getProperty(IFacetDataModelProperties.FACETED_PROJECT_WORKING_COPY);
IRuntime primaryRuntime = fpwc.getPrimaryRuntime();
return primaryRuntime == null ? null : ProjectUtils.getGaeSdkLocation(primaryRuntime);
}
/**
* Does some project name validations. Borrowed from WebAppProjectCreator.
*/
private static String sanitizeProjectName(String projectName) {
assert projectName != null && projectName.length() > 0;
String sanitized = null;
// Replace first character if it's invalid
char firstChar = projectName.charAt(0);
if (Character.isJavaIdentifierStart(firstChar)) {
sanitized = String.valueOf(firstChar);
} else {
sanitized = "_";
}
// Replace remaining invalid characters
for (int i = 1; i < projectName.length(); i++) {
char ch = projectName.charAt(i);
if (Character.isJavaIdentifierPart(ch)) {
sanitized += String.valueOf(ch);
} else {
sanitized += "_";
}
}
return sanitized;
}
}
|
package de.darwinspl.importer.evolution;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import de.darwinspl.importer.FeatureModelConstraintsTuple;
import eu.hyvar.dataValues.HyEnum;
import eu.hyvar.dataValues.HyEnumLiteral;
import eu.hyvar.evolution.HyName;
import eu.hyvar.evolution.HyNamedElement;
import eu.hyvar.evolution.util.HyEvolutionUtil;
import eu.hyvar.feature.HyBooleanAttribute;
import eu.hyvar.feature.HyEnumAttribute;
import eu.hyvar.feature.HyFeature;
import eu.hyvar.feature.HyFeatureAttribute;
import eu.hyvar.feature.HyFeatureChild;
import eu.hyvar.feature.HyFeatureFactory;
import eu.hyvar.feature.HyFeatureModel;
import eu.hyvar.feature.HyFeatureType;
import eu.hyvar.feature.HyGroup;
import eu.hyvar.feature.HyGroupComposition;
import eu.hyvar.feature.HyGroupType;
import eu.hyvar.feature.HyGroupTypeEnum;
import eu.hyvar.feature.HyNumberAttribute;
import eu.hyvar.feature.HyRootFeature;
import eu.hyvar.feature.HyStringAttribute;
import eu.hyvar.feature.constraint.HyConstraint;
import eu.hyvar.feature.constraint.HyConstraintFactory;
import eu.hyvar.feature.constraint.HyConstraintModel;
import eu.hyvar.feature.expression.HyAbstractFeatureReferenceExpression;
import eu.hyvar.feature.expression.HyBinaryExpression;
import eu.hyvar.feature.expression.HyExpression;
import eu.hyvar.feature.expression.HyFeatureReferenceExpression;
import eu.hyvar.feature.expression.HyUnaryExpression;
import eu.hyvar.feature.util.HyFeatureEvolutionUtil;
public class DwFeatureModelEvolutionImporter {
protected HyGroup getBestMatchingGroup(HyFeature featureToBeAdded,
HyGroupComposition groupCompositionOfFeatureToBeAdded, HyFeature parentInMergedModel,
HyGroupTypeEnum groupTypeEnum, Map<HyFeature, HyFeature> featureMap, Date date) {
List<HyFeatureChild> featureChildrenOfParentInMergedModel = HyEvolutionUtil.getValidTemporalElements(parentInMergedModel.getParentOf(), date);
if(featureChildrenOfParentInMergedModel == null || featureChildrenOfParentInMergedModel.size() == 0) {
return null;
}
if(featureChildrenOfParentInMergedModel.size() > 1) {
System.err.println("");
return null;
}
return featureChildrenOfParentInMergedModel.get(0).getChildGroup();
// HyGroup matchingGroup = null;
// int maximumAmountOfMatchingSiblings = 0;
// for (HyFeatureChild featureChild : HyEvolutionUtil.getValidTemporalElements(parentInMergedModel.getParentOf(),
// date)) {
// HyGroup childGroupOfParentInMergedModel = featureChild.getChildGroup();
// if (HyEvolutionUtil.getValidTemporalElement(childGroupOfParentInMergedModel.getTypes(), date).getType().equals(groupTypeEnum)) {
// if(HyEvolutionUtil.getValidTemporalElement(childGroupOfParentInMergedModel.getTypes(), date).getType().equals(HyGroupTypeEnum.AND)) {
// // For and groups it does not matter in which group they are. just return it.
// return childGroupOfParentInMergedModel;
// int amountOfMatchingSiblings = 0;
// for (HyFeature featureInGroup : groupCompositionOfFeatureToBeAdded.getFeatures()) {
// if (featureInGroup == featureToBeAdded) {
// continue;
// if (featureMap.get(featureInGroup) != null) {
// amountOfMatchingSiblings++;
// if (amountOfMatchingSiblings > maximumAmountOfMatchingSiblings) {
// amountOfMatchingSiblings = maximumAmountOfMatchingSiblings;
// matchingGroup = childGroupOfParentInMergedModel;
// return matchingGroup;
}
protected void addFeatureToGroup(HyFeature featureToBeAdded, HyGroupComposition oldGroupComposition, HyGroup targetGroup, HyFeature newParentFeature, HyGroupTypeEnum groupTypeEnum, HyFeatureModel mergedFeatureModel, Date date) {
if (targetGroup != null) {
// Add feature to best matching alternative group
HyGroupComposition newGroupComposition;
HyGroupComposition oldGroupCompositionOfTargetGroup = HyEvolutionUtil
.getValidTemporalElement(targetGroup.getParentOf(), date);
// Prevents the creation of a new group composition for each new feature that is added.
if(oldGroupCompositionOfTargetGroup.getValidSince().equals(date)) {
newGroupComposition = oldGroupCompositionOfTargetGroup;
}
else {
oldGroupCompositionOfTargetGroup.setValidUntil(date);
newGroupComposition = HyFeatureFactory.eINSTANCE.createHyGroupComposition();
newGroupComposition.setValidSince(date);
targetGroup.getParentOf().add(newGroupComposition);
newGroupComposition.getFeatures().addAll(oldGroupCompositionOfTargetGroup.getFeatures());
}
newGroupComposition.getFeatures().add(featureToBeAdded);
} else {
// create a new group
HyGroup newGroup = HyFeatureFactory.eINSTANCE.createHyGroup();
newGroup.setValidSince(date);
mergedFeatureModel.getGroups().add(newGroup);
HyFeatureChild newFeatureChild = HyFeatureFactory.eINSTANCE.createHyFeatureChild();
newFeatureChild.setValidSince(date);
newFeatureChild.setChildGroup(newGroup);
newFeatureChild.setParent(newParentFeature);
HyGroupType newGroupType = HyFeatureFactory.eINSTANCE.createHyGroupType();
newGroupType.setValidSince(date);
newGroupType.setType(groupTypeEnum);
newGroup.getTypes().add(newGroupType);
HyGroupComposition newGroupComposition = HyFeatureFactory.eINSTANCE.createHyGroupComposition();
newGroupComposition.setValidSince(date);
newGroupComposition.getFeatures().add(featureToBeAdded);
newGroupComposition.setCompositionOf(newGroup);
}
oldGroupComposition.getFeatures().remove(featureToBeAdded);
}
/**
* Creates a new group if necessary.
*
* @param featureToBeAdded
* @param groupCompositionOfFeatureToBeAdded
* @param parentInMergedModel
* @param groupTypeEnum
* @param featureMap
* @param mergedFeatureModel
* @param date
*/
protected void addFeatureToBestMatchingGroup(HyFeature featureToBeAdded,
HyGroupComposition groupCompositionOfFeatureToBeAdded, HyFeature parentInMergedModel,
HyGroupTypeEnum groupTypeEnum, Map<HyFeature, HyFeature> featureMap, HyFeatureModel mergedFeatureModel,
Date date) {
HyGroup matchingGroup = getBestMatchingGroup(featureToBeAdded, groupCompositionOfFeatureToBeAdded, parentInMergedModel, groupTypeEnum, featureMap, date);
addFeatureToGroup(featureToBeAdded, groupCompositionOfFeatureToBeAdded, matchingGroup, parentInMergedModel, groupTypeEnum, mergedFeatureModel, date);
}
protected boolean checkForEquality(EObject o1, EObject o2, Date date) {
if (o1 instanceof HyNamedElement && o2 instanceof HyNamedElement) {
HyNamedElement namedElement1 = (HyNamedElement) o1;
HyNamedElement namedElement2 = (HyNamedElement) o2;
HyName name1 = HyEvolutionUtil.getValidTemporalElement(namedElement1.getNames(), date);
HyName name2 = HyEvolutionUtil.getValidTemporalElement(namedElement2.getNames(), date);
if (name1.getName().equals(name2.getName())) {
return true;
} else {
return false;
}
} else if (o1 instanceof HyEnumLiteral && o2 instanceof HyEnumLiteral) {
HyEnumLiteral enumLiteral1 = (HyEnumLiteral) o1;
HyEnumLiteral enumLiteral2 = (HyEnumLiteral) o2;
if (enumLiteral1.getName().equals(enumLiteral2.getName())) {
return true;
} else {
return false;
}
}
return false;
}
/**
*
* @param elementToBeChecked
* @param elementsOfMergedModel
* @return null if no equivalent element exists. Otherwise the equivalentElement
*/
protected <S extends EObject> S checkIfElementAlreadyExists(S elementToBeChecked, List<S> elementsOfMergedModel,
Date date) {
for (S featureOfMergedModel : elementsOfMergedModel) {
if (checkForEquality(elementToBeChecked, featureOfMergedModel, date)) {
return featureOfMergedModel;
}
}
return null;
}
/**
* Merges multiple feature model evolution snapshots to one Temporal Feature
* Model
*
* @param models
* Each feature model has to be associated to a date at which the
* changes have occured.
* @return The whole feature model history merged into one TFM.
* @throws Exception
*/
public FeatureModelConstraintsTuple importFeatureModelEvolutionSnapshots(Map<FeatureModelConstraintsTuple, Date> models)
throws Exception {
Map<Date, FeatureModelConstraintsTuple> darwinSPLModels = new HashMap<Date, FeatureModelConstraintsTuple>();
for (Entry<FeatureModelConstraintsTuple, Date> entry : models.entrySet()) {
darwinSPLModels.put(entry.getValue(), entry.getKey());
HyConstraintModel constraintModel = entry.getKey().getConstraintModel();
if(constraintModel!=null) {
EcoreUtil.resolveAll(entry.getKey().getConstraintModel());
}
}
FeatureModelConstraintsTuple mergedModels = mergeFeatureModels(darwinSPLModels);
return mergedModels;
}
protected void mergeEnumAttributes(HyEnumAttribute equivalentEnumAttribute,
HyEnumAttribute enumAttributeOfFeatureToBeMerged, Date date) throws Exception {
if (equivalentEnumAttribute.getEnumType() == null || enumAttributeOfFeatureToBeMerged.getEnumType() == null) {
throw new Exception("Enum type of attribute "
+ HyEvolutionUtil.getValidTemporalElement(equivalentEnumAttribute.getNames(), date).getName()
+ " of either the merged or the input model is null. Aborting Merge!");
}
if (equivalentEnumAttribute.getEnumType().getName()
.equals(enumAttributeOfFeatureToBeMerged.getEnumType().getName())) {
List<HyEnumLiteral> literalsToBeAdded = new ArrayList<HyEnumLiteral>();
for (HyEnumLiteral enumLiteralOfFeatureAttributeToBeMerged : enumAttributeOfFeatureToBeMerged.getEnumType()
.getLiterals()) {
HyEnumLiteral equivalentEnumLiteral = checkIfElementAlreadyExists(
enumLiteralOfFeatureAttributeToBeMerged, HyEvolutionUtil.getValidTemporalElements(
equivalentEnumAttribute.getEnumType().getLiterals(), date),
date);
boolean equivalentLiteralExists = (equivalentEnumLiteral != null);
if (!equivalentLiteralExists) {
literalsToBeAdded.add(enumLiteralOfFeatureAttributeToBeMerged);
}
}
List<Integer> alreadyUsedLiteralValues = new ArrayList<Integer>();
if (!literalsToBeAdded.isEmpty()) {
for (HyEnumLiteral literalOfEquivalentAttribute : equivalentEnumAttribute.getEnumType().getLiterals()) {
alreadyUsedLiteralValues.add(literalOfEquivalentAttribute.getValue());
}
}
for (HyEnumLiteral literalToBeAdded : literalsToBeAdded) {
int value = 0;
while (alreadyUsedLiteralValues.contains(value)) {
value++;
}
alreadyUsedLiteralValues.add(value);
literalToBeAdded.setValue(value);
equivalentEnumAttribute.getEnumType().getLiterals().add(literalToBeAdded);
}
} else {
throw new Exception("Attribute names of "
+ HyEvolutionUtil.getValidTemporalElement(equivalentEnumAttribute.getNames(), date).getName()
+ " are the same but enum types do not match. Aborting merge!");
}
}
protected List<HyFeatureAttribute> mergeFeatureAttributes(HyFeature featureToBeMerged,
HyFeature equivalentFeatureOfMergedModel, Date date) throws Exception {
// Step 2: check whether attributes are matching.
List<HyFeatureAttribute> attributesToBeAddedToEquivalentFeature = new ArrayList<HyFeatureAttribute>();
for (HyFeatureAttribute attributeOfFeatureToBeMerged : featureToBeMerged.getAttributes()) {
HyFeatureAttribute equivalentAttribute = checkIfElementAlreadyExists(attributeOfFeatureToBeMerged,
HyEvolutionUtil.getValidTemporalElements(equivalentFeatureOfMergedModel.getAttributes(), date),
date);
boolean attributeAlreadyExists = (equivalentAttribute != null);
if (!attributeAlreadyExists) {
attributesToBeAddedToEquivalentFeature.add(attributeOfFeatureToBeMerged);
} else {
// Step 1.a: Check whether attribute domains are the same. If not, extend them
// to have the union of their domains
if (equivalentAttribute instanceof HyNumberAttribute
&& attributeOfFeatureToBeMerged instanceof HyNumberAttribute) {
HyNumberAttribute equivalentNumberAttribute = (HyNumberAttribute) equivalentAttribute;
HyNumberAttribute numberAttributeOfFeatureToBeMerged = (HyNumberAttribute) attributeOfFeatureToBeMerged;
int minimum = Math.min(equivalentNumberAttribute.getMin(),
numberAttributeOfFeatureToBeMerged.getMin());
int maximum = Math.max(equivalentNumberAttribute.getMax(),
numberAttributeOfFeatureToBeMerged.getMax());
equivalentNumberAttribute.setMin(minimum);
equivalentNumberAttribute.setMax(maximum);
} else if (equivalentAttribute instanceof HyBooleanAttribute
&& attributeOfFeatureToBeMerged instanceof HyBooleanAttribute) {
// nothing to do.
} else if (equivalentAttribute instanceof HyEnumAttribute
&& attributeOfFeatureToBeMerged instanceof HyEnumAttribute) {
HyEnumAttribute equivalentEnumAttribute = (HyEnumAttribute) equivalentAttribute;
HyEnumAttribute enumAttributeOfFeatureToBeMerged = (HyEnumAttribute) attributeOfFeatureToBeMerged;
mergeEnumAttributes(equivalentEnumAttribute, enumAttributeOfFeatureToBeMerged, date);
} else if (equivalentAttribute instanceof HyStringAttribute
&& attributeOfFeatureToBeMerged instanceof HyStringAttribute) {
// nothing to do.
} else {
throw new Exception("Attributes "
+ HyEvolutionUtil.getValidTemporalElement(equivalentAttribute.getNames(), date).getName()
+ " have the same name but have different types. Cannot merge.");
}
}
}
for (HyFeatureAttribute attributeToBeAdded : attributesToBeAddedToEquivalentFeature) {
attributeToBeAdded.setValidSince(date);
equivalentFeatureOfMergedModel.getAttributes().add(attributeToBeAdded);
}
return attributesToBeAddedToEquivalentFeature;
}
/**
* No evolution shall exist in the input models.
*
* @param models
* @return
* @throws Exception
*/
protected FeatureModelConstraintsTuple mergeFeatureModels(Map<Date, FeatureModelConstraintsTuple> models)
throws Exception {
HyFeatureModel mergedFeatureModel = HyFeatureFactory.eINSTANCE.createHyFeatureModel();
HyConstraintModel mergedConstraintModel = HyConstraintFactory.eINSTANCE.createHyConstraintModel();
List<Date> sortedDateList = new ArrayList<Date>(models.keySet());
sortedDateList.remove(null);
Collections.sort(sortedDateList);
ZonedDateTime zdt = ZonedDateTime.now();
System.out.println(zdt.toString()+": Importing base model");
long start = System.currentTimeMillis();
if (models.get(null) != null) {
mergeModels(models.get(null), mergedFeatureModel, mergedConstraintModel, null);
}
long end = System.currentTimeMillis();
System.out.println("Importing base model took "+(end-start)+" milliseconds.");
for (Date date : sortedDateList) {
zdt = ZonedDateTime.now();
System.out.println(zdt.toString()+": Importing model at date "+date);
start = System.currentTimeMillis();
mergeModels(models.get(date), mergedFeatureModel, mergedConstraintModel, date);
end = System.currentTimeMillis();
System.out.println("Importing model at date "+date+ " took "+(end-start)+" milliseconds");
}
FeatureModelConstraintsTuple mergedModels = new FeatureModelConstraintsTuple(mergedFeatureModel,
mergedConstraintModel);
return mergedModels;
}
/**
*
* @param featureModelToBeMerged
* @param mergedFeatureModel
* @param featureMap key: feature from model to be merged, value: feature from merged model
* @param date
* @return key: group from model to be merged, value: group from merged model
*/
protected Map<HyGroup, HyGroup> matchGroups(HyFeatureModel featureModelToBeMerged, HyFeatureModel mergedFeatureModel, Map<HyFeature, HyFeature> featureMap, Date date) {
Map<HyGroup, HyGroup> groupMap = new HashMap<HyGroup, HyGroup>();
List<HyGroup> potentialGroupMatchingPartners = new ArrayList<HyGroup>();
potentialGroupMatchingPartners.addAll(HyEvolutionUtil.getValidTemporalElements(mergedFeatureModel.getGroups(), date));
HyGroup matchedGroupMatchingPartners = null;
// first link all And groups with the same parent.
for (HyGroup groupToBeMerged : featureModelToBeMerged.getGroups()) {
if(matchedGroupMatchingPartners != null) {
potentialGroupMatchingPartners.remove(matchedGroupMatchingPartners);
matchedGroupMatchingPartners = null;
}
HyFeature parentFeatureOfGroupToBeMerged = HyFeatureEvolutionUtil.getParentOfGroup(groupToBeMerged, date);
HyFeature equivalentToParentOfGroupToBeMerged = featureMap.get(parentFeatureOfGroupToBeMerged);
if(equivalentToParentOfGroupToBeMerged != null) {
List<HyFeatureChild> validFeatureChildren = HyEvolutionUtil.getValidTemporalElements(equivalentToParentOfGroupToBeMerged.getParentOf(), date);
if(validFeatureChildren != null && validFeatureChildren.size() > 0) {
if(validFeatureChildren.size() > 1) {
System.err.println("Cannot perform group match as multiple child groups under feature "+HyEvolutionUtil.getValidTemporalElement(equivalentToParentOfGroupToBeMerged.getNames(), date).getName()+" at date "+date);
continue;
}
HyGroup potentialMatchingPartner = validFeatureChildren.get(0).getChildGroup();
if(potentialGroupMatchingPartners.contains(potentialMatchingPartner)) {
groupMap.put(groupToBeMerged, potentialMatchingPartner);
matchedGroupMatchingPartners = potentialMatchingPartner;
}
else {
System.err.println("Cannot perform group match as input model seems to have multiple groups under feature "+ HyEvolutionUtil.getValidTemporalElement(parentFeatureOfGroupToBeMerged.getNames(), date).getName()+" at date "+date);
continue;
}
}
}
}
// List<HyGroup> potentialGroupMatchingPartners = new ArrayList<HyGroup>();
// potentialGroupMatchingPartners.addAll(HyEvolutionUtil.getValidTemporalElements(mergedFeatureModel.getGroups(), date));
// HyGroup matchedGroupMatchingPartners = null;
// // first link all And groups with the same parent.
// linkAndGroupsLoop:
// for (HyGroup groupToBeMerged : featureModelToBeMerged.getGroups()) {
// if(!HyFeatureEvolutionUtil.getType(groupToBeMerged, date).getType().equals(HyGroupTypeEnum.AND)) {
// // no and group -> skip
// continue;
// if(matchedGroupMatchingPartners != null) {
// potentialGroupMatchingPartners.remove(matchedGroupMatchingPartners);
// matchedGroupMatchingPartners = null;
// HyFeature parentFeatureOfGroupToBeMerged = HyFeatureEvolutionUtil.getParentOfGroup(groupToBeMerged, date);
// HyFeature equivalentToParentOfGroupToBeMerged = featureMap.get(parentFeatureOfGroupToBeMerged);
// if(equivalentToParentOfGroupToBeMerged != null) {
// for(HyGroup groupFromMergedModel: potentialGroupMatchingPartners) {
// if(!HyFeatureEvolutionUtil.getType(groupFromMergedModel, date).getType().equals(HyGroupTypeEnum.AND)) {
// // no and group -> skip
// continue;
// HyFeature parentFeatureOfPotentialMatchingPartner = HyFeatureEvolutionUtil.getParentOfGroup(groupFromMergedModel, date);
// if(parentFeatureOfPotentialMatchingPartner == equivalentToParentOfGroupToBeMerged) {
// groupMap.put(groupToBeMerged, groupFromMergedModel);
// matchedGroupMatchingPartners = groupFromMergedModel;
// continue linkAndGroupsLoop;
// matchedGroupMatchingPartners = null;
// groupsToBeMergedLoop:
// for (HyGroup groupToBeMerged : featureModelToBeMerged.getGroups()) {
// // Only compare the group to be merged to groups which are valid at that point in time.
// if(matchedGroupMatchingPartners != null) {
// potentialGroupMatchingPartners.remove(matchedGroupMatchingPartners);
// matchedGroupMatchingPartners = null;
// for(HyGroup groupFromMergedModel: potentialGroupMatchingPartners) {
// int amountOfSimilarFeatures = 0;
// List<HyFeature> featuresOfMergedGroup = HyFeatureEvolutionUtil.getFeaturesOfGroup(groupFromMergedModel,
// date);
// for (HyFeature featureOfGroupToBeMerged : HyFeatureEvolutionUtil.getFeaturesOfGroup(groupToBeMerged,
// date)) {
// if (featuresOfMergedGroup.contains(featureMap.get(featureOfGroupToBeMerged))) {
// amountOfSimilarFeatures++;
// double sameFeatureRatio = (double) amountOfSimilarFeatures / (double) featuresOfMergedGroup.size();
// if (sameFeatureRatio >= 0.75) {
// groupMap.put(groupToBeMerged, groupFromMergedModel);
// matchedGroupMatchingPartners = groupFromMergedModel;
// continue groupsToBeMergedLoop;
return groupMap;
}
/**
*
* @param featureModelToBeMerged
* @param mergedFeatureModel
* @param featuresToInvalidate List of all features from merged model which not have been matched. Will indicate which features won't have a matching partner and thus be invalidated.
* @param addedFeatureAttributes List of feature attributes which have been matched during this method
* @param featuresToBeAddedToMergedModel List of all features from input model which not have been matched and, thus, have to be added to the merged model
* @param date
* @return key: feature from model to be merged, value: feature from merged model
* @throws Exception
*/
protected Map<HyFeature, HyFeature> matchFeatures(HyFeatureModel featureModelToBeMerged, HyFeatureModel mergedFeatureModel, List<HyFeature> featuresToInvalidate, List<HyFeatureAttribute> addedFeatureAttributes, List<HyFeature> featuresToBeAddedToMergedModel, Date date) throws Exception {
Map<HyFeature, HyFeature> featureMap = new HashMap<HyFeature, HyFeature>();
List<HyFeature> potentialFeatureMatchingPartners = new ArrayList<HyFeature>();
potentialFeatureMatchingPartners.addAll(HyEvolutionUtil.getValidTemporalElements(mergedFeatureModel.getFeatures(), date));
for (HyFeature featureToBeMerged : featureModelToBeMerged.getFeatures()) {
HyFeature equivalentFeature = checkIfElementAlreadyExists(featureToBeMerged,
potentialFeatureMatchingPartners, date);
boolean featureAlreadyExists = (equivalentFeature != null);
if (!featureAlreadyExists) {
featuresToBeAddedToMergedModel.add(featureToBeMerged);
} else {
potentialFeatureMatchingPartners.remove(equivalentFeature);
featuresToInvalidate.remove(equivalentFeature);
featureMap.put(featureToBeMerged, equivalentFeature);
addedFeatureAttributes.addAll(mergeFeatureAttributes(featureToBeMerged, equivalentFeature, date));
}
}
return featureMap;
}
protected void mergeModels(FeatureModelConstraintsTuple modelsToBeMerged, HyFeatureModel mergedFeatureModel,
HyConstraintModel mergedConstraintModel, Date date) throws Exception {
List<HyFeature> featuresToInvalidate = new ArrayList<HyFeature>(HyEvolutionUtil.getValidTemporalElements(mergedFeatureModel.getFeatures(), date));
// Step 1: Check that each feature / attribute exists. If not create it and set
// valid since. If a feature / attribute existed before, but not anymore, set
// valid until.
HyFeatureModel featureModelToBeMerged = modelsToBeMerged.getFeatureModel();
List<HyFeature> featuresToBeAddedToMergedModel = new ArrayList<HyFeature>();
List<HyFeatureAttribute> addedFeatureAttributes = new ArrayList<HyFeatureAttribute>();
ZonedDateTime zdt = ZonedDateTime.now();
System.out.println(zdt.toString()+": Searching for matching features");
// Key is the feature of the input model and value is the feature of the merged
// model.
Map<HyFeature, HyFeature> featureMap = matchFeatures(featureModelToBeMerged, mergedFeatureModel, featuresToInvalidate, addedFeatureAttributes, featuresToBeAddedToMergedModel, date);
zdt = ZonedDateTime.now();
System.out.println(zdt.toString()+": Searching for matching groups");
Map<HyGroup, HyGroup> groupMap = matchGroups(featureModelToBeMerged, mergedFeatureModel, featureMap, date);
consistencyCheck(mergedFeatureModel);
zdt = ZonedDateTime.now();
System.out.println(zdt.toString()+": Checking whether features have to be moved");
moveFeaturesIfTheyHaveBeenMovedInInputModel(mergedFeatureModel, featureMap, groupMap, date);
consistencyCheck(mergedFeatureModel);
zdt = ZonedDateTime.now();
System.out.println(zdt.toString()+": Checking whether feature types need to be updated");
updateFeatureTypes(mergedFeatureModel, featureMap, date);
consistencyCheck(mergedFeatureModel);
zdt = ZonedDateTime.now();
System.out.println(zdt.toString()+": Checking whether group types need to be updated");
updateGroupTypes(groupMap, date);
consistencyCheck(mergedFeatureModel);
zdt = ZonedDateTime.now();
System.out.println(zdt.toString()+": Adding new features to merged model");
addNewFeatures(featuresToBeAddedToMergedModel, mergedFeatureModel, featureMap, date);
consistencyCheck(mergedFeatureModel);
zdt = ZonedDateTime.now();
System.out.println(zdt.toString()+": Adding enums of feature attributes");
// handle enums. Only considered enums which are used by feature attributes.
Set<HyEnum> enums = new HashSet<HyEnum>();
for (HyFeatureAttribute addedFeatureAttribute : addedFeatureAttributes) {
if (addedFeatureAttribute instanceof HyEnumAttribute) {
HyEnumAttribute enumAttribute = (HyEnumAttribute) addedFeatureAttribute;
enums.add(enumAttribute.getEnumType());
}
}
mergedFeatureModel.getEnums().addAll(enums);
consistencyCheck(mergedFeatureModel);
zdt = ZonedDateTime.now();
System.out.println(zdt.toString()+": Invalidating features");
// Invalidate features which do not exist anymore. Update group composition.
for (HyFeature featureToInvalidate : featuresToInvalidate) {
HyFeatureEvolutionUtil.removeFeatureFromGroup(featureToInvalidate, date);
HyFeatureEvolutionUtil.getName(featureToInvalidate, date).setValidUntil(date);
HyFeatureEvolutionUtil.getType(featureToInvalidate, date).setValidUntil(date);
for(HyFeatureAttribute attribute: HyEvolutionUtil.getValidTemporalElements(featureToInvalidate.getAttributes(), date)) {
attribute.setValidUntil(date);
}
featureToInvalidate.setValidUntil(date);
}
consistencyCheck(mergedFeatureModel);
// Merge constraint models
HyConstraintModel constraintModelToBeMerged = modelsToBeMerged.getConstraintModel();
if (constraintModelToBeMerged != null) {
zdt = ZonedDateTime.now();
System.out.println(zdt.toString()+": Merging constraint model");
mergeConstraintModel(constraintModelToBeMerged, mergedConstraintModel, featureMap, date);
}
consistencyCheck(mergedFeatureModel);
}
protected void updateGroupTypes(Map<HyGroup, HyGroup> groupMap, Date date) {
for (Entry<HyGroup, HyGroup> entry : groupMap.entrySet()) {
HyGroupType groupTypeOfGroupToBeMerged = HyFeatureEvolutionUtil.getType(entry.getKey(), date);
HyGroupType groupTypeOfMergedGroup = HyFeatureEvolutionUtil.getType(entry.getValue(), date);
if (!groupTypeOfGroupToBeMerged.getType().equals(groupTypeOfMergedGroup.getType())) {
groupTypeOfMergedGroup.setValidUntil(date);
HyGroupType newGroupType = HyFeatureFactory.eINSTANCE.createHyGroupType();
newGroupType.setValidSince(date);
newGroupType.setType(groupTypeOfGroupToBeMerged.getType());
entry.getValue().getTypes().add(newGroupType);
}
}
}
protected void updateFeatureTypes(HyFeatureModel mergedFeatureModel, Map<HyFeature, HyFeature> featureMap,
Date date) {
for (Entry<HyFeature, HyFeature> entry : featureMap.entrySet()) {
// key feature from input mode, value feature from merged model
HyFeatureType inputType = HyFeatureEvolutionUtil.getType(entry.getKey(), date);
HyFeatureType mergedType = HyFeatureEvolutionUtil.getType(entry.getValue(), date);
if (!inputType.getType().equals(mergedType.getType())) {
mergedType.setValidUntil(date);
HyFeatureType newFeatureType = HyFeatureFactory.eINSTANCE.createHyFeatureType();
newFeatureType.setValidSince(date);
newFeatureType.setType(inputType.getType());
entry.getValue().getTypes().add(newFeatureType);
}
}
}
protected void addNewFeatures(List<HyFeature> featuresToBeAddedToMergedModel, HyFeatureModel mergedFeatureModel,
Map<HyFeature, HyFeature> featureMap, Date date) throws Exception {
for (HyFeature featureToBeAdded : featuresToBeAddedToMergedModel) {
// set validity of feature, its name and type to date
HyFeatureModel oldFeatureModel = featureToBeAdded.getFeatureModel();
mergedFeatureModel.getFeatures().add(featureToBeAdded);
featureToBeAdded.setValidSince(date);
featureToBeAdded.setValidUntil(null);
// clear everything from evolution.
HyName validName = HyEvolutionUtil.getValidTemporalElement(featureToBeAdded.getNames(), date);
validName.setValidSince(date);
validName.setValidUntil(null);
featureToBeAdded.getNames().clear();
featureToBeAdded.getNames().add(validName);
HyFeatureType validType = HyEvolutionUtil.getValidTemporalElement(featureToBeAdded.getTypes(), date);
validType.setValidSince(date);
validType.setValidUntil(null);
featureToBeAdded.getTypes().clear();
featureToBeAdded.getTypes().add(validType);
List<HyFeatureChild> validFeatureChildren = HyEvolutionUtil
.getValidTemporalElements(featureToBeAdded.getParentOf(), date);
featureToBeAdded.getParentOf().clear();
for (HyFeatureChild featureChild : validFeatureChildren) {
featureToBeAdded.getParentOf().add(featureChild);
featureChild.setValidSince(date);
featureChild.setValidUntil(null);
HyGroup group = featureChild.getChildGroup();
mergedFeatureModel.getGroups().add(group);
group.setValidSince(date);
group.setValidUntil(null);
HyGroupType validGroupType = HyEvolutionUtil.getValidTemporalElement(group.getTypes(), date);
group.getTypes().clear();
validGroupType.setValidSince(date);
validGroupType.setValidUntil(null);
group.getTypes().add(validGroupType);
HyGroupComposition validGroupComposition = HyEvolutionUtil.getValidTemporalElement(group.getParentOf(),
date);
validGroupComposition.setValidSince(date);
validGroupComposition.setValidUntil(null);
group.getParentOf().clear();
group.getParentOf().add(validGroupComposition);
List<HyFeature> featuresOfGroupComposition = new ArrayList<HyFeature>();
featuresOfGroupComposition.addAll(validGroupComposition.getFeatures());
for(HyFeature featureOfGroupComposition: featuresOfGroupComposition) {
HyFeature equivalentFeature = featureMap.get(featureOfGroupComposition);
if(equivalentFeature != null) {
validGroupComposition.getFeatures().remove(featureOfGroupComposition);
validGroupComposition.getFeatures().add(equivalentFeature);
}
}
}
// Put feature in correct group
HyGroupComposition groupComposition = HyEvolutionUtil
.getValidTemporalElement(featureToBeAdded.getGroupMembership(), date);
if (groupComposition != null) {
HyGroup group = groupComposition.getCompositionOf();
HyFeatureChild featureChildOfGroup = HyEvolutionUtil.getValidTemporalElement(group.getChildOf(), date);
HyFeature parentFeatureInInputModel = featureChildOfGroup.getParent();
if (featuresToBeAddedToMergedModel.contains(parentFeatureInInputModel)) {
// parent feature is also added to the new model. We are done.
continue;
}
HyFeature parentInMergedModel = featureMap.get(parentFeatureInInputModel);
if (parentInMergedModel != null) {
HyGroupType groupType = HyEvolutionUtil.getValidTemporalElement(group.getTypes(), date);
HyGroupTypeEnum groupTypeEnum = groupType.getType();
addFeatureToBestMatchingGroup(featureToBeAdded, groupComposition, parentInMergedModel,
groupTypeEnum, featureMap, mergedFeatureModel, date);
} else {
throw new Exception("We have a problem. The parent of the feature "
+ HyEvolutionUtil.getValidTemporalElement(featureToBeAdded.getNames(), date).getName()
+ " is neither newly added to the merged model nor is it already existent in it. Aborting whole merging process");
}
}
else {
HyRootFeature oldFeatureModelRootFeature = HyEvolutionUtil
.getValidTemporalElement(oldFeatureModel.getRootFeature(), date);
if (oldFeatureModelRootFeature == null || oldFeatureModelRootFeature.getFeature() != featureToBeAdded) {
throw new Exception("Feature "
+ HyEvolutionUtil.getValidTemporalElement(featureToBeAdded.getNames(), date).getName()
+ " did not have a group but is no root feature. Aborted merge.");
}
HyRootFeature oldRootFeature = HyEvolutionUtil
.getValidTemporalElement(mergedFeatureModel.getRootFeature(), date);
if (oldRootFeature != null) {
oldRootFeature.setValidUntil(date);
}
HyRootFeature newRootFeature = HyFeatureFactory.eINSTANCE.createHyRootFeature();
newRootFeature.setValidSince(date);
newRootFeature.setFeature(featureToBeAdded);
mergedFeatureModel.getRootFeature().add(newRootFeature);
}
}
}
protected void moveFeaturesIfTheyHaveBeenMovedInInputModel(HyFeatureModel mergedFeatureModel,
Map<HyFeature, HyFeature> featureMap, Map<HyGroup, HyGroup> groupMap, Date date) {
for (Entry<HyFeature, HyFeature> featureEntrySet : featureMap.entrySet()) {
HyFeature parentOfMergedFeature = HyFeatureEvolutionUtil
.getParentFeatureOfFeature(featureEntrySet.getValue(), date);
HyFeature parentFeatureFromInputModel = HyFeatureEvolutionUtil
.getParentFeatureOfFeature(featureEntrySet.getKey(), date);
if (parentFeatureFromInputModel == null) {
// seems to be new root.
continue;
}
HyFeature equivalentToParentFromInputModel = featureMap.get(parentFeatureFromInputModel);
if (equivalentToParentFromInputModel == null) {
// Parent will be added to the merged model.
// Has to be removed from its current group.
// When the new parent will be added to the model, this feature will be added to its group.
HyFeatureEvolutionUtil.removeFeatureFromGroup(featureEntrySet.getValue(), date);
} else if (equivalentToParentFromInputModel == parentOfMergedFeature) {
continue;
// TODO may be wrong if the group changed for the same parent
// HyFeature inputFeature = featureEntrySet.getKey();
// HyFeature equivalentFeature = featureEntrySet.getValue();
// HyGroup groupOfInputFeature = HyEvolutionUtil.getValidTemporalElement(inputFeature.getGroupMembership(), date).getCompositionOf();
// HyGroupType groupTypeOfInputGroup = HyEvolutionUtil.getValidTemporalElement(groupOfInputFeature.getTypes(), date);
// HyGroupComposition groupCompositionOfInputFeature = HyEvolutionUtil.getValidTemporalElement(inputFeature.getGroupMembership(), date);
// HyGroup groupOfEquivalentFeature = HyEvolutionUtil.getValidTemporalElement(equivalentFeature.getGroupMembership(), date).getCompositionOf();
// HyGroup equivalentGroup = groupMap.get(groupOfInputFeature);
// if(equivalentGroup != null && equivalentGroup == groupOfEquivalentFeature) {
// // groups also stayed the same. done
// continue;
// System.out.println("New Feature Move method");
// // Group didn't stay the same.
// HyGroup bestMatchingGroupOfMergedModel = getBestMatchingGroup(inputFeature, groupCompositionOfInputFeature, equivalentToParentFromInputModel, groupTypeOfInputGroup.getType(), featureMap, date);
// if(bestMatchingGroupOfMergedModel != null) {
// if(bestMatchingGroupOfMergedModel == groupOfEquivalentFeature) {
// // done. best matching group is still the same as before.
// continue;
// addFeatureToGroup(inputFeature, groupCompositionOfInputFeature, bestMatchingGroupOfMergedModel, equivalentToParentFromInputModel, groupTypeOfInputGroup.getType(), mergedFeatureModel, date);
} else {
// parents are different.
HyGroupComposition groupCompositionOfFeatureFromInputModel = HyEvolutionUtil
.getValidTemporalElement(featureEntrySet.getKey().getGroupMembership(), date);
HyGroupTypeEnum groupTypeOfGroupOfFeatureFromInputModel = HyEvolutionUtil.getValidTemporalElement(
groupCompositionOfFeatureFromInputModel.getCompositionOf().getTypes(), date).getType();
addFeatureToBestMatchingGroup(featureEntrySet.getValue(), groupCompositionOfFeatureFromInputModel,
equivalentToParentFromInputModel, groupTypeOfGroupOfFeatureFromInputModel, featureMap,
mergedFeatureModel, date);
HyFeatureEvolutionUtil.removeFeatureFromGroup(featureEntrySet.getValue(), date);
}
}
}
protected void mergeConstraintModel(HyConstraintModel constraintModelToBeMerged,
HyConstraintModel mergedConstraintModel, Map<HyFeature, HyFeature> featureMap, Date date) {
// For each constraint in model to be merged:
// Create a map, in which constraints from the model to be merged are mapped to
// equal constraints from the merged model
// Key is the constraint from model to be merged and value is constraint from
// merged model
List<HyConstraint> constraintsToBeMergedWithoutMatchingPartner = new ArrayList<HyConstraint>(
constraintModelToBeMerged.getConstraints());
List<HyConstraint> remainingMatchingPartners = new ArrayList<HyConstraint>(
HyEvolutionUtil.getValidTemporalElements(mergedConstraintModel.getConstraints(), date));
ZonedDateTime zdt = ZonedDateTime.now();
System.out.println(zdt.toString()+": Finding matching constraints");
for (HyConstraint constraintToBeMerged : constraintModelToBeMerged.getConstraints()) {
HyConstraint equalConstraint = findEqualConstraint(constraintToBeMerged, remainingMatchingPartners,
featureMap, date);
if (equalConstraint != null) {
remainingMatchingPartners.remove(equalConstraint);
constraintsToBeMergedWithoutMatchingPartner.remove(constraintToBeMerged);
zdt = ZonedDateTime.now();
// System.err.println(zdt.toString()+": Matched a constraint.");
continue;
}
}
// For each constraint of the model to be merged that does not have a mapping
// partner: add the constraint with valid since
zdt = ZonedDateTime.now();
System.out.println(zdt.toString()+": Adding new constraints");
for (HyConstraint constraintToBeMergedWithoutMatchingPartner : constraintsToBeMergedWithoutMatchingPartner) {
mergedConstraintModel.getConstraints()
.add(createConstraintInMergedModel(constraintToBeMergedWithoutMatchingPartner, featureMap, date));
}
// For each constraint of the merged model that does not have a mapping partner:
// set the valid until of the constraint
zdt = ZonedDateTime.now();
System.out.println(zdt.toString()+": Invalidate constraints");
for (HyConstraint unmatchedConstraint : remainingMatchingPartners) {
unmatchedConstraint.setValidUntil(date);
}
}
protected HyConstraint findEqualConstraint(HyConstraint constraint, List<HyConstraint> potentialMatchingPartners,
Map<HyFeature, HyFeature> featureMap, Date date) {
for (HyConstraint potentialMatchingPartner : potentialMatchingPartners) {
if (areExpressionsEqual(constraint.getRootExpression(), potentialMatchingPartner.getRootExpression(),
featureMap, date)) {
return potentialMatchingPartner;
}
}
return null;
}
protected boolean areExpressionsEqual(HyExpression expressionOfConstraintToBeMerged,
HyExpression expressionOfMergedConstraint, Map<HyFeature, HyFeature> featureMap, Date date) {
if (expressionOfConstraintToBeMerged.getClass().toString()
.equals(expressionOfMergedConstraint.getClass().toString())) {
if (expressionOfConstraintToBeMerged instanceof HyBinaryExpression) {
HyBinaryExpression bin1 = (HyBinaryExpression) expressionOfConstraintToBeMerged;
HyBinaryExpression bin2 = (HyBinaryExpression) expressionOfMergedConstraint;
boolean operandsMatch = false;
operandsMatch = areExpressionsEqual(bin1.getOperand1(), bin2.getOperand1(), featureMap, date)
&& areExpressionsEqual(bin1.getOperand2(), bin2.getOperand2(), featureMap, date);
return operandsMatch;
} else if (expressionOfConstraintToBeMerged instanceof HyUnaryExpression) {
HyUnaryExpression unary1 = (HyUnaryExpression) expressionOfConstraintToBeMerged;
HyUnaryExpression unary2 = (HyUnaryExpression) expressionOfMergedConstraint;
return areExpressionsEqual(unary1.getOperand(), unary2.getOperand(), featureMap, date);
} else if (expressionOfConstraintToBeMerged instanceof HyAbstractFeatureReferenceExpression) {
HyAbstractFeatureReferenceExpression featureRef1 = (HyAbstractFeatureReferenceExpression) expressionOfConstraintToBeMerged;
HyAbstractFeatureReferenceExpression featureRef2 = (HyAbstractFeatureReferenceExpression) expressionOfMergedConstraint;
HyFeature equivalentFeatureFromMergedFeatureModel = featureMap.get(featureRef1.getFeature());
boolean featuresMatch = equivalentFeatureFromMergedFeatureModel==featureRef2.getFeature();
return featuresMatch;
} else {
System.err.println(
"Currently unsupported expressions have been compared in de.darwinspl.importer.evolution.DwFeatureModelEvolutionImporter.areExpressionsEqual(HyExpression, HyExpression, Map<HyFeature, HyFeature>, Date)");
return false;
}
} else {
return false;
}
}
protected HyConstraint createConstraintInMergedModel(HyConstraint constraintToBeMerged,
Map<HyFeature, HyFeature> featureMap, Date date) {
HyConstraint constraint = EcoreUtil.copy(constraintToBeMerged);
constraint.setValidSince(date);
TreeIterator<EObject> iterator = constraint.eAllContents();
while (iterator.hasNext()) {
EObject eObject = iterator.next();
if (eObject instanceof HyFeatureReferenceExpression) {
HyFeatureReferenceExpression featureReference = (HyFeatureReferenceExpression) eObject;
// no versions are supported
featureReference.setVersionRestriction(null);
HyFeature equivalentFeatureInMergedModel = featureMap.get(featureReference.getFeature());
if(equivalentFeatureInMergedModel != null) {
featureReference.setFeature(equivalentFeatureInMergedModel);
}
}
}
return constraint;
}
/**
* Only use this method if you have the feeling that something isn't imported correctly.
* @param mergedFeatureModel
*/
private void consistencyCheck(HyFeatureModel mergedFeatureModel) {
// List<Date> dates = HyEvolutionUtil.collectDates(mergedFeatureModel);
// if(dates.size() != 0) {
// Date firstDate = dates.get(0);
// Calendar cal = new GregorianCalendar();
// cal.setTime(firstDate);
// cal.add(Calendar.DAY_OF_MONTH, -1);
// Date beforeFirstDate = cal.getTime();
// dates.add(beforeFirstDate);
// if(dates.size() > 1) {
// Date lastDate = dates.get(dates.size()-1);
// cal.setTime(lastDate);
// cal.add(Calendar.DAY_OF_MONTH, 1);
// Date afterLastDate = cal.getTime();
// dates.add(afterLastDate);
// Collections.sort(dates);
// for(HyFeature feature: HyEvolutionUtil.getValidTemporalElements(mergedFeatureModel.getFeatures(), date)) {
// if(HyEvolutionUtil.isValid(feature, date)) {
// List<HyGroupComposition> groupMemberships = HyEvolutionUtil.getValidTemporalElements(feature.getGroupMembership(), date) ;
// if(groupMemberships == null || groupMemberships.size() == 0) {
// System.err.println("Feature "+HyEvolutionUtil.getValidTemporalElement(feature.getNames(), date).getName()+ " has no group membership at date "+date);
// else if(groupMemberships.size() > 1) {
// System.err.println("Feature "+HyEvolutionUtil.getValidTemporalElement(feature.getNames(), date).getName()+ " has multiple group membership at date "+date);
// List<HyFeatureChild> validFeatureChildren = HyEvolutionUtil.getValidTemporalElements(feature.getParentOf(), date);
// if(validFeatureChildren != null && validFeatureChildren.size()>1) {
// System.err.println("Feature "+HyEvolutionUtil.getValidTemporalElement(feature.getNames(), date).getName()+" has more than one child group at date "+date);
// for(HyGroup group: mergedFeatureModel.getGroups()) {
// if(HyEvolutionUtil.isValid(group, date)) {
// List<HyFeatureChild> featureChildrenParent = HyEvolutionUtil.getValidTemporalElements(group.getChildOf(), date);
// List<HyGroupComposition> groupCompositions = HyEvolutionUtil.getValidTemporalElements(group.getParentOf(), date);
// if(featureChildrenParent == null || featureChildrenParent.size() == 0) {
// System.err.println("Group has no group parent feature at date "+date);
// else if(featureChildrenParent.size() > 1) {
// System.err.println("Group has multiple group parent feature at date "+date);
// if(groupCompositions == null || groupCompositions.size() == 0) {
// System.err.println("Group has no composition at date "+date);
// else if(groupCompositions.size() > 1) {
// System.err.println("Group has multiple compositions at date "+date);
// for(HyGroup group: mergedFeatureModel.getGroups()) {
// for(HyGroupComposition groupComposition: group.getParentOf()) {
// if(!mergedFeatureModel.getFeatures().containsAll(groupComposition.getFeatures())) {
// System.err.println("Non consistent!");
// return;
}
}
|
package org.yakindu.sct.generator.genmodel.scoping;
import org.eclipse.core.runtime.Assert;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.xtext.EcoreUtil2;
import org.eclipse.xtext.resource.IEObjectDescription;
import org.eclipse.xtext.resource.XtextResourceSet;
import org.eclipse.xtext.scoping.IScope;
import org.eclipse.xtext.scoping.impl.FilteringScope;
import org.eclipse.xtext.scoping.impl.SimpleScope;
import org.eclipse.xtext.xbase.scoping.XbaseScopeProvider;
import org.yakindu.sct.generator.core.extensions.GeneratorExtensions;
import org.yakindu.sct.generator.core.extensions.GeneratorExtensions.GeneratorDescriptor;
import org.yakindu.sct.generator.core.extensions.LibraryExtensions;
import org.yakindu.sct.generator.core.extensions.LibraryExtensions.LibraryDescriptor;
import org.yakindu.sct.generator.genmodel.resource.FeatureResourceDescription;
import org.yakindu.sct.model.sgen.FeatureConfiguration;
import org.yakindu.sct.model.sgen.GeneratorModel;
import org.yakindu.sct.model.sgen.SGenPackage;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.google.inject.Injector;
/**
*
* @author andreas muelder - Initial contribution and API
*
*/
@SuppressWarnings("restriction")
public class SGenScopeProvider extends XbaseScopeProvider {
@Inject
private XtextResourceSet resourceSet;
@Inject
private Injector injector;
@Override
public IScope getScope(EObject context, EReference reference) {
if (reference.getName().equals("type")) {
return scope_Type(context, reference);
}
if (reference.getName().equals("parameter")) {
return scope_Parameter(context, reference);
}
if (reference.getName().equals("elementRef")) {
return scope_GeneratorEntry_elementRef(context, reference);
}
return super.getScope(context, reference);
}
private IScope scope_GeneratorEntry_elementRef(final EObject context,
final EReference reference) {
GeneratorModel generatorModel = (GeneratorModel) EcoreUtil2
.getRootContainer(context);
String id = generatorModel.getGeneratorId();
final GeneratorDescriptor desc = GeneratorExtensions
.getGeneratorDescriptorForId(id);
final Class<?> elementRefType = desc.getElementRefType();
return new FilteringScope(getDelegate().getScope(context, reference),
new Predicate<IEObjectDescription>() {
public boolean apply(IEObjectDescription input) {
return elementRefType.isAssignableFrom(input
.getEClass().getInstanceClass());
}
});
}
private IScope scope_Parameter(final EObject context, EReference reference) {
IScope libraryScope = getLibraryScope(context.eResource());
return new FilteringScope(libraryScope,
new Predicate<IEObjectDescription>() {
public boolean apply(IEObjectDescription input) {
if (!input.getEClass().equals(
SGenPackage.Literals.FEATURE_PARAMETER)) {
return false;
}
// Only allow references to FeatureParameters defined by
// enclosing Feature
FeatureConfiguration configuration = EcoreUtil2
.getContainerOfType(context,
FeatureConfiguration.class);
if(configuration == null || configuration.getType() == null)
return false;
String featureName = configuration.getType().getName();
if (featureName == null) {
return false;
}
return featureName.equals(input
.getUserData(FeatureResourceDescription.FEATURE_CONTAINER));
}
});
}
private IScope scope_Type(EObject context, EReference reference) {
IScope libraryScope = getLibraryScope(context.eResource());
return new FilteringScope(libraryScope,
new Predicate<IEObjectDescription>() {
public boolean apply(IEObjectDescription input) {
return input.getEClass().equals(
SGenPackage.Literals.FEATURE_TYPE);
}
});
}
private SimpleScope getLibraryScope(Resource resource) {
GeneratorModel generatorModel = (GeneratorModel) EcoreUtil
.getObjectByType(resource.getContents(),
SGenPackage.Literals.GENERATOR_MODEL);
Assert.isNotNull(generatorModel);
String generatorId = generatorModel.getGeneratorId();
Iterable<IEObjectDescription> allElements = Lists.newArrayList();
Iterable<LibraryDescriptor> libraryDescriptor = LibraryExtensions
.getLibraryDescriptor(generatorId);
for (LibraryDescriptor desc : libraryDescriptor) {
Resource library = resourceSet.getResource(desc.getURI(), true);
FeatureResourceDescription description = new FeatureResourceDescription(
library);
injector.injectMembers(description);
allElements = Iterables.concat(allElements,
description.getExportedObjects());
}
return new SimpleScope(allElements);
}
}
|
package org.copperengine.performancetest.main;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import org.copperengine.core.AbstractDependencyInjector;
import org.copperengine.core.CopperRuntimeException;
import org.copperengine.core.DependencyInjector;
import org.copperengine.core.EngineIdProvider;
import org.copperengine.core.EngineIdProviderBean;
import org.copperengine.core.PersistentProcessingEngine;
import org.copperengine.core.batcher.RetryingTxnBatchRunner;
import org.copperengine.core.batcher.impl.BatcherImpl;
import org.copperengine.core.common.DefaultProcessorPoolManager;
import org.copperengine.core.common.JdkRandomUUIDFactory;
import org.copperengine.core.common.ProcessorPoolManager;
import org.copperengine.core.common.WorkflowRepository;
import org.copperengine.core.monitoring.LoggingStatisticCollector;
import org.copperengine.core.monitoring.RuntimeStatisticsCollector;
import org.copperengine.core.persistent.DatabaseDialect;
import org.copperengine.core.persistent.DerbyDbDialect;
import org.copperengine.core.persistent.H2Dialect;
import org.copperengine.core.persistent.MySqlDialect;
import org.copperengine.core.persistent.OracleDialect;
import org.copperengine.core.persistent.PersistentPriorityProcessorPool;
import org.copperengine.core.persistent.PersistentProcessorPool;
import org.copperengine.core.persistent.PersistentScottyEngine;
import org.copperengine.core.persistent.PostgreSQLDialect;
import org.copperengine.core.persistent.ScottyDBStorage;
import org.copperengine.core.persistent.ScottyDBStorageInterface;
import org.copperengine.core.persistent.Serializer;
import org.copperengine.core.persistent.StandardJavaSerializer;
import org.copperengine.core.persistent.cassandra.CassandraSessionManagerImpl;
import org.copperengine.core.persistent.cassandra.CassandraStorage;
import org.copperengine.core.persistent.hybrid.DefaultTimeoutManager;
import org.copperengine.core.persistent.hybrid.HybridDBStorage;
import org.copperengine.core.persistent.hybrid.HybridTransactionController;
import org.copperengine.core.persistent.hybrid.StorageCache;
import org.copperengine.core.persistent.txn.CopperTransactionController;
import org.copperengine.core.persistent.txn.TransactionController;
import org.copperengine.core.util.Backchannel;
import org.copperengine.core.util.BackchannelDefaultImpl;
import org.copperengine.ext.wfrepo.classpath.ClasspathWorkflowRepository;
import org.copperengine.performancetest.impl.MockAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class PerformanceTestContext implements AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(PerformanceTestContext.class);
protected final Map<String, Supplier<?>> suppliers = new HashMap<>();
protected final Supplier<Properties> props;
protected final Supplier<MockAdapter> mockAdapter;
protected final Supplier<DependencyInjector> dependencyInjector;
protected final Supplier<Backchannel> backchannel;
protected final Supplier<PersistentProcessingEngine> engine;
protected final Supplier<WorkflowRepository> repo;
protected final Supplier<LoggingStatisticCollector> statisticsCollector;
protected final Supplier<EngineIdProvider> engineIdProvider;
protected final Supplier<Serializer> serializer;
protected final Supplier<ProcessorPoolManager<PersistentProcessorPool>> processorPoolManager;
protected final Supplier<ConfigurationManager> configManager;
protected TransactionController transactionController = null;
private final List<Runnable> shutdownHooks = new ArrayList<>();
public PerformanceTestContext() {
configManager = Suppliers.memoize(new Supplier<ConfigurationManager>() {
@Override
public ConfigurationManager get() {
return createConfigurationManager();
}
});
suppliers.put("configManager", configManager);
processorPoolManager = Suppliers.memoize(new Supplier<ProcessorPoolManager<PersistentProcessorPool>>() {
@Override
public ProcessorPoolManager<PersistentProcessorPool> get() {
return createProcessorPoolManager();
}
});
suppliers.put("processorPoolManager", processorPoolManager);
serializer = Suppliers.memoize(new Supplier<Serializer>() {
@Override
public Serializer get() {
return createSerializer();
}
});
suppliers.put("serializer", serializer);
engineIdProvider = Suppliers.memoize(new Supplier<EngineIdProvider>() {
@Override
public EngineIdProvider get() {
return createEngineIdProvider();
}
});
suppliers.put("engineIdProvider", engineIdProvider);
statisticsCollector = Suppliers.memoize(new Supplier<LoggingStatisticCollector>() {
@Override
public LoggingStatisticCollector get() {
return createStatisticsCollector();
}
});
suppliers.put("statisticsCollector", statisticsCollector);
repo = Suppliers.memoize(new Supplier<WorkflowRepository>() {
@Override
public WorkflowRepository get() {
return createWorkflowRepository();
}
});
suppliers.put("repo", repo);
engine = Suppliers.memoize(new Supplier<PersistentProcessingEngine>() {
@Override
public PersistentProcessingEngine get() {
return createPersistentProcessingEngine();
}
});
suppliers.put("engine", engine);
props = Suppliers.memoize(new Supplier<Properties>() {
@Override
public Properties get() {
return createProperties();
}
});
suppliers.put("props", props);
mockAdapter = Suppliers.memoize(new Supplier<MockAdapter>() {
@Override
public MockAdapter get() {
return createMockAdapter();
}
});
suppliers.put("mockAdapter", mockAdapter);
backchannel = Suppliers.memoize(new Supplier<Backchannel>() {
@Override
public Backchannel get() {
return createBackchannel();
}
});
suppliers.put("backchannel", backchannel);
dependencyInjector = Suppliers.memoize(new Supplier<DependencyInjector>() {
@Override
public DependencyInjector get() {
return createDependencyInjector();
}
});
suppliers.put("dependencyInjector", dependencyInjector);
startup();
}
protected ConfigurationManager createConfigurationManager() {
return new ConfigurationManager(props.get());
}
protected ProcessorPoolManager<PersistentProcessorPool> createProcessorPoolManager() {
return new DefaultProcessorPoolManager<PersistentProcessorPool>();
}
protected Serializer createSerializer() {
StandardJavaSerializer serializer = new StandardJavaSerializer();
boolean compression = configManager.get().getConfigBoolean(ConfigParameter.COMPRESSION);
logger.debug("compression={}", compression);
serializer.setCompress(compression);
return serializer;
}
protected EngineIdProvider createEngineIdProvider() {
return new EngineIdProviderBean("perftest");
}
protected LoggingStatisticCollector createStatisticsCollector() {
LoggingStatisticCollector statCollector = new LoggingStatisticCollector();
statCollector.setLoggingIntervalSec(10);
statCollector.setResetAfterLogging(false);
return statCollector;
}
protected WorkflowRepository createWorkflowRepository() {
return new ClasspathWorkflowRepository("org.copperengine.performancetest.workflows");
}
protected DatabaseDialect createDialect(DataSource ds, WorkflowRepository wfRepository, EngineIdProvider engineIdProvider, RuntimeStatisticsCollector runtimeStatisticsCollector, Serializer serializer) {
Connection c = null;
try {
c = ds.getConnection();
String name = c.getMetaData().getDatabaseProductName();
logger.info("Test database type is {}", name);
if ("oracle".equalsIgnoreCase(name)) {
OracleDialect dialect = new OracleDialect();
dialect.setWfRepository(wfRepository);
dialect.setEngineIdProvider(engineIdProvider);
dialect.setMultiEngineMode(false);
dialect.setRuntimeStatisticsCollector(runtimeStatisticsCollector);
dialect.setSerializer(serializer);
dialect.startup();
return dialect;
}
if ("Apache Derby".equalsIgnoreCase(name)) {
DerbyDbDialect dialect = new DerbyDbDialect();
dialect.setDataSource(ds);
dialect.setWfRepository(wfRepository);
dialect.setRuntimeStatisticsCollector(runtimeStatisticsCollector);
dialect.setSerializer(serializer);
return dialect;
}
if ("H2".equalsIgnoreCase(name)) {
H2Dialect dialect = new H2Dialect();
dialect.setDataSource(ds);
dialect.setWfRepository(wfRepository);
dialect.setRuntimeStatisticsCollector(runtimeStatisticsCollector);
dialect.setSerializer(serializer);
return dialect;
}
if ("MySQL".equalsIgnoreCase(name)) {
MySqlDialect dialect = new MySqlDialect();
dialect.setWfRepository(wfRepository);
dialect.setRuntimeStatisticsCollector(runtimeStatisticsCollector);
dialect.setSerializer(serializer);
return dialect;
}
if ("PostgreSQL".equalsIgnoreCase(name)) {
PostgreSQLDialect dialect = new PostgreSQLDialect();
dialect.setWfRepository(wfRepository);
dialect.setRuntimeStatisticsCollector(runtimeStatisticsCollector);
dialect.setSerializer(serializer);
return dialect;
}
throw new Error("No dialect available for DBMS " + name);
} catch (Exception e) {
throw new CopperRuntimeException("Unable to create dialect", e);
} finally {
if (c != null)
try {
c.close();
} catch (SQLException e) {
logger.error("unable to close connection", e);
}
}
}
protected PersistentProcessingEngine createPersistentProcessingEngine() {
ScottyDBStorageInterface dbStorageInterface = null;
if (!isCassandraTest()) {
final int batcherNumbOfThreads = configManager.get().getConfigInt(ConfigParameter.BATCHER_NUMB_OF_THREADS);
logger.debug("Starting batcher with {} worker threads", batcherNumbOfThreads);
final ComboPooledDataSource dataSource = DataSourceFactory.createDataSource(props.get());
transactionController = new CopperTransactionController(dataSource);
final BatcherImpl batcher = new BatcherImpl(batcherNumbOfThreads);
batcher.setBatchRunner(new RetryingTxnBatchRunner<>(dataSource));
batcher.setStatisticsCollector(statisticsCollector.get());
batcher.startup();
ScottyDBStorage dbStorage = new ScottyDBStorage();
dbStorage.setBatcher(batcher);
dbStorage.setCheckDbConsistencyAtStartup(false);
dbStorage.setDialect(createDialect(dataSource, repo.get(), engineIdProvider.get(), statisticsCollector.get(), serializer.get()));
dbStorage.setTransactionController(transactionController);
dbStorageInterface = dbStorage;
shutdownHooks.add(new Runnable() {
@Override
public void run() {
batcher.shutdown();
dataSource.close();
}
});
}
else {
transactionController = new HybridTransactionController();
final String cassandraHosts = props.get().getProperty(ConfigParameter.CASSANDRA_HOSTS.getKey());
final CassandraSessionManagerImpl sessionManager = new CassandraSessionManagerImpl(Arrays.asList(cassandraHosts.split(",")), configManager.get().getConfigInteger(ConfigParameter.CASSANDRA_PORT), configManager.get().getConfigString(ConfigParameter.CASSANDRA_KEYSPACE));
sessionManager.startup();
final DefaultTimeoutManager timeoutManager = new DefaultTimeoutManager();
timeoutManager.startup();
final ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
CassandraStorage storage = new CassandraStorage(sessionManager, pool, statisticsCollector.get());
storage.setCreateSchemaOnStartup(true);
HybridDBStorage dbStorage = new HybridDBStorage(serializer.get(), repo.get(), new StorageCache(storage), timeoutManager, pool);
dbStorageInterface = dbStorage;
shutdownHooks.add(new Runnable() {
@Override
public void run() {
try {
timeoutManager.shutdown();
sessionManager.shutdown();
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
}
catch (Exception e) {
logger.error("shutdown failed", e);
}
}
});
}
final int procPoolNumbOfThreads = configManager.get().getConfigInt(ConfigParameter.PROC_POOL_NUMB_OF_THREADS);
logger.debug("Starting default processor pool with {} worker threads", procPoolNumbOfThreads);
final List<PersistentProcessorPool> pools = new ArrayList<PersistentProcessorPool>();
final PersistentPriorityProcessorPool pool = new PersistentPriorityProcessorPool(PersistentProcessorPool.DEFAULT_POOL_ID, transactionController, procPoolNumbOfThreads);
pool.setDequeueBulkSize(configManager.get().getConfigInt(ConfigParameter.PROC_DEQUEUE_BULK_SIZE));
pools.add(pool);
processorPoolManager.get().setProcessorPools(pools);
PersistentScottyEngine engine = new PersistentScottyEngine();
engine.setWfRepository(repo.get());
engine.setStatisticsCollector(statisticsCollector.get());
engine.setEngineIdProvider(engineIdProvider.get());
engine.setIdFactory(new JdkRandomUUIDFactory());
engine.setProcessorPoolManager(processorPoolManager.get());
engine.setDbStorage(dbStorageInterface);
engine.setDependencyInjector(dependencyInjector.get());
return engine;
}
protected DependencyInjector createDependencyInjector() {
AbstractDependencyInjector dependencyInjector = new AbstractDependencyInjector() {
@Override
public String getType() {
return null;
}
@Override
protected Object getBean(String beanId) {
Supplier<?> supplier = suppliers.get(beanId);
if (supplier == null) {
throw new RuntimeException("No supplier with id '" + beanId + "' found!");
}
else {
return supplier.get();
}
}
};
return dependencyInjector;
}
protected Properties createProperties() {
try {
Properties defaults = new Properties();
logger.debug("Loading properties from 'performancetest.default.properties'...");
defaults.load(DataSourceFactory.class.getResourceAsStream("/performancetest.default.properties"));
Properties specific = new Properties();
String username = System.getProperty("user.name", "undefined");
InputStream is = DataSourceFactory.class.getResourceAsStream("/performancetest." + username + ".properties");
if (is != null) {
logger.info("Loading properties from 'performancetest." + username + ".properties'...");
specific.load(is);
}
Properties p = new Properties();
p.putAll(defaults);
p.putAll(specific);
p.putAll(System.getProperties());
List<String> keys = new ArrayList<>();
for (Object key : p.keySet()) {
keys.add(key.toString());
}
Collections.sort(keys);
for (String key : keys) {
logger.debug("Property {}='{}'", key, p.getProperty(key));
}
return p;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("failed to load properties", e);
}
}
protected Backchannel createBackchannel() {
return new BackchannelDefaultImpl();
}
protected MockAdapter createMockAdapter() {
int numberOfThreads = configManager.get().getConfigInt(ConfigParameter.MOCK_ADAPTER_NUMB_OF_THREADS);
logger.debug("MockAdapter.numberOfThreads={}", numberOfThreads);
MockAdapter x = new MockAdapter(numberOfThreads);
x.setEngine(engine.get());
return x;
}
public PersistentProcessingEngine getEngine() {
return engine.get();
}
public void startup() {
for (Supplier<?> s : suppliers.values()) {
s.get();
}
mockAdapter.get().startup();
statisticsCollector.get().start();
engine.get().startup();
};
public void shutdown() {
engine.get().shutdown();
statisticsCollector.get().shutdown();
mockAdapter.get().shutdown();
for (Runnable r : shutdownHooks) {
r.run();
}
}
@Override
public void close() {
shutdown();
}
public void registerBean(final String id, final Object bean) {
suppliers.put(id, new Supplier<Object>() {
@Override
public Object get() {
return bean;
}
});
}
public LoggingStatisticCollector getStatisticsCollector() {
return statisticsCollector.get();
}
public Backchannel getBackchannel() {
return backchannel.get();
}
public ProcessorPoolManager<PersistentProcessorPool> getProcessorPoolManager() {
return processorPoolManager.get();
}
public TransactionController getTransactionController() {
return transactionController;
}
public ConfigurationManager getConfigManager() {
return configManager.get();
}
public boolean isCassandraTest() {
final String cassandraHosts = props.get().getProperty(ConfigParameter.CASSANDRA_HOSTS.getKey());
return cassandraHosts != null && !cassandraHosts.isEmpty();
}
}
|
package nl.idgis.publisher.provider.database;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import scala.concurrent.Future;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.dispatch.Futures;
import akka.dispatch.Mapper;
import akka.dispatch.OnFailure;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.japi.Function2;
import akka.pattern.Patterns;
import nl.idgis.publisher.protocol.messages.Failure;
import nl.idgis.publisher.provider.database.messages.Convert;
import nl.idgis.publisher.provider.database.messages.Converted;
import nl.idgis.publisher.provider.protocol.database.Record;
import nl.idgis.publisher.provider.protocol.database.Records;
import nl.idgis.publisher.stream.StreamCursor;
public class DatabaseCursor extends StreamCursor<ResultSet, Records> {
private final LoggingAdapter log = Logging.getLogger(getContext().system(), this);
private final ActorRef converter;
private final int messageSize;
public DatabaseCursor(ResultSet t, int messageSize, ActorRef converter) {
super(t);
this.converter = converter;
this.messageSize = messageSize;
}
public static Props props(ResultSet t, int messageSize, ActorRef converter) {
return Props.create(DatabaseCursor.class, t, messageSize, converter);
}
private Future<Record> toRecord() throws SQLException {
int columnCount = t.getMetaData().getColumnCount();
List<Future<Object>> valueFutures = new ArrayList<>();
for(int j = 0; j < columnCount; j++) {
Object o = t.getObject(j + 1);
if(o == null) {
valueFutures.add(Futures.<Object>successful(new Converted(null)));
} else {
Future<Object> future = Patterns.ask(converter, new Convert(o), 15000);
future.onFailure(new OnFailure() {
@Override
public void onFailure(Throwable t) throws Throwable {
log.error(t, "conversion failure");
}
}, getContext().dispatcher());
valueFutures.add(future);
}
}
return Futures.fold(new ArrayList<Object>(), valueFutures, new Function2<List<Object>, Object, List<Object>>() {
@Override
public List<Object> apply(List<Object> values, Object value) throws Exception {
if(value instanceof Converted) {
values.add(((Converted) value).getValue());
} else if(value instanceof Failure) {
Throwable cause = ((Failure) value).getCause();
log.error(cause, "failed to convert value");
throw new Exception(cause);
}
return values;
}
}, getContext().dispatcher()).map(new Mapper<List<Object>, Record>() {
@Override
public Record apply(List<Object> values) {
return new Record(values);
}
}, getContext().dispatcher());
}
@Override
protected Future<Records> next() {
log.debug("fetching next records");
try {
List<Future<Record>> recordFutures = new ArrayList<>();
recordFutures.add(toRecord());
for(int i = 1; i < messageSize; i++) {
if(!t.next()) {
break;
}
recordFutures.add(toRecord());
}
Future<Records> records = Futures.fold(new ArrayList<Record>(), recordFutures, new Function2<List<Record>, Record, List<Record>>() {
@Override
public List<Record> apply(List<Record> records, Record record) throws Exception {
records.add(record);
return records;
}
}, getContext().dispatcher()).map(new Mapper<List<Record>, Records>() {
@Override
public Records apply(List<Record> records) {
return new Records(records);
}
}, getContext().dispatcher());
log.debug("records future created");
return records;
} catch(Throwable t) {
log.error(t, "failed to fetch records");
return Futures.failed(t);
}
}
@Override
protected boolean hasNext() throws Exception {
return t.next();
}
@Override
public void postStop() throws SQLException {
t.getStatement().close();
t.close();
}
}
|
package com.github.dreamsnatcher.utils;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.Disposable;
public class Assets implements Disposable {
//DO THIS WITH ASSETMANAGER LATER TODO
public static TextureRegion spaceShip0;
public static TextureRegion spaceShip1;
public static TextureRegion spaceShip2;
public static TextureRegion spaceShip3;
public static TextureRegion spaceShipEmpty;
public static TextureRegion planet;
public static TextureRegion planetBonus;
public static TextureRegion planetBonusLow;
public static TextureRegion stars0;
public static TextureRegion stars1;
public static TextureRegion stars2;
public static TextureRegion stars3;
public static TextureRegion asteroid0;
public static TextureRegion asteroid1;
public static TextureRegion spaceBar;
public static TextureRegion spaceBarFinish;
public static TextureRegion asteroid2;
public static TextureRegion asteroid3;
public static TextureRegion energyBar;
public static TextureRegion energyPixel;
public static TextureRegion spaceShipHarvest;
public static TextureRegion planetDead;
public static TextureRegion planetLow;
public static TextureRegion indicator;
public static TextureRegion planetBonusDead;
public static TextureRegion bierpixel;
public static TextureRegion schaumkrone;
public static TextureRegion finishWookie;
public static TextureRegion nightmare;
//Animations
public static Animation shipAnimationSpeed1;
public static Animation shipAnimationSpeed2;
public static Animation shipAnimationSpeed3;
//static Array<Animation> allAnimations = new Array<Animation>();
public static void init() {
shipAnimationSpeed1 = loadAnimation("animations/spaceship_speed_0_", 3, 0.3f);
shipAnimationSpeed2 = loadAnimation("animations/spaceship_speed_1_", 3, 0.3f);
shipAnimationSpeed3 = loadAnimation("animations/spaceship_speed_2_", 3, 0.3f);
spaceShip0 = new TextureRegion(new Texture("spaceship_speed0.png"));
spaceShip0.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
spaceShip1 = new TextureRegion(new Texture("spaceship_speed1.png"));
spaceShip1.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
spaceShip2 = new TextureRegion(new Texture("spaceship_speed2.png"));
spaceShip2.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
spaceShip3 = new TextureRegion(new Texture("spaceship_speed3.png"));
spaceShip3.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
spaceShipEmpty = new TextureRegion(new Texture("spaceship_empty.png"));
spaceShipEmpty.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
spaceShipHarvest = new TextureRegion(new Texture("spaceship_extract_energy.png"));
spaceShipHarvest.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
planet = new TextureRegion(new Texture("planet_high_pop.png"));
planet.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
planetLow = new TextureRegion(new Texture("planet_small_pop.png"));
planetLow.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
planetBonus = new TextureRegion(new Texture("planet_3_high_pop.png"));
planetBonus.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
planetBonusLow = new TextureRegion(new Texture("planet_3_small_pop.png"));
planetBonusLow.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
planetBonusDead = new TextureRegion(new Texture("dead_planet_3.png"));
planetBonusDead.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
planetDead = new TextureRegion(new Texture("dead_planet.png"));
planetDead.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
stars0 = new TextureRegion(new Texture("space_1_v2.png"));
stars0.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
stars1 = new TextureRegion(new Texture("space_2_v2.png"));
stars1.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
stars2 = new TextureRegion(new Texture("space_3_v2.png"));
stars2.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
stars3 = new TextureRegion(new Texture("space_4_v2.png"));
stars3.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
asteroid0 = new TextureRegion(new Texture("asteriod_small01.png"));
asteroid1 = new TextureRegion(new Texture("asteriod_small02.png"));
asteroid2 = new TextureRegion(new Texture("asteriod_big01.png"));
asteroid3 = new TextureRegion(new Texture("asteriod_small04.png"));
energyBar = new TextureRegion(new Texture("energybar_container.png"));
energyPixel = new TextureRegion(new Texture("pixel.png"));
indicator = new TextureRegion(new Texture("indicator.png"));
indicator.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
spaceBar = new TextureRegion(new Texture("spacebar.png"));
spaceBar.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
spaceBarFinish = new TextureRegion(new Texture("spacebar_landed.png"));
spaceBarFinish.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
bierpixel = new TextureRegion(new Texture("bierpixel.png"));
bierpixel.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
schaumkrone = new TextureRegion(new Texture("schaumkrone.png"));
schaumkrone.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
finishWookie = new TextureRegion(new Texture("wookie.png"));
finishWookie.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
nightmare = new TextureRegion(new Texture("nightmare.png"));
nightmare.getTexture().setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
}
private static Animation loadAnimation(String path, int frames, float frameDuration) {
TextureRegion[] regions = new TextureRegion[frames];
for(int i = 0; i < frames; i++) {
Texture tex = new Texture(Gdx.files.internal(path + i + ".png"));
regions[i] = new TextureRegion(tex);
}
return new Animation(frameDuration, regions);
}
@Override
public void dispose() {
spaceShip0.getTexture().dispose();
planet.getTexture().dispose();
stars0.getTexture().dispose();
stars1.getTexture().dispose();
stars2.getTexture().dispose();
stars3.getTexture().dispose();
//allAnimations.dispose();
}
}
|
package com.mygdx.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class FogMainTestEnvironment extends ApplicationAdapter {
SpriteBatch batch;
Texture img;
float x,y;
Texture menuPic;
private BitmapFont font;
@Override
public void create () {
batch = new SpriteBatch();
font = new BitmapFont();
font.setColor(Color.RED);
img = new Texture("Monk.png");
Gdx.audio.newMusic(Gdx.files.internal("AOE_mp3.mp3")).play();
menuPic = new Texture("mab_meme.png");
batch = new SpriteBatch();
}
@Override
public void render () {
if(Gdx.input.isKeyPressed(Keys.UP)){
if(y+5 < 760){
y = y+ 5;} else{
y=y;
}
}
if(Gdx.input.isKeyPressed(Keys.DOWN)){
if(y-5 > 0){
y = y- 5;
}else{ y=y;}
}
if(Gdx.input.isKeyPressed(Keys.RIGHT)){
if(x+5 < 1070){
x = x+ 5;}else{x=x;}
}
if(Gdx.input.isKeyPressed(Keys.LEFT)){
if(x-5>0){
x = x- 5;}else{x=x;}
}
if(Gdx.input.isKeyJustPressed(Keys.E)){
Gdx.audio.newMusic(Gdx.files.internal("Sound1.mp3")).play();
}
batch.begin();
batch.draw(menuPic,0,0);
batch.draw(img, x, y, 100,100);
font.draw(batch, "Press E", x+35, y+115);
batch.end();
Gdx.audio.newMusic(Gdx.files.internal("AOE_mp3.mp3"));
}
@Override
public void dispose () {
Gdx.audio.newMusic(Gdx.files.internal("AOE_mp3.mp3")).dispose();
Gdx.audio.newMusic(Gdx.files.internal("Sound1.mp3")).dispose();
batch.dispose();
menuPic.dispose();
img.dispose();
font.dispose();
}
}
|
package com.surviveandthrive;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.Input.Keys;
public class SurviveAndThrive extends ApplicationAdapter {
SpriteBatch batch;
Texture img;
Texture car;
Rectangle test = new Rectangle();
@Override
public void create() {
batch = new SpriteBatch();
img = new Texture("badlogic.jpg");
car = new Texture("car.png");
test.height = 80;
test.width = 60;
test.x = 100;
test.y = 60;
}
@Override
public void render() {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(img, 0, 0);
//draws the car at the tests x and y locations
batch.draw(car, test.x, test.y);
batch.end();
//these if statements check to see if the arrow keys are being pressed
if(Gdx.input.isKeyPressed(Keys.LEFT)) test.x -= 15;
if(Gdx.input.isKeyPressed(Keys.RIGHT)) test.x += 15;
if(Gdx.input.isKeyPressed(Keys.DOWN)) test.y -= 15;
if(Gdx.input.isKeyPressed(Keys.UP)) test.y += 15;
}
@Override
public void dispose() {
batch.dispose();
img.dispose();
}
}
|
package hudson.model;
import hudson.model.MultiStageTimeSeries.TimeScale;
import hudson.triggers.SafeTimerTask;
import hudson.triggers.Trigger;
import hudson.util.ChartUtil;
import hudson.util.ColorPalette;
import hudson.util.NoOverlapCategoryAxis;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.category.CategoryDataset;
import org.jfree.ui.RectangleInsets;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import java.awt.*;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
/**
* Utilization statistics for a node or a set of nodes.
*
* <h2>Implementation Note</h2>
* <p>
* Instances of this class is not capable of updating the statistics itself
* — instead, it's done by the single {@link #register()} method.
* This is more efficient (as it allows us a single pass to update all stats),
* but it's not clear to me if the loss of autonomy is worth it.
*
* @author Kohsuke Kawaguchi
* @see Label#loadStatistics
* @see Hudson#overallLoad
*/
public abstract class LoadStatistics {
/**
* Number of busy executors and how it changes over time.
*/
public final MultiStageTimeSeries busyExecutors;
/**
* Number of total executors and how it changes over time.
*/
public final MultiStageTimeSeries totalExecutors;
/**
* Number of {@link Queue.BuildableItem}s that can run on any node in this node set but blocked.
*/
public final MultiStageTimeSeries queueLength;
protected LoadStatistics(int initialTotalExecutors, int initialBusyExecutors) {
this.totalExecutors = new MultiStageTimeSeries(initialTotalExecutors,DECAY);
this.busyExecutors = new MultiStageTimeSeries(initialBusyExecutors,DECAY);
this.queueLength = new MultiStageTimeSeries(0,DECAY);
}
public float getLatestIdleExecutors(TimeScale timeScale) {
return totalExecutors.pick(timeScale).getLatest() - busyExecutors.pick(timeScale).getLatest();
}
/**
* Computes the # of idle executors right now and obtains the snapshot value.
*/
public abstract int computeIdleExecutors();
/**
* Computes the # of total executors right now and obtains the snapshot value.
*/
public abstract int computeTotalExecutors();
/**
* Computes the # of queue length right now and obtains the snapshot value.
*/
public abstract int computeQueueLength();
/**
* Creates a trend chart.
*/
public JFreeChart createChart(CategoryDataset ds) {
final JFreeChart chart = ChartFactory.createLineChart(null, // chart title
null, // unused
null, // range axis label
ds, // data
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips
false // urls
);
chart.setBackgroundPaint(Color.white);
final CategoryPlot plot = chart.getCategoryPlot();
plot.setBackgroundPaint(Color.WHITE);
plot.setOutlinePaint(null);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.black);
final LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
renderer.setBaseStroke(new BasicStroke(3));
configureRenderer(renderer);
final CategoryAxis domainAxis = new NoOverlapCategoryAxis(null);
plot.setDomainAxis(domainAxis);
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
domainAxis.setLowerMargin(0.0);
domainAxis.setUpperMargin(0.0);
domainAxis.setCategoryMargin(0.0);
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
// crop extra space around the graph
plot.setInsets(new RectangleInsets(0, 0, 0, 5.0));
return chart;
}
protected void configureRenderer(LineAndShapeRenderer renderer) {
renderer.setSeriesPaint(0, ColorPalette.BLUE); // total
renderer.setSeriesPaint(1, ColorPalette.RED); // busy
renderer.setSeriesPaint(2, ColorPalette.GREY); // queue
}
/**
* Creates {@link CategoryDataset} which then becomes the basis
* of the load statistics graph.
*/
public CategoryDataset createDataset(TimeScale timeScale) {
return createDataset(timeScale,
new float[][]{
totalExecutors.pick(timeScale).getHistory(),
busyExecutors.pick(timeScale).getHistory(),
queueLength.pick(timeScale).getHistory()
},
new String[]{
Messages.LoadStatistics_Legends_TotalExecutors(),
Messages.LoadStatistics_Legends_BusyExecutors(),
Messages.LoadStatistics_Legends_QueueLength()
});
}
protected final DefaultCategoryDataset createDataset(TimeScale timeScale, float[][] dataPoints, String[] legends) {
assert dataPoints.length==legends.length;
int dataLength = dataPoints[0].length;
for (float[] dataPoint : dataPoints)
assert dataLength ==dataPoint.length;
DefaultCategoryDataset ds = new DefaultCategoryDataset();
DateFormat format = timeScale.createDateFormat();
Date dt = new Date(System.currentTimeMillis()-timeScale.tick*dataLength);
for (int i = dataLength-1; i>=0; i
dt = new Date(dt.getTime()+timeScale.tick);
String l = format.format(dt);
for(int j=0; j<dataPoints.length; j++)
ds.addValue(dataPoints[j][i],legends[j],l);
}
return ds;
}
/**
* Generates the load statistics graph.
*/
public void doGraph(StaplerRequest req, StaplerResponse rsp, @QueryParameter String type) throws IOException {
if(type==null) type=TimeScale.MIN.name();
TimeScale scale = Enum.valueOf(TimeScale.class, type.toUpperCase());
ChartUtil.generateGraph(req, rsp, createChart(createDataset(scale)), 500, 400);
}
/**
* Start updating the load average.
*/
/*package*/ static void register() {
Trigger.timer.scheduleAtFixedRate(
new SafeTimerTask() {
protected void doRun() {
Hudson h = Hudson.getInstance();
List<Queue.BuildableItem> bis = h.getQueue().getBuildableItems();
// update statistics on slaves
for( Label l : h.getLabels() ) {
l.loadStatistics.totalExecutors.update(l.getTotalExecutors());
l.loadStatistics.busyExecutors .update(l.getBusyExecutors());
int q=0;
for (Queue.BuildableItem bi : bis) {
if(bi.task.getAssignedLabel()==l)
q++;
}
l.loadStatistics.queueLength.update(q);
}
// update statistics of the entire system
ComputerSet cs = h.getComputer();
h.overallLoad.totalExecutors.update(cs.getTotalExecutors());
h.overallLoad.busyExecutors .update(cs.getBusyExecutors());
int q=0;
for (Queue.BuildableItem bi : bis) {
if(bi.task.getAssignedLabel()==null)
q++;
}
h.overallLoad.queueLength.update(q);
h.overallLoad.totalQueueLength.update(bis.size());
}
}, CLOCK, CLOCK
);
}
/**
* With 0.90 decay ratio for every 10sec, half reduction is about 1 min.
*/
public static final float DECAY = Float.parseFloat(System.getProperty(LoadStatistics.class.getName()+".decay","0.9"));
/**
* Load statistics clock cycle in milliseconds. Specify a small value for quickly debugging this feature and node provisioning through cloud.
*/
public static int CLOCK = Integer.getInteger(LoadStatistics.class.getName()+".clock",10*1000);
}
|
package hudson.util;
import com.thoughtworks.xstream.alias.CannotResolveClassException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.mapper.Mapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Collection;
/**
* {@link List}-like implementation that has copy-on-write semantics.
*
* <p>
* This class is suitable where highly concurrent access is needed, yet
* the write operation is relatively uncommon.
*
* @author Kohsuke Kawaguchi
*/
public class CopyOnWriteList<E> implements Iterable<E> {
private volatile List<? extends E> core;
public CopyOnWriteList(List<E> core) {
this(core,false);
}
private CopyOnWriteList(List<E> core, boolean noCopy) {
this.core = noCopy ? core : new ArrayList<E>(core);
}
public CopyOnWriteList() {
this.core = Collections.emptyList();
}
public synchronized void add(E e) {
List<E> n = new ArrayList<E>(core);
n.add(e);
core = n;
}
/**
* Removes an item from the list.
*
* @return
* true if the list contained the item. False if it didn't,
* in which case there's no change.
*/
public synchronized boolean remove(E e) {
List<E> n = new ArrayList<E>(core);
boolean r = n.remove(e);
core = n;
return r;
}
/**
* Returns an iterator.
*
* The returned iterator doesn't support the <tt>remove</tt> operation.
*/
public Iterator<E> iterator() {
final Iterator<? extends E> itr = core.iterator();
return new Iterator<E>() {
public boolean hasNext() {
return itr.hasNext();
}
public E next() {
return itr.next();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
/**
* Completely replaces this list by the contents of the given list.
*/
public void replaceBy(CopyOnWriteList<? extends E> that) {
this.core = that.core;
}
/**
* Completely replaces this list by the contents of the given list.
*/
public void replaceBy(Collection<? extends E> that) {
this.core = new ArrayList<E>(that);
}
public E[] toArray(E[] array) {
return core.toArray(array);
}
/**
* {@link Converter} implementation for XStream.
*/
public static final class ConverterImpl extends AbstractCollectionConverter {
public ConverterImpl(Mapper mapper) {
super(mapper);
}
public boolean canConvert(Class type) {
return type==CopyOnWriteList.class;
}
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
for (Object o : (CopyOnWriteList) source)
writeItem(o, context, writer);
}
@SuppressWarnings("unchecked")
public CopyOnWriteList unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
// read the items from xml into a list
List items = new ArrayList();
while (reader.hasMoreChildren()) {
reader.moveDown();
try {
Object item = readItem(reader, context, items);
items.add(item);
} catch (CannotResolveClassException e) {
System.err.println("failed to locate class: "+e);
}
reader.moveUp();
}
return new CopyOnWriteList(items,true);
}
}
}
|
package tk.mybatis.mapper.util;
import tk.mybatis.mapper.MapperException;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.IDynamicTableName;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* OGNL
*
* @author liuzh
*/
public abstract class OGNL {
public static final String SAFE_DELETE_ERROR = "<[ Mapper safeDelete=true]> delete !";
public static final String SAFE_DELETE_EXCEPTION = "<[ Mapper safeDelete=true]> delete !";
/**
* Example entityClass
*
* @param parameter
* @param entityFullName
* @return
*/
public static boolean checkExampleEntityClass(Object parameter, String entityFullName) {
if (parameter != null && parameter instanceof Example && StringUtil.isNotEmpty(entityFullName)) {
Example example = (Example) parameter;
Class<?> entityClass = example.getEntityClass();
if (!entityClass.getCanonicalName().equals(entityFullName)) {
throw new MapperException(" Example :" + entityFullName
+ ", Example entityClass :" + entityClass.getCanonicalName());
}
}
return true;
}
/**
* paremeter fields null
*
* @param parameter
* @param fields
* @return
*/
public static boolean notAllNullParameterCheck(Object parameter, String fields) {
if (parameter != null) {
try {
Set<EntityColumn> columns = EntityHelper.getColumns(parameter.getClass());
Set<String> fieldSet = new HashSet<String>(Arrays.asList(fields.split(",")));
for (EntityColumn column : columns) {
if (fieldSet.contains(column.getProperty())) {
Object value = column.getEntityField().getValue(parameter);
if (value != null) {
return true;
}
}
}
} catch (Exception e) {
throw new MapperException(SAFE_DELETE_ERROR, e);
}
}
throw new MapperException(SAFE_DELETE_EXCEPTION);
}
/**
* paremeter fields null
*
* @param parameter
* @return
*/
public static boolean exampleHasAtLeastOneCriteriaCheck(Object parameter) {
if (parameter != null) {
try {
if (parameter instanceof Example) {
List<Example.Criteria> criteriaList = ((Example) parameter).getOredCriteria();
if (criteriaList != null && criteriaList.size() > 0) {
return true;
}
} else {
Method getter = parameter.getClass().getDeclaredMethod("getOredCriteria");
Object list = getter.invoke(parameter);
if(list != null && list instanceof List && ((List) list).size() > 0){
return true;
}
}
} catch (Exception e) {
throw new MapperException(SAFE_DELETE_ERROR, e);
}
}
throw new MapperException(SAFE_DELETE_EXCEPTION);
}
/**
*
*
* @param parameter
* @return
*/
public static boolean hasSelectColumns(Object parameter) {
if (parameter != null && parameter instanceof Example) {
Example example = (Example) parameter;
if (example.getSelectColumns() != null && example.getSelectColumns().size() > 0) {
return true;
}
}
return false;
}
/**
* Count
*
* @param parameter
* @return
*/
public static boolean hasCountColumn(Object parameter) {
if (parameter != null && parameter instanceof Example) {
Example example = (Example) parameter;
return StringUtil.isNotEmpty(example.getCountColumn());
}
return false;
}
/**
* forUpdate
*
* @param parameter
* @return
*/
public static boolean hasForUpdate(Object parameter) {
if (parameter != null && parameter instanceof Example) {
Example example = (Example) parameter;
return example.isForUpdate();
}
return false;
}
/**
*
*
* @param parameter
* @return
*/
public static boolean hasNoSelectColumns(Object parameter) {
return !hasSelectColumns(parameter);
}
/**
*
*
* @param parameter
* @return truefalse
*/
public static boolean isDynamicParameter(Object parameter) {
if (parameter != null && parameter instanceof IDynamicTableName) {
return true;
}
return false;
}
/**
* b
*
* @param parameter
* @return truefalse
*/
public static boolean isNotDynamicParameter(Object parameter) {
return !isDynamicParameter(parameter);
}
/**
* and or
*
* @param parameter
* @return
*/
public static String andOr(Object parameter) {
if (parameter instanceof Example.Criteria) {
return ((Example.Criteria) parameter).getAndOr();
} else if (parameter instanceof Example.Criterion) {
return ((Example.Criterion) parameter).getAndOr();
} else if (parameter.getClass().getCanonicalName().endsWith("Criteria")) {
return "or";
} else {
return "and";
}
}
}
|
package org.jboss.as.patching.cli;
import static java.lang.System.getProperty;
import static java.lang.System.getSecurityManager;
import static java.lang.System.getenv;
import static java.security.AccessController.doPrivileged;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import org.jboss.as.cli.CommandContext;
import org.jboss.as.cli.CommandFormatException;
import org.jboss.as.cli.CommandLineException;
import org.jboss.as.cli.Util;
import org.jboss.as.cli.handlers.CommandHandlerWithHelp;
import org.jboss.as.cli.handlers.DefaultFilenameTabCompleter;
import org.jboss.as.cli.handlers.FilenameTabCompleter;
import org.jboss.as.cli.handlers.SimpleTabCompleter;
import org.jboss.as.cli.handlers.WindowsFilenameTabCompleter;
import org.jboss.as.cli.impl.ArgumentWithValue;
import org.jboss.as.cli.impl.ArgumentWithoutValue;
import org.jboss.as.cli.impl.DefaultCompleter;
import org.jboss.as.cli.impl.FileSystemPathArgument;
import org.jboss.as.cli.operation.ParsedCommandLine;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.patching.Constants;
import org.jboss.as.patching.PatchMessages;
import org.jboss.as.patching.tool.PatchOperationBuilder;
import org.jboss.as.patching.tool.PatchOperationTarget;
import org.jboss.dmr.ModelNode;
import org.wildfly.security.manager.action.ReadEnvironmentPropertyAction;
import org.wildfly.security.manager.action.ReadPropertyAction;
public class PatchHandler extends CommandHandlerWithHelp {
static final String PATCH = "patch";
static final String APPLY = "apply";
static final String ROLLBACK = "rollback";
static final String HISTORY = "history";
static final String INFO = "info";
private final ArgumentWithValue host;
private final ArgumentWithValue action;
private final ArgumentWithoutValue path;
private final ArgumentWithValue patchId;
private final ArgumentWithoutValue rollbackTo;
private final ArgumentWithValue resetConfiguration;
private final ArgumentWithoutValue overrideModules;
private final ArgumentWithoutValue overrideAll;
private final ArgumentWithValue override;
private final ArgumentWithValue preserve;
private final ArgumentWithoutValue distribution;
private final ArgumentWithoutValue modulePath;
private final ArgumentWithoutValue bundlePath;
private static final String lineSeparator = getSecurityManager() == null ? getProperty("line.separator") : doPrivileged(new ReadPropertyAction("line.separator"));
public PatchHandler(final CommandContext context) {
super(PATCH, false);
action = new ArgumentWithValue(this, new SimpleTabCompleter(new String[]{APPLY, ROLLBACK, INFO, HISTORY}), 0, "--action");
host = new ArgumentWithValue(this, new DefaultCompleter(CandidatesProviders.HOSTS), "--host") {
@Override
public boolean canAppearNext(CommandContext ctx) throws CommandFormatException {
boolean connected = ctx.getControllerHost() != null;
return connected && ctx.isDomainMode() && super.canAppearNext(ctx);
}
};
// apply & rollback arguments
overrideModules = new ArgumentWithoutValue(this, "--override-modules") {
@Override
public boolean canAppearNext(CommandContext ctx) throws CommandFormatException {
if (canOnlyAppearAfterActions(ctx, APPLY, ROLLBACK)) {
return super.canAppearNext(ctx);
}
return false;
}
};
overrideModules.addRequiredPreceding(action);
overrideAll = new ArgumentWithoutValue(this, "--override-all") {
@Override
public boolean canAppearNext(CommandContext ctx) throws CommandFormatException {
if (canOnlyAppearAfterActions(ctx, APPLY, ROLLBACK)) {
return super.canAppearNext(ctx);
}
return false;
}
};
overrideAll.addRequiredPreceding(action);
override = new ArgumentWithValue(this, "--override") {
@Override
public boolean canAppearNext(CommandContext ctx) throws CommandFormatException {
if (canOnlyAppearAfterActions(ctx, APPLY, ROLLBACK)) {
return super.canAppearNext(ctx);
}
return false;
}
};
override.addRequiredPreceding(action);
preserve = new ArgumentWithValue(this, "--preserve") {
@Override
public boolean canAppearNext(CommandContext ctx) throws CommandFormatException {
if (canOnlyAppearAfterActions(ctx, APPLY, ROLLBACK)) {
return super.canAppearNext(ctx);
}
return false;
}
};
preserve.addRequiredPreceding(action);
// apply arguments
final FilenameTabCompleter pathCompleter = Util.isWindows() ? new WindowsFilenameTabCompleter(context) : new DefaultFilenameTabCompleter(context);
path = new FileSystemPathArgument(this, pathCompleter, 1, "--path") {
@Override
public boolean canAppearNext(CommandContext ctx) throws CommandFormatException {
if (canOnlyAppearAfterActions(ctx, APPLY)) {
return super.canAppearNext(ctx);
}
return false;
}
};
path.addRequiredPreceding(action);
// rollback arguments
patchId = new ArgumentWithValue(this, "--patch-id") {
@Override
public boolean canAppearNext(CommandContext ctx) throws CommandFormatException {
if (canOnlyAppearAfterActions(ctx, ROLLBACK)) {
return super.canAppearNext(ctx);
}
return false;
}
};
patchId.addRequiredPreceding(action);
rollbackTo = new ArgumentWithoutValue(this, "--rollback-to") {
@Override
public boolean canAppearNext(CommandContext ctx) throws CommandFormatException {
if (canOnlyAppearAfterActions(ctx, ROLLBACK)) {
return super.canAppearNext(ctx);
}
return false;
}
};
rollbackTo.addRequiredPreceding(action);
resetConfiguration = new ArgumentWithValue(this, SimpleTabCompleter.BOOLEAN, "--reset-configuration") {
@Override
public boolean canAppearNext(CommandContext ctx) throws CommandFormatException {
if (canOnlyAppearAfterActions(ctx, ROLLBACK)) {
return super.canAppearNext(ctx);
}
return false;
}
};
resetConfiguration.addRequiredPreceding(action);
distribution = new FileSystemPathArgument(this, pathCompleter, "--distribution") {
@Override
public boolean canAppearNext(CommandContext ctx) throws CommandFormatException {
// TODO this is hidden from the tab-completion for now (and also not documented),
// although if the argument name is typed in and followed with the '=',
// the tab-completion for its value will work
return false;
}
};
modulePath = new FileSystemPathArgument(this, pathCompleter, "--module-path") {
@Override
public boolean canAppearNext(CommandContext ctx) throws CommandFormatException {
// TODO this is hidden from the tab-completion for now (and also not documented),
// although if the argument name is typed in and followed with the '=',
// the tab-completion for its value will work
return false;
}
};
bundlePath = new FileSystemPathArgument(this, pathCompleter, "--bundle-path") {
@Override
public boolean canAppearNext(CommandContext ctx) throws CommandFormatException {
// TODO this is hidden from the tab-completion for now (and also not documented),
// although if the argument name is typed in and followed with the '=',
// the tab-completion for its value will work
return false;
}
};
}
private boolean canOnlyAppearAfterActions(CommandContext ctx, String... actions) {
final String actionStr = this.action.getValue(ctx.getParsedCommandLine());
if(actionStr == null || actions.length == 0) {
return false;
}
return Arrays.asList(actions).contains(actionStr);
}
@Override
protected void doHandle(CommandContext ctx) throws CommandLineException {
final PatchOperationTarget target = createPatchOperationTarget(ctx);
final PatchOperationBuilder builder = createPatchOperationBuilder(ctx.getParsedCommandLine());
final ModelNode result;
try {
result = builder.execute(target);
} catch (Exception e) {
throw new CommandLineException("Unable to apply patch", e);
}
if (!Util.isSuccess(result)) {
final ModelNode fd = result.get(ModelDescriptionConstants.FAILURE_DESCRIPTION);
if(!fd.isDefined()) {
throw new CommandLineException("Failed to apply patch: " + result.asString());
}
if(fd.has(Constants.CONFLICTS)) {
final StringBuilder buf = new StringBuilder();
buf.append(fd.get(Constants.MESSAGE).asString()).append(": ");
final ModelNode conflicts = fd.get(Constants.CONFLICTS);
String title = "";
if(conflicts.has(Constants.BUNDLES)) {
formatConflictsList(buf, conflicts, "", Constants.BUNDLES);
title = ", ";
}
if(conflicts.has(Constants.MODULES)) {
formatConflictsList(buf, conflicts, title, Constants.MODULES);
title = ", ";
}
if(conflicts.has(Constants.MISC)) {
formatConflictsList(buf, conflicts, title, Constants.MISC);
}
buf.append(lineSeparator).append("Use the --override-all, --override=[] or --preserve=[] arguments in order to resolve the conflict.");
throw new CommandLineException(buf.toString());
} else {
throw new CommandLineException(Util.getFailureDescription(result));
}
}
ctx.printLine(result.toJSONString(false));
}
protected void formatConflictsList(final StringBuilder buf, final ModelNode conflicts, String title, String contentType) {
buf.append(title);
final List<ModelNode> list = conflicts.get(contentType).asList();
int i = 0;
while(i < list.size()) {
final ModelNode item = list.get(i++);
buf.append(item.asString());
if(i < list.size()) {
buf.append(", ");
}
}
}
private PatchOperationBuilder createPatchOperationBuilder(ParsedCommandLine args) throws CommandFormatException {
final String action = this.action.getValue(args, true);
PatchOperationBuilder builder;
if (APPLY.equals(action)) {
final String path = this.path.getValue(args, true);
final File f = new File(path);
if(!f.exists()) {
// i18n is never used for CLI exceptions
throw new CommandFormatException("Path " + f.getAbsolutePath() + " doesn't exist.");
}
if(f.isDirectory()) {
throw new CommandFormatException(f.getAbsolutePath() + " is a directory.");
}
builder = PatchOperationBuilder.Factory.patch(f);
} else if (ROLLBACK.equals(action)) {
String resetConfigValue = resetConfiguration.getValue(args, true);
boolean resetConfig;
if(Util.TRUE.equalsIgnoreCase(resetConfigValue)) {
resetConfig = true;
} else if(Util.FALSE.equalsIgnoreCase(resetConfigValue)) {
resetConfig = false;
} else {
throw new CommandFormatException("Unexpected value for --reset-configuration (only true and false are allowed): " + resetConfigValue);
}
if(patchId.isPresent(args)) {
final String id = patchId.getValue(args, true);
final boolean rollbackTo = this.rollbackTo.isPresent(args);
builder = PatchOperationBuilder.Factory.rollback(id, rollbackTo, resetConfig);
} else {
builder = PatchOperationBuilder.Factory.rollbackLast(resetConfig);
}
} else if (INFO.equals(action)) {
builder = PatchOperationBuilder.Factory.info();
return builder;
} else if (HISTORY.equals(action)) {
builder = PatchOperationBuilder.Factory.history();
return builder;
} else {
throw new CommandFormatException("Unrecognized action '" + action + "'");
}
if (overrideModules.isPresent(args)) {
builder.ignoreModuleChanges();
}
if (overrideAll.isPresent(args)) {
builder.overrideAll();
}
if (override.isPresent(args)) {
final String overrideList = override.getValue(args);
if(overrideList == null || overrideList.isEmpty()) {
throw new CommandFormatException(override.getFullName() + " is missing value.");
}
for (String path : overrideList.split(",+")) {
builder.overrideItem(path);
}
}
if (preserve.isPresent(args)) {
final String preserveList = preserve.getValue(args);
if(preserveList == null || preserveList.isEmpty()) {
throw new CommandFormatException(preserve.getFullName() + " is missing value.");
}
for (String path : preserveList.split(",+")) {
builder.preserveItem(path);
}
}
return builder;
}
private PatchOperationTarget createPatchOperationTarget(CommandContext ctx) throws CommandLineException {
final PatchOperationTarget target;
boolean connected = ctx.getControllerHost() != null;
if (connected) {
if (ctx.isDomainMode()) {
String hostName = host.getValue(ctx.getParsedCommandLine(), true);
target = PatchOperationTarget.createHost(hostName, ctx.getModelControllerClient());
} else {
target = PatchOperationTarget.createStandalone(ctx.getModelControllerClient());
}
} else {
final ParsedCommandLine args = ctx.getParsedCommandLine();
final String jbossHome = getJBossHome(args);
final File root = new File(jbossHome);
final List<File> modules = getFSArgument(modulePath, args, root, "modules");
final List<File> bundles = getFSArgument(bundlePath, args, root, "bundles");
try {
target = PatchOperationTarget.createLocal(root, modules, bundles);
} catch (Exception e) {
throw new CommandLineException("Unable to apply patch to local JBOSS_HOME=" + jbossHome, e);
}
}
return target;
}
private static final String HOME = "JBOSS_HOME";
private static final String HOME_DIR = "jboss.home.dir";
private String getJBossHome(final ParsedCommandLine args) {
final String targetDistro = distribution.getValue(args);
if(targetDistro != null) {
return targetDistro;
}
String resolved = getSecurityManager() == null ? getenv(HOME) : doPrivileged(new ReadEnvironmentPropertyAction(HOME));
if (resolved == null) {
resolved = getSecurityManager() == null ? getProperty(HOME_DIR) : doPrivileged(new ReadPropertyAction(HOME_DIR));
}
if (resolved == null) {
throw PatchMessages.MESSAGES.cliFailedToResolveDistribution();
}
return resolved;
}
private static List<File> getFSArgument(final ArgumentWithoutValue arg, final ParsedCommandLine args, final File root, final String param) {
final String value = arg.getValue(args);
if (value != null) {
final String[] values = value.split(Pattern.quote(File.pathSeparator));
if (values.length == 1) {
return Collections.singletonList(new File(value));
}
final List<File> resolved = new ArrayList<File>(values.length);
for (final String path : values) {
resolved.add(new File(path));
}
return resolved;
}
return Collections.singletonList(new File(root, param));
}
}
|
package com.mindcoders.phial;
import android.app.Application;
import com.mindcoders.phial.internal.keyvalue.BuildInfoWriter;
import com.mindcoders.phial.internal.keyvalue.InfoWriter;
import com.mindcoders.phial.internal.keyvalue.SystemInfoWriter;
import com.mindcoders.phial.internal.share.attachment.AttacherAdaptor;
import com.mindcoders.phial.internal.util.Precondition;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Creates and configures phial overlay pages
*/
public class PhialBuilder {
private final Application application;
private final List<Shareable> shareables = new ArrayList<>();
private final List<ListAttacher> attachers = new ArrayList<>();
private final List<Page> pages = new ArrayList<>();
private boolean attachScreenshots = true;
private boolean attachKeyValues = true;
private InfoWriter systemInfoWriter;
private InfoWriter buildInfoWriter;
private boolean enableKeyValueView = true;
private boolean enableShareView = true;
private String shareDataFilePattern = "'data_M'MM'D'dd_'H'HH_mm_ss";
public PhialBuilder(Application application) {
this.application = application;
this.systemInfoWriter = new SystemInfoWriter(application);
this.buildInfoWriter = new BuildInfoWriter(application);
}
/**
* Adds custom shareables that will be shown under ShareTab.
* See {@link Shareable}
*
* @param shareable shareable that will be added to ShareTab
* @return same instance of builder
*/
public PhialBuilder addShareable(Shareable shareable) {
this.shareables.add(shareable);
return this;
}
/**
* Adds custom attacher that will include extra information to share attachment.
* See {@link Attacher}, {@link ListAttacher}, {@link SimpleFileAttacher} for more infor
*
* @param attacher that will include extra information to Share data
* @return same instance of builder
*/
public PhialBuilder addAttachmentProvider(Attacher attacher) {
this.attachers.add(AttacherAdaptor.adapt(attacher));
return this;
}
/**
* Adds custom attacher that will include extra information to share attachment.
* See {@link Attacher}, {@link ListAttacher}, {@link SimpleFileAttacher} for more infor
*
* @param attacher that will include extra information to Share data
* @return same instance of builder
*/
public PhialBuilder addAttachmentProvider(ListAttacher attacher) {
this.attachers.add(attacher);
return this;
}
/**
* Rather include screen shot in share attachment.
*
* @param attachScreenshot true to include, false to not include.
* default true
* @return same instance of builder
*/
public PhialBuilder attachScreenshot(boolean attachScreenshot) {
this.attachScreenshots = attachScreenshot;
return this;
}
/**
* Rather include system info (e.g. Android version, screen size ...) in key-value tab and share attachment.
*
* @param applySystemInfo true to include, false to not include.
* default true
* @return same instance of builder
*/
public PhialBuilder applySystemInfo(boolean applySystemInfo) {
if (applySystemInfo) {
this.systemInfoWriter = new SystemInfoWriter(application);
} else {
systemInfoWriter = null;
}
return this;
}
/**
* Rather include build info (e.g. app version, package ...) in key-value tab and share attachment.
*
* @param applyBuildInfo true to include, false to not include.
* default true
* @return same instance of builder
*/
public PhialBuilder applyBuildInfo(boolean applyBuildInfo) {
if (applyBuildInfo) {
this.buildInfoWriter = new BuildInfoWriter(application);
} else {
buildInfoWriter = null;
}
return this;
}
/**
* Includes build info (e.g. app version, package ...) in key-value tab and share attachment.
* And extends it with buildTime and commit.
* <p>
* <pre>
* {@code
* def getGitHash = { ->
* def stdout = new ByteArrayOutputStream()
* exec {
* commandLine 'git', 'rev-parse', '--short', 'HEAD'
* standardOutput = stdout
* }
* return stdout.toString().trim()
* }
*
* android {
* defaultConfig { // or added to target flavor or buildType
* buildConfigField "long", "BUILD_TIMESTAMP", "${new Date().time}L"
* buildConfigField "String", "GIT_HASH", "\"${getGitHash()}\""
* }
* }
* }
*
* and call applyBuildInfo(BuildConfig.BUILD_TIMESTAMP, BuildConfig.GIT_HASH)
* </pre>
*
* @param buildTime timestamp when build was build
* @param commit commit hash that was used for build
* @return same instance of builder
*/
public PhialBuilder applyBuildInfo(long buildTime, String commit) {
this.buildInfoWriter = new BuildInfoWriter(application, buildTime, commit);
return this;
}
/**
* Adds custom page to Phial pages.
* by default Phial has only 2 pages: share and key-value
*
* @param page page to add. See {@link Page}
* @return same instance of builder
*/
public PhialBuilder addPage(Page page) {
this.pages.add(page);
return this;
}
/**
* Rather display key value view.
* The page that show system and build info.
* <p>
* See {@link com.mindcoders.phial.keyvalue.Phial} in order to add custom key-values to page
*
* @param enableKeyValueView true to display, false to not display.
* default true
* @return same instance of builder
*/
public PhialBuilder enableKeyValueView(boolean enableKeyValueView) {
this.enableKeyValueView = enableKeyValueView;
return this;
}
/**
* Rather display share view.
* The page that allows share debug data.
* <p>
* The share page can be extended by Shareables. See {@link Shareable}, {@link #addShareable(Shareable)}
*
* @param enableShareView true to display, false to not display.
* default true
* @return same instance of builder
*/
public PhialBuilder enableShareView(boolean enableShareView) {
this.enableShareView = enableShareView;
return this;
}
/**
* Rather include key-values shot in share attachment.
* Key-values are included as json file
*
* @param attachKeyValues true to include, false to not include.
* default true
* @return same instance of builder
*/
public PhialBuilder attachKeyValues(boolean attachKeyValues) {
this.attachKeyValues = attachKeyValues;
return this;
}
/**
* Set's shared zips archive name.
* These pattern will be passed to {@link java.text.SimpleDateFormat} so need contain valid pattern for SimpleDateFormat
*
* @param shareDataFilePattern the pattern describing the file name format
* @return same instance of builder
*/
public PhialBuilder setShareDataFilePattern(String shareDataFilePattern) {
this.shareDataFilePattern = shareDataFilePattern;
return this;
}
/**
* Initializes Phial with provided configs and creates overlay view with pages.
* <p>
* Calling initPhial will destroy previously created PhialOverlay instances.
* In order to destroy Phial call {@link PhialOverlay#destroy()}
*/
public void initPhial() {
PhialOverlay.init(this);
}
public Application getApplication() {
return application;
}
public List<Shareable> getShareables() {
return Collections.unmodifiableList(shareables);
}
public List<ListAttacher> getAttachers() {
return Collections.unmodifiableList(attachers);
}
public List<Page> getPages() {
return Collections.unmodifiableList(pages);
}
public boolean attachScreenshots() {
return attachScreenshots;
}
public List<InfoWriter> getInfoWriters() {
final List<InfoWriter> writers = new ArrayList<>(2);
if (buildInfoWriter != null) {
writers.add(buildInfoWriter);
}
if (systemInfoWriter != null) {
writers.add(systemInfoWriter);
}
return writers;
}
public boolean attachKeyValues() {
return attachKeyValues;
}
public boolean enableKeyValueView() {
return enableKeyValueView;
}
public boolean enableShareView() {
return enableShareView;
}
public String getShareDataFilePattern() {
return shareDataFilePattern;
}
}
|
package org.objectweb.proactive.examples.masterslave.nqueens;
import java.net.MalformedURLException;
import java.util.Vector;
import org.objectweb.proactive.examples.masterslave.AbstractExample;
import org.objectweb.proactive.examples.masterslave.nqueens.query.Query;
import org.objectweb.proactive.examples.masterslave.nqueens.query.QueryExtern;
import org.objectweb.proactive.examples.masterslave.nqueens.query.QueryGenerator;
import org.objectweb.proactive.examples.masterslave.util.Pair;
import org.objectweb.proactive.extra.masterslave.ProActiveMaster;
import org.objectweb.proactive.extra.masterslave.TaskAlreadySubmittedException;
import org.objectweb.proactive.extra.masterslave.TaskException;
/**
* This examples calculates the Nqueen
* @author fviale
*
*/
public class NQueensExample extends AbstractExample {
public static int nqueen_board_size;
public static int nqueen_algorithm_depth;
private ProActiveMaster<QueryExtern, Pair<Long, Long>> master;
public ProActiveMaster getMaster() {
return master;
}
public static void main(String[] args)
throws MalformedURLException, TaskAlreadySubmittedException {
NQueensExample instance = new NQueensExample();
// Getting command line parameters
instance.init(args, 2, " nqueen_board_size nqueen_algorithm_depth");
// Creating the Master
instance.master = new ProActiveMaster<QueryExtern, Pair<Long, Long>>();
// Register shutdown process
instance.registerHook();
instance.master.addResources(instance.descriptor_url, instance.vn_name);
System.out.println("Launching NQUEENS solutions finder for n = " +
nqueen_board_size + " with a depth of " + nqueen_algorithm_depth);
long sumResults = 0;
long sumTime = 0;
long begin = System.currentTimeMillis();
// Generating the queries for the NQueens
Vector<Query> unresolvedqueries = QueryGenerator.generateQueries(nqueen_board_size,
nqueen_algorithm_depth);
// Splitting Queries
Vector<QueryExtern> toSolve = new Vector<QueryExtern>();
while (!unresolvedqueries.isEmpty()) {
Query query = unresolvedqueries.remove(0);
Vector<Query> splitted = QueryGenerator.splitAQuery(query);
if (!splitted.isEmpty()) {
for (Query splitquery : splitted) {
toSolve.add(new QueryExtern(splitquery));
}
} else {
toSolve.add(new QueryExtern(query));
}
}
instance.master.solve(toSolve);
// Print results on the fly
while (!instance.master.isEmpty()) {
try {
Pair<Long, Long> res = instance.master.waitOneResult();
sumResults += res.getFirst();
sumTime += res.getSecond();
System.out.println("Current nb of results : " + sumResults);
} catch (TaskException e) {
// Exception in the algorithm
e.printStackTrace();
}
}
// Calculation finished, printing summary and total number of solutions
long end = System.currentTimeMillis();
int nbslaves = instance.master.slavepoolSize();
System.out.println("Total number of configurations found for n = " +
nqueen_board_size + " and with " + nbslaves + " slaves : " +
sumResults);
System.out.println("Time needed with " + nbslaves + " slaves : " +
((end - begin) / 3600000) +
String.format("h %1$tMm %1$tSs %1$tLms", end - begin));
System.out.println("Total slaves calculation time : " +
(sumTime / 3600000) +
String.format("h %1$tMm %1$tSs %1$tLms", sumTime));
System.exit(0);
}
@Override
protected void init_specialized(String[] args) {
nqueen_board_size = Integer.parseInt(args[2]);
nqueen_algorithm_depth = Integer.parseInt(args[3]);
}
}
|
package co.smartreceipts.android.sync.drive.services;
import android.support.annotation.NonNull;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.events.CompletionEvent;
import com.google.android.gms.drive.events.DriveEventService;
import com.google.common.base.Preconditions;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import co.smartreceipts.android.utils.log.Logger;
public class DriveCompletionEventService extends DriveEventService {
private static final Object sLock = new Object();
private static final Map<DriveId, DriveIdUploadCompleteCallback> sDriveIdDriveIdCallbackMap = new HashMap<>();
private static final Map<DriveId, Boolean> sUnhandledEvents = new HashMap<>();
@Override
public void onCompletion(CompletionEvent event) {
final DriveIdUploadCompleteCallback callback;
synchronized (sLock) {
callback = sDriveIdDriveIdCallbackMap.remove(event.getDriveId());
if (callback == null) {
sUnhandledEvents.put(event.getDriveId(), event.getStatus() == CompletionEvent.STATUS_SUCCESS);
}
}
if (callback != null) {
if (event.getStatus() == CompletionEvent.STATUS_SUCCESS) {
Logger.info(DriveCompletionEventService.class, "Calling back with persisted drive resource id: {}", event.getDriveId().getResourceId());
callback.onSuccess(event.getDriveId());
} else {
Logger.error(DriveCompletionEventService.class, "Calling back drive resource id failure");
callback.onFailure(event.getDriveId());
}
} else {
// Note: doing this outside our lock
Logger.warn(DriveCompletionEventService.class, "Received an event before a callback was registered. Saving for later");
}
event.dismiss();
}
/**
* Google unfortunately didn't make things very flexible here, so we're pretty limited in our design choices.
* Making this package protected to reduce the exposure of this behavior
* @param driveId
* @param callback
*/
static void registerCallback(@NonNull DriveId driveId, @NonNull DriveIdUploadCompleteCallback callback) {
Preconditions.checkNotNull(driveId);
Preconditions.checkNotNull(callback);
Logger.info(DriveCompletionEventService.class, "Registering for completion of id: {}", driveId.getResourceId());
// This Boolean is tri-state. null => not used, true => STATUS_SUCCESS, false => STATUS_FAIL
final Boolean wasIdSuccessfullySaved;
synchronized (sLock) {
wasIdSuccessfullySaved = sUnhandledEvents.remove(driveId);
if (wasIdSuccessfullySaved == null) {
sDriveIdDriveIdCallbackMap.put(driveId, callback);
}
}
if (wasIdSuccessfullySaved != null) {
if (wasIdSuccessfullySaved) {
Logger.info(DriveCompletionEventService.class, "Immediately handling callback for: {}", driveId.getResourceId());
callback.onSuccess(driveId);
} else {
Logger.warn(DriveCompletionEventService.class, "Immediately handling callback failure for: {}", driveId.getResourceId());
callback.onFailure(driveId);
}
}
}
}
|
package com.pearson.statspoller.internal_metric_collectors.linux.ProcessStatus;
import com.pearson.statspoller.internal_metric_collectors.InternalCollectorFramework;
import com.pearson.statspoller.metric_formats.graphite.GraphiteMetric;
import com.pearson.statspoller.utilities.FileIo;
import com.pearson.statspoller.utilities.StackTrace;
import com.pearson.statspoller.utilities.Threads;
import java.io.BufferedReader;
import java.io.StringReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProcessStatusCollector extends InternalCollectorFramework implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(ProcessStatusCollector.class.getName());
private static final HashSet<String> CORE_STATES = getSetOfCoreProcessStates();
public ProcessStatusCollector(boolean isEnabled, long collectionInterval, String metricPrefix, String outputFilePathAndFilename, boolean writeOutputFiles) {
super(isEnabled, collectionInterval, metricPrefix, outputFilePathAndFilename, writeOutputFiles);
}
@Override
public void run() {
while(super.isEnabled()) {
long routineStartTime = System.currentTimeMillis();
// get the update stats in graphite format
List<GraphiteMetric> graphiteMetrics = getProcessStatusMetrics();
// output graphite metrics
super.outputGraphiteMetrics(graphiteMetrics);
long routineTimeElapsed = System.currentTimeMillis() - routineStartTime;
logger.info("Finished Linux-ProcessState metric collection routine. " +
"MetricsCollected=" + graphiteMetrics.size() +
", MetricCollectionTime=" + routineTimeElapsed);
long sleepTimeInMs = getCollectionInterval() - routineTimeElapsed;
if (sleepTimeInMs >= 0) Threads.sleepMilliseconds(sleepTimeInMs);
}
}
private List<GraphiteMetric> getProcessStatusMetrics() {
List<GraphiteMetric> allGraphiteMetrics = new ArrayList<>();
try {
int currentTimestampInSeconds = (int) (System.currentTimeMillis() / 1000);
List<String> listOfDirectoriesInProc = FileIo.getListOfDirectoryNamesInADirectory(super.getLinuxProcFileSystemLocation());
List<String> listOfProcessDirectoriesInProc = new ArrayList<>();
for (String directoryInProc : listOfDirectoriesInProc) {
if ((directoryInProc == null) || directoryInProc.isEmpty()) continue;
boolean isDirectoryNumeric = StringUtils.isNumeric(directoryInProc);
boolean doesStatusExist = FileIo.doesFileExist(super.getLinuxProcFileSystemLocation() + "/" + directoryInProc + "/status" );
if (isDirectoryNumeric && doesStatusExist) listOfProcessDirectoriesInProc.add(directoryInProc);
}
Map<String,String> stateOfEveryPid = new HashMap<>(); // k=pid#, v=status
AtomicInteger countOfThreads = new AtomicInteger(0);
getProcessStatusMetrics(listOfProcessDirectoriesInProc, stateOfEveryPid, countOfThreads);
allGraphiteMetrics.addAll(createMetrics(listOfProcessDirectoriesInProc, stateOfEveryPid, countOfThreads, currentTimestampInSeconds));
}
catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
}
return allGraphiteMetrics;
}
private void getProcessStatusMetrics(List<String> listOfProcessDirectoriesInProc, Map<String,String> stateOfEveryPid, AtomicInteger countOfThreads) {
if ((listOfProcessDirectoriesInProc == null) || (stateOfEveryPid == null) || (countOfThreads == null)) {
return;
}
BufferedReader reader = null;
for (String pid : listOfProcessDirectoriesInProc) {
try {
String rawPidStatus = FileIo.readFileToString(super.getLinuxProcFileSystemLocation() + "/" + pid + "/status");
if ((rawPidStatus == null) || rawPidStatus.isEmpty()) continue;
reader = new BufferedReader(new StringReader(rawPidStatus));
String currentLine = reader.readLine();
while (currentLine != null) {
String currentLineTrimmed = currentLine.trim();
// get the process state
if (currentLineTrimmed.startsWith("State:")) {
int leftBoundary = currentLineTrimmed.indexOf(':') + 1;
int rightBoundary = currentLineTrimmed.indexOf('(');
if ((leftBoundary > 0) && (rightBoundary > 0)) stateOfEveryPid.put(pid, currentLineTrimmed.substring(leftBoundary, rightBoundary).trim());
}
// get number of threads
if (currentLineTrimmed.startsWith("Threads:")) {
int leftBoundary = currentLineTrimmed.indexOf(':') + 1;
if (leftBoundary > 0) {
String threadsString = currentLineTrimmed.substring(leftBoundary, currentLineTrimmed.length()).trim();
int threadsInt = Integer.parseInt(threadsString);
countOfThreads.addAndGet(threadsInt);
}
}
currentLine = reader.readLine();
}
}
catch (Exception e) {
logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
}
finally {
try {
if (reader != null) {
reader.close();
}
}
catch (Exception e) {
logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
}
}
}
}
private List<GraphiteMetric> createMetrics(List<String> listOfProcessDirectoriesInProc, Map<String,String> stateOfEveryPid, AtomicInteger countOfThreads, int currentTimestampInSeconds) {
if ((listOfProcessDirectoriesInProc == null) || (listOfProcessDirectoriesInProc.size() <= 0) || (stateOfEveryPid == null) || (countOfThreads == null)) {
return new ArrayList<>();
}
List<GraphiteMetric> graphiteMetrics = new ArrayList<>();
try {
// create process state metrics
HashMap<String,AtomicInteger> countOfStates = new HashMap<>();
for (String pid : stateOfEveryPid.keySet()) {
String state = stateOfEveryPid.get(pid);
if (countOfStates.containsKey(state)) countOfStates.get(state).incrementAndGet();
else countOfStates.put(state.trim(), new AtomicInteger(1));
}
for (String coreState : CORE_STATES) {
if (!countOfStates.containsKey(coreState)) {
countOfStates.put(coreState.trim(), new AtomicInteger(0));
}
}
for (String state : countOfStates.keySet()) {
AtomicInteger stateCount = countOfStates.get(state);
graphiteMetrics.add(new GraphiteMetric(("States.CountOfProcessesInState-" + state), new BigDecimal(stateCount.get()), currentTimestampInSeconds));
}
// create process other process status metrics
graphiteMetrics.add(new GraphiteMetric(("TotalProcessCount"), new BigDecimal(listOfProcessDirectoriesInProc.size()), currentTimestampInSeconds));
graphiteMetrics.add(new GraphiteMetric(("TotalThreadCount"), new BigDecimal(countOfThreads.get()), currentTimestampInSeconds));
}
catch (Exception e) {
logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
}
return graphiteMetrics;
}
private static HashSet<String> getSetOfCoreProcessStates() {
HashSet<String> coreProcessStates = new HashSet<>();
coreProcessStates.add("R");
coreProcessStates.add("S");
coreProcessStates.add("D");
coreProcessStates.add("Z");
coreProcessStates.add("T");
return coreProcessStates;
}
}
|
package net.sf.taverna.t2.activities.stringconstant.actions;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import javax.swing.JOptionPane;
import net.sf.taverna.t2.activities.stringconstant.StringConstantActivity;
import net.sf.taverna.t2.activities.stringconstant.StringConstantConfigurationBean;
import net.sf.taverna.t2.activities.stringconstant.servicedescriptions.StringConstantActivityIcon;
import net.sf.taverna.t2.workbench.ui.actions.activity.ActivityConfigurationAction;
public class StringConstantActivityConfigurationAction extends
ActivityConfigurationAction<StringConstantActivity, StringConstantConfigurationBean> {
public static final String CONFIGURE_STRINGCONSTANT = "Edit value";
private static final long serialVersionUID = 2518716617809186972L;
private final Frame owner;
public StringConstantActivityConfigurationAction(StringConstantActivity activity,Frame owner) {
super(activity);
putValue(Action.NAME, CONFIGURE_STRINGCONSTANT);
this.owner = owner;
}
public void actionPerformed(ActionEvent e) {
StringConstantConfigurationBean bean = new StringConstantConfigurationBean();
String value = getActivity().getConfiguration().getValue();
String newValue =
(String) JOptionPane.showInputDialog(owner,
"Enter value",
getRelativeName(),
JOptionPane.QUESTION_MESSAGE,
StringConstantActivityIcon.getStringConstantIcon(),
null,
value);
if (newValue!=null) {
bean.setValue(newValue);
configureActivity(bean);
}
}
}
|
package org.mtransit.parser.ca_victoria_regional_transit_system_bus;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.mtransit.commons.StrategicMappingCommons;
import org.mtransit.parser.CleanUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.Pair;
import org.mtransit.parser.SplitUtils;
import org.mtransit.parser.SplitUtils.RouteTripSpec;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.gtfs.data.GTripStop;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MTrip;
import org.mtransit.parser.mt.data.MTripStop;
public class VictoriaRegionalTransitSystemBusAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-victoria-regional-transit-system-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new VictoriaRegionalTransitSystemBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
System.out.printf("\nGenerating Victoria Regional TS bus data...");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this, true);
super.start(args);
System.out.printf("\nGenerating Victoria Regional TS bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludingAll() {
return this.serviceIds != null && this.serviceIds.isEmpty();
}
private static final String INCLUDE_ONLY_SERVICE_ID_STARTS_WITH = null;
private static final String INCLUDE_ONLY_SERVICE_ID_STARTS_WITH2 = null;
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (INCLUDE_ONLY_SERVICE_ID_STARTS_WITH != null && !gCalendar.getServiceId().startsWith(INCLUDE_ONLY_SERVICE_ID_STARTS_WITH)
&& INCLUDE_ONLY_SERVICE_ID_STARTS_WITH2 != null && !gCalendar.getServiceId().startsWith(INCLUDE_ONLY_SERVICE_ID_STARTS_WITH2)) {
return true;
}
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (INCLUDE_ONLY_SERVICE_ID_STARTS_WITH != null && !gCalendarDates.getServiceId().startsWith(INCLUDE_ONLY_SERVICE_ID_STARTS_WITH)
&& INCLUDE_ONLY_SERVICE_ID_STARTS_WITH2 != null && !gCalendarDates.getServiceId().startsWith(INCLUDE_ONLY_SERVICE_ID_STARTS_WITH2)) {
return true;
}
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
private static final String INCLUDE_AGENCY_ID = "1"; // Victoria Regional Transit System only
@Override
public boolean excludeRoute(GRoute gRoute) {
if (!INCLUDE_AGENCY_ID.equals(gRoute.getAgencyId())) {
return true;
}
return super.excludeRoute(gRoute);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (INCLUDE_ONLY_SERVICE_ID_STARTS_WITH != null && !gTrip.getServiceId().startsWith(INCLUDE_ONLY_SERVICE_ID_STARTS_WITH)
&& INCLUDE_ONLY_SERVICE_ID_STARTS_WITH2 != null && !gTrip.getServiceId().startsWith(INCLUDE_ONLY_SERVICE_ID_STARTS_WITH2)) {
return true;
}
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
@Override
public long getRouteId(GRoute gRoute) {
return Long.parseLong(gRoute.getRouteShortName()); // use route short name as route ID
}
@Override
public String getRouteLongName(GRoute gRoute) {
String routeLongName = gRoute.getRouteLongName();
routeLongName = CleanUtils.cleanNumbers(routeLongName);
routeLongName = CleanUtils.cleanStreetTypes(routeLongName);
return CleanUtils.cleanLabel(routeLongName);
}
private static final String AGENCY_COLOR_GREEN = "34B233";// GREEN (from PDF Corporate Graphic Standards)
private static final String AGENCY_COLOR_BLUE = "002C77"; // BLUE (from PDF Corporate Graphic Standards)
private static final String AGENCY_COLOR = AGENCY_COLOR_GREEN;
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
@Override
public String getRouteColor(GRoute gRoute) {
if (StringUtils.isEmpty(gRoute.getRouteColor())) {
return AGENCY_COLOR_BLUE;
}
return super.getRouteColor(gRoute);
}
private static final String AND = " & ";
private static final String EXCH = "Exch";
private static final String DOWNTOWN = "Downtown";
private static final String OAK_BAY = "Oak Bay";
private static final String SOUTH_OAK_BAY = "South " + OAK_BAY;
private static final String ROYAL_OAK = "Royal Oak";
private static final String ROYAL_OAK_EXCH = ROYAL_OAK + " " + EXCH;
private static final String CAMOSUN = "Camosun";
private static final String JAMES_BAY = "James Bay";
private static final String DOCKYARD = "Dockyard";
private static final String ADMIRALS_WALK = "Admirals Walk";
private static final String HILLSIDE = "Hillside";
private static final String HILLSIDE_MALL = HILLSIDE + " Mall";
private static final String U_VIC = "UVic";
private static final String BRENTWOOD = "Brentwood";
private static final String SAANICHTON = "Saanichton";
private static final String SAANICHTON_EXCH = SAANICHTON + " " + EXCH;
private static final String SWARTZ_BAY = "Swartz Bay";
private static final String SWARTZ_BAY_FERRY = SWARTZ_BAY + " Ferry";
private static final String SOOKE = "Sooke";
private static final String LANGFORD = "Langford";
private static final String LANGFORD_EXCH = LANGFORD + " " + EXCH;
private static final String COLWOOD_EXCH = "Colwood " + EXCH;
private static final String HAPPY_VLY = "Happy Vly";
private static final String TILLICUM_MALL = "Tillicum Mall";
private static final String SPECTRUM_SCHOOL = "Spectrum School";
private static final String GORGE = "Gorge";
private static final String INTERURBAN = "Interurban";
private static final String MILE_HOUSE = "Mile House";
private static final String VERDIER = "Verdier";
private static final String SIDNEY = "Sidney";
private static final String BEAR_MOUTAIN = "Bear Mtn";
private static final String MC_DONALD_PARK = "McDonald Pk";
private static final String MC_TAVISH = "McTavish";
private static final String MC_TAVISH_EXCH = MC_TAVISH + " " + EXCH;
private static final String VIC_GENERAL = "Vic General";
private static final String UPTOWN = "Uptown";
private static final String RICHMOND = "Richmond";
private static final String MC_KENZIE = "McKenzie";
private static final String DOUGLAS = "Douglas";
private static final String WILLOWS = "Willows";
private static final String WESTHILLS_EXCH = "Westhills Exch";
private static final String KEATING = "Keating";
private static final String SHORELINE_SCHOOL = "Shoreline Sch";
private static final String R_JUBILEE = "R. Jubilee";
private static final String VIC_WEST = "Vic West";
private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2;
static {
HashMap<Long, RouteTripSpec> map2 = new HashMap<Long, RouteTripSpec>();
ALL_ROUTE_TRIPS2 = map2;
}
@Override
public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) {
if (ALL_ROUTE_TRIPS2.containsKey(routeId)) {
return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop, this);
}
return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop);
}
@Override
public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips();
}
return super.splitTrip(mRoute, gTrip, gtfs);
}
@Override
public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId()), this);
}
return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS);
}
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return; // split
}
if (mRoute.getId() == 1L) {
if (gTrip.getDirectionId() == 0) { // DOWNTOWN - WEST
if (Arrays.asList(
"Downtown"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // SOUTH OAK BAY - EAST
if (Arrays.asList(
"South Oak Bay via Richardson"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mRoute.getId() == 2L) {
if (gTrip.getDirectionId() == 0) { // JAMES BAY - WEST
if (Arrays.asList(
"James Bay - Fisherman's Wharf"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // OAK BAY - EAST
if (Arrays.asList(
"James Bay - Fisherman's Wharf",
"Downtown",
"South Oak Bay - Oak Bay Village",
"Willows - Oak Bay Village"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mRoute.getId() == 3L) {
if (gTrip.getDirectionId() == 0) { // JAMES BAY - CLOCKWISE
if (Arrays.asList(
"Downtown Only",
"James Bay To 10 R. Jubilee",
"James Bay - Linden to 10 R. Jubilee",
"James Bay - Quimper To 10 R. Jubilee"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.CLOCKWISE);
return;
}
} else if (gTrip.getDirectionId() == 1) { // ROYAL JUBILEE - COUNTERCLOCKWISE
if (Arrays.asList(
"Royal Jubilee - Cook St Village",
"Royal Jubilee - Cook St Vlg/Quimper"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.COUNTERCLOCKWISE);
return;
}
}
} else if (mRoute.getId() == 4L) {
if (gTrip.getDirectionId() == 0) { // DOWNTOWN - WEST
if (Arrays.asList(
"Downtown",
"To Gorge & Douglas"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UVIC - EAST
if (Arrays.asList(
"UVic Via Hillside"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mRoute.getId() == 6L) {
if (gTrip.getDirectionId() == 0) { // ROYAL OAK - NORTH
if (Arrays.asList(
"Royal Oak Exch Via Royal Oak Mall",
"6A Royal Oak Exch Via Emily Carr",
"6B Royal Oak Exch Via Chatterton"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // DOWNTOWN - SOUTH
if (Arrays.asList(
"Downtown",
"6B Downtown Via Chatterton",
"6A Downtown Via Emily Carr"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (mRoute.getId() == 7L) {
if (gTrip.getDirectionId() == 0) { // DOWNTOWN - CLOCKWISE
if (Arrays.asList(
"Downtown Only",
"7N Downtown Only",
"Downtown - To 21 Interurban",
"7N Downtown - To 21 Interurban",
"Downtown To 21 Interurban"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.CLOCKWISE);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UVIC - COUNTERCLOCKWISE
if (Arrays.asList(
"UVic Via Fairfield",
"7N UVic - Cook St Village"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.COUNTERCLOCKWISE);
return;
}
}
} else if (mTrip.getRouteId() == 8L) {
if (gTrip.getDirectionId() == 0) { // INTERURBAN - WEST
if (Arrays.asList(
"Tillicum Mall Via Finalyson",
"Interurban Via Finlayson"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // OAK BAY - EAST
if (Arrays.asList(
"To Richmond & Oak Bay Ave Only",
"To Douglas Only - Mayfair Mall",
"Oak Bay Via Finalyson"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 9L) {
if (gTrip.getDirectionId() == 0) { // ROYAL OAK - WEST
if (Arrays.asList(
"Royal Oak Exch - Hillside/Gorge"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UVIC - EAST
if (Arrays.asList(
"UVic - Gorge/Hillside"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 10L) {
if (gTrip.getDirectionId() == 0) { // ROYAL JUBILEE - CLOCKWISE
if (Arrays.asList(
"Royal Jubilee Via Vic West"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.CLOCKWISE);
return;
}
} else if (gTrip.getDirectionId() == 1) { // JAMES BAY - COUNTERCLOCKWISE
if (Arrays.asList(
"James Bay - To 3 R. Jubilee",
"To Vic West Only"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.COUNTERCLOCKWISE);
return;
}
}
} else if (mTrip.getRouteId() == 11L) {
if (gTrip.getDirectionId() == 0) { // TILLICUM MALL - WEST
if (Arrays.asList(
"Tillicum Mall Via Gorge"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UVIC - EAST
if (Arrays.asList(
"Downtown",
"UVic Via Uplands"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 12L) {
if (gTrip.getDirectionId() == 0) { // UNIVERSITY HGTS - WEST
if (Arrays.asList(
"University Hgts Via Kenmore"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UVIC - EAST
if (Arrays.asList(
"UVic Via Kenmore"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 13L) {
if (gTrip.getDirectionId() == 0) { // UVIC - WEST
if (Arrays.asList(
"UVic"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // TEN MILE POINT - EAST
if (Arrays.asList(
"Ten Mile Point"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 14L) {
if (gTrip.getDirectionId() == 0) { // VIC GENERAL - WEST
if (Arrays.asList(
"Downtown",
"Vic General Via Craigflower"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UVIC - EAST
if (Arrays.asList(
"Downtown",
"UVic",
"UVic Via Richmond"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 15L) {
if (gTrip.getDirectionId() == 0) { // ESQUIMALT - WEST
if (Arrays.asList(
"Esquimalt",
"Esquimalt - Fort/Yates Exp"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UVIC - EAST
if (Arrays.asList(
"Downtown",
"UVic - Foul Bay Exp"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 16L) {
if (gTrip.getDirectionId() == 0) { // UPTOWN - WEST
if (Arrays.asList(
"Uptown - McKenzie Exp"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UVIC - EAST
if (Arrays.asList(
"UVic - McKenzie Exp"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 17L) {
if (gTrip.getDirectionId() == 0) { // Downtown - WEST
if (Arrays.asList(
"Downtown Via Quadra"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UVIC - EAST
if (Arrays.asList(
"UVic Via Cedar Hill Sch"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 21L) {
if (gTrip.getDirectionId() == 0) { // INTERURBAN - CLOCKWISE
if (Arrays.asList(
"Interurban - VI Tech Park",
"Interurban - Camosun Only",
"Interurban - Viaduct Loop",
"21N Camosun Via Burnside"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.CLOCKWISE);
return;
}
} else if (gTrip.getDirectionId() == 1) { // DOWNTOWN - COUNTERCLOCKWISE
if (Arrays.asList(
"Downtown To 7 UVic"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.COUNTERCLOCKWISE);
return;
}
}
} else if (mTrip.getRouteId() == 22L) {
if (gTrip.getDirectionId() == 0) { // VIC GENERAL - NORTH
if (Arrays.asList(
"Downtown",
"Vic General - Watkiss Way Via Burnside",
"22A Vic General - Watkiss Wy Via S. Vale",
"22A Vic General Via S. Vale",
"To Spectrum School",
"Vic General Via Burnside"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // NILLSIDE MALL - SOUTH
if (Arrays.asList(
"Downtown",
"22A Hillside Mall Via Straw Vale",
"Hillside Mall Via Fernwood"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (mTrip.getRouteId() == 24L) {
if (gTrip.getDirectionId() == 0) { // Admirals Walk - WEST
if (Arrays.asList(
"Downtown",
"Admirals Walk Via Parklands/Colville",
"Admirals Walk Via Colville"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Cedar Hill - EAST
if (Arrays.asList(
"Cedar Hill",
"Cedar Hill Via Parklands"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 25L) {
if (gTrip.getDirectionId() == 0) { // Admirals Walk - WEST
if (Arrays.asList(
"Shoreline Sch Via Munro",
"Admirals Walk Via Munro"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // Maplewood - EAST
if (Arrays.asList(
"Maplewood"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 26L) {
if (gTrip.getDirectionId() == 0) { // DOCKYARD - WEST
if (Arrays.asList(
"To Uptown Only",
"Dockyard Via McKenzie"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UVIC - EAST
if (Arrays.asList(
"To Uptown Only",
"UVic Via McKenzie"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 27L) {
if (gTrip.getDirectionId() == 0) { // GORDON HEAD - NORTH
if (Arrays.asList(
"Gordon Head Via Shelbourne"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // DOWNTOWN - SOUTH
if (Arrays.asList(
"27X Express To Downtown",
"To Hillside Only",
"Downtown"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (mTrip.getRouteId() == 28L) {
if (gTrip.getDirectionId() == 0) { // MAJESTIC - NORTH
if (Arrays.asList(
"28X Express To Majestic",
"Majestic Via Shelbourne"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // DOWNTOWN - SOUTH
if (Arrays.asList(
"To McKenzie Only",
"To Hillside Only",
"Downtown"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (mTrip.getRouteId() == 30L) {
if (Arrays.asList(
"Royal Oak Exch Via Carey",
"Royal Oak Exch To 75 Saanichton"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
if (Arrays.asList(
"Downtown"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
} else if (mTrip.getRouteId() == 31L) {
if (gTrip.getDirectionId() == 0) { // ROYAL OAK - NORTH
if (Arrays.asList(
"Royal Oak Exch To 75 Saanichton",
"Royal Oak Exch Via Glanford"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // DOWNTOWN - SOUTH
if (Arrays.asList(
"To Gorge Only",
"To Uptown Only",
"Downtown"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (mTrip.getRouteId() == 32L) {
if (gTrip.getDirectionId() == 0) { // Cordova Bay - NORTH
if (Arrays.asList(
"Cordova Bay"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // ROYAL OAK - SOUTH
if (Arrays.asList(
"Downtown",
"Royal Oak Exch"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (mTrip.getRouteId() == 35L) {
// TODO split? NORTH/SOUTH
if (gTrip.getDirectionId() == 0) { // Ridge - CLOCKWISE
if (Arrays.asList(
"Ridge"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.CLOCKWISE);
return;
}
}
} else if (mTrip.getRouteId() == 39L) {
if (gTrip.getDirectionId() == 0) { // WESTHILLS - WEST
if (Arrays.asList(
"Royal Oak Exch",
"Interurban",
"Westhills Exch"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UVIC - EAST
if (Arrays.asList(
"UVic Via Royal Oak"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 43L) {
if (gTrip.getDirectionId() == 0) { // ROYAL ROADS - CLOCKWISE
if (Arrays.asList(
"Belmont Park - Royal Roads"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.CLOCKWISE);
return;
}
}
} else if (mTrip.getRouteId() == 46L) {
if (gTrip.getDirectionId() == 0) { // WESTHILLS - WEST
if (Arrays.asList(
"Westhills Exch"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // DOCKYARD - EAST
if (Arrays.asList(
"Dockyard"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 47L) {
if (gTrip.getDirectionId() == 0) { // GOLDSTREAM MEADOWS - WEST
if (Arrays.asList(
"Goldstream Mdws Via Thetis Hgts"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // DOWNTOWN - EAST
if (Arrays.asList(
"Downtown"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 48L) {
if (gTrip.getDirectionId() == 0) { // HAPPY VALLEY - WEST
if (Arrays.asList(
"Happy Valley via Colwood",
"HAPPY VALLEY VIA COLWOOD"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // DOWNTOWN - EAST
if (Arrays.asList(
"Downtown"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 50L) {
if (gTrip.getDirectionId() == 0) { // LANGFORD - WEST
if (Arrays.asList(
"Langford To 61 Sooke",
"Langford"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // DOWNTOWN - EAST
if (Arrays.asList(
"Downtown"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 51L) {
if (gTrip.getDirectionId() == 0) { // LANGFORD - WEST
if (Arrays.asList(
"Langford - McKenzie Exp"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UVIC - EAST
if (Arrays.asList(
"UVic - McKenzie Exp"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 52L) {
if (gTrip.getDirectionId() == 0) { // BEAR MOUNTAIN - WEST
if (Arrays.asList(
"Langford Exch Via Royal Bay",
"Langford Exch Via Lagoon",
"Langford Exch",
"Bear Mountain - Lagoon/Royal Bay",
"Bear Mountain Via Lagoon",
"Bear Mountain"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // COLWOOD EXCHANGE - EAST
if (Arrays.asList(
"Langford Exch",
"Colwood Exch Via Royal Bay/Lagoon",
"Colwood Exch Via Royal Bay",
"Colwood Exch Via Lagoon",
"Colwood Exch"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 53L) {
if (gTrip.getDirectionId() == 0) { // COLWOOD EXCHANGE - CLOCKWISE
if (Arrays.asList(
"Colwood Exch Via Atkins"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.CLOCKWISE);
return;
}
} else if (gTrip.getDirectionId() == 1) { // LANGFORD EXCHANGE - COUNTERCLOCKWISE
if (Arrays.asList(
"Langford Exch Via Atkins"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.COUNTERCLOCKWISE);
return;
}
}
} else if (mTrip.getRouteId() == 54L) {
if (gTrip.getDirectionId() == 0) { // LANGFORD EXCHANGE - CLOCKWISE
if (Arrays.asList(
"Metchosin"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.CLOCKWISE);
return;
}
}
} else if (mTrip.getRouteId() == 55L) {
if (gTrip.getDirectionId() == 1) { // LANGFORD EXCHANGE - COUNTERCLOCKWISE
if (Arrays.asList(
"Happy Valley To Colwood Exch",
"Happy Valley"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.COUNTERCLOCKWISE);
return;
}
}
} else if (mTrip.getRouteId() == 56L) {
if (gTrip.getDirectionId() == 0) { // THETIS HEIGHTS - NORTH
if (Arrays.asList(
"Thetis Heights Via Florence Lake"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // LANGFORD EXCHANGE - SOUTH
if (Arrays.asList(
"Langford Exch"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (mTrip.getRouteId() == 57L) {
if (gTrip.getDirectionId() == 0) { // THETIS HEIGHTS - NORTH
if (Arrays.asList(
"Theits Heights Via Millstream"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // LANGFORD EXCHANGE - SOUTH
if (Arrays.asList(
"Langford Exch"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (mTrip.getRouteId() == 58L) {
if (gTrip.getDirectionId() == 1) { // GOLDSTREAM MEADOWS - OUTBOUND
if (Arrays.asList(
"Goldstream Mdws"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.OUTBOUND);
return;
}
}
} else if (mTrip.getRouteId() == 59L) {
if (gTrip.getDirectionId() == 1) { // LANGFORD EXCHANGE - COUNTERCLOCKWISE
if (Arrays.asList(
"Triangle Mtn Via Royal Bay",
"Triangle Mtn"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.COUNTERCLOCKWISE);
return;
}
}
} else if (mTrip.getRouteId() == 60L) {
if (gTrip.getDirectionId() == 0) { // LANGFORD EXCHANGE - CLOCKWISE
if (Arrays.asList(
"Wishart Via Royal Bay",
"Wishart"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.CLOCKWISE);
return;
}
}
} else if (mTrip.getRouteId() == 61L) {
if (gTrip.getDirectionId() == 0) { // SOOKE - WEST
if (Arrays.asList(
"Sooke"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // DOWNTOWN - EAST
if (Arrays.asList(
"Langford - Jacklin/Station",
"Langford Exch To 50 Downtown",
"Downtown"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 63L) {
// TODO split?
if (gTrip.getDirectionId() == 0) { // OTTER POINT - WEST
if (Arrays.asList(
"Otter Point"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
}
} else if (mTrip.getRouteId() == 64L) {
// TODO split
if (gTrip.getDirectionId() == 0) { // SOOKE - CLOCKWISE
if (Arrays.asList(
"East Sooke To 17 Mile House",
"East Sooke To Langford",
"East Sooke To Sooke"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.CLOCKWISE);
return;
}
}
if (isGoodEnoughAccepted()) {
if (gTrip.getDirectionId() == 1) { // SOOKE - ????
if (Arrays.asList(
"East Sooke"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.COUNTERCLOCKWISE);
return;
}
}
}
} else if (mTrip.getRouteId() == 65L) {
if (gTrip.getDirectionId() == 0) { // SOOKE - WEST
if (Arrays.asList(
"Sooke Via Westhills"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.WEST);
return;
}
} else if (gTrip.getDirectionId() == 1) { // DOWNTOWN - EAST
if (Arrays.asList(
"Downtown Via Westhills"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.EAST);
return;
}
}
} else if (mTrip.getRouteId() == 70L) {
if (gTrip.getDirectionId() == 0) { // SWARTZ BAY FERRY - NORTH
if (Arrays.asList(
"Swartz Bay Ferry Via Hwy
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // DOWNTOWN - SOUTH
if (Arrays.asList(
"To Gorge Only Via Hwy
"Downtown Via Hwy
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (mTrip.getRouteId() == 71L) {
if (gTrip.getDirectionId() == 0) { // SWARTZ BAY FERRY - NORTH
if (Arrays.asList(
"Swartz Bay Ferry Via West Sidney"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // DOWNTOWN - SOUTH
if (Arrays.asList(
"Downtown"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (mTrip.getRouteId() == 72L) {
if (gTrip.getDirectionId() == 0) { // SWARTZ BAY FERRY - NORTH
if (Arrays.asList(
"McDonald Park Via Saanichton",
"Swartz Bay Ferry Via Saanichton"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // DOWNTOWN - SOUTH
if (Arrays.asList(
"McTavish Exch",
"Downtown"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (mTrip.getRouteId() == 75L) {
if (gTrip.getDirectionId() == 0) { // SAANICHTON - NORTH
if (Arrays.asList(
"To Keating Only",
"Saanichton Exch Via Verdier",
"Saanichton Exch"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // DOWNTOWN - SOUTH
if (Arrays.asList(
"Royal Oak Exch To 30 Downtown",
"Royal Oak Exch To 31 Downtown",
"Downtown"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (mTrip.getRouteId() == 76L) {
if (isGoodEnoughAccepted()) { // TODO check
if (gTrip.getDirectionId() == 0) { // SWARTZ BAY FERRY - NORTH
if (Arrays.asList(
"Swartz Bay Ferry Non-Stop"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // UVIC - SOUTH
if (Arrays.asList(
"UVic - Via Express"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
}
} else if (mTrip.getRouteId() == 81L) {
if (gTrip.getDirectionId() == 0) { // SWARTZ BAY FERRY - NORTH
if (Arrays.asList(
"To Sidney Only",
"Swartz Bay Ferry"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // BRENTWOOD - SOUTH
if (Arrays.asList(
"Saanichton Exch",
"Brentwood To Verdier Only",
"Brentwood"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (mTrip.getRouteId() == 82L) {
if (gTrip.getDirectionId() == 0) { // SIDNEY - NORTH
if (Arrays.asList(
"Sidney Via Stautw"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // SAANICHTON - SOUTH
if (Arrays.asList(
"To Brentwood Via Stautw",
"Saanichton Exch Via Stautw"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (mTrip.getRouteId() == 83L) {
if (gTrip.getDirectionId() == 0) { // SIDNEY - NORTH
if (Arrays.asList(
"Sidney Via West Saanich"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // ROYAL OAK - SOUTH
if (Arrays.asList(
"Royal Oak Exch Via West Saanich"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (mTrip.getRouteId() == 85L) {
// TODO split
if (gTrip.getDirectionId() == 0) { // NORTH SAANICH - CLOCKWISE
if (Arrays.asList(
"North Saanich"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.CLOCKWISE);
return;
}
} else if (gTrip.getDirectionId() == 1) { // NORTH SAANICH - CLOCKWISE
if (Arrays.asList(
"North Saanich"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.CLOCKWISE);
return;
}
}
} else if (mTrip.getRouteId() == 87L) {
if (gTrip.getDirectionId() == 0) { // SIDNEY - NORTH
if (Arrays.asList(
"Sidney"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // SAANICHTON - SOUTH
if (Arrays.asList(
"Dean Park Via Airport To Saanichton"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
} else if (mTrip.getRouteId() == 88L) {
if (gTrip.getDirectionId() == 0) { // SIDNEY - NORTH
if (Arrays.asList(
"Sidney"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.NORTH);
return;
}
} else if (gTrip.getDirectionId() == 1) { // AIRPORT - SOUTH
if (Arrays.asList(
"Airport"
).contains(gTrip.getTripHeadsign())) {
mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), StrategicMappingCommons.SOUTH);
return;
}
}
}
System.out.printf("\n%s: Unexpected trips headsign for %s!\n", mTrip.getRouteId(), gTrip);
System.exit(-1);
}
@Override
public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) {
List<String> headsignsValues = Arrays.asList(mTrip.getHeadsignValue(), mTripToMerge.getHeadsignValue());
if (mTrip.getRouteId() == 2L) {
if (Arrays.asList(
JAMES_BAY,
DOWNTOWN,
WILLOWS,
SOUTH_OAK_BAY
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(SOUTH_OAK_BAY, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 3L) {
if (Arrays.asList(
DOWNTOWN,
R_JUBILEE,
JAMES_BAY
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(JAMES_BAY, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 4L) {
if (Arrays.asList(
GORGE + AND + DOUGLAS,
DOWNTOWN
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 6L) {
if (Arrays.asList(
"A " + DOWNTOWN,
"B " + DOWNTOWN,
DOWNTOWN
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList(
"A " + ROYAL_OAK_EXCH,
"B " + ROYAL_OAK_EXCH,
ROYAL_OAK_EXCH
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(ROYAL_OAK_EXCH, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 7L) {
if (Arrays.asList(
"N " + U_VIC,
U_VIC
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(U_VIC, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList(
INTERURBAN,
"N " + DOWNTOWN,
DOWNTOWN
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 8L) {
if (Arrays.asList(
DOUGLAS,
RICHMOND + AND + OAK_BAY + " Ave",
OAK_BAY
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(OAK_BAY, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList(
TILLICUM_MALL,
INTERURBAN
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(INTERURBAN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 10L) {
if (Arrays.asList(
VIC_WEST,
JAMES_BAY
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(JAMES_BAY, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 11L) {
if (Arrays.asList(
DOWNTOWN,
U_VIC
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(U_VIC, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 14L) {
if (Arrays.asList(
DOWNTOWN,
U_VIC
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(U_VIC, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList(
DOWNTOWN,
VIC_GENERAL
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(VIC_GENERAL, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 15L) {
if (Arrays.asList(
DOWNTOWN,
U_VIC
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(U_VIC, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 21L) {
if (Arrays.asList(
"N " + CAMOSUN,
INTERURBAN
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(INTERURBAN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 22L) {
if (Arrays.asList(
DOWNTOWN,
"A " + VIC_GENERAL,
SPECTRUM_SCHOOL,
VIC_GENERAL
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(VIC_GENERAL, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList(
DOWNTOWN,
"A " + HILLSIDE_MALL,
HILLSIDE_MALL
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(HILLSIDE_MALL, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 24L) {
if (Arrays.asList(
DOWNTOWN,
ADMIRALS_WALK
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(ADMIRALS_WALK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 25L) {
if (Arrays.asList(
SHORELINE_SCHOOL,
ADMIRALS_WALK
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(ADMIRALS_WALK, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 26L) {
if (Arrays.asList(
UPTOWN,
U_VIC
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(U_VIC, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList(
UPTOWN,
DOCKYARD
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOCKYARD, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 27L) {
if (Arrays.asList(
HILLSIDE,
DOWNTOWN
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 28L) {
if (Arrays.asList(
MC_KENZIE,
HILLSIDE,
DOWNTOWN
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 30L) {
if (Arrays.asList(
SAANICHTON,
ROYAL_OAK_EXCH
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(ROYAL_OAK_EXCH, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 31L) {
if (Arrays.asList(
SAANICHTON,
ROYAL_OAK_EXCH
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(ROYAL_OAK_EXCH, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList(
GORGE,
UPTOWN,
DOWNTOWN
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 32L) {
if (Arrays.asList(
DOWNTOWN,
ROYAL_OAK_EXCH
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(ROYAL_OAK_EXCH, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 39L) {
if (Arrays.asList(
ROYAL_OAK_EXCH,
INTERURBAN,
WESTHILLS_EXCH
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(WESTHILLS_EXCH, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 50L) {
if (Arrays.asList(
LANGFORD,
SOOKE
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(LANGFORD, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 52L) {
if (Arrays.asList(
LANGFORD_EXCH,
COLWOOD_EXCH
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(COLWOOD_EXCH, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList(
LANGFORD_EXCH,
BEAR_MOUTAIN
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(BEAR_MOUTAIN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 55L) {
if (Arrays.asList(
COLWOOD_EXCH,
HAPPY_VLY
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(HAPPY_VLY, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 61L) {
if (Arrays.asList(
LANGFORD,
DOWNTOWN
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 64L) {
if (Arrays.asList(
MILE_HOUSE,
LANGFORD,
SOOKE
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(SOOKE, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 70L) {
if (Arrays.asList(
GORGE,
DOWNTOWN
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 72L) {
if (Arrays.asList(
MC_DONALD_PARK,
SWARTZ_BAY_FERRY
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(SWARTZ_BAY_FERRY, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList(
MC_TAVISH_EXCH,
DOWNTOWN
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 75L) {
if (Arrays.asList(
KEATING,
SAANICHTON_EXCH
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(SAANICHTON_EXCH, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList(
ROYAL_OAK_EXCH,
DOWNTOWN
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(DOWNTOWN, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 81L) {
if (Arrays.asList(
SAANICHTON_EXCH,
VERDIER,
BRENTWOOD
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(BRENTWOOD, mTrip.getHeadsignId());
return true;
} else if (Arrays.asList(
SIDNEY,
SWARTZ_BAY_FERRY
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(SWARTZ_BAY_FERRY, mTrip.getHeadsignId());
return true;
}
} else if (mTrip.getRouteId() == 82L) {
if (Arrays.asList(
SAANICHTON_EXCH,
BRENTWOOD
).containsAll(headsignsValues)) {
mTrip.setHeadsignString(BRENTWOOD, mTrip.getHeadsignId());
return true;
}
}
System.out.printf("\nUnexpected trips to merges %s & %s!\n", mTrip, mTripToMerge);
System.exit(-1);
return false;
}
private static final Pattern EXCHANGE = Pattern.compile("((^|\\W){1}(exchange)(\\W|$){1})", Pattern.CASE_INSENSITIVE);
private static final String EXCHANGE_REPLACEMENT = "$2" + EXCH + "$4";
private static final Pattern HEIGHTS = Pattern.compile("((^|\\W){1}(Hghts)(\\W|$){1})", Pattern.CASE_INSENSITIVE);
private static final String HEIGHTS_REPLACEMENT = "$2Hts$4";
private static final Pattern STARTS_WITH_NUMBER = Pattern.compile("(^[\\d]+)", Pattern.CASE_INSENSITIVE);
private static final Pattern ENDS_WITH_EXPRESS = Pattern.compile("( express.*$)", Pattern.CASE_INSENSITIVE);
private static final Pattern ENDS_WITH_VIA = Pattern.compile("( via .*$)", Pattern.CASE_INSENSITIVE);
private static final Pattern STARTS_WITH_TO = Pattern.compile("(^.* to )", Pattern.CASE_INSENSITIVE);
private static final Pattern STARTS_WITH_TO_ = Pattern.compile("(^to )", Pattern.CASE_INSENSITIVE);
private static final Pattern ENDS_WITH_DASH = Pattern.compile("( \\- .*$)", Pattern.CASE_INSENSITIVE);
private static final Pattern ENDS_WITH_NON_STOP = Pattern.compile("( non\\-stop$)", Pattern.CASE_INSENSITIVE);
private static final Pattern ENDS_WITH_ONLY = Pattern.compile("( only$)", Pattern.CASE_INSENSITIVE);
@Override
public String cleanTripHeadsign(String tripHeadsign) {
if (Utils.isUppercaseOnly(tripHeadsign, true, true)) {
tripHeadsign = tripHeadsign.toLowerCase(Locale.ENGLISH);
}
tripHeadsign = EXCHANGE.matcher(tripHeadsign).replaceAll(EXCHANGE_REPLACEMENT);
tripHeadsign = HEIGHTS.matcher(tripHeadsign).replaceAll(HEIGHTS_REPLACEMENT);
tripHeadsign = ENDS_WITH_DASH.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = ENDS_WITH_VIA.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = STARTS_WITH_TO.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = ENDS_WITH_EXPRESS.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = STARTS_WITH_NUMBER.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = STARTS_WITH_TO_.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = ENDS_WITH_NON_STOP.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = ENDS_WITH_ONLY.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = CleanUtils.cleanSlashes(tripHeadsign);
tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign);
tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign);
return CleanUtils.cleanLabel(tripHeadsign);
}
private static final Pattern STARTS_WITH_BOUND = Pattern.compile("(^(east|west|north|south)bound)", Pattern.CASE_INSENSITIVE);
private static final Pattern UVIC = Pattern.compile("((^|\\W){1}(uvic)(\\W|$){1})", Pattern.CASE_INSENSITIVE);
private static final String UVIC_REPLACEMENT = "$2" + U_VIC + "$4";
private static final Pattern STARTS_WITH_IMPL = Pattern.compile("(^(\\(\\-IMPL\\-\\)))", Pattern.CASE_INSENSITIVE);
@Override
public String cleanStopName(String gStopName) {
gStopName = STARTS_WITH_IMPL.matcher(gStopName).replaceAll(StringUtils.EMPTY);
gStopName = STARTS_WITH_BOUND.matcher(gStopName).replaceAll(StringUtils.EMPTY);
gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT);
gStopName = CleanUtils.CLEAN_AND.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT);
gStopName = EXCHANGE.matcher(gStopName).replaceAll(EXCHANGE_REPLACEMENT);
gStopName = UVIC.matcher(gStopName).replaceAll(UVIC_REPLACEMENT);
gStopName = CleanUtils.cleanStreetTypes(gStopName);
gStopName = CleanUtils.cleanNumbers(gStopName);
return CleanUtils.cleanLabel(gStopName);
}
@Override
public int getStopId(GStop gStop) {
return Integer.parseInt(gStop.getStopCode()); // use stop code as stop ID
}
}
|
package com.grayben.riskExtractor.htmlScorer.partScorers.elementScorers;
import com.grayben.riskExtractor.htmlScorer.partScorers.ScorerTest;
import com.grayben.riskExtractor.htmlScorer.partScorers.tagScorers.TagEmphasisScorer;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static com.grayben.riskExtractor.htmlScorer.partScorers.TestHelper.*;
import static junit.framework.Assert.assertEquals;
import static junit.framework.TestCase.fail;
@RunWith(MockitoJUnitRunner.class)
public class SegmentationElementScorerTest
extends ScorerTest<Element> {
SegmentationElementScorer elementScorerSUT;
public Element elementToBeScoredMock;
@Before
public void setUp() throws Exception {
TagEmphasisScorer tagScorer
= new TagEmphasisScorer(TagEmphasisScorer.defaultMap());
elementScorerSUT = new SegmentationElementScorer(tagScorer);
super.setScorerSUT(elementScorerSUT);
super.setArgumentToBeScoredMock(elementToBeScoredMock);
super.setUp();
}
@After
public void tearDown() throws Exception {
elementScorerSUT = null;
super.tearDown();
}
@Override
@Test
public void
test_ScoreReturnsInteger_WhenArgumentIsNotEmpty() throws Exception {
Tag tagStub = stubTag("a-tag-name");
Attributes attributeStubs = dummyAttributes();
elementToBeScoredMock = stubElement(tagStub, attributeStubs);
Integer returned = elementScorerSUT.score(elementToBeScoredMock);
assertEquals(Integer.class, returned.getClass());
}
@Override
@Test
public void
test_ScoreGivesExpectedResult_WhenSimpleInput() throws Exception {
fail("Test not implemented");
}
@Test
public void
test_ScoreThrowsIllegalArgumentException_WhenEmptyInput() throws Exception {
fail("Test not implemented: decide whether appropriate");
}
}
|
package com.intellij.ide.actions;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.impl.LaterInvocator;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.openapi.ui.popup.PopupStep;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.util.ui.EmptyIcon;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
public class ShowFilePathAction extends AnAction {
private static final Logger LOG = Logger.getInstance("#com.intellij.ide.actions.ShowFilePathAction");
@Override
public void update(final AnActionEvent e) {
if (!isSupported()) {
e.getPresentation().setVisible(false);
return;
}
e.getPresentation().setEnabled(getFile(e) != null);
}
public static boolean isSupported() {
return isJava6() || SystemInfo.isMac;
}
private static boolean isJava6() {
return System.getProperty("java.version").startsWith("1.6");
}
public void actionPerformed(final AnActionEvent e) {
show(getFile(e), new ShowAction() {
public void show(final ListPopup popup) {
final DataContext context = DataManager.getInstance().getDataContext();
popup.showInBestPositionFor(context);
}
});
}
public static void show(final VirtualFile file, final MouseEvent e) {
show(file, new ShowAction() {
public void show(final ListPopup popup) {
if (!e.getComponent().isShowing()) return;
popup.show(new RelativePoint(e));
}
});
}
public static void show(final VirtualFile file, final ShowAction show) {
if (!isSupported()) return;
final ArrayList<VirtualFile> files = new ArrayList<VirtualFile>();
final ArrayList<String> fileUrls = new ArrayList<String>();
VirtualFile eachParent = file;
while (eachParent != null) {
final int index = files.size() == 0 ? 0 : files.size();
files.add(index, eachParent);
fileUrls.add(index, getPresentableUrl(eachParent));
if (eachParent.getParent() == null && eachParent.getFileSystem() instanceof JarFileSystem) {
eachParent = JarFileSystem.getInstance().getVirtualFileForJar(eachParent);
if (eachParent == null) break;
}
eachParent = eachParent.getParent();
}
final ArrayList<Icon> icons = new ArrayList<Icon>();
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
public void run() {
for (String each : fileUrls) {
final File ioFile = new File(each);
Icon eachIcon;
if (ioFile.exists()) {
eachIcon = FileSystemView.getFileSystemView().getSystemIcon(ioFile);
} else {
eachIcon = new EmptyIcon(16, 16);
}
icons.add(eachIcon);
}
LaterInvocator.invokeLater(new Runnable() {
public void run() {
show.show(createPopup(files, icons));
}
});
}
});
}
private static String getPresentableUrl(final VirtualFile eachParent) {
String url = eachParent.getPresentableUrl();
if (eachParent.getParent() == null && SystemInfo.isWindows) {
url += "\\";
}
return url;
}
interface ShowAction {
void show(ListPopup popup);
}
private static ListPopup createPopup(final ArrayList<VirtualFile> files, final ArrayList<Icon> icons) {
final BaseListPopupStep<VirtualFile> step = new BaseListPopupStep<VirtualFile>("File Path", files, icons) {
@NotNull
@Override
public String getTextFor(final VirtualFile value) {
return value.getPresentableName();
}
@Override
public PopupStep onChosen(final VirtualFile selectedValue, final boolean finalChoice) {
final Ref<File> open = new Ref<File>();
final Ref<File> toSelect = new Ref<File>();
final File selectedIoFile = new File(getPresentableUrl(selectedValue));
if (files.indexOf(selectedValue) == 0 && files.size() > 1) {
open.set(new File(getPresentableUrl(files.get(1))));
toSelect.set(selectedIoFile);
} else {
open.set(selectedIoFile);
}
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
public void run() {
open(open.get(), toSelect.get());
}
});
return FINAL_CHOICE;
}
};
final ListPopup popup = JBPopupFactory.getInstance().createListPopup(step);
return popup;
}
private static void open(final File ioFile, File toSelect) {
if (SystemInfo.isMac) {
String cmd = "open";
String path = ioFile.getAbsolutePath();
try {
File parent = ioFile.getParentFile();
if (parent != null) {
Runtime.getRuntime().exec(cmd + " " + path, new String[0], parent);
} else {
Runtime.getRuntime().exec(cmd + " " + path);
}
}
catch (IOException e) {
LOG.warn(e);
}
} else if (isJava6()) {
try {
final Object desktopObject = Class.forName("java.awt.Desktop").getMethod("getDesktop").invoke(null);
desktopObject.getClass().getMethod("open", File.class).invoke(desktopObject, ioFile);
}
catch (Exception e) {
LOG.debug(e);
}
} else {
throw new UnsupportedOperationException();
}
}
private VirtualFile getFile(final AnActionEvent e) {
return PlatformDataKeys.VIRTUAL_FILE.getData(e.getDataContext());
}
}
|
package com.rhomobile.rhodes;
import com.rhomobile.rhodes.osfunctionality.AndroidFunctionalityManager;
import com.rhomobile.rhodes.util.PerformOnUiThread;
import com.rhomobile.rhodes.util.Utils;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
public class BaseActivity extends Activity implements ServiceConnection {
private static final String TAG = BaseActivity.class.getSimpleName();
private static final boolean DEBUG = false;
private static boolean setFullScreenFlag = false;
public static final String INTENT_SOURCE = BaseActivity.class.getName();
public boolean mEnableScreenOrientationOverride = false;
public static class ScreenProperties {
private int mScreenWidth;
private int mScreenHeight;
private int mScreenOrientation;
private float mScreenPpiX;
private float mScreenPpiY;
ScreenProperties(Context context) {
reread(context);
}
public void reread(Context context) {
Logger.T(TAG, "Updating screen properties");
WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display d = wm.getDefaultDisplay();
mScreenWidth = d.getWidth();
mScreenHeight = d.getHeight();
DisplayMetrics metrics = new DisplayMetrics();
d.getMetrics(metrics);
mScreenPpiX = metrics.xdpi;
mScreenPpiY = metrics.ydpi;
mScreenOrientation = AndroidFunctionalityManager.getAndroidFunctionality().getScreenOrientation(context);
Logger.D(TAG, "New screen properties - width: " + mScreenWidth + ", height: " + mScreenHeight + ", orientation: " + mScreenOrientation);
}
public int getWidth() { return mScreenWidth; }
public int getHeight() { return mScreenHeight; }
public int getOrientation() { return mScreenOrientation; }
public float getPpiX() { return mScreenPpiX; }
public float getPpiY() { return mScreenPpiY; }
}
private static ScreenProperties sScreenProp = null;
public static ScreenProperties getScreenProperties() { return sScreenProp; }
private static boolean sFullScreen = RhoConf.isExist("full_screen") ? RhoConf.getBool("full_screen") : false;
protected RhodesService mRhodesService;
private boolean mBoundToService;
private static int sActivitiesActive;
private static BaseActivity sTopActivity = null;
private static boolean sScreenAutoRotate = true;
public static void onActivityStarted(Activity activity) {
sTopActivity = null;
activityStarted();
}
public static void onActivityStopped(Activity activity) {
activityStopped();
}
public static void onActivityStarted(BaseActivity activity) {
sTopActivity = activity;
activityStarted();
}
public static void onActivityStopped(BaseActivity activity) {
if(sTopActivity == activity) {
sTopActivity = null;
}
activityStopped();
}
private static void activityStarted() {
Logger.D(TAG, "activityStarted (1): sActivitiesActive=" + sActivitiesActive);
if (sActivitiesActive == 0) {
Logger.D(TAG, "first activity started");
RhodesService r = RhodesService.getInstance();
if (r != null)
r.handleAppActivation();
}
++sActivitiesActive;
Logger.D(TAG, "activityStarted (2): sActivitiesActive=" + sActivitiesActive);
}
public static void activityStopped() {
Logger.D(TAG, "activityStopped (1): sActivitiesActive=" + sActivitiesActive);
--sActivitiesActive;
if (sActivitiesActive == 0) {
Logger.D(TAG, "last activity stopped");
RhodesService r = RhodesService.getInstance();
if (r != null)
r.handleAppDeactivation();
}
Logger.D(TAG, "activityStopped (2): sActivitiesActive=" + sActivitiesActive);
}
public static int getActivitiesCount() {
return sActivitiesActive;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Logger.T(TAG, "onCreate");
Intent intent = new Intent(this, RhodesService.class);
intent.putExtra(RhodesService.INTENT_SOURCE, INTENT_SOURCE);
ComponentName serviceName = startService(intent);
if (serviceName == null)
throw new RuntimeException("Can not start Rhodes service");
bindService(intent, this, Context.BIND_AUTO_CREATE);
mBoundToService = true;
if (RhoConf.isExist("disable_screen_rotation")) {
sScreenAutoRotate = !RhoConf.getBool("disable_screen_rotation");
}
if (mEnableScreenOrientationOverride) {
sScreenAutoRotate = true;
}
if (sScreenProp == null) {
sScreenProp = new ScreenProperties(this);
} else {
if (!sScreenAutoRotate) {
Logger.D(TAG, "Screen rotation is disabled. Force orientation: " + getScreenProperties().getOrientation());
setRequestedOrientation(getScreenProperties().getOrientation());
}
}
}
@Override
protected void onDestroy() {
if (mBoundToService) {
unbindService(this);
mBoundToService = false;
}
super.onDestroy();
}
@Override
protected void onStart() {
super.onStart();
onActivityStarted(this);
}
@Override
protected void onResume() {
super.onResume();
if((RhoConf.isExist("full_screen") ? RhoConf.getBool("full_screen") : false ) && setFullScreenFlag ==false){
setFullScreen(true);
}else if(sFullScreen){
setFullScreen(true);
}else{
setFullScreen(false);
}
//setFullScreen(sFullScreen);
if (sScreenAutoRotate) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
}
@Override
protected void onStop() {
onActivityStopped(this);
super.onStop();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
//Utils.platformLog("$$$$$", "BaseActivity.onConfigurationChanged()");
Logger.T(TAG, "onConfigurationChanged");
super.onConfigurationChanged(newConfig);
if(!sScreenAutoRotate)
{
//Utils.platformLog("$$$$$", "BaseActivity.onConfigurationChanged()
if (!mEnableScreenOrientationOverride) {
//Utils.platformLog("$$$$$", "BaseActivity.onConfigurationChanged()
Logger.D(TAG, "Screen rotation is disabled. Force old orientation: " + getScreenProperties().getOrientation());
setRequestedOrientation(getScreenProperties().getOrientation());
}
}
else
{
//Utils.platformLog("$$$$$", "BaseActivity.onConfigurationChanged()
ScreenProperties props = getScreenProperties();
props.reread(this);
int rotation = 0;
switch(props.getOrientation()) {
case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
rotation = 90;
break;
case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
rotation = 180;
break;
case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
rotation = 270;
break;
case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
default:
rotation = 0;
break;
}
RhodesService.onScreenOrientationChanged(props.getWidth(), props.getHeight(), rotation);
}
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mRhodesService = ((RhodesService.LocalBinder)service).getService();
if (DEBUG)
Log.d(TAG, "Connected to service: " + mRhodesService);
}
@Override
public void onServiceDisconnected(ComponentName name) {
if (DEBUG)
Log.d(TAG, "Disconnected from service: " + mRhodesService);
mRhodesService = null;
}
public static void setFullScreenMode(final boolean mode) {
sFullScreen = mode;
setFullScreenFlag = true;
PerformOnUiThread.exec(new Runnable() {
@Override public void run() {
if (sTopActivity != null) {
sTopActivity.setFullScreen(mode);
}
}
});
}
public static boolean getFullScreenMode() {
return sFullScreen;
}
public static void setScreenAutoRotateMode(boolean mode) {
//Utils.platformLog("$$$$$", "BaseActivity.setScreenAutoRotateMode("+String.valueOf(mode)+")");
sScreenAutoRotate = mode;
if (sScreenAutoRotate && (sTopActivity!=null)) {
sTopActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
}
public static boolean getScreenAutoRotateMode() {
//Utils.platformLog("$$$$$", "BaseActivity.getScreenAutoRotateMode("+String.valueOf(sScreenAutoRotate)+")");
return sScreenAutoRotate;
}
public void setFullScreen(boolean enable) {
sFullScreen = enable;
Window window = getWindow();
if (enable) {
window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
else {
window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
window.setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
}
}
|
package com.mattunderscore.tcproxy.selector;
import java.nio.channels.ClosedChannelException;
import com.mattunderscore.tcproxy.io.IOSelectionKey;
import com.mattunderscore.tcproxy.io.IOSelector;
import com.mattunderscore.tcproxy.io.IOServerSocketChannel;
/**
* {@link Registration} of a server runnable for an {@link IOServerSocketChannel}.
* @author Matt Champion on 26/10/2015
*/
final class IOServerSocketChannelRegistrationRequest implements RegistrationRequest, Registration {
private final IOServerSocketChannel channel;
private final SelectorRunnable<IOServerSocketChannel> runnable;
IOServerSocketChannelRegistrationRequest(IOServerSocketChannel channel, SelectorRunnable<IOServerSocketChannel> runnable) {
this.channel = channel;
this.runnable = runnable;
}
@Override
public void register(IOSelector selector) throws ClosedChannelException {
channel.register(selector, this);
}
@Override
public void run(IOSelectionKey selectionKey) {
runnable.run(channel, selectionKey);
}
}
|
package com.intellij.idea;
import com.intellij.diagnostic.DefaultIdeaErrorLogger;
import com.intellij.diagnostic.LoadingState;
import com.intellij.diagnostic.VMOptions;
import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector;
import com.intellij.ide.plugins.PluginUtil;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Attachment;
import com.intellij.openapi.diagnostic.IdeaLoggingEvent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.PluginId;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class MutedErrorLogger extends MutedLogger {
private static final int FREQUENCY = Integer.getInteger("ide.muted.error.logger.frequency", 10);
@NotNull
@Contract("_ -> new")
public static Logger of(@NotNull Logger delegate) {
return new MutedErrorLogger(delegate);
}
public static boolean isEnabled() {
return !Boolean.getBoolean("ide.muted.error.logger.disabled");
}
private MutedErrorLogger(@NotNull Logger delegate) {
super(delegate);
}
@Override
protected void logAdded(int hash, @NotNull Throwable t) {
log("Hash for the following exception is '" + hash + "': " + t);
}
@Override
protected void logOccurrences(int hash, @NotNull Throwable t, int occurrences) {
reportToFus(t);
if (occurrences % FREQUENCY == 0) {
logRemoved(hash, occurrences);
}
}
private static void reportToFus(@NotNull Throwable t) {
Application application = ApplicationManager.getApplication();
if (application != null && !application.isUnitTestMode() && !application.isDisposed()) {
PluginId pluginId = PluginUtil.getInstance().findPluginId(t);
VMOptions.MemoryKind kind = DefaultIdeaErrorLogger.getOOMErrorKind(t);
LifecycleUsageTriggerCollector.onError(pluginId, t, kind);
}
}
@Override
protected void logRemoved(int hash, int occurrences) {
if (occurrences > 1) {
log("Exception with the following hash '" + hash + "' was reported " + occurrences + " times");
}
}
private void log(@NotNull String message) {
myDelegate.error(message, (Throwable)null);
}
@Override
public void error(Object message) {
if (message instanceof IdeaLoggingEvent) {
Throwable t = ((IdeaLoggingEvent)message).getThrowable();
if (!shouldBeReported(t)) {
return;
}
}
myDelegate.error(message);
}
@Override
public void error(String message, @Nullable Throwable t, Attachment @NotNull ... attachments) {
if (shouldBeReported(t)) {
myDelegate.error(message, t, attachments);
}
}
@Override
public void error(String message, @Nullable Throwable t, String @NotNull ... details) {
if (shouldBeReported(t)) {
myDelegate.error(message, t, details);
}
}
@Override
public void error(String message, @Nullable Throwable t) {
if (shouldBeReported(t)) {
myDelegate.error(message, t);
}
}
@Override
public void error(@NotNull Throwable t) {
if (shouldBeReported(t)) {
myDelegate.error(t);
}
}
private boolean shouldBeReported(@Nullable Throwable t) {
return !LoadingState.COMPONENTS_LOADED.isOccurred() || !isAlreadyReported(t);
}
}
|
package org.strangeforest.tcb.stats.model.records.categories;
import java.util.function.*;
import org.strangeforest.tcb.stats.model.records.*;
import org.strangeforest.tcb.stats.model.records.details.*;
import static java.lang.String.*;
import static java.util.Arrays.*;
import static org.strangeforest.tcb.stats.model.records.RecordDomain.*;
public class BestPlayerThatNeverCategory extends RecordCategory {
private static final String POINTS_WIDTH = "120";
private static final String OLYMPICS_DOB_THRESHOLD = "01-01-1950";
private static final String CARPET_DOB_THRESHOLD = "01-01-1985";
private static final RecordColumn GOAT_POINTS_COLUMN = new RecordColumn("value", null, "valueUrl", POINTS_WIDTH, "right", "GOAT Points");
private static final BiFunction<Integer, IntegerRecordDetail, String> PLAYER_GOAT_POINTS_URL_FORMATTER =
(playerId, recordDetail) -> format("/playerProfile?playerId=%1$d&tab=goatPoints", playerId);
public BestPlayerThatNeverCategory() {
super("Best Player That Never...");
register(bestPlayerThatNeverWon(GRAND_SLAM, "grand_slams"));
register(bestPlayerThatNeverWon(TOUR_FINALS, "tour_finals"));
register(bestPlayerThatNeverWon(ALL_FINALS, "tour_finals + coalesce(alt_finals, 0)", N_A, "Any Tour Finals Title (Official or Alternative)", null));
register(bestPlayerThatNeverWon(MASTERS, "masters"));
register(bestPlayerThatNeverWon(OLYMPICS, "olympics", " AND dob >= DATE '" + OLYMPICS_DOB_THRESHOLD + "'", null, "Born after " + OLYMPICS_DOB_THRESHOLD));
register(bestPlayerThatNeverWonMedal(OLYMPICS, " AND dob >= DATE '" + OLYMPICS_DOB_THRESHOLD + "'", "Born after " + OLYMPICS_DOB_THRESHOLD));
register(bestPlayerThatNeverWon(BIG_TOURNAMENTS, "big_titles"));
register(bestPlayerThatNeverWon(HARD_TOURNAMENTS, "hard_titles"));
register(bestPlayerThatNeverWon(CLAY_TOURNAMENTS, "clay_titles"));
register(bestPlayerThatNeverWon(GRASS_TOURNAMENTS, "grass_titles"));
register(bestPlayerThatNeverWon(CARPET_TOURNAMENTS, "carpet_titles", " AND dob < DATE '" + CARPET_DOB_THRESHOLD + "'", null, "Born before " + CARPET_DOB_THRESHOLD));
register(bestPlayerThatNeverWon(OUTDOOR_TOURNAMENTS, "outdoor_titles"));
register(bestPlayerThatNeverWon(INDOOR_TOURNAMENTS, "indoor_titles"));
register(bestPlayerThatNeverWon(ALL_WO_TEAM, "titles"));
register(bestPlayerThatNeverReachedTopN(NO_1, NO_1_NAME, ATP, "best_rank", 1));
register(bestPlayerThatNeverReachedTopN(TOP_2, TOP_2_NAME, ATP, "best_rank", 2));
register(bestPlayerThatNeverReachedTopN(TOP_3, TOP_3_NAME, ATP, "best_rank", 3));
register(bestPlayerThatNeverReachedTopN(TOP_5, TOP_5_NAME, ATP, "best_rank", 5));
register(bestPlayerThatNeverReachedTopN(TOP_10, TOP_10_NAME, ATP, "best_rank", 10));
register(bestPlayerThatNeverReachedTopN(NO_1, NO_1_NAME, ELO, "best_elo_rank", 1));
register(bestPlayerThatNeverReachedTopN(TOP_2, TOP_2_NAME, ELO, "best_elo_rank", 2));
register(bestPlayerThatNeverReachedTopN(TOP_3, TOP_3_NAME, ELO, "best_elo_rank", 3));
register(bestPlayerThatNeverReachedTopN(TOP_5, TOP_5_NAME, ELO, "best_elo_rank", 5));
register(bestPlayerThatNeverReachedTopN(TOP_10, TOP_10_NAME, ELO, "best_elo_rank", 10));
}
private static Record bestPlayerThatNeverWon(RecordDomain domain, String titleColumn) {
return bestPlayerThatNeverWon(domain, titleColumn, N_A, null, null);
}
private static Record bestPlayerThatNeverWon(RecordDomain domain, String titleColumn, String condition, String domainTitleOverride, String notes) {
String domainTitle = domainTitleOverride != null ? prefix(domainTitleOverride, " ") : prefix(domain.name, " ") + " Title" + prefix(domain.nameSuffix, " ");
return new Record<>(
"BestPlayerThatNeverWon" + domain.id + "Title", "Best Player That Never Won" + domainTitle,
/* language=SQL */
"SELECT player_id, goat_points AS value FROM player\n" +
"LEFT JOIN player_titles USING (player_id) INNER JOIN player_goat_points USING (player_id)\n" +
"WHERE goat_points > 0 AND coalesce(" + titleColumn + ", 0) = 0" + condition,
"r.value", "r.value DESC", "r.value DESC",
IntegerRecordDetail.class, PLAYER_GOAT_POINTS_URL_FORMATTER,
asList(GOAT_POINTS_COLUMN), notes
);
}
private static Record bestPlayerThatNeverWonMedal(RecordDomain domain, String condition, String notes) {
String domainTitle = prefix(domain.name, " ") + " Medal" + prefix(domain.nameSuffix, " ");
return new Record<>(
"BestPlayerThatNeverWon" + domain.id + "Medal", "Best Player That Never Won" + domainTitle,
/* language=SQL */
"SELECT player_id, g.goat_points AS value FROM player p\n" +
"INNER JOIN player_goat_points g USING (player_id)\n" +
"WHERE g.goat_points > 0" + condition + "\n" +
"AND NOT EXISTS (SELECT * FROM player_tournament_event_result r INNER JOIN tournament_event e USING (tournament_event_id) WHERE r.player_id = p.player_id AND r.result >= 'BR'" + prefix(domain.condition, " AND e.") + ")",
"r.value", "r.value DESC", "r.value DESC",
IntegerRecordDetail.class, PLAYER_GOAT_POINTS_URL_FORMATTER,
asList(GOAT_POINTS_COLUMN), notes
);
}
private static Record bestPlayerThatNeverReachedTopN(String id, String name, String rankType, String rankColumn, int bestRank) {
return new Record<>(
"BestPlayerThatNeverReached" + id + rankType + "Ranking", "Best Player That Never Reached" + prefix(name, " ") + prefix(rankType, " ") + " Ranking",
/* language=SQL */
"SELECT player_id, goat_points AS value FROM player_v\n" +
"WHERE goat_points > 0 AND " + rankColumn + " > " + bestRank,
"r.value", "r.value DESC", "r.value DESC",
IntegerRecordDetail.class, PLAYER_GOAT_POINTS_URL_FORMATTER,
asList(GOAT_POINTS_COLUMN)
);
}
}
|
package com.microsoft.alm.plugin.idea;
import com.intellij.testFramework.fixtures.BasePlatformTestCase;
import com.microsoft.alm.plugin.AbstractTest;
import com.microsoft.alm.plugin.events.ServerPollingManager;
public abstract class IdeaLightweightTest extends BasePlatformTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
AbstractTest.setup();
}
@Override
protected void tearDown() throws Exception {
ServerPollingManager.getInstance().stopPolling();
AbstractTest.cleanup();
super.tearDown();
}
}
|
//FILE: Cameras.java
//PROJECT: Micro-Manager
//SUBSYSTEM: ASIdiSPIM plugin
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package org.micromanager.asidispim.Data;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import javax.swing.JOptionPane;
import mmcorej.CMMCore;
import org.micromanager.api.ScriptInterface;
import org.micromanager.utils.ReportingUtils;
/**
* Holds utility functions for cameras
*
* @author Jon
*/
public class Cameras {
private final Devices devices_; // object holding information about
// selected/available devices
private final Properties props_; // object handling all property read/writes
private final ScriptInterface gui_;
private final CMMCore core_;
private Devices.Keys currentCameraKey_;
public static enum TriggerModes {
EXTERNAL_START,
EXTERNAL_BULB,
INTERNAL;
}
public Cameras(ScriptInterface gui, Devices devices, Properties props) {
devices_ = devices;
props_ = props;
gui_ = gui;
core_ = gui_.getMMCore();
}// constructor
/**
* associative class to store information for camera combo boxes. Contains
* string shown in combo box, key of corresponding device
*/
public static class CameraData {
public String displayString;
public Devices.Keys deviceKey;
public Devices.Sides side;
/**
* @param displayString string used in camera drop-down
* @param deviceKey enum from Devices.Keys for the device
*/
public CameraData(String displayString, Devices.Keys deviceKey,
Devices.Sides side) {
this.displayString = displayString;
this.deviceKey = deviceKey;
this.side = side;
}
public boolean equals(CameraData a) {
return (this.displayString.equals(a.displayString)
&& this.deviceKey == a.deviceKey && this.side == a.side);
}
@Override
public int hashCode() {
return (this.displayString.hashCode()
+ this.deviceKey.toString().hashCode() + this.side.hashCode());
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final CameraData other = (CameraData) obj;
if ((this.displayString == null) ? (other.displayString != null)
: !this.displayString.equals(other.displayString)) {
return false;
}
if (this.deviceKey != other.deviceKey) {
return false;
}
if (this.side != other.side) {
return false;
}
return true;
}
}
/**
* used to generate selection list for cameras
*
* @return array with with CameraData structures
*/
public CameraData[] getCameraData() {
List<CameraData> list = new ArrayList<CameraData>();
list.add(new CameraData(devices_.getDeviceDisplay(Devices.Keys.CAMERAPREVIOUS),
Devices.Keys.CAMERAPREVIOUS, Devices.Sides.NONE));
for (Devices.Keys devKey : Devices.CAMERAS) {
if (devices_.getMMDevice(devKey) != null) {
String dispKey = devices_.getMMDevice(devKey); // getDeviceDisplay(devKey);
list.add(new CameraData(dispKey, devKey,
Devices.getSideFromKey(devKey)));
}
}
List<CameraData> noduplicates = new ArrayList<CameraData>(
new LinkedHashSet<CameraData>(list));
return noduplicates.toArray(new CameraData[0]);
}
/**
* Switches the active camera to the desired one. Takes care of possible side
* effects.
*/
public void setCamera(Devices.Keys key) {
if (Devices.CAMERAS.contains(key)) {
if (key == Devices.Keys.CAMERAPREVIOUS) {
return;
}
String mmDevice = devices_.getMMDevice(key);
if (mmDevice != null) {
try {
boolean liveEnabled = gui_.isLiveModeOn();
if (liveEnabled) {
enableLiveMode(false);
}
currentCameraKey_ = key;
props_.setPropValue(Devices.Keys.CORE, Properties.Keys.CAMERA,
mmDevice);
gui_.refreshGUIFromCache();
if (liveEnabled) {
enableLiveMode(true);
}
} catch (Exception ex) {
gui_.showError("Failed to set Core Camera property");
}
}
}
}
/**
* @return device key, e.g. CAMERAA or CAMERALOWER
*/
public Devices.Keys getCurrentCamera() {
return currentCameraKey_;
}
/**
* @return false if and only if a camera is not set (checks this class, not
* Core-Camera)
*/
public boolean isCurrentCameraValid() {
return !((currentCameraKey_ == null) || (currentCameraKey_ == Devices.Keys.NONE));
}
/**
* Turns live mode on or off via core call
*/
public void enableLiveMode(boolean enable) {
if (enable) {
setSPIMCameraTriggerMode(TriggerModes.INTERNAL);
}
gui_.enableLiveMode(enable);
}
/**
* Internal use only, take care of low-level property setting to make
* internal or external depending on camera type (via the DeviceLibrary)
* currently HamamatsuHam, PCO_Camera, and Andor sCMOS are supported
*
* @param devKey
* @param mode enum from this class
*/
private void setCameraTriggerMode(Devices.Keys devKey, TriggerModes mode) {
Devices.Libraries camLibrary = devices_.getMMDeviceLibrary(devKey);
switch (camLibrary) {
case HAMCAM:
props_.setPropValue(
devKey,
Properties.Keys.TRIGGER_SOURCE,
((mode == TriggerModes.EXTERNAL_START)
? Properties.Values.EXTERNAL
: Properties.Values.INTERNAL), true);
// // this mode useful for maximum speed: exposure is ended by start of
// next frame => requires one extra trigger pulse?
// props_.setPropValue(devKey, Properties.Keys.TRIGGER_ACTIVE,
// Properties.Values.SYNCREADOUT);
break;
case PCOCAM:
props_.setPropValue(
devKey,
Properties.Keys.TRIGGER_MODE,
((mode == TriggerModes.EXTERNAL_START)
? Properties.Values.EXTERNAL_LC
: Properties.Values.INTERNAL_LC), true);
break;
case ANDORCAM:
props_.setPropValue(
devKey,
Properties.Keys.TRIGGER_MODE_ANDOR,
((mode == TriggerModes.EXTERNAL_START)
? Properties.Values.EXTERNAL_LC
: Properties.Values.INTERNAL_ANDOR), true);
break;
default:
break;
}
}
/**
* Utility: calculates the offset from centered on the vertical axis.
* @param roi
* @param sensor
* @return
*/
private int roiVerticalOffset(Rectangle roi, Rectangle sensor) {
return (roi.y + roi.height / 2) - (sensor.y + sensor.height / 2);
}
/**
* Utility: calculates the number of rows that need to be read out
* @param roi
* @param sensor
* @return
*/
private int roiReadoutRowsSplitReadout(Rectangle roi, Rectangle sensor) {
return Math.abs(roiVerticalOffset(roi, sensor)) + roi.height / 2;
}
/**
* Returns true if the camera is a Zyla 5.5
*/
private boolean isZyla55(Devices.Keys camKey) {
return props_.getPropValueString(camKey, Properties.Keys.CAMERA_NAME)
.substring(0, 8).equals("Zyla 5.5");
}
/**
* Goes to properties and sees if this camera has slow readout enabled
* (which affects row transfer speed and thus reset/readout time).
* @param camKey
* @return
*/
private boolean isSlowReadout(Devices.Keys camKey) {
switch(devices_.getMMDeviceLibrary(camKey)) {
case HAMCAM:
return props_.getPropValueString(camKey, Properties.Keys.SCAN_MODE).equals("1");
case PCOCAM:
break;
case ANDORCAM:
if (isZyla55(camKey)) {
return props_.getPropValueString(camKey, Properties.Keys.PIXEL_READOUT_RATE)
.substring(0, 3).equals("200");
} else {
return props_.getPropValueString(camKey, Properties.Keys.PIXEL_READOUT_RATE)
.substring(0, 3).equals("216");
}
default:
break;
}
return false;
}
private Rectangle getSensorSize(Devices.Keys camKey) {
switch(devices_.getMMDeviceLibrary(camKey)) {
case HAMCAM:
return new Rectangle(0, 0, 2048, 2048);
case PCOCAM:
break;
case ANDORCAM:
if (isZyla55(camKey)) {
return new Rectangle(0, 0, 2560, 2160);
} else {
return new Rectangle(0, 0, 2048, 2048);
}
default:
break;
}
ReportingUtils.showError(
"Was not able to get sensor size of camera "
+ devices_.getMMDevice(camKey));
return new Rectangle(0, 0, 0, 0);
}
/**
* Gets the per-row readout time of the camera in ms.
* Assumes fast readout mode (should include slow readout too).
*
* @param camKey
* @return
*/
private double getRowReadoutTime(Devices.Keys camKey) {
switch(devices_.getMMDeviceLibrary(camKey)) {
case HAMCAM:
if (isSlowReadout(camKey)) {
return (2592 / 266e3 * (10./3));
} else {
return (2592 / 266e3);
}
case PCOCAM:
break;
case ANDORCAM:
if (isZyla55(camKey)) {
if (isSlowReadout(camKey)) {
return (2624 * 2 / 206.54e3);
} else {
return (2624 * 2 / 568e3);
}
} else {
if (isSlowReadout(camKey)) {
return (2592 * 2 / 216e3);
} else {
return (2592 * 2 / 540e3);
}
}
default:
break;
}
ReportingUtils.showError(
"Was not able to get per-row readout time of camera "
+ devices_.getMMDevice(camKey));
return 1;
}
/**
* True if reset and readout occur at same time (synchronous or overlap mode)
* @param camKey
* @return
*/
public boolean resetAndReadoutOverlap(Devices.Keys camKey) {
switch (devices_.getMMDeviceLibrary(camKey)) {
case HAMCAM:
if (props_.getPropValueString(camKey, Properties.Keys.TRIGGER_ACTIVE,
true).equals(Properties.Values.SYNCREADOUT.toString())) {
return true;
}
break;
case PCOCAM:
break;
case ANDORCAM:
if (props_.getPropValueString(camKey, Properties.Keys.ANDOR_OVERLAP,
true).equals(Properties.Values.ON.toString())) {
return true;
}
break;
default:
break;
}
return false;
}
/**
* Gets an estimate of a specific camera's time between trigger and global
* exposure, i.e. how long it takes for reset. Will depend on whether we
* have/use global reset, the ROI size, etc.
*
* @param camKey
* @return
*/
public float computeCameraResetTime(Devices.Keys camKey) {
float resetTimeMs = 10;
double rowReadoutTime = getRowReadoutTime(camKey);
int numRowsOverhead;
switch (devices_.getMMDeviceLibrary(camKey)) {
case HAMCAM:
// global reset mode not yet exposed in Micro-manager
// it will be 17+1 rows of overhead but nothing else
if (props_.getPropValueString(camKey, Properties.Keys.TRIGGER_ACTIVE,
true).equals(Properties.Values.SYNCREADOUT.toString())) {
numRowsOverhead = 18; // overhead of 17 rows plus jitter of 1 row
} else { // for EDGE and LEVEL trigger modes
numRowsOverhead = 10; // overhead of 9 rows plus jitter of 1 row
}
resetTimeMs = computeCameraReadoutTime(camKey) + (float) (numRowsOverhead * rowReadoutTime);
break;
case PCOCAM:
JOptionPane.showMessageDialog(null,
"Easy timing mode for PCO cameras not yet implemented in plugin.",
"Warning", JOptionPane.WARNING_MESSAGE);
break;
case ANDORCAM:
numRowsOverhead = 1; // TODO make sure this is accurate; don't have sufficient documentation yet
resetTimeMs = computeCameraReadoutTime(camKey) + (float) (numRowsOverhead * rowReadoutTime);
break;
default:
break;
}
core_.logMessage("camera reset time computed as " + resetTimeMs +
" for camera" + devices_.getMMDevice(camKey), true);
return resetTimeMs; // assume 10ms readout if not otherwise possible to calculate
}
/**
* Gets an estimate of a specific camera's readout time based on ROI and
* other settings.
*
* @param camKey device key for camera in question
* @return readout time in ms
*/
public float computeCameraReadoutTime(Devices.Keys camKey) {
float readoutTimeMs = 10;
Rectangle roi = new Rectangle();
String origCamera = props_.getPropValueString(Devices.Keys.CORE, Properties.Keys.CAMERA, false);
try {
// to get the correct ROI we first set the camera to be active
// (return to original value in finally statement)
setCamera(camKey);
roi = core_.getROI();
} catch (Exception e) {
gui_.showError(e);
} finally {
props_.setPropValue(Devices.Keys.CORE, Properties.Keys.CAMERA, origCamera);
}
double rowReadoutTime = getRowReadoutTime(camKey);
int numReadoutRows;
switch (devices_.getMMDeviceLibrary(camKey)) {
case HAMCAM:
// device adapter provides readout time rounded to nearest 0.1ms; we
// calculate it ourselves instead
// note that Flash4's ROI is always set in increments of 4 pixels
if (props_.getPropValueString(camKey, Properties.Keys.SENSOR_MODE,
true).equals(Properties.Values.PROGRESSIVE.toString())) {
numReadoutRows = roi.height;
} else {
numReadoutRows = roiReadoutRowsSplitReadout(roi, getSensorSize(camKey));
}
readoutTimeMs = ((float) (numReadoutRows * rowReadoutTime));
break;
case PCOCAM:
JOptionPane.showMessageDialog(null,
"Easy timing mode for PCO cameras not yet implemented.",
"Warning", JOptionPane.WARNING_MESSAGE);
break;
case ANDORCAM:
numReadoutRows = roiReadoutRowsSplitReadout(roi, getSensorSize(camKey));
readoutTimeMs = ((float) (numReadoutRows * rowReadoutTime));
break;
default:
break;
}
core_.logMessage("camera readout time computed as " + readoutTimeMs +
" for camera" + devices_.getMMDevice(camKey), true);
return readoutTimeMs; // assume 10ms readout if not otherwise possible to calculate
}
/**
* Sets cameras A and B to external or internal mode
*
* @param external
*/
public void setSPIMCameraTriggerMode(TriggerModes mode) {
setCameraTriggerMode(Devices.Keys.CAMERAA, mode);
setCameraTriggerMode(Devices.Keys.CAMERAB, mode);
}
}
|
package org.opendaylight.yangtools.yang.model.repo.util;
import com.google.common.annotations.Beta;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.FutureFallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.annotation.concurrent.GuardedBy;
import org.opendaylight.yangtools.util.concurrent.ExceptionMapper;
import org.opendaylight.yangtools.util.concurrent.ReflectiveExceptionMapper;
import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Abstract base class for {@link SchemaRepository} implementations. It handles registration
* and lookup of schema sources, subclasses need only to provide their own
* {@link #createSchemaContextFactory(SchemaSourceFilter)} implementation.
*/
@Beta
public abstract class AbstractSchemaRepository implements SchemaRepository, SchemaSourceRegistry {
private static final Logger LOG = LoggerFactory.getLogger(AbstractSchemaRepository.class);
private static final ExceptionMapper<SchemaSourceException> FETCH_MAPPER = ReflectiveExceptionMapper.create("Schema source fetch", SchemaSourceException.class);
/*
* Source identifier -> representation -> provider map. We usually are looking for
* a specific representation of a source.
*/
@GuardedBy("this")
private final Map<SourceIdentifier, ListMultimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>>> sources = new HashMap<>();
/*
* Schema source listeners.
*/
@GuardedBy("this")
private final Collection<SchemaListenerRegistration> listeners = new ArrayList<>();
private static <T extends SchemaSourceRepresentation> CheckedFuture<T, SchemaSourceException> fetchSource(final SourceIdentifier id, final Iterator<AbstractSchemaSourceRegistration<?>> it) {
final AbstractSchemaSourceRegistration<?> reg = it.next();
@SuppressWarnings("unchecked")
final CheckedFuture<? extends T, SchemaSourceException> f = ((SchemaSourceProvider<T>)reg.getProvider()).getSource(id);
return Futures.makeChecked(Futures.withFallback(f, new FutureFallback<T>() {
@Override
public ListenableFuture<T> create(final Throwable t) throws SchemaSourceException {
LOG.debug("Failed to acquire source from {}", reg, t);
if (it.hasNext()) {
return fetchSource(id, it);
}
throw new MissingSchemaSourceException("All available providers exhausted", id, t);
}
}), FETCH_MAPPER);
}
@Override
public <T extends SchemaSourceRepresentation> CheckedFuture<T, SchemaSourceException> getSchemaSource(final SourceIdentifier id, final Class<T> representation) {
final ArrayList<AbstractSchemaSourceRegistration<?>> sortedSchemaSourceRegistrations;
synchronized (this) {
final ListMultimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> srcs = sources.get(id);
if (srcs == null) {
return Futures.immediateFailedCheckedFuture(new MissingSchemaSourceException("No providers registered for source" + id, id));
}
sortedSchemaSourceRegistrations = Lists.newArrayList(srcs.get(representation));
}
// TODO, remove and make sources keep sorted multimap (e.g. ArrayListMultimap with SortedLists)
Collections.sort(sortedSchemaSourceRegistrations, SchemaProviderCostComparator.INSTANCE);
final Iterator<AbstractSchemaSourceRegistration<?>> regs = sortedSchemaSourceRegistrations.iterator();
if (!regs.hasNext()) {
return Futures.immediateFailedCheckedFuture(
new MissingSchemaSourceException("No providers for source " + id + " representation " + representation + " available", id));
}
CheckedFuture<T, SchemaSourceException> fetchSourceFuture = fetchSource(id, regs);
// Add callback to notify cache listeners about encountered schema
Futures.addCallback(fetchSourceFuture, new FutureCallback<T>() {
@Override
public void onSuccess(final T result) {
for (final SchemaListenerRegistration listener : listeners) {
listener.getInstance().schemaSourceEncountered(result);
}
}
@Override
public void onFailure(final Throwable t) {
LOG.trace("Skipping notification for encountered source {}, fetching source failed", id, t);
}
});
return fetchSourceFuture;
}
private synchronized <T extends SchemaSourceRepresentation> void addSource(final PotentialSchemaSource<T> source, final AbstractSchemaSourceRegistration<T> reg) {
ListMultimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> m = sources.get(source.getSourceIdentifier());
if (m == null) {
m = ArrayListMultimap.create();
sources.put(source.getSourceIdentifier(), m);
}
m.put(source.getRepresentation(), reg);
final Collection<PotentialSchemaSource<?>> reps = Collections.singleton(source);
for (SchemaListenerRegistration l : listeners) {
l.getInstance().schemaSourceRegistered(reps);
}
}
private synchronized <T extends SchemaSourceRepresentation> void removeSource(final PotentialSchemaSource<?> source, final SchemaSourceRegistration<?> reg) {
final Multimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> m = sources.get(source.getSourceIdentifier());
if (m != null) {
m.remove(source.getRepresentation(), reg);
for (SchemaListenerRegistration l : listeners) {
l.getInstance().schemaSourceUnregistered(source);
}
if (m.isEmpty()) {
sources.remove(source.getSourceIdentifier());
}
}
}
@Override
public <T extends SchemaSourceRepresentation> SchemaSourceRegistration<T> registerSchemaSource(final SchemaSourceProvider<? super T> provider, final PotentialSchemaSource<T> source) {
final PotentialSchemaSource<T> src = source.cachedReference();
final AbstractSchemaSourceRegistration<T> ret = new AbstractSchemaSourceRegistration<T>(provider, src) {
@Override
protected void removeRegistration() {
removeSource(src, this);
}
};
addSource(src, ret);
return ret;
}
@Override
public SchemaListenerRegistration registerSchemaSourceListener(final SchemaSourceListener listener) {
final SchemaListenerRegistration ret = new AbstractSchemaListenerRegistration(listener) {
@Override
protected void removeRegistration() {
listeners.remove(this);
}
};
synchronized (this) {
final Collection<PotentialSchemaSource<?>> col = new ArrayList<>();
for (Multimap<Class<? extends SchemaSourceRepresentation>, AbstractSchemaSourceRegistration<?>> m : sources.values()) {
for (AbstractSchemaSourceRegistration<?> r : m.values()) {
col.add(r.getInstance());
}
}
// Notify first, so translator-type listeners, who react by registering a source
// do not cause infinite loop.
listener.schemaSourceRegistered(col);
listeners.add(ret);
}
return ret;
}
private static class SchemaProviderCostComparator implements Comparator<AbstractSchemaSourceRegistration<?>> {
public static final SchemaProviderCostComparator INSTANCE = new SchemaProviderCostComparator();
@Override
public int compare(final AbstractSchemaSourceRegistration<?> o1, final AbstractSchemaSourceRegistration<?> o2) {
return o1.getInstance().getCost() - o2.getInstance().getCost();
}
}
}
|
package dr.app.beagle.evomodel.branchmodel.lineagespecific;
import dr.app.bss.Utils;
import dr.inference.model.Parameter;
import dr.math.GammaFunction;
import dr.math.distributions.Distribution;
import dr.math.distributions.MultivariateDistribution;
public class StickBreakingProcessPrior implements MultivariateDistribution {
private Distribution baseDistribution;
private Parameter mdParameter;
private Parameter uCategories;
private int categoryCount;
public StickBreakingProcessPrior(Distribution baseDistribution,
Parameter mdParameter,
Parameter uCategories
) {
this.baseDistribution = baseDistribution;
this.mdParameter = mdParameter;
this.uCategories = uCategories;
this.categoryCount = mdParameter.getDimension();
}// END: Constructor
private int[] getCounts() {
int[] counts = new int[categoryCount];
int[] branchAssignments = new int[uCategories.getDimension()];
for (int i = 0; i < branchAssignments.length; i++) {
counts[branchAssignments[i]]++;
}
return counts;
}// END: getBranchAssignmentCounts
private double[] getValues() {
double[] values = new double[categoryCount];
for (int i = 0; i < categoryCount; i++) {
values[i] = mdParameter.getParameterValue(i);
}
return values;
}// END: getValues
/*
* Distribution Likelihood
*/
public double getLogLikelihood() {
double logLike = 0.0;
int[] counts = getCounts();
double[] values = getValues();
double countSum = Utils.sumArray(counts);
logLike += GammaFunction.lnGamma(countSum);
for (int i = 0; i < categoryCount; i++) {
logLike += ((counts[i] - 1) * Math.log(values[i]) - GammaFunction
.lnGamma(counts[i]));
}// END: i loop
return logLike;
}// END: getLogLikelihood
@Override
public double logPdf(double[] x) {
double logLike = 0.0;
int[] counts = getCounts();
double countSum = Utils.sumArray(counts);
logLike += GammaFunction.lnGamma(countSum);
for (int i = 0; i < categoryCount; i++) {
logLike += ((counts[i] - 1) * Math.log(x[i]) - GammaFunction
.lnGamma(counts[i]));
}// END: i loop
return logLike;
}// END: logPdf
@Override
public double[] getMean() {
int[] counts = getCounts();
double countSum = Utils.sumArray(counts);
double[] mean = new double[categoryCount];
for (int i = 0; i < categoryCount; i++) {
mean[i] = counts[i] / countSum;
}
return mean;
}// END: mean
@Override
public double[][] getScaleMatrix() {
return null;
}
@Override
public String getType() {
return null;
}
}// END: class
|
package eu.ydp.empiria.player.client.controller.flow.processing.commands;
import com.google.gwt.core.client.JavaScriptObject;
public abstract class FlowCommand implements IFlowCommand {
protected String name;
private FlowCommand(String name){
this.name = name;
}
public String getName(){
return name;
}
public static IFlowCommand fromJsObject(JavaScriptObject commandJsObject){
String objName = getJsObjectName(commandJsObject);
if (objName == null || objName.equals(""))
return null;
int objIndex = getJsObjectIndex(commandJsObject);
IFlowCommand command = null;
if (NavigateNextItem.NAME.equals(objName)) {
command = new NavigateNextItem();
} else if (NavigatePreviousItem.NAME.equals(objName)) {
command = new NavigatePreviousItem();
} else if (NavigateFirstItem.NAME.equals(objName)) {
command = new NavigateFirstItem();
} else if (NavigateLastItem.NAME.equals(objName)) {
command = new NavigateLastItem();
} else if (NavigateToc.NAME.equals(objName)) {
command = new NavigateToc();
} else if (NavigateTest.NAME.equals(objName)) {
command = new NavigateTest();
} else if (NavigateSummary.NAME.equals(objName)) {
command = new NavigateSummary();
} else if (NavigateGotoItem.NAME.equals(objName)) {
command = new NavigateGotoItem(objIndex);
} else if (NavigatePreviewItem.NAME.equals(objName)) {
command = new NavigatePreviewItem(objIndex);
} else if (Continue.NAME.equals(objName)) {
command = new Continue();
} else if (Check.NAME.equals(objName)) {
command = new Check();
} else if (Reset.NAME.equals(objName)) {
command = new Reset();
} else if (ShowAnswers.NAME.equals(objName)) {
command = new ShowAnswers();
} else if (Lock.NAME.equals(objName)) {
command = new Lock();
}else if (Unlock.NAME.equals(objName)) {
command = new Unlock();
}
return command;
}
private static native String getJsObjectName(JavaScriptObject obj)/*-{
if (typeof obj.name == 'string')
return obj.name;
return "";
}-*/;
private static native int getJsObjectIndex(JavaScriptObject obj)/*-{
if (typeof obj.index == 'number')
return obj.index;
return -1;
}-*/;
public final static class NavigateNextItem extends FlowCommand{
public NavigateNextItem(){
super(NAME);
}
public static final String NAME = "NAVIGATE_NEXT_ITEM";
@Override
public void execute(FlowCommandsListener listener) {
listener.nextPage();
}
}
public final static class NavigatePreviousItem extends FlowCommand{
public NavigatePreviousItem(){
super(NAME);
}
public static final String NAME = "NAVIGATE_PREVIOUS_ITEM";
@Override
public void execute(FlowCommandsListener listener) {
listener.previousPage();
}
}
public final static class NavigateFirstItem extends FlowCommand{
public NavigateFirstItem(){
super(NAME);
}
public static final String NAME = "NAVIGATE_FIRST_ITEM";
@Override
public void execute(FlowCommandsListener listener) {
listener.gotoFirstPage();
}
}
public final static class NavigateLastItem extends FlowCommand{
public NavigateLastItem(){
super(NAME);
}
public static final String NAME = "NAVIGATE_LAST_ITEM";
@Override
public void execute(FlowCommandsListener listener) {
listener.gotoLastPage();
}
}
public final static class NavigateToc extends FlowCommand{
public NavigateToc(){
super(NAME);
}
public static final String NAME = "NAVIGATE_TOC";
@Override
public void execute(FlowCommandsListener listener) {
listener.gotoToc();
}
}
public final static class NavigateTest extends FlowCommand{
public NavigateTest(){
super(NAME);
}
public static final String NAME = "NAVIGATE_TEST";
@Override
public void execute(FlowCommandsListener listener) {
listener.gotoTest();
}
}
public final static class NavigateSummary extends FlowCommand{
public NavigateSummary(){
super(NAME);
}
public static final String NAME = "NAVIGATE_SUMMARY";
@Override
public void execute(FlowCommandsListener listener) {
listener.gotoSummary();
}
}
public abstract static class FlowCommandWithIndex extends FlowCommand{
public FlowCommandWithIndex(String name, int index){
super(name);
this.index = index;
}
protected int index;
}
public final static class NavigateGotoItem extends FlowCommandWithIndex{
public NavigateGotoItem(int index){
super(NAME, index);
}
public static final String NAME = "NAVIGATE_GOTO_ITEM";
@Override
public void execute(FlowCommandsListener listener) {
listener.gotoPage(index);
}
}
public final static class NavigatePreviewItem extends FlowCommandWithIndex{
public NavigatePreviewItem(int index){
super(NAME, index);
}
public static final String NAME = "NAVIGATE_PREVIEW_ITEM";
@Override
public void execute(FlowCommandsListener listener) {
listener.previewPage(index);
}
}
public static class Check extends FlowCommand{
public Check(){
super(NAME);
}
public static final String NAME = "CHECK";
@Override
public void execute(FlowCommandsListener listener) {
listener.checkPage();
}
}
public static class Continue extends FlowCommand{
public Continue(){
super(NAME);
}
public static final String NAME = "CONTINUE";
@Override
public void execute(FlowCommandsListener listener) {
listener.continuePage();
}
}
public static class Reset extends FlowCommand{
public Reset(){
super(NAME);
}
public static final String NAME = "RESET";
@Override
public void execute(FlowCommandsListener listener) {
listener.resetPage();
}
}
public static class ShowAnswers extends FlowCommand{
public ShowAnswers(){
super(NAME);
}
public static final String NAME = "SHOW_ANSWERS";
@Override
public void execute(FlowCommandsListener listener) {
listener.showAnswers();
}
}
public static class Lock extends FlowCommand{
public Lock(){
super(NAME);
}
public static final String NAME = "LOCK";
@Override
public void execute(FlowCommandsListener listener) {
listener.lockPage();
}
}
public static class Unlock extends FlowCommand{
public Unlock(){
super(NAME);
}
public static final String NAME = "UNLOCK";
@Override
public void execute(FlowCommandsListener listener) {
listener.unlockPage();
}
}
}
|
package com.example.madiskar.experiencesamplingapp;
import android.support.test.espresso.ViewInteraction;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiSelector;
import android.support.test.uiautomator.Until;
import android.test.suitebuilder.annotation.LargeTest;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.replaceText;
import static android.support.test.espresso.action.ViewActions.scrollTo;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withClassName;
import static android.support.test.espresso.matcher.ViewMatchers.withContentDescription;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withParent;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.is;
@RunWith(AndroidJUnit4.class)
public class Test2EventActivity {
@Rule
public ActivityTestRule<LoginActivity> mActivityTestRule = new ActivityTestRule<>(LoginActivity.class);
UiDevice mDevice;
@Before
public void setUp() throws Exception {
//super.setUp();
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
}
@Test
public void eventActivityTest() throws Exception {
ViewInteraction appCompatButton2 = onView(
allOf(withId(R.id.event_button), withText("Event"),
withParent(childAtPosition(
withId(android.R.id.list),
0)),
isDisplayed()));
appCompatButton2.perform(click());
ViewInteraction appCompatCheckedTextView = onView(
allOf(withId(android.R.id.text1), withText("Running"),
childAtPosition(
allOf(withClassName(is("com.android.internal.app.AlertController$RecycleListView")),
withParent(withClassName(is("android.widget.FrameLayout")))),
0),
isDisplayed()));
appCompatCheckedTextView.perform(click());
ViewInteraction appCompatButton3 = onView(
allOf(withId(android.R.id.button1), withText("Start")));
appCompatButton3.perform(click());
mDevice.openNotification();
mDevice.wait(Until.hasObject(By.pkg("com.android.systemui")), 10000);
UiObject eventText = mDevice.findObject(new UiSelector().text("Active Event"));
assertTrue(eventText.exists());
UiObject eventName = mDevice.findObject(new UiSelector().text("Running"));
assertTrue(eventName.exists());
UiObject eventFalseName = mDevice.findObject(new UiSelector().text("Cooking"));
assertFalse(eventFalseName.exists());
UiObject eventStopButton = mDevice.findObject(new UiSelector().textMatches("STOP|Stop|stop"));
assertTrue(eventStopButton.exists());
eventStopButton.click();
}
private static Matcher<View> childAtPosition(
final Matcher<View> parentMatcher, final int position) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText("Child at position " + position + " in parent ");
parentMatcher.describeTo(description);
}
@Override
public boolean matchesSafely(View view) {
ViewParent parent = view.getParent();
return parent instanceof ViewGroup && parentMatcher.matches(parent)
&& view.equals(((ViewGroup) parent).getChildAt(position));
}
};
}
}
|
package org.rstudio.studio.client.panmirror.command;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.rstudio.studio.client.palette.model.CommandPaletteEntrySource;
import org.rstudio.studio.client.palette.model.CommandPaletteItem;
import com.google.gwt.aria.client.MenuitemRole;
import com.google.gwt.aria.client.Roles;
public class PanmirrorToolbarCommands implements CommandPaletteEntrySource
{
public PanmirrorToolbarCommands(PanmirrorCommand[] commands)
{
PanmirrorCommandIcons icons = PanmirrorCommandIcons.INSTANCE;
// init commands
commands_ = commands;
// text editing
add(PanmirrorCommands.Undo, "Undo");
add(PanmirrorCommands.Redo, "Redo");
add(PanmirrorCommands.SelectAll, "Select All");
// formatting
add(PanmirrorCommands.Strong, "Bold", icons.BOLD);
add(PanmirrorCommands.Em, "Italic", icons.ITALIC);
add(PanmirrorCommands.Code, "Code", icons.CODE);
add(PanmirrorCommands.Strikeout, "Strikeout");
add(PanmirrorCommands.Superscript, "Superscript");
add(PanmirrorCommands.Subscript, "Subscript");
add(PanmirrorCommands.Smallcaps, "Small Caps");
add(PanmirrorCommands.Span, "Span...");
add(PanmirrorCommands.Paragraph, "Normal", Roles.getMenuitemradioRole());
add(PanmirrorCommands.Heading1, "Heading 1", Roles.getMenuitemradioRole());
add(PanmirrorCommands.Heading2, "Heading 2", Roles.getMenuitemradioRole());
add(PanmirrorCommands.Heading3, "Heading 3", Roles.getMenuitemradioRole());
add(PanmirrorCommands.Heading4, "Heading 4", Roles.getMenuitemradioRole());
add(PanmirrorCommands.Heading5, "Heading 5", Roles.getMenuitemradioRole());
add(PanmirrorCommands.Heading6, "Heading 6", Roles.getMenuitemradioRole());
add(PanmirrorCommands.CodeBlock, "Code Block", Roles.getMenuitemradioRole());
add(PanmirrorCommands.CodeBlockFormat, "Code Block...");
add(PanmirrorCommands.Blockquote, "Blockquote", Roles.getMenuitemcheckboxRole(), icons.BLOCKQUOTE);
add(PanmirrorCommands.LineBlock, "Line Block", Roles.getMenuitemcheckboxRole());
add(PanmirrorCommands.Div, "Div...");
add(PanmirrorCommands.AttrEdit, "Edit Attributes...");
add(PanmirrorCommands.ClearFormatting, "Clear Formatting", icons.CLEAR_FORMATTING);
// raw
add(PanmirrorCommands.TexInline, "TeX Inline", Roles.getMenuitemcheckboxRole());
add(PanmirrorCommands.TexBlock, "TeX Block", Roles.getMenuitemcheckboxRole());
add(PanmirrorCommands.HTMLInline, "HTML Inline...");
add(PanmirrorCommands.HTMLBlock, "HTML Block", Roles.getMenuitemcheckboxRole());
add(PanmirrorCommands.RawInline, "Raw Inline...");
add(PanmirrorCommands.RawBlock, "Raw Block...");
// chunk
add(PanmirrorCommands.RCodeChunk, "R");
add(PanmirrorCommands.BashCodeChunk, "Bash");
add(PanmirrorCommands.D3CodeChunk, "D3");
add(PanmirrorCommands.PythonCodeChunk, "Python");
add(PanmirrorCommands.RcppCodeChunk, "Rcpp");
add(PanmirrorCommands.SQLCodeChunk, "SQL");
add(PanmirrorCommands.StanCodeChunk, "Stan");
// lists
add(PanmirrorCommands.BulletList, "Bulleted List", Roles.getMenuitemcheckboxRole(), icons.BULLET_LIST);
add(PanmirrorCommands.OrderedList, "Numbered List", Roles.getMenuitemcheckboxRole(), icons.NUMBERED_LIST);
add(PanmirrorCommands.TightList, "Tight List", Roles.getMenuitemcheckboxRole());
add(PanmirrorCommands.ListItemSink, "Sink Item");
add(PanmirrorCommands.ListItemLift, "Lift Item");
add(PanmirrorCommands.ListItemCheck, "Item Checkbox");
add(PanmirrorCommands.ListItemCheckToggle, "Item Checked", Roles.getMenuitemcheckboxRole());
add(PanmirrorCommands.EditListProperties, "List Attributes...");
// tables
add(PanmirrorCommands.TableInsertTable, "Insert Table...", icons.TABLE);
add(PanmirrorCommands.TableToggleHeader, "Table Header", Roles.getMenuitemcheckboxRole());
add(PanmirrorCommands.TableToggleCaption, "Table Caption", Roles.getMenuitemcheckboxRole());
add(PanmirrorCommands.TableAddColumnAfter, "Table:::Insert Column Right", "Insert %d Columns Right", null);
add(PanmirrorCommands.TableAddColumnBefore, "Table:::Insert Column Left", "Insert %d Columns Left", null);
add(PanmirrorCommands.TableDeleteColumn, "Table:::Delete Column", "Table:::Delete %d Columns", null);
add(PanmirrorCommands.TableAddRowAfter, "Table:::Insert Row Below", "Table:::Insert %d Rows Below", null);
add(PanmirrorCommands.TableAddRowBefore, "Table:::Insert Row Above", "Table:::Insert %d Rows Above", null);
add(PanmirrorCommands.TableDeleteRow, "Table:::Delete Row", "Delete %d Rows", null);
add(PanmirrorCommands.TableDeleteTable, "Delete Table");
add(PanmirrorCommands.TableNextCell, "Table:::Next Cell");
add(PanmirrorCommands.TablePreviousCell, "Table:::Previous Cell");
add(PanmirrorCommands.TableAlignColumnLeft, "Table Align Column:::Left", Roles.getMenuitemcheckboxRole());
add(PanmirrorCommands.TableAlignColumnRight, "Table Align Column:::Right", Roles.getMenuitemcheckboxRole());
add(PanmirrorCommands.TableAlignColumnCenter, "Table Align Column:::Center", Roles.getMenuitemcheckboxRole());
add(PanmirrorCommands.TableAlignColumnDefault, "Table Align Column:::Default", Roles.getMenuitemcheckboxRole());
// insert
add(PanmirrorCommands.OmniInsert, "Any...", icons.OMNI);
add(PanmirrorCommands.Link, "Link...", icons.LINK);
add(PanmirrorCommands.RemoveLink, "Remove Link");
add(PanmirrorCommands.Image, "Image...", icons.IMAGE);
add(PanmirrorCommands.Footnote, "Footnote");
add(PanmirrorCommands.HorizontalRule, "Horizontal Rule");
add(PanmirrorCommands.ParagraphInsert, "Paragraph");
add(PanmirrorCommands.HTMLComment, "Comment", icons.COMMENT);
add(PanmirrorCommands.YamlMetadata, "YAML Block");
add(PanmirrorCommands.Shortcode, "Shortcode");
add(PanmirrorCommands.InsertDiv, "Div...");
add(PanmirrorCommands.InlineMath, "Inline Math");
add(PanmirrorCommands.DisplayMath, "Display Math");
add(PanmirrorCommands.DefinitionList, "Definition List");
add(PanmirrorCommands.DefinitionTerm, "Term");
add(PanmirrorCommands.DefinitionDescription, "Description");
add(PanmirrorCommands.Citation, "Citation...", icons.CITATION);
add(PanmirrorCommands.CrossReference, "Cross Reference");
add(PanmirrorCommands.InsertEmoji, "Insert Emoji...");
add(PanmirrorCommands.InsertSymbol, "Insert Unicode...");
add(PanmirrorCommands.EmDash, "Insert:::Em Dash (—)");
add(PanmirrorCommands.EnDash, "Insert:::En Dash (–)");
add(PanmirrorCommands.NonBreakingSpace, "Insert:::Non-Breaking Space");
add(PanmirrorCommands.HardLineBreak, "Insert:::Hard Line Break");
// outline
add(PanmirrorCommands.GoToNextSection, "Go to Next Section");
add(PanmirrorCommands.GoToPreviousSection, "Go to Previous Section");
}
public PanmirrorCommandUI get(String id)
{
return commandsUI_.get(id);
}
public boolean exec(String id)
{
PanmirrorCommandUI command = get(id);
if (command != null)
{
if (command.isEnabled())
{
command.execute();
}
return true;
}
else
{
return false;
}
}
@Override
public List<CommandPaletteItem> getCommandPaletteItems()
{
List<CommandPaletteItem> items = new ArrayList<CommandPaletteItem>();
for (PanmirrorCommandUI cmd: commandsUI_.values())
{
if (cmd != null && cmd.isVisible())
{
items.add(new PanmirrorCommandPaletteItem(cmd));
}
}
return items;
}
private void add(String id, String menuText)
{
add(id, menuText, Roles.getMenuitemRole());
}
private void add(String id, String menuText, String pluralMenuText, String image)
{
add(id, menuText, pluralMenuText, Roles.getMenuitemRole(), image);
}
private void add(String id, String menuText, String image)
{
add(id, menuText, Roles.getMenuitemRole(), image);
}
private void add(String id, String menuText, MenuitemRole role)
{
add(id, menuText, role, null);
}
private void add(String id, String menuText, MenuitemRole role, String image)
{
add(id, menuText, null, role, image);
}
private void add(String id, String menuText, String pluralMenuText, MenuitemRole role, String image)
{
// lookup the underlying command
PanmirrorCommand command = null;
for (PanmirrorCommand cmd : commands_) {
if (cmd.id == id) {
command = cmd;
break;
}
}
// add it
commandsUI_.put(id, new PanmirrorCommandUI(command, menuText, pluralMenuText, role, image));
}
private PanmirrorCommand[] commands_ = null;
private final HashMap<String,PanmirrorCommandUI> commandsUI_ = new HashMap<String,PanmirrorCommandUI>();
}
|
package org.rstudio.studio.client.workbench.views.source;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import org.rstudio.core.client.*;
import org.rstudio.core.client.command.AppCommand;
import org.rstudio.core.client.command.CommandBinder;
import org.rstudio.core.client.command.Handler;
import org.rstudio.core.client.files.FileSystemItem;
import org.rstudio.core.client.js.JsObject;
import org.rstudio.core.client.js.JsUtil;
import org.rstudio.core.client.widget.Operation;
import org.rstudio.core.client.widget.OperationWithInput;
import org.rstudio.core.client.widget.ProgressIndicator;
import org.rstudio.studio.client.RStudioGinjector;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.FilePathUtils;
import org.rstudio.studio.client.common.GlobalDisplay;
import org.rstudio.studio.client.common.GlobalProgressDelayer;
import org.rstudio.studio.client.common.SimpleRequestCallback;
import org.rstudio.studio.client.common.dependencies.DependencyManager;
import org.rstudio.studio.client.common.filetypes.*;
import org.rstudio.studio.client.common.synctex.Synctex;
import org.rstudio.studio.client.events.GetEditorContextEvent;
import org.rstudio.studio.client.palette.model.CommandPaletteEntrySource;
import org.rstudio.studio.client.palette.model.CommandPaletteItem;
import org.rstudio.studio.client.rmarkdown.model.RmdChosenTemplate;
import org.rstudio.studio.client.rmarkdown.model.RmdFrontMatter;
import org.rstudio.studio.client.rmarkdown.model.RmdOutputFormat;
import org.rstudio.studio.client.rmarkdown.model.RmdTemplateData;
import org.rstudio.studio.client.server.ServerError;
import org.rstudio.studio.client.server.ServerRequestCallback;
import org.rstudio.studio.client.server.VoidServerRequestCallback;
import org.rstudio.studio.client.workbench.FileMRUList;
import org.rstudio.studio.client.workbench.commands.Commands;
import org.rstudio.studio.client.workbench.model.ClientState;
import org.rstudio.studio.client.workbench.model.Session;
import org.rstudio.studio.client.workbench.model.UnsavedChangesTarget;
import org.rstudio.studio.client.workbench.model.helper.JSObjectStateValue;
import org.rstudio.studio.client.workbench.prefs.model.UserPrefs;
import org.rstudio.studio.client.workbench.prefs.model.UserState;
import org.rstudio.studio.client.workbench.ui.unsaved.UnsavedChangesDialog;
import org.rstudio.studio.client.workbench.views.environment.events.DebugModeChangedEvent;
import org.rstudio.studio.client.workbench.views.output.find.events.FindInFilesEvent;
import org.rstudio.studio.client.workbench.views.source.editors.EditingTarget;
import org.rstudio.studio.client.workbench.views.source.editors.EditingTargetSource;
import org.rstudio.studio.client.workbench.views.source.editors.codebrowser.CodeBrowserEditingTarget;
import org.rstudio.studio.client.workbench.views.source.editors.data.DataEditingTarget;
import org.rstudio.studio.client.workbench.views.source.editors.explorer.ObjectExplorerEditingTarget;
import org.rstudio.studio.client.workbench.views.source.editors.explorer.model.ObjectExplorerHandle;
import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor;
import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay;
import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTarget;
import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTargetRMarkdownHelper;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Range;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Selection;
import org.rstudio.studio.client.workbench.views.source.editors.text.events.EditingTargetSelectedEvent;
import org.rstudio.studio.client.workbench.views.source.editors.text.ui.NewRMarkdownDialog;
import org.rstudio.studio.client.workbench.views.source.events.*;
import org.rstudio.studio.client.workbench.views.source.model.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
@Singleton
public class SourceColumnManager implements CommandPaletteEntrySource,
SourceExtendedTypeDetectedEvent.Handler,
DebugModeChangedEvent.Handler
{
public interface CPSEditingTargetCommand
{
void execute(EditingTarget editingTarget, Command continuation);
}
public static class State extends JavaScriptObject
{
public static native State createState(JsArrayString names) /*-{
return {
names: names
}
}-*/;
protected State()
{}
public final String[] getNames()
{
return JsUtil.toStringArray(getNamesNative());
}
private native JsArrayString getNamesNative() /*-{
return this.names;
}-*/;
}
interface Binder extends CommandBinder<Commands, SourceColumnManager>
{
}
SourceColumnManager() { RStudioGinjector.INSTANCE.injectMembers(this);}
@Inject
public SourceColumnManager(Binder binder,
Source.Display display,
SourceServerOperations server,
GlobalDisplay globalDisplay,
Commands commands,
EditingTargetSource editingTargetSource,
FileTypeRegistry fileTypeRegistry,
EventBus events,
DependencyManager dependencyManager,
final Session session,
Synctex synctex,
UserPrefs userPrefs,
UserState userState,
Provider<FileMRUList> pMruList,
SourceWindowManager windowManager)
{
commands_ = commands;
binder.bind(commands_, this);
server_ = server;
globalDisplay_ = globalDisplay;
editingTargetSource_ = editingTargetSource;
fileTypeRegistry_ = fileTypeRegistry;
events_ = events;
dependencyManager_ = dependencyManager;
session_ = session;
synctex_ = synctex;
userPrefs_ = userPrefs;
userState_ = userState;
pMruList_ = pMruList;
windowManager_ = windowManager;
rmarkdown_ = new TextEditingTargetRMarkdownHelper();
vimCommands_ = new SourceVimCommands();
columnState_ = null;
initDynamicCommands();
events_.addHandler(SourceExtendedTypeDetectedEvent.TYPE, this);
events_.addHandler(DebugModeChangedEvent.TYPE, this);
events_.addHandler(EditingTargetSelectedEvent.TYPE,
new EditingTargetSelectedEvent.Handler()
{
@Override
public void onEditingTargetSelected(EditingTargetSelectedEvent event)
{
setActive(event.getTarget());
}
});
events_.addHandler(SourceFileSavedEvent.TYPE, new SourceFileSavedHandler()
{
public void onSourceFileSaved(SourceFileSavedEvent event)
{
pMruList_.get().add(event.getPath());
}
});
events_.addHandler(DocTabActivatedEvent.TYPE, new DocTabActivatedEvent.Handler()
{
public void onDocTabActivated(DocTabActivatedEvent event)
{
setActiveDocId(event.getId());
}
});
events_.addHandler(SwitchToDocEvent.TYPE, new SwitchToDocHandler()
{
public void onSwitchToDoc(SwitchToDocEvent event)
{
ensureVisible(false);
activeColumn_.setPhysicalTabIndex(event.getSelectedIndex());
// Fire an activation event just to ensure the activated
// tab gets focus
commands_.activateSource().execute();
}
});
sourceNavigationHistory_.addChangeHandler(event -> manageSourceNavigationCommands());
new JSObjectStateValue("source-column-manager",
"column-info",
ClientState.PERSISTENT,
session_.getSessionInfo().getClientState(),
false)
{
@Override
protected void onInit(JsObject value)
{
if (value == null)
{
columnState_ = State.createState(JsUtil.toJsArrayString(getNames(false)));
return;
}
columnState_ = value.cast();
for (int i = 0; i < columnState_.getNames().length; i++)
{
String name = columnState_.getNames()[i];
if (!StringUtil.equals(name, MAIN_SOURCE_NAME))
add(name, false);
}
}
@Override
protected JsObject getValue()
{
return columnState_.cast();
}
};
SourceColumn column = GWT.create(SourceColumn.class);
column.loadDisplay(MAIN_SOURCE_NAME, display, this);
columnList_.add(column);
setActive(column.getName());
}
public String add()
{
Source.Display display = GWT.create(SourcePane.class);
return add(display, false);
}
public String add(Source.Display display)
{
return add(display, false);
}
public String add(String name, boolean updateState)
{
return add(name, false, updateState);
}
public String add (String name, boolean activate, boolean updateState)
{
Source.Display display = GWT.create(SourcePane.class);
return add(name, display, activate, updateState);
}
public String add(Source.Display display, boolean activate)
{
return add(display, activate, true);
}
public String add(Source.Display display, boolean activate, boolean updateState)
{
return add(COLUMN_PREFIX + StringUtil.makeRandomId(12),
display,
activate,
updateState);
}
public String add(String name, Source.Display display, boolean activate, boolean updateState)
{
if (contains(name))
return "";
SourceColumn column = GWT.create(SourceColumn.class);
column.loadDisplay(name, display, this);
columnList_.add(column);
if (activate || activeColumn_ == null)
setActive(column);
if (updateState)
columnState_ = State.createState(JsUtil.toJsArrayString(getNames(false)));
return column.getName();
}
public void initialSelect(int index)
{
getActive().initialSelect(index);
}
public void setActive(int xpos)
{
SourceColumn column = findByPosition(xpos);
if (column == null)
return;
setActive(column);
}
public void setActive(String name)
{
if (StringUtil.isNullOrEmpty(name) &&
activeColumn_ != null)
{
if (hasActiveEditor())
activeColumn_.setActiveEditor("");
activeColumn_ = null;
return;
}
// If we can't find the column, use the main column. This may happen on start up.
SourceColumn column = getByName(name);
if (column == null)
column = getByName(MAIN_SOURCE_NAME);
setActive(column);
}
private void setActive(EditingTarget target)
{
setActive(findByDocument(target.getId()));
activeColumn_.setActiveEditor(target);
}
private void setActive(SourceColumn column)
{
SourceColumn prevColumn = activeColumn_;
activeColumn_ = column;
// If the active column changed, we need to update the active editor
if (prevColumn != null && prevColumn != activeColumn_)
{
prevColumn.setActiveEditor("");
if (!hasActiveEditor())
activeColumn_.setActiveEditor();
manageCommands(true);
}
}
private void setActiveDocId(String docId)
{
if (StringUtil.isNullOrEmpty(docId))
return;
for (SourceColumn column : columnList_)
{
EditingTarget target = column.setActiveEditor(docId);
if (target != null)
{
setActive(target);
return;
}
}
}
public void setDocsRestored()
{
docsRestored_ = true;
}
public void setOpeningForSourceNavigation(boolean value)
{
openingForSourceNavigation_ = value;
}
public void activateColumns(final Command afterActivation)
{
if (!hasActiveEditor())
{
if (activeColumn_ == null)
setActive(MAIN_SOURCE_NAME);
newDoc(FileTypeRegistry.R, new ResultCallback<EditingTarget, ServerError>()
{
@Override
public void onSuccess(EditingTarget target)
{
setActive(target);
doActivateSource(afterActivation);
}
});
}
else
{
doActivateSource(afterActivation);
}
}
// This method sets activeColumn_ to the main column if it is null. It should be used in cases
// where it is better for the column to be the main column than null.
public SourceColumn getActive()
{
if (activeColumn_ != null)
return activeColumn_;
setActive(MAIN_SOURCE_NAME);
return activeColumn_;
}
public String getActiveDocId()
{
if (hasActiveEditor())
return activeColumn_.getActiveEditor().getId();
return null;
}
public String getActiveDocPath()
{
if (hasActiveEditor())
return activeColumn_.getActiveEditor().getPath();
return null;
}
public boolean hasActiveEditor()
{
return activeColumn_ != null && activeColumn_.getActiveEditor() != null;
}
public boolean isActiveEditor(EditingTarget editingTarget)
{
return hasActiveEditor() && activeColumn_.getActiveEditor() == editingTarget;
}
public boolean getDocsRestored()
{
return docsRestored_;
}
// see if there are additional command palette items made available
// by the active editor
public List<CommandPaletteItem> getCommandPaletteItems()
{
if (!hasActiveEditor())
return null;
return activeColumn_.getActiveEditor().getCommandPaletteItems();
}
public int getTabCount()
{
return activeColumn_.getTabCount();
}
public int getPhysicalTabIndex()
{
if (getActive() != null)
return getActive().getPhysicalTabIndex();
else
return -1;
}
public ArrayList<String> getNames(boolean excludeMain)
{
ArrayList<String> result = new ArrayList<>();
columnList_.forEach((column) ->{
if (!excludeMain || !StringUtil.equals(column.getName(), MAIN_SOURCE_NAME))
result.add(column.getName());
});
return result;
}
public ArrayList<Widget> getWidgets(boolean excludeMain)
{
ArrayList<Widget> result = new ArrayList<>();
for (SourceColumn column : columnList_)
{
if (!excludeMain || !StringUtil.equals(column.getName(), MAIN_SOURCE_NAME))
result.add(column.asWidget());
}
return result;
}
public ArrayList<SourceColumn> getColumnList()
{
return columnList_;
}
public Widget getWidget(String name)
{
return getByName(name) == null ? null : getByName(name).asWidget();
}
public Session getSession()
{
return session_;
}
public SourceNavigationHistory getSourceNavigationHistory()
{
return sourceNavigationHistory_;
}
public void recordCurrentNavigationHistoryPosition()
{
if (hasActiveEditor())
activeColumn_.getActiveEditor().recordCurrentNavigationPosition();
}
public String getEditorPositionString()
{
if (hasActiveEditor())
return activeColumn_.getActiveEditor().getCurrentStatus();
return "No document tabs open";
}
public Synctex getSynctex()
{
return synctex_;
}
public UserState getUserState()
{
return userState_;
}
public int getSize()
{
return columnList_.size();
}
public int getUntitledNum(String prefix)
{
AtomicInteger max = new AtomicInteger();
columnList_.forEach((column) ->
max.set(Math.max(max.get(), column.getUntitledNum(prefix))));
return max.intValue();
}
public native final int getUntitledNum(String name, String prefix) /*-{
var match = (new RegExp("^" + prefix + "([0-9]{1,5})$")).exec(name);
if (!match)
return 0;
return parseInt(match[1]);
}-*/;
public void clearSourceNavigationHistory()
{
if (!hasDoc())
sourceNavigationHistory_.clear();
}
public void manageCommands(boolean forceSync)
{
boolean saveAllEnabled = false;
for (SourceColumn column : columnList_)
{
if (column.isInitialized() &&
!StringUtil.equals(activeColumn_.getName(), column.getName()))
column.manageCommands(forceSync, activeColumn_);
// if one document is dirty then we are enabled
if (!saveAllEnabled && column.isSaveCommandActive())
saveAllEnabled = true;
}
// the active column is always managed last because any column can disable a command, but
// only the active one can enable a command
if (activeColumn_.isInitialized())
activeColumn_.manageCommands(forceSync, activeColumn_);
if (!session_.getSessionInfo().getAllowShell())
commands_.sendToTerminal().setVisible(false);
// if source windows are open, managing state of the command becomes
// complicated, so leave it enabled
if (windowManager_.areSourceWindowsOpen())
commands_.saveAllSourceDocs().setEnabled(saveAllEnabled);
manageSourceNavigationCommands();
}
private void manageSourceNavigationCommands()
{
commands_.sourceNavigateBack().setEnabled(
sourceNavigationHistory_.isBackEnabled());
commands_.sourceNavigateBack().setEnabled(
sourceNavigationHistory_.isBackEnabled());
}
public EditingTarget addTab(SourceDocument doc, int mode, SourceColumn column)
{
if (column == null)
column = activeColumn_;
return column.addTab(doc, mode);
}
public EditingTarget addTab(SourceDocument doc, boolean atEnd,
int mode, SourceColumn column)
{
if (column == null)
column = activeColumn_;
return column.addTab(doc, atEnd, mode);
}
public EditingTarget findEditor(String docId)
{
for (SourceColumn column : columnList_)
{
EditingTarget target = column.getDoc(docId);
if (target != null)
return target;
}
return null;
}
public EditingTarget findEditorByPath(String path)
{
if (StringUtil.isNullOrEmpty(path))
return null;
for (SourceColumn column : columnList_)
{
EditingTarget target = column.getEditorWithPath(path);
if (target != null)
return target;
}
return null;
}
public SourceColumn findByDocument(String docId)
{
for (SourceColumn column : columnList_)
{
if (column.hasDoc(docId))
return column;
}
return null;
}
public SourceColumn findByPosition(int x)
{
for (SourceColumn column : columnList_)
{
Widget w = column.asWidget();
int left = w.getAbsoluteLeft();
int right = w.getAbsoluteLeft() + w.getOffsetWidth();
if (x >= left && x <= right)
return column;
}
return null;
}
public boolean isEmpty(String name)
{
return getByName(name) == null || getByName(name).getTabCount() == 0;
}
public boolean attemptTextEditorActivate()
{
if (!(hasActiveEditor() ||
activeColumn_.getActiveEditor() instanceof TextEditingTarget))
return false;
TextEditingTarget editingTarget = (TextEditingTarget) activeColumn_.getActiveEditor();
editingTarget.ensureTextEditorActive(() -> {
getEditorContext(
editingTarget.getId(),
editingTarget.getPath(),
editingTarget.getDocDisplay()
);
});
return true;
}
public void activateCodeBrowser(
final String codeBrowserPath,
boolean replaceIfActive,
final ResultCallback<CodeBrowserEditingTarget, ServerError> callback)
{
// first check to see if this request can be fulfilled with an existing
// code browser tab
EditingTarget target = selectTabWithDocPath(codeBrowserPath);
if (target != null)
{
callback.onSuccess((CodeBrowserEditingTarget) target);
return;
}
// then check to see if the active editor is a code browser -- if it is,
// we'll use it as is, replacing its contents
if (replaceIfActive &&
hasActiveEditor() &&
activeColumn_.getActiveEditor() instanceof CodeBrowserEditingTarget)
{
events_.fireEvent(new CodeBrowserCreatedEvent(activeColumn_.getActiveEditor().getId(),
codeBrowserPath));
callback.onSuccess((CodeBrowserEditingTarget) activeColumn_.getActiveEditor());
return;
}
// create a new one
newDoc(FileTypeRegistry.CODEBROWSER,
new ResultCallback<EditingTarget, ServerError>()
{
@Override
public void onSuccess(EditingTarget arg)
{
events_.fireEvent(new CodeBrowserCreatedEvent(
arg.getId(), codeBrowserPath));
callback.onSuccess((CodeBrowserEditingTarget) arg);
}
@Override
public void onFailure(ServerError error)
{
callback.onFailure(error);
}
@Override
public void onCancelled()
{
callback.onCancelled();
}
});
}
public void activateObjectExplorer(ObjectExplorerHandle handle)
{
columnList_.forEach((column) -> {
for (EditingTarget target : column.getEditors())
{
// bail if this isn't an object explorer filetype
FileType fileType = target.getFileType();
if (!(fileType instanceof ObjectExplorerFileType))
continue;
// check for identical titles
if (handle.getTitle() == target.getTitle())
{
((ObjectExplorerEditingTarget) target).update(handle);
ensureVisible(false);
column.selectTab(target.asWidget());
return;
}
}
});
ensureVisible(true);
server_.newDocument(
FileTypeRegistry.OBJECT_EXPLORER.getTypeId(),
null,
(JsObject) handle.cast(),
new SimpleRequestCallback<SourceDocument>("Show Object Explorer")
{
@Override
public void onResponseReceived(SourceDocument response)
{
activeColumn_.addTab(response, Source.OPEN_INTERACTIVE);
}
});
}
public void showOverflowPopout()
{
ensureVisible(false);
activeColumn_.showOverflowPopout();
}
public void showDataItem(DataItem data)
{
columnList_.forEach((column) -> {
for (EditingTarget target : column.getEditors())
{
String path = target.getPath();
if (path != null && path.equals(data.getURI()))
{
((DataEditingTarget) target).updateData(data);
ensureVisible(false);
column.selectTab(target.asWidget());
return;
}
}
});
ensureVisible(true);
server_.newDocument(
FileTypeRegistry.DATAFRAME.getTypeId(),
null,
(JsObject) data.cast(),
new SimpleRequestCallback<SourceDocument>("Show Data Frame")
{
@Override
public void onResponseReceived(SourceDocument response)
{
activeColumn_.addTab(response, Source.OPEN_INTERACTIVE);
}
});
}
public void showUnsavedChangesDialog(
String title,
ArrayList<UnsavedChangesTarget> dirtyTargets,
OperationWithInput<UnsavedChangesDialog.Result> saveOperation,
Command onCancelled)
{
activeColumn_.showUnsavedChangesDialog(title, dirtyTargets, saveOperation, onCancelled);
}
public boolean insertSource(String code, boolean isBlock)
{
if (!hasActiveEditor())
return false;
return activeColumn_.insertCode(code, isBlock);
}
@Handler
public void onMoveTabRight()
{
activeColumn_.moveTab(activeColumn_.getPhysicalTabIndex(), 1);
}
@Handler
public void onMoveTabLeft()
{
activeColumn_.moveTab(activeColumn_.getPhysicalTabIndex(), -1);
}
@Handler
public void onMoveTabToFirst()
{
activeColumn_.moveTab(activeColumn_.getPhysicalTabIndex(),
activeColumn_.getPhysicalTabIndex() * -1);
}
@Handler
public void onMoveTabToLast()
{
activeColumn_.moveTab(activeColumn_.getPhysicalTabIndex(),
(activeColumn_.getTabCount() -
activeColumn_.getPhysicalTabIndex()) - 1);
}
@Handler
public void onSwitchToTab()
{
if (activeColumn_.getTabCount() == 0)
return;
showOverflowPopout();
}
@Handler
public void onFirstTab()
{
if (activeColumn_.getTabCount() == 0)
return;
ensureVisible(false);
if (activeColumn_.getTabCount() > 0)
activeColumn_.setPhysicalTabIndex(0);
}
@Handler
public void onPreviousTab()
{
switchToTab(-1, userPrefs_.wrapTabNavigation().getValue());
}
@Handler
public void onNextTab()
{
switchToTab(1, userPrefs_.wrapTabNavigation().getValue());
}
@Handler
public void onLastTab()
{
if (activeColumn_.getTabCount() == 0)
return;
activeColumn_.ensureVisible(false);
if (activeColumn_.getTabCount() > 0)
activeColumn_.setPhysicalTabIndex(activeColumn_.getTabCount() - 1);
}
@Handler
public void onCloseSourceDoc()
{
closeSourceDoc(true);
}
@Handler
public void onFindInFiles()
{
String searchPattern = "";
if (hasActiveEditor() && activeColumn_.getActiveEditor() instanceof TextEditingTarget)
{
TextEditingTarget textEditor = (TextEditingTarget) activeColumn_.getActiveEditor();
String selection = textEditor.getSelectedText();
boolean multiLineSelection = selection.indexOf('\n') != -1;
if ((selection.length() != 0) && !multiLineSelection)
searchPattern = selection;
}
events_.fireEvent(new FindInFilesEvent(searchPattern));
}
@Override
public void onDebugModeChanged(DebugModeChangedEvent evt)
{
// when debugging ends, always disengage any active debug highlights
if (!evt.debugging() && hasActiveEditor())
{
activeColumn_.getActiveEditor().endDebugHighlighting();
}
}
@Override
public void onSourceExtendedTypeDetected(SourceExtendedTypeDetectedEvent e)
{
// set the extended type of the specified source file
EditingTarget target = findEditor(e.getDocId());
if (target != null)
target.adaptToExtendedFileType(e.getExtendedType());
}
public void nextTabWithWrap()
{
switchToTab(1, true);
}
public void prevTabWithWrap()
{
switchToTab(-1, true);
}
private void switchToTab(int delta, boolean wrap)
{
if (getActive().getTabCount() == 0)
return;
activeColumn_.ensureVisible(false);
int targetIndex = activeColumn_.getPhysicalTabIndex() + delta;
if (targetIndex > (activeColumn_.getTabCount() - 1))
{
if (wrap)
targetIndex = 0;
else
return;
}
else if (targetIndex < 0)
{
if (wrap)
targetIndex = activeColumn_.getTabCount() - 1;
else
return;
}
activeColumn_.setPhysicalTabIndex(targetIndex);
}
private void doActivateSource(final Command afterActivation)
{
activeColumn_.ensureVisible(false);
if (hasActiveEditor())
{
activeColumn_.getActiveEditor().focus();
activeColumn_.getActiveEditor().ensureCursorVisible();
}
if (afterActivation != null)
afterActivation.execute();
}
// new doc functions
public void newRMarkdownV1Doc()
{
newSourceDocWithTemplate(FileTypeRegistry.RMARKDOWN,
"",
"v1.Rmd",
Position.create(3, 0));
}
public void newRMarkdownV2Doc()
{
rmarkdown_.showNewRMarkdownDialog(
new OperationWithInput<NewRMarkdownDialog.Result>()
{
@Override
public void execute(final NewRMarkdownDialog.Result result)
{
if (result == null)
{
// No document chosen, just create an empty one
newSourceDocWithTemplate(FileTypeRegistry.RMARKDOWN, "", "default.Rmd");
}
else if (result.isNewDocument())
{
NewRMarkdownDialog.RmdNewDocument doc =
result.getNewDocument();
String author = doc.getAuthor();
if (author.length() > 0)
{
userPrefs_.documentAuthor().setGlobalValue(author);
userPrefs_.writeUserPrefs();
}
newRMarkdownV2Doc(doc);
}
else
{
newDocFromRmdTemplate(result);
}
}
});
}
private void newDocFromRmdTemplate(final NewRMarkdownDialog.Result result)
{
final RmdChosenTemplate template = result.getFromTemplate();
if (template.createDir())
{
rmarkdown_.createDraftFromTemplate(template);
return;
}
rmarkdown_.getTemplateContent(template,
new OperationWithInput<String>()
{
@Override
public void execute(final String content)
{
if (content.length() == 0)
globalDisplay_.showErrorMessage("Template Content Missing",
"The template at " + template.getTemplatePath() +
" is missing.");
newDoc(FileTypeRegistry.RMARKDOWN, content, null);
}
});
}
private void newRMarkdownV2Doc(
final NewRMarkdownDialog.RmdNewDocument doc)
{
rmarkdown_.frontMatterToYAML((RmdFrontMatter) doc.getJSOResult().cast(),
null,
new CommandWithArg<String>()
{
@Override
public void execute(final String yaml)
{
String template = "";
// select a template appropriate to the document type we're creating
if (doc.getTemplate().equals(RmdTemplateData.PRESENTATION_TEMPLATE))
template = "presentation.Rmd";
else if (doc.isShiny())
{
if (doc.getFormat().endsWith(
RmdOutputFormat.OUTPUT_PRESENTATION_SUFFIX))
template = "shiny_presentation.Rmd";
else
template = "shiny.Rmd";
}
else
template = "document.Rmd";
newSourceDocWithTemplate(FileTypeRegistry.RMARKDOWN,
"",
template,
Position.create(1, 0),
null,
new TransformerCommand<String>()
{
@Override
public String transform(String input)
{
return RmdFrontMatter.FRONTMATTER_SEPARATOR +
yaml +
RmdFrontMatter.FRONTMATTER_SEPARATOR + "\n" +
input;
}
});
}
});
}
public void newSourceDocWithTemplate(final TextFileType fileType,
String name,
String template)
{
newSourceDocWithTemplate(fileType, name, template, null);
}
public void newSourceDocWithTemplate(final TextFileType fileType,
String name,
String template,
final Position cursorPosition)
{
newSourceDocWithTemplate(fileType, name, template, cursorPosition, null);
}
public void newSourceDocWithTemplate(
final TextFileType fileType,
String name,
String template,
final Position cursorPosition,
final CommandWithArg<EditingTarget> onSuccess)
{
newSourceDocWithTemplate(fileType, name, template, cursorPosition, onSuccess, null);
}
public void startDebug()
{
activeColumn_.setPendingDebugSelection();
}
private EditingTarget selectTabWithDocPath(String path)
{
for (SourceColumn column : columnList_)
{
EditingTarget editor = column.getEditorWithPath(path);
if (editor != null)
{
column.selectTab(editor.asWidget());
return editor;
}
}
return null;
}
private void newSourceDocWithTemplate(
final TextFileType fileType,
String name,
String template,
final Position cursorPosition,
final CommandWithArg<EditingTarget> onSuccess,
final TransformerCommand<String> contentTransformer)
{
final ProgressIndicator indicator = new GlobalProgressDelayer(
globalDisplay_, 500, "Creating new document...").getIndicator();
server_.getSourceTemplate(name,
template,
new ServerRequestCallback<String>()
{
@Override
public void onResponseReceived(String templateContents)
{
indicator.onCompleted();
if (contentTransformer != null)
templateContents = contentTransformer.transform(templateContents);
newDoc(fileType,
templateContents,
new ResultCallback<EditingTarget, ServerError>()
{
@Override
public void onSuccess(EditingTarget target)
{
if (cursorPosition != null)
target.setCursorPosition(cursorPosition);
if (onSuccess != null)
onSuccess.execute(target);
}
});
}
@Override
public void onError(ServerError error)
{
indicator.onError(error.getUserMessage());
}
});
}
public void newDoc(EditableFileType fileType,
ResultCallback<EditingTarget, ServerError> callback)
{
getActive().newDoc(fileType, callback);
}
public void newDoc(EditableFileType fileType,
final String contents,
final ResultCallback<EditingTarget, ServerError> resultCallback)
{
getActive().newDoc(fileType, contents, resultCallback);
}
public void disownDoc(String docId)
{
SourceColumn column = findByDocument(docId);
column.closeDoc(docId);
}
// When dragging between columns/windows, we need to be specific about which column we're
// removing the document from as it may exist in more than one column. If the column is null,
// it is assumed that we are a satellite window and do not have multiple displays.
public void disownDocOnDrag(String docId, SourceColumn column)
{
if (column == null)
{
if (getSize() > 1)
Debug.logWarning("Warning: No column was provided to remove the doc from.");
column = getActive();
}
column.closeDoc(docId);
column.cancelTabDrag();
}
public void selectTab(EditingTarget target)
{
SourceColumn column = findByDocument(target.getId());
column.ensureVisible(false);
column.selectTab(target.asWidget());
}
public void closeTabs(JsArrayString ids)
{
if (ids != null)
columnList_.forEach((column) -> column.closeTabs(ids));
}
public void closeTabWithPath(String path, boolean interactive)
{
EditingTarget target = findEditorByPath(path);
closeTab(target, interactive);
}
public void closeTab(boolean interactive)
{
closeTab(activeColumn_.getActiveEditor(), interactive);
}
public void closeTab(EditingTarget target, boolean interactive)
{
findByDocument(target.getId()).closeTab(target.asWidget(), interactive, null);
}
public void closeTab(EditingTarget target, boolean interactive, Command onClosed)
{
findByDocument(target.getId()).closeTab(
target.asWidget(), interactive, onClosed);
}
public void closeAllTabs(boolean excludeActive, boolean excludeMain)
{
columnList_.forEach((column) -> closeAllTabs(column, excludeActive, excludeMain));
}
public void closeAllTabs(SourceColumn column, boolean excludeActive, boolean excludeMain)
{
if (!excludeMain || !StringUtil.equals(column.getName(), MAIN_SOURCE_NAME))
{
cpsExecuteForEachEditor(column.getEditors(),
new CPSEditingTargetCommand()
{
@Override
public void execute(EditingTarget target, Command continuation)
{
if (excludeActive && target == activeColumn_.getActiveEditor())
{
continuation.execute();
return;
}
else
{
column.closeTab(target.asWidget(), false, continuation);
}
}
});
}
}
void closeSourceDoc(boolean interactive)
{
if (activeColumn_.getTabCount() == 0)
return;
closeTab(interactive);
}
public void saveAllSourceDocs()
{
columnList_.forEach((column) -> cpsExecuteForEachEditor(
column.getEditors(),
(editingTarget, continuation) -> {
if (editingTarget.dirtyState().getValue())
{
editingTarget.save(continuation);
}
else
{
continuation.execute();
}
}));
}
public void revertUnsavedTargets(Command onCompleted)
{
ArrayList<EditingTarget> unsavedTargets = new ArrayList<>();
columnList_.forEach((column) -> unsavedTargets.addAll(
column.getUnsavedEditors(Source.TYPE_FILE_BACKED, null)));
// revert all of them
cpsExecuteForEachEditor(
// targets the user chose not to save
unsavedTargets,
// save each editor
(saveTarget, continuation) -> {
if (saveTarget.getPath() != null)
{
// file backed document -- revert it
saveTarget.revertChanges(continuation);
}
else
{
// untitled document -- just close the tab non-interactively
closeTab(saveTarget, false, continuation);
}
},
// onCompleted at the end
onCompleted
);
}
public void closeAllLocalSourceDocs(String caption,
SourceColumn sourceColumn,
Command onCompleted,
final boolean excludeActive)
{
// save active editor for exclusion (it changes as we close tabs)
final EditingTarget excludeEditor = (excludeActive) ? activeColumn_.getActiveEditor() :
null;
// collect up a list of dirty documents
ArrayList<EditingTarget> dirtyTargets = new ArrayList<>();
// if sourceColumn is not provided, assume we are closing editors for every column
if (sourceColumn == null)
columnList_.forEach((column) ->
dirtyTargets.addAll(column.getDirtyEditors(excludeEditor)));
else
dirtyTargets.addAll(sourceColumn.getDirtyEditors(excludeEditor));
// create a command used to close all tabs
final Command closeAllTabsCommand = sourceColumn == null ?
() -> closeAllTabs(excludeActive, false) :
() -> closeAllTabs(sourceColumn, excludeActive, false);
saveEditingTargetsWithPrompt(caption,
dirtyTargets,
CommandUtil.join(closeAllTabsCommand,
onCompleted),
null);
}
public void consolidateColumns(int num)
{
if (num >= columnList_.size() || num < 1)
return;
for (SourceColumn column : columnList_)
{
if (!column.hasDoc())
{
closeColumn(column.getName());
if (num >= columnList_.size() || num == 1)
break;
}
}
// if we could not remove empty columns to get to the desired amount, consolidate editors
ArrayList<SourceDocument> moveEditors = new ArrayList<>();
SourceColumn mainColumn = getByName(MAIN_SOURCE_NAME);
if (num < columnList_.size())
{
CPSEditingTargetCommand moveCommand = new CPSEditingTargetCommand()
{
@Override
public void execute(EditingTarget editingTarget, Command continuation)
{
}
};
ArrayList<SourceColumn> moveColumns = new ArrayList<>(columnList_);
moveColumns.remove(mainColumn);
int additionalColumnCount = num - 1;
if (num > 1 &&
moveColumns.size() != additionalColumnCount)
moveColumns = new ArrayList<>(moveColumns.subList(0,
moveColumns.size() - additionalColumnCount));
for (SourceColumn column : moveColumns)
{
ArrayList<EditingTarget> editors = column.getEditors();
for (EditingTarget target : editors)
{
server_.getSourceDocument(target.getId(),
new ServerRequestCallback<SourceDocument>()
{
@Override
public void onResponseReceived(final SourceDocument doc)
{
mainColumn.addTab(doc, Source.OPEN_INTERACTIVE);
}
@Override
public void onError(ServerError error)
{
globalDisplay_.showErrorMessage("Document Tab Move Failed",
"Couldn't move the tab to this window: \n" +
error.getMessage());
}
});
}
closeColumn(column, true);
}
}
columnState_ = State.createState(JsUtil.toJsArrayString(getNames(false)));
}
public void closeColumn(String name)
{
SourceColumn column = getByName(name);
if (column.getTabCount() > 0)
return;
if (column == activeColumn_)
setActive(MAIN_SOURCE_NAME);
columnList_.remove(column);
columnState_ = State.createState(JsUtil.toJsArrayString(getNames(false)));
}
public void closeColumn(SourceColumn column, boolean force)
{
if (column.getTabCount() > 0)
{
if (!force)
return;
else
{
for (EditingTarget target : column.getEditors())
column.closeDoc(target.getId());
}
}
if (column == activeColumn_)
setActive("");
columnList_.remove(column);
columnState_ = State.createState(JsUtil.toJsArrayString(getNames(false)));
}
public void ensureVisible(boolean newTabPending)
{
if (getActive() == null)
return;
getActive().ensureVisible(newTabPending);
}
public void openFile(FileSystemItem file)
{
openFile(file, fileTypeRegistry_.getTextTypeForFile(file));
}
public void openFile(FileSystemItem file, TextFileType fileType)
{
openFile(file,
fileType,
new CommandWithArg<EditingTarget>()
{
@Override
public void execute(EditingTarget arg)
{
}
});
}
public void openFile(final FileSystemItem file,
final TextFileType fileType,
final CommandWithArg<EditingTarget> executeOnSuccess)
{
// add this work to the queue
openFileQueue_.add(new OpenFileEntry(file, fileType, executeOnSuccess));
// begin queue processing if it's the only work in the queue
if (openFileQueue_.size() == 1)
processOpenFileQueue();
}
private void editFile(final String path)
{
server_.ensureFileExists(
path,
new ServerRequestCallback<Boolean>()
{
@Override
public void onResponseReceived(Boolean success)
{
if (success)
{
FileSystemItem file = FileSystemItem.createFile(path);
openFile(file);
}
}
@Override
public void onError(ServerError error)
{
Debug.logError(error);
}
});
}
public void openProjectDocs(final Session session, boolean mainColumn)
{
if (mainColumn && activeColumn_ != getByName(MAIN_SOURCE_NAME))
setActive(MAIN_SOURCE_NAME);
JsArrayString openDocs = session.getSessionInfo().getProjectOpenDocs();
if (openDocs.length() > 0)
{
// set new tab pending for the duration of the continuation
activeColumn_.incrementNewTabPending();
// create a continuation for opening the source docs
SerializedCommandQueue openCommands = new SerializedCommandQueue();
for (int i = 0; i < openDocs.length(); i++)
{
String doc = openDocs.get(i);
final FileSystemItem fsi = FileSystemItem.createFile(doc);
openCommands.addCommand(new SerializedCommand()
{
@Override
public void onExecute(final Command continuation)
{
openFile(fsi,
fileTypeRegistry_.getTextTypeForFile(fsi),
new CommandWithArg<EditingTarget>()
{
@Override
public void execute(EditingTarget arg)
{
continuation.execute();
}
});
}
});
}
// decrement newTabPending and select first tab when done
openCommands.addCommand(new SerializedCommand()
{
@Override
public void onExecute(Command continuation)
{
activeColumn_.decrementNewTabPending();
onFirstTab();
continuation.execute();
}
});
// execute the continuation
openCommands.run();
}
}
public void fireDocTabsChanged()
{
activeColumn_.fireDocTabsChanged();
}
private boolean hasDoc()
{
for (SourceColumn column : columnList_)
{
if (column.hasDoc())
return true;
}
return false;
}
private void vimSetTabIndex(int index)
{
int tabCount = activeColumn_.getTabCount();
if (index >= tabCount)
return;
activeColumn_.setPhysicalTabIndex(index);
}
private void processOpenFileQueue()
{
// no work to do
if (openFileQueue_.isEmpty())
return;
// find the first work unit
final OpenFileEntry entry = openFileQueue_.peek();
// define command to advance queue
final Command processNextEntry = new Command()
{
@Override
public void execute()
{
openFileQueue_.remove();
if (!openFileQueue_.isEmpty())
processOpenFileQueue();
}
};
openFile(
entry.file,
entry.fileType,
new ResultCallback<EditingTarget, ServerError>()
{
@Override
public void onSuccess(EditingTarget target)
{
processNextEntry.execute();
if (entry.executeOnSuccess != null)
entry.executeOnSuccess.execute(target);
}
@Override
public void onCancelled()
{
super.onCancelled();
processNextEntry.execute();
}
@Override
public void onFailure(ServerError error)
{
String message = error.getUserMessage();
// see if a special message was provided
JSONValue errValue = error.getClientInfo();
if (errValue != null)
{
JSONString errMsg = errValue.isString();
if (errMsg != null)
message = errMsg.stringValue();
}
globalDisplay_.showMessage(GlobalDisplay.MSG_ERROR,
"Error while opening file",
message);
processNextEntry.execute();
}
});
}
public void openFile(FileSystemItem file,
final ResultCallback<EditingTarget, ServerError> resultCallback)
{
openFile(file, fileTypeRegistry_.getTextTypeForFile(file), resultCallback);
}
// top-level wrapper for opening files. takes care of:
// - making sure the view is visible
// - checking whether it is already open and re-selecting its tab
// - prohibit opening very large files (>500KB)
// - confirmation of opening large files (>100KB)
// - finally, actually opening the file from the server
// via the call to the lower level openFile method
public void openFile(final FileSystemItem file,
final TextFileType fileType,
final ResultCallback<EditingTarget, ServerError> resultCallback)
{
activeColumn_.ensureVisible(true);
if (fileType.isRNotebook())
{
openNotebook(file, resultCallback);
return;
}
if (file == null)
{
newDoc(fileType, resultCallback);
return;
}
if (openFileAlreadyOpen(file, resultCallback))
return;
EditingTarget target = editingTargetSource_.getEditingTarget(fileType);
if (file.getLength() > target.getFileSizeLimit())
{
if (resultCallback != null)
resultCallback.onCancelled();
showFileTooLargeWarning(file, target.getFileSizeLimit());
}
else if (file.getLength() > target.getLargeFileSize())
{
confirmOpenLargeFile(file, new Operation()
{
public void execute()
{
openFileFromServer(file, fileType, resultCallback);
}
}, new Operation()
{
public void execute()
{
// user (wisely) cancelled
if (resultCallback != null)
resultCallback.onCancelled();
}
});
}
else
{
openFileFromServer(file, fileType, resultCallback);
}
}
public void openNotebook(
final FileSystemItem rmdFile,
final SourceDocumentResult doc,
final ResultCallback<EditingTarget, ServerError> resultCallback)
{
if (!StringUtil.isNullOrEmpty(doc.getDocPath()))
{
// this happens if we created the R Markdown file, or if the R Markdown
// file on disk matched the one inside the notebook
openFileFromServer(rmdFile,
FileTypeRegistry.RMARKDOWN, resultCallback);
}
else if (!StringUtil.isNullOrEmpty(doc.getDocId()))
{
// this happens when we have to open an untitled buffer for the the
// notebook (usually because the of a conflict between the Rmd on disk
// and the one in the .nb.html file)
server_.getSourceDocument(doc.getDocId(),
new ServerRequestCallback<SourceDocument>()
{
@Override
public void onResponseReceived(SourceDocument doc)
{
// create the editor
EditingTarget target = getActive().addTab(doc, Source.OPEN_INTERACTIVE);
// show a warning bar
if (target instanceof TextEditingTarget)
{
((TextEditingTarget) target).showWarningMessage(
"This notebook has the same name as an R Markdown " +
"file, but doesn't match it.");
}
resultCallback.onSuccess(target);
}
@Override
public void onError(ServerError error)
{
globalDisplay_.showErrorMessage(
"Notebook Open Failed",
"This notebook could not be opened. " +
"If the error persists, try removing the " +
"accompanying R Markdown file. \n\n" +
error.getMessage());
resultCallback.onFailure(error);
}
});
}
}
public void beforeShow()
{
columnList_.forEach((column) -> column.onBeforeShow());
}
public void beforeShow(String name)
{
SourceColumn column = getByName(name);
if (column == null)
{
Debug.logWarning("WARNING: Unknown column " + name);
return;
}
column.onBeforeShow();
}
public void inEditorForId(String id, OperationWithInput<EditingTarget> onEditorLocated)
{
EditingTarget editor = findEditor(id);
if (editor != null)
onEditorLocated.execute(editor);
}
public void inEditorForPath(String path, OperationWithInput<EditingTarget> onEditorLocated)
{
EditingTarget editor = findEditorByPath(path);
if (editor != null)
onEditorLocated.execute(editor);
}
public void withTarget(String id, CommandWithArg<TextEditingTarget> command)
{
withTarget(id, command, null);
}
public void withTarget(String id,
CommandWithArg<TextEditingTarget> command,
Command onFailure)
{
EditingTarget target = StringUtil.isNullOrEmpty(id)
? activeColumn_.getActiveEditor()
: findEditor(id);
if (target == null)
{
if (onFailure != null)
onFailure.execute();
return;
}
if (!(target instanceof TextEditingTarget))
{
if (onFailure != null)
onFailure.execute();
return;
}
command.execute((TextEditingTarget) target);
}
public HashSet<AppCommand> getDynamicCommands()
{
return dynamicCommands_;
}
private void getEditorContext(String id, String path, DocDisplay docDisplay)
{
getEditorContext(id, path, docDisplay, server_);
}
public static void getEditorContext(String id, String path, DocDisplay docDisplay,
SourceServerOperations server)
{
AceEditor editor = (AceEditor) docDisplay;
Selection selection = editor.getNativeSelection();
Range[] ranges = selection.getAllRanges();
// clamp ranges to document boundaries
for (Range range : ranges)
{
Position start = range.getStart();
start.setRow(MathUtil.clamp(start.getRow(), 0, editor.getRowCount()));
start.setColumn(MathUtil.clamp(start.getColumn(), 0, editor.getLine(start.getRow()).length()));
Position end = range.getEnd();
end.setRow(MathUtil.clamp(end.getRow(), 0, editor.getRowCount()));
end.setColumn(MathUtil.clamp(end.getColumn(), 0, editor.getLine(end.getRow()).length()));
}
JsArray<GetEditorContextEvent.DocumentSelection> docSelections = JavaScriptObject.createArray().cast();
for (Range range : ranges)
{
docSelections.push(GetEditorContextEvent.DocumentSelection.create(
range,
editor.getTextForRange(range)));
}
id = StringUtil.notNull(id);
path = StringUtil.notNull(path);
GetEditorContextEvent.SelectionData data =
GetEditorContextEvent.SelectionData.create(id, path, editor.getCode(), docSelections);
server.getEditorContextCompleted(data, new VoidServerRequestCallback());
}
private void initDynamicCommands()
{
dynamicCommands_ = new HashSet<>();
dynamicCommands_.add(commands_.saveSourceDoc());
dynamicCommands_.add(commands_.reopenSourceDocWithEncoding());
dynamicCommands_.add(commands_.saveSourceDocAs());
dynamicCommands_.add(commands_.saveSourceDocWithEncoding());
dynamicCommands_.add(commands_.printSourceDoc());
dynamicCommands_.add(commands_.vcsFileLog());
dynamicCommands_.add(commands_.vcsFileDiff());
dynamicCommands_.add(commands_.vcsFileRevert());
dynamicCommands_.add(commands_.executeCode());
dynamicCommands_.add(commands_.executeCodeWithoutFocus());
dynamicCommands_.add(commands_.executeAllCode());
dynamicCommands_.add(commands_.executeToCurrentLine());
dynamicCommands_.add(commands_.executeFromCurrentLine());
dynamicCommands_.add(commands_.executeCurrentFunction());
dynamicCommands_.add(commands_.executeCurrentSection());
dynamicCommands_.add(commands_.executeLastCode());
dynamicCommands_.add(commands_.insertChunk());
dynamicCommands_.add(commands_.insertSection());
dynamicCommands_.add(commands_.executeSetupChunk());
dynamicCommands_.add(commands_.executePreviousChunks());
dynamicCommands_.add(commands_.executeSubsequentChunks());
dynamicCommands_.add(commands_.executeCurrentChunk());
dynamicCommands_.add(commands_.executeNextChunk());
dynamicCommands_.add(commands_.previewJS());
dynamicCommands_.add(commands_.previewSql());
dynamicCommands_.add(commands_.sourceActiveDocument());
dynamicCommands_.add(commands_.sourceActiveDocumentWithEcho());
dynamicCommands_.add(commands_.knitDocument());
dynamicCommands_.add(commands_.toggleRmdVisualMode());
dynamicCommands_.add(commands_.enableProsemirrorDevTools());
dynamicCommands_.add(commands_.previewHTML());
dynamicCommands_.add(commands_.compilePDF());
dynamicCommands_.add(commands_.compileNotebook());
dynamicCommands_.add(commands_.synctexSearch());
dynamicCommands_.add(commands_.popoutDoc());
dynamicCommands_.add(commands_.returnDocToMain());
dynamicCommands_.add(commands_.findReplace());
dynamicCommands_.add(commands_.findNext());
dynamicCommands_.add(commands_.findPrevious());
dynamicCommands_.add(commands_.findFromSelection());
dynamicCommands_.add(commands_.replaceAndFind());
dynamicCommands_.add(commands_.extractFunction());
dynamicCommands_.add(commands_.extractLocalVariable());
dynamicCommands_.add(commands_.commentUncomment());
dynamicCommands_.add(commands_.reindent());
dynamicCommands_.add(commands_.reflowComment());
dynamicCommands_.add(commands_.jumpTo());
dynamicCommands_.add(commands_.jumpToMatching());
dynamicCommands_.add(commands_.goToHelp());
dynamicCommands_.add(commands_.goToDefinition());
dynamicCommands_.add(commands_.setWorkingDirToActiveDoc());
dynamicCommands_.add(commands_.debugDumpContents());
dynamicCommands_.add(commands_.debugImportDump());
dynamicCommands_.add(commands_.goToLine());
dynamicCommands_.add(commands_.checkSpelling());
dynamicCommands_.add(commands_.wordCount());
dynamicCommands_.add(commands_.codeCompletion());
dynamicCommands_.add(commands_.findUsages());
dynamicCommands_.add(commands_.debugBreakpoint());
dynamicCommands_.add(commands_.vcsViewOnGitHub());
dynamicCommands_.add(commands_.vcsBlameOnGitHub());
dynamicCommands_.add(commands_.editRmdFormatOptions());
dynamicCommands_.add(commands_.reformatCode());
dynamicCommands_.add(commands_.showDiagnosticsActiveDocument());
dynamicCommands_.add(commands_.renameInScope());
dynamicCommands_.add(commands_.insertRoxygenSkeleton());
dynamicCommands_.add(commands_.expandSelection());
dynamicCommands_.add(commands_.shrinkSelection());
dynamicCommands_.add(commands_.toggleDocumentOutline());
dynamicCommands_.add(commands_.knitWithParameters());
dynamicCommands_.add(commands_.clearKnitrCache());
dynamicCommands_.add(commands_.goToNextSection());
dynamicCommands_.add(commands_.goToPrevSection());
dynamicCommands_.add(commands_.goToNextChunk());
dynamicCommands_.add(commands_.goToPrevChunk());
dynamicCommands_.add(commands_.profileCode());
dynamicCommands_.add(commands_.profileCodeWithoutFocus());
dynamicCommands_.add(commands_.saveProfileAs());
dynamicCommands_.add(commands_.restartRClearOutput());
dynamicCommands_.add(commands_.restartRRunAllChunks());
dynamicCommands_.add(commands_.notebookCollapseAllOutput());
dynamicCommands_.add(commands_.notebookExpandAllOutput());
dynamicCommands_.add(commands_.notebookClearOutput());
dynamicCommands_.add(commands_.notebookClearAllOutput());
dynamicCommands_.add(commands_.notebookToggleExpansion());
dynamicCommands_.add(commands_.sendToTerminal());
dynamicCommands_.add(commands_.openNewTerminalAtEditorLocation());
dynamicCommands_.add(commands_.sendFilenameToTerminal());
dynamicCommands_.add(commands_.renameSourceDoc());
dynamicCommands_.add(commands_.sourceAsLauncherJob());
dynamicCommands_.add(commands_.sourceAsJob());
dynamicCommands_.add(commands_.runSelectionAsJob());
dynamicCommands_.add(commands_.runSelectionAsLauncherJob());
dynamicCommands_.add(commands_.toggleSoftWrapMode());
for (AppCommand command : dynamicCommands_)
{
command.setVisible(false);
command.setEnabled(false);
}
}
public void initVimCommands()
{
vimCommands_.save(this);
vimCommands_.selectTabIndex(this);
vimCommands_.selectNextTab(this);
vimCommands_.selectPreviousTab(this);
vimCommands_.closeActiveTab(this);
vimCommands_.closeAllTabs(this);
vimCommands_.createNewDocument(this);
vimCommands_.saveAndCloseActiveTab(this);
vimCommands_.readFile(this, userPrefs_.defaultEncoding().getValue());
vimCommands_.runRScript(this);
vimCommands_.reflowText(this);
vimCommands_.showVimHelp(
RStudioGinjector.INSTANCE.getShortcutViewer());
vimCommands_.showHelpAtCursor(this);
vimCommands_.reindent(this);
vimCommands_.expandShrinkSelection(this);
vimCommands_.openNextFile(this);
vimCommands_.openPreviousFile(this);
vimCommands_.addStarRegister();
}
public SourceAppCommand getSourceCommand(AppCommand command, SourceColumn column)
{
// check if we've already create a SourceAppCommand for this command
String key = command.getId() + column.getName();
if (sourceAppCommands_.get(key) != null)
return sourceAppCommands_.get(key);
// if not found, create it
SourceAppCommand sourceCommand =
new SourceAppCommand(command, column.getName(), this);
sourceAppCommands_.put(key, sourceCommand);
return sourceCommand;
}
private void openNotebook(final FileSystemItem rnbFile,
final ResultCallback<EditingTarget, ServerError> resultCallback)
{
// construct path to .Rmd
final String rnbPath = rnbFile.getPath();
final String rmdPath = FilePathUtils.filePathSansExtension(rnbPath) + ".Rmd";
final FileSystemItem rmdFile = FileSystemItem.createFile(rmdPath);
// if we already have associated .Rmd file open, then just edit it
// TODO: should we perform conflict resolution here as well?
if (openFileAlreadyOpen(rmdFile, resultCallback))
return;
// ask the server to extract the .Rmd, then open that
Command extractRmdCommand = new Command()
{
@Override
public void execute()
{
server_.extractRmdFromNotebook(
rnbPath,
new ServerRequestCallback<SourceDocumentResult>()
{
@Override
public void onResponseReceived(SourceDocumentResult doc)
{
openNotebook(rmdFile, doc, resultCallback);
}
@Override
public void onError(ServerError error)
{
globalDisplay_.showErrorMessage("Notebook Open Failed",
"This notebook could not be opened. \n\n" +
error.getMessage());
resultCallback.onFailure(error);
}
});
}
};
dependencyManager_.withRMarkdown("R Notebook", "Using R Notebooks", extractRmdCommand);
}
private void openFileFromServer(
final FileSystemItem file,
final TextFileType fileType,
final ResultCallback<EditingTarget, ServerError> resultCallback)
{
final Command dismissProgress = globalDisplay_.showProgress(
"Opening file...");
server_.openDocument(
file.getPath(),
fileType.getTypeId(),
userPrefs_.defaultEncoding().getValue(),
new ServerRequestCallback<SourceDocument>()
{
@Override
public void onError(ServerError error)
{
dismissProgress.execute();
pMruList_.get().remove(file.getPath());
Debug.logError(error);
if (resultCallback != null)
resultCallback.onFailure(error);
}
@Override
public void onResponseReceived(SourceDocument document)
{
// apply (dynamic) doc property defaults
SourceColumn.applyDocPropertyDefaults(document, false, userPrefs_);
// if we are opening for a source navigation then we
// need to force Rmds into source mode
if (openingForSourceNavigation_)
{
document.getProperties().setString(
TextEditingTarget.RMD_VISUAL_MODE,
DocUpdateSentinel.PROPERTY_FALSE
);
}
dismissProgress.execute();
pMruList_.get().add(document.getPath());
EditingTarget target = getActive().addTab(document, Source.OPEN_INTERACTIVE);
if (resultCallback != null)
resultCallback.onSuccess(target);
}
});
}
private boolean openFileAlreadyOpen(final FileSystemItem file,
final ResultCallback<EditingTarget, ServerError> resultCallback)
{
for (SourceColumn column : columnList_)
{
// check to see if any local editors have the file open
for (int i = 0; i < column.getEditors().size(); i++)
{
EditingTarget target = column.getEditors().get(i);
String thisPath = target.getPath();
if (thisPath != null
&& thisPath.equalsIgnoreCase(file.getPath()))
{
column.selectTab(target.asWidget());
pMruList_.get().add(thisPath);
if (resultCallback != null)
resultCallback.onSuccess(target);
return true;
}
}
}
return false;
}
private void showFileTooLargeWarning(FileSystemItem file,
long sizeLimit)
{
StringBuilder msg = new StringBuilder();
msg.append("The file '" + file.getName() + "' is too ");
msg.append("large to open in the source editor (the file is ");
msg.append(StringUtil.formatFileSize(file.getLength()) + " and the ");
msg.append("maximum file size is ");
msg.append(StringUtil.formatFileSize(sizeLimit) + ")");
globalDisplay_.showMessage(GlobalDisplay.MSG_WARNING,
"Selected File Too Large",
msg.toString());
}
private void confirmOpenLargeFile(FileSystemItem file,
Operation openOperation,
Operation noOperation)
{
StringBuilder msg = new StringBuilder();
msg.append("The source file '" + file.getName() + "' is large (");
msg.append(StringUtil.formatFileSize(file.getLength()) + ") ");
msg.append("and may take some time to open. ");
msg.append("Are you sure you want to continue opening it?");
globalDisplay_.showYesNoMessage(GlobalDisplay.MSG_WARNING,
"Confirm Open",
msg.toString(),
false, // Don't include cancel
openOperation,
noOperation,
false); // 'No' is default
}
private void saveEditingTargetsWithPrompt(
String title,
ArrayList<EditingTarget> editingTargets,
final Command onCompleted,
final Command onCancelled)
{
// execute on completed right away if the list is empty
if (editingTargets.size() == 0)
{
onCompleted.execute();
}
// if there is just one thing dirty then go straight to the save dialog
else if (editingTargets.size() == 1)
{
editingTargets.get(0).saveWithPrompt(onCompleted, onCancelled);
}
// otherwise use the multi save changes dialog
else
{
// convert to UnsavedChangesTarget collection
ArrayList<UnsavedChangesTarget> unsavedTargets =
new ArrayList<>(editingTargets);
// show dialog
showUnsavedChangesDialog(
title,
unsavedTargets,
new OperationWithInput<UnsavedChangesDialog.Result>()
{
@Override
public void execute(UnsavedChangesDialog.Result result)
{
saveChanges(result.getSaveTargets(), onCompleted);
}
},
onCancelled);
}
}
public ArrayList<UnsavedChangesTarget> getUnsavedChanges(int type, Set<String> ids)
{
ArrayList<UnsavedChangesTarget> targets = new ArrayList<>();
columnList_.forEach((column) -> targets.addAll(column.getUnsavedEditors(type, ids)));
return targets;
}
public void saveChanges(ArrayList<UnsavedChangesTarget> targets,
Command onCompleted)
{
// convert back to editing targets
ArrayList<EditingTarget> saveTargets = new ArrayList<>();
for (UnsavedChangesTarget target: targets)
{
EditingTarget saveTarget =
findEditor(target.getId());
if (saveTarget != null)
saveTargets.add(saveTarget);
}
CPSEditingTargetCommand saveCommand =
new CPSEditingTargetCommand()
{
@Override
public void execute(EditingTarget saveTarget,
Command continuation)
{
saveTarget.save(continuation);
}
};
// execute the save
cpsExecuteForEachEditor(
// targets the user chose to save
saveTargets,
// save each editor
saveCommand,
// onCompleted at the end
onCompleted
);
}
private void pasteFileContentsAtCursor(final String path, final String encoding)
{
if (activeColumn_ == null)
return;
EditingTarget activeEditor = activeColumn_.getActiveEditor();
if (activeEditor instanceof TextEditingTarget)
{
final TextEditingTarget target = (TextEditingTarget) activeEditor;
server_.getFileContents(path, encoding, new ServerRequestCallback<String>()
{
@Override
public void onResponseReceived(String content)
{
target.insertCode(content, false);
}
@Override
public void onError(ServerError error)
{
Debug.logError(error);
}
});
}
}
private void pasteRCodeExecutionResult(final String code)
{
server_.executeRCode(code, new ServerRequestCallback<String>()
{
@Override
public void onResponseReceived(String output)
{
if (hasActiveEditor() &&
activeColumn_.getActiveEditor() instanceof TextEditingTarget)
{
TextEditingTarget editor = (TextEditingTarget) activeColumn_.getActiveEditor();
editor.insertCode(output, false);
}
}
@Override
public void onError(ServerError error)
{
Debug.logError(error);
}
});
}
private void reflowText()
{
if (hasActiveEditor() &&
activeColumn_.getActiveEditor() instanceof TextEditingTarget)
{
TextEditingTarget editor = (TextEditingTarget) activeColumn_.getActiveEditor();
editor.reflowText();
}
}
private void reindent()
{
if (hasActiveEditor() &&
activeColumn_.getActiveEditor() instanceof TextEditingTarget)
{
TextEditingTarget editor = (TextEditingTarget) activeColumn_.getActiveEditor();
editor.getDocDisplay().reindent();
}
}
private void saveActiveSourceDoc()
{
if (hasActiveEditor() &&
activeColumn_.getActiveEditor() instanceof TextEditingTarget)
{
TextEditingTarget target = (TextEditingTarget) activeColumn_.getActiveEditor();
target.save();
}
}
private void saveAndCloseActiveSourceDoc()
{
if (hasActiveEditor() &&
activeColumn_.getActiveEditor() instanceof TextEditingTarget)
{
TextEditingTarget target = (TextEditingTarget) activeColumn_.getActiveEditor();
target.save(new Command()
{
@Override
public void execute()
{
onCloseSourceDoc();
}
});
}
}
private void revertActiveDocument()
{
if (!hasActiveEditor())
return;
if (activeColumn_.getActiveEditor().getPath() != null)
activeColumn_.getActiveEditor().revertChanges(null);
// Ensure that the document is in view
activeColumn_.getActiveEditor().ensureCursorVisible();
}
private void showHelpAtCursor()
{
if (hasActiveEditor() &&
activeColumn_.getActiveEditor() instanceof TextEditingTarget)
{
TextEditingTarget editor = (TextEditingTarget) activeColumn_.getActiveEditor();
editor.showHelpAtCursor();
}
}
/**
* Execute the given command for each editor, using continuation-passing
* style. When executed, the CPSEditingTargetCommand needs to execute its
* own Command parameter to continue the iteration.
* @param command The command to run on each EditingTarget
*/
private void cpsExecuteForEachEditor(ArrayList<EditingTarget> editors,
final CPSEditingTargetCommand command,
final Command completedCommand)
{
SerializedCommandQueue queue = new SerializedCommandQueue();
// Clone editors_, since the original may be mutated during iteration
for (final EditingTarget editor : new ArrayList<>(editors))
{
queue.addCommand(new SerializedCommand()
{
@Override
public void onExecute(Command continuation)
{
command.execute(editor, continuation);
}
});
}
if (completedCommand != null)
{
queue.addCommand(new SerializedCommand() {
public void onExecute(Command continuation)
{
completedCommand.execute();
continuation.execute();
}
});
}
}
public SourceColumn getByName(String name)
{
for (SourceColumn column : columnList_)
{
if (StringUtil.equals(column.getName(), name))
return column;
}
return null;
}
private boolean contains(String name)
{
for (SourceColumn column : columnList_)
{
if (StringUtil.equals(column.getName(), name))
return true;
}
return false;
}
private void cpsExecuteForEachEditor(ArrayList<EditingTarget> editors,
final CPSEditingTargetCommand command)
{
cpsExecuteForEachEditor(editors, command, null);
}
private static class OpenFileEntry
{
public OpenFileEntry(FileSystemItem fileIn, TextFileType fileTypeIn,
CommandWithArg<EditingTarget> executeIn)
{
file = fileIn;
fileType = fileTypeIn;
executeOnSuccess = executeIn;
}
public final FileSystemItem file;
public final TextFileType fileType;
public final CommandWithArg<EditingTarget> executeOnSuccess;
}
private State columnState_;
private SourceColumn activeColumn_;
private boolean openingForSourceNavigation_ = false;
private boolean docsRestored_ = false;
private final Queue<OpenFileEntry> openFileQueue_ = new LinkedList<>();
private final ArrayList<SourceColumn> columnList_ = new ArrayList<>();
private HashSet<AppCommand> dynamicCommands_ = new HashSet<>();
private HashMap<String, SourceAppCommand> sourceAppCommands_ = new HashMap<>();
private SourceVimCommands vimCommands_;
private Commands commands_;
private EventBus events_;
private Provider<FileMRUList> pMruList_;
private SourceWindowManager windowManager_;
private Session session_;
private Synctex synctex_;
private UserPrefs userPrefs_;
private UserState userState_;
private GlobalDisplay globalDisplay_;
private TextEditingTargetRMarkdownHelper rmarkdown_;
private EditingTargetSource editingTargetSource_;
private FileTypeRegistry fileTypeRegistry_;
private SourceServerOperations server_;
private DependencyManager dependencyManager_;
private final SourceNavigationHistory sourceNavigationHistory_ =
new SourceNavigationHistory(30);
public final static String COLUMN_PREFIX = "Source";
public final static String MAIN_SOURCE_NAME = COLUMN_PREFIX;
}
|
package org.eclipse.birt.report.designer.ui.editors;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.internal.ui.editors.IReportEditor;
import org.eclipse.birt.report.designer.internal.ui.views.actions.GlobalActionFactory;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IPropertyListener;
import org.eclipse.ui.IURIEditorInput;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartConstants;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.internal.part.NullEditorInput;
import org.eclipse.ui.part.EditorPart;
/**
* ReportEditorProxy is a editor proxy, which use in eclipse IDE enviroment.
*
* ReportEditorProxy determines editor input, then create a proper editor
* instance to represents the editor behaivors.
*/
public class ReportEditorProxy extends EditorPart implements
IPartListener,
IPropertyListener,
IReportEditor
{
/**
* The ID of the Report Editor
*/
public static final String REPROT_EDITOR_ID = "org.eclipse.birt.report.designer.ui.editors.ReportEditor"; //$NON-NLS-1$
/**
* The ID of the Template Editor
*/
public static final String TEMPLATE_EDITOR_ID = "org.eclipse.birt.report.designer.ui.editors.TemplateEditor"; //$NON-NLS-1$
/**
* The ID of the Library Editor
*/
public static final String LIBRARY_EDITOR_ID = "org.eclipse.birt.report.designer.ui.editors.LibraryEditor"; //$NON-NLS-1$
MultiPageReportEditor instance;
private String title = ""; //$NON-NLS-1$
/**
* This is to adapte change for Bug 103810, which required site access even
* after part disposed.
*/
private IEditorSite cachedSite;
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.EditorPart#getEditorInput()
*/
@SuppressWarnings("restriction")
public IEditorInput getEditorInput( )
{
if ( instance != null )
{
return instance.getEditorInput( );
}
return new NullEditorInput( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.EditorPart#getEditorSite()
*/
public IEditorSite getEditorSite( )
{
if ( instance != null )
{
return instance.getEditorSite( );
}
return cachedSite;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.EditorPart#init(org.eclipse.ui.IEditorSite,
* org.eclipse.ui.IEditorInput)
*/
public void init( IEditorSite site, IEditorInput input )
throws PartInitException
{
cachedSite = site;
if ( instance != null )
{
getSite( ).getWorkbenchWindow( )
.getPartService( )
.removePartListener( instance );
instance.dispose( );
}
if ( input instanceof IFileEditorInput
|| input instanceof IURIEditorInput )
{
instance = new IDEMultiPageReportEditor( );
}
else
{
instance = new MultiPageReportEditor( );
}
// must add property listener before init.
instance.addPropertyListener( this );
instance.init( site, input );
getSite( ).getWorkbenchWindow( )
.getPartService( )
.addPartListener( this );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets
* .Composite)
*/
public void createPartControl( Composite parent )
{
instance.createPartControl( parent );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.WorkbenchPart#dispose()
*/
public void dispose( )
{
if ( instance != null )
{
instance.dispose( );
getSite( ).getWorkbenchWindow( )
.getPartService( )
.removePartListener( this );
instance.removePropertyListener( this );
}
instance = null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.WorkbenchPart#getSite()
*/
public IWorkbenchPartSite getSite( )
{
if ( instance != null )
{
return instance.getSite( );
}
return cachedSite;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.WorkbenchPart#getTitle()
*/
public String getTitle( )
{
return this.title;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.EditorPart#getTitleToolTip()
*/
public String getTitleToolTip( )
{
if ( instance != null )
{
return instance.getTitleToolTip( );
}
return ""; //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.WorkbenchPart#setFocus()
*/
public void setFocus( )
{
if ( instance != null )
{
instance.setFocus( );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.WorkbenchPart#getAdapter(java.lang.Class)
*/
public Object getAdapter( Class adapter )
{
if ( instance != null )
{
return instance.getAdapter( adapter );
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.EditorPart#doSave(org.eclipse.core.runtime.
* IProgressMonitor)
*/
public void doSave( IProgressMonitor monitor )
{
if ( instance != null )
{
instance.doSave( monitor );
firePropertyChange( PROP_DIRTY );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.EditorPart#doSaveAs()
*/
public void doSaveAs( )
{
if ( instance != null )
{
instance.doSaveAs( );
firePropertyChange( PROP_DIRTY );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.EditorPart#isDirty()
*/
public boolean isDirty( )
{
if ( instance != null )
{
return instance.isDirty( );
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.EditorPart#isSaveAsAllowed()
*/
public boolean isSaveAsAllowed( )
{
if ( instance != null )
{
return instance.isSaveAsAllowed( );
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.EditorPart#isSaveOnCloseNeeded()
*/
public boolean isSaveOnCloseNeeded( )
{
if ( instance != null )
{
return instance.isSaveOnCloseNeeded( );
}
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.EditorPart#setInput(org.eclipse.ui.IEditorInput)
*/
protected void setInput( IEditorInput input )
{
super.setInput( input );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.EditorPart#setPartName(java.lang.String)
*/
protected void setPartName( String partName )
{
this.title = partName;
super.setPartName( partName );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.IPartListener#partActivated(org.eclipse.ui.IWorkbenchPart)
*/
public void partActivated( IWorkbenchPart part )
{
if ( part instanceof ReportEditorProxy )
{
instance.partActivated( ( (ReportEditorProxy) part ).getEditorPart( ) );
}
else
{
instance.partActivated( part );
}
// if ( part != this )
// if ( part instanceof PageBookView )
// PageBookView view = (PageBookView) part;
// if ( view.getCurrentPage( ) instanceof DesignerOutlinePage )
// ISelectionProvider provider = (ISelectionProvider)
// view.getCurrentPage( );
// ReportRequest request = new ReportRequest( view.getCurrentPage( ) );
// List list = new ArrayList( );
// if ( provider.getSelection( ) instanceof IStructuredSelection )
// list = ( (IStructuredSelection) provider.getSelection( ) ).toList( );
// request.setSelectionObject( list );
// request.setType( ReportRequest.SELECTION );
// // no convert
// // request.setRequestConvert(new
// // EditorReportRequestConvert());
// SessionHandleAdapter.getInstance( )
// .getMediator( )
// .notifyRequest( request );
// SessionHandleAdapter.getInstance( )
// .getMediator( )
// .pushState( );
// if ( instance.getActiveEditor( ) instanceof
// GraphicalEditorWithFlyoutPalette )
// if ( ( (GraphicalEditorWithFlyoutPalette) instance.getActiveEditor( )
// ).getGraphicalViewer( )
// .getEditDomain( )
// .getPaletteViewer( ) != null )
// GraphicalEditorWithFlyoutPalette editor =
// (GraphicalEditorWithFlyoutPalette) instance.getActiveEditor( );
// GraphicalViewer view = editor.getGraphicalViewer( );
// view.getEditDomain( ).loadDefaultTool( );
// return;
// if ( part == this )
// // use the asynchronized execution to ensure correct active page
// // index.
// Display.getCurrent( ).asyncExec( new Runnable( ) {
// public void run( )
// // if ( instance.getActivePageInstance( ) instanceof
// GraphicalEditorWithFlyoutPalette )
// // GraphicalEditorWithFlyoutPalette editor =
// (GraphicalEditorWithFlyoutPalette) instance.getActivePageInstance( );
// // GraphicalViewer view = editor.getGraphicalViewer( );
// // UIUtil.resetViewSelection( view, true );
// if ( getEditorInput( ).exists( ) )
// instance.handleActivation( );
// SessionHandleAdapter.getInstance( )
// .setReportDesignHandle( instance.getModel( ) );
// DataSetManager.initCurrentInstance( getEditorInput( ) );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.IPartListener#partBroughtToTop(org.eclipse.ui.IWorkbenchPart
* )
*/
public void partBroughtToTop( IWorkbenchPart part )
{
if ( instance == null )
{
return;
}
if ( part instanceof ReportEditorProxy )
{
instance.partBroughtToTop( ( (ReportEditorProxy) part ).getEditorPart( ) );
}
else
{
instance.partBroughtToTop( part );
}
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.IPartListener#partClosed(org.eclipse.ui.IWorkbenchPart)
*/
public void partClosed( IWorkbenchPart part )
{
if ( instance == null )
{
return;
}
if ( part instanceof ReportEditorProxy )
{
instance.partClosed( ( (ReportEditorProxy) part ).getEditorPart( ) );
}
else
{
instance.partClosed( part );
}
// instance.partClosed( part );
// FIXME ugly code
if ( part == this )
{
SessionHandleAdapter.getInstance( ).clear( instance.getModel( ) );
if ( instance.getModel( ) != null )
{
GlobalActionFactory.removeStackActions( instance.getModel( )
.getCommandStack( ) );
}
}
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.IPartListener#partDeactivated(org.eclipse.ui.IWorkbenchPart
* )
*/
public void partDeactivated( IWorkbenchPart part )
{
if ( instance == null )
{
return;
}
if ( part instanceof ReportEditorProxy )
{
instance.partDeactivated( ( (ReportEditorProxy) part ).getEditorPart( ) );
}
else
{
instance.partDeactivated( part );
}
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.IPartListener#partOpened(org.eclipse.ui.IWorkbenchPart)
*/
public void partOpened( IWorkbenchPart part )
{
if ( instance == null )
{
return;
}
if ( part instanceof ReportEditorProxy )
{
instance.partOpened( ( (ReportEditorProxy) part ).getEditorPart( ) );
}
else
{
instance.partOpened( part );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IPropertyListener#propertyChanged(java.lang.Object,
* int)
*/
public void propertyChanged( Object source, int propId )
{
if ( propId == IWorkbenchPartConstants.PROP_PART_NAME )
{
setPartName( instance.getPartName( ) );
}
firePropertyChange( propId );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.designer.internal.ui.editors.IReportEditor#
* getEditorPart()
*/
public IEditorPart getEditorPart( )
{
return instance;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals( Object obj )
{
if ( obj == instance )
{
return true;
}
return super.equals( obj );
}
}
|
// checkstyle: Checks Java source code for adherence to a set of rules.
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.puppycrawl.tools.checkstyle.checks.coding;
import java.util.Set;
import com.google.common.collect.Sets;
import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
/**
* <p>
* Checks that any combination of String literals
* is on the left side of an equals() comparison.
* Also checks for String literals assigned to some field
* (such as <code>someString.equals(anotherString = "text")</code>).
*
* <p>
* Rationale: Calling the equals() method on String literals
* will avoid a potential NullPointerException. Also, it is
* pretty common to see null check right before equals comparisons
* which is not necessary in the below example.
*
* For example:
*
* <pre>
* {@code
* String nullString = null;
* nullString.equals("My_Sweet_String");
* }
* </pre>
* should be refactored to
*
* <pre>
* {@code
* String nullString = null;
* "My_Sweet_String".equals(nullString);
* }
* </pre>
*
* @author Travis Schneeberger
* @author Vladislav Lisetskiy
*/
public class EqualsAvoidNullCheck extends Check {
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_EQUALS_AVOID_NULL = "equals.avoid.null";
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_EQUALS_IGNORE_CASE_AVOID_NULL = "equalsIgnoreCase.avoid.null";
/** Method name for comparison. */
private static final String EQUALS = "equals";
/** Type name for comparison. */
private static final String STRING = "String";
/** Whether to process equalsIgnoreCase() invocations. */
private boolean ignoreEqualsIgnoreCase;
/** Stack of sets of field names, one for each class of a set of nested classes. */
private FieldFrame currentFrame;
@Override
public int[] getDefaultTokens() {
return getAcceptableTokens();
}
@Override
public int[] getAcceptableTokens() {
return new int[] {
TokenTypes.METHOD_CALL,
TokenTypes.CLASS_DEF,
TokenTypes.METHOD_DEF,
TokenTypes.LITERAL_IF,
TokenTypes.LITERAL_FOR,
TokenTypes.LITERAL_WHILE,
TokenTypes.LITERAL_DO,
TokenTypes.LITERAL_CATCH,
TokenTypes.LITERAL_TRY,
TokenTypes.VARIABLE_DEF,
TokenTypes.PARAMETER_DEF,
TokenTypes.CTOR_DEF,
TokenTypes.SLIST,
TokenTypes.ENUM_DEF,
TokenTypes.ENUM_CONSTANT_DEF,
TokenTypes.LITERAL_NEW,
};
}
@Override
public int[] getRequiredTokens() {
return getAcceptableTokens();
}
/**
* Whether to ignore checking {@code String.equalsIgnoreCase(String)}.
* @param newValue whether to ignore checking
* {@code String.equalsIgnoreCase(String)}.
*/
public void setIgnoreEqualsIgnoreCase(boolean newValue) {
ignoreEqualsIgnoreCase = newValue;
}
@Override
public void beginTree(DetailAST rootAST) {
currentFrame = new FieldFrame(null);
}
@Override
public void visitToken(final DetailAST ast) {
switch (ast.getType()) {
case TokenTypes.VARIABLE_DEF:
case TokenTypes.PARAMETER_DEF:
currentFrame.addField(ast);
break;
case TokenTypes.METHOD_CALL:
processMethodCall(ast);
break;
case TokenTypes.SLIST:
processSlist(ast);
break;
case TokenTypes.LITERAL_NEW:
processLiteralNew(ast);
break;
default:
processFrame(ast);
}
}
@Override
public void leaveToken(DetailAST ast) {
final int astType = ast.getType();
if (astType != TokenTypes.VARIABLE_DEF
&& astType != TokenTypes.PARAMETER_DEF
&& astType != TokenTypes.METHOD_CALL
&& astType != TokenTypes.SLIST
&& astType != TokenTypes.LITERAL_NEW
|| astType == TokenTypes.LITERAL_NEW
&& ast.branchContains(TokenTypes.LCURLY)) {
currentFrame = currentFrame.getParent();
}
else if (astType == TokenTypes.SLIST) {
leaveSlist(ast);
}
}
@Override
public void finishTree(DetailAST ast) {
traverseFieldFrameTree(currentFrame);
}
/**
* Determine whether SLIST begins static or non-static block and add it as
* a frame in this case.
* @param ast SLIST ast.
*/
private void processSlist(DetailAST ast) {
final int parentType = ast.getParent().getType();
if (parentType == TokenTypes.SLIST
|| parentType == TokenTypes.STATIC_INIT
|| parentType == TokenTypes.INSTANCE_INIT) {
final FieldFrame frame = new FieldFrame(currentFrame);
currentFrame.addChild(frame);
currentFrame = frame;
}
}
/**
* Determine whether SLIST begins static or non-static block and
* @param ast SLIST ast.
*/
private void leaveSlist(DetailAST ast) {
final int parentType = ast.getParent().getType();
if (parentType == TokenTypes.SLIST
|| parentType == TokenTypes.STATIC_INIT
|| parentType == TokenTypes.INSTANCE_INIT) {
currentFrame = currentFrame.getParent();
}
}
/**
* Process CLASS_DEF, METHOD_DEF, LITERAL_IF, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO,
* LITERAL_CATCH, LITERAL_TRY, CTOR_DEF, ENUM_DEF, ENUM_CONSTANT_DEF.
* @param ast processed ast.
*/
private void processFrame(DetailAST ast) {
final FieldFrame frame = new FieldFrame(currentFrame);
final int astType = ast.getType();
if (astType == TokenTypes.CLASS_DEF
|| astType == TokenTypes.ENUM_DEF
|| astType == TokenTypes.ENUM_CONSTANT_DEF) {
frame.setClassOrEnumOrEnumConstDef(true);
frame.setFrameName(ast.findFirstToken(TokenTypes.IDENT).getText());
}
currentFrame.addChild(frame);
currentFrame = frame;
}
/**
* Add the method call to the current frame if it should be processed.
* @param methodCall METHOD_CALL ast.
*/
private void processMethodCall(DetailAST methodCall) {
final DetailAST dot = methodCall.getFirstChild();
if (dot.getType() == TokenTypes.DOT) {
final String methodName = dot.getLastChild().getText();
if (EQUALS.equals(methodName)
|| !ignoreEqualsIgnoreCase && "equalsIgnoreCase".equals(methodName)) {
currentFrame.addMethodCall(methodCall);
}
}
}
/**
* Determine whether LITERAL_NEW is an anonymous class definition and add it as
* a frame in this case.
* @param ast LITERAL_NEW ast.
*/
private void processLiteralNew(DetailAST ast) {
if (ast.branchContains(TokenTypes.LCURLY)) {
final FieldFrame frame = new FieldFrame(currentFrame);
currentFrame.addChild(frame);
currentFrame = frame;
}
}
/**
* Traverse the tree of the field frames to check all equals method calls.
* @param frame to check method calls in.
*/
private void traverseFieldFrameTree(FieldFrame frame) {
for (FieldFrame child: frame.getChildren()) {
if (!child.getChildren().isEmpty()) {
traverseFieldFrameTree(child);
}
currentFrame = child;
for (DetailAST methodCall: child.getMethodCalls()) {
checkMethodCall(methodCall);
}
}
}
/**
* Check whether the method call should be violated.
* @param methodCall method call to check.
*/
private void checkMethodCall(DetailAST methodCall) {
DetailAST objCalledOn = methodCall.getFirstChild().getFirstChild();
if (objCalledOn.getType() == TokenTypes.DOT) {
objCalledOn = objCalledOn.getLastChild();
}
final DetailAST expr = methodCall.findFirstToken(TokenTypes.ELIST).getFirstChild();
if (isObjectValid(objCalledOn)
&& containsOneArgument(methodCall)
&& containsAllSafeTokens(expr)
&& calledOnStringField(objCalledOn)) {
final String methodName = methodCall.getFirstChild().getLastChild().getText();
if (EQUALS.equals(methodName)) {
log(methodCall.getLineNo(), methodCall.getColumnNo(),
MSG_EQUALS_AVOID_NULL);
}
else {
log(methodCall.getLineNo(), methodCall.getColumnNo(),
MSG_EQUALS_IGNORE_CASE_AVOID_NULL);
}
}
}
/**
* Check whether the object equals method is called on is not a String literal
* and not too complex.
* @param objCalledOn the object equals method is called on ast.
* @return true if the object is valid.
*/
private static boolean isObjectValid(DetailAST objCalledOn) {
boolean result = true;
final DetailAST previousSibling = objCalledOn.getPreviousSibling();
if (previousSibling != null
&& previousSibling.getType() == TokenTypes.DOT) {
result = false;
}
if (isStringLiteral(objCalledOn)) {
result = false;
}
return result;
}
/**
* Checks for calling equals on String literal and
* anon object which cannot be null
* @param objCalledOn object AST
* @return if it is string literal
*/
private static boolean isStringLiteral(DetailAST objCalledOn) {
return objCalledOn.getType() == TokenTypes.STRING_LITERAL
|| objCalledOn.getType() == TokenTypes.LITERAL_NEW;
}
/**
* Verify that method call has one argument.
*
* @param methodCall METHOD_CALL DetailAST
* @return true if method call has one argument.
*/
private static boolean containsOneArgument(DetailAST methodCall) {
final DetailAST elist = methodCall.findFirstToken(TokenTypes.ELIST);
return elist.getChildCount() == 1;
}
/**
* <p>
* Looks for all "safe" Token combinations in the argument
* expression branch.
* @param expr the argument expression
* @return - true if any child matches the set of tokens, false if not
*/
private static boolean containsAllSafeTokens(final DetailAST expr) {
DetailAST arg = expr.getFirstChild();
if (arg.branchContains(TokenTypes.METHOD_CALL)) {
return false;
}
arg = skipVariableAssign(arg);
//Plus assignment can have ill affects
//do not want to recommend moving expression
//See example:
//String s = "SweetString";
//s.equals(s += "SweetString"); //false
//s = "SweetString";
//(s += "SweetString").equals(s); //true
return !arg.branchContains(TokenTypes.PLUS_ASSIGN)
&& !arg.branchContains(TokenTypes.IDENT)
&& !arg.branchContains(TokenTypes.LITERAL_NULL);
}
/**
* Skips over an inner assign portion of an argument expression.
* @param currentAST current token in the argument expression
* @return the next relevant token
*/
private static DetailAST skipVariableAssign(final DetailAST currentAST) {
if (currentAST.getType() == TokenTypes.ASSIGN
&& currentAST.getFirstChild().getType() == TokenTypes.IDENT) {
return currentAST.getFirstChild().getNextSibling();
}
return currentAST;
}
/**
* Determine, whether equals method is called on a field of String type.
* @param objCalledOn object ast.
* @return true if the object is of String type.
*/
private boolean calledOnStringField(DetailAST objCalledOn) {
boolean result = false;
final DetailAST previousSiblingAst = objCalledOn.getPreviousSibling();
final String name = objCalledOn.getText();
if (previousSiblingAst != null) {
if (previousSiblingAst.getType() == TokenTypes.LITERAL_THIS) {
final DetailAST field = getObjectFrame(currentFrame).findField(name);
result = STRING.equals(getFieldType(field));
}
else {
final String className = previousSiblingAst.getText();
FieldFrame frame = getObjectFrame(currentFrame);
while (frame != null) {
if (className.equals(frame.getFrameName())) {
final DetailAST field = frame.findField(name);
result = STRING.equals(getFieldType(field));
break;
}
frame = getObjectFrame(frame.getParent());
}
}
}
else {
FieldFrame frame = currentFrame;
while (frame != null) {
final DetailAST field = frame.findField(name);
if (field != null
&& (frame.isClassOrEnumOrEnumConstDef()
|| checkLineNo(field, objCalledOn))) {
result = STRING.equals(getFieldType(field));
break;
}
frame = frame.getParent();
}
}
return result;
}
/**
* Get the nearest parent frame which is CLASS_DEF, ENUM_DEF or ENUM_CONST_DEF.
* @param frame to start the search from.
* @return the nearest parent frame which is CLASS_DEF, ENUM_DEF or ENUM_CONST_DEF.
*/
private static FieldFrame getObjectFrame(FieldFrame frame) {
FieldFrame objectFrame = frame;
while (objectFrame != null && !objectFrame.isClassOrEnumOrEnumConstDef()) {
objectFrame = objectFrame.getParent();
}
return objectFrame;
}
/**
* Check whether the field is declared before the method call in case of
* methods and initialization blocks.
* @param field field to check.
* @param objCalledOn object equals method called on.
* @return true if the field is declared before the method call.
*/
private static boolean checkLineNo(DetailAST field, DetailAST objCalledOn) {
boolean result = false;
if (field.getLineNo() < objCalledOn.getLineNo()
|| field.getLineNo() == objCalledOn.getLineNo()
&& field.getColumnNo() < objCalledOn.getColumnNo()) {
result = true;
}
return result;
}
/**
* Get field type.
* @param field to get the type from.
* @return type of the field.
*/
private static String getFieldType(DetailAST field) {
String fieldType = null;
final DetailAST identAst = field.findFirstToken(TokenTypes.TYPE)
.findFirstToken(TokenTypes.IDENT);
if (identAst != null) {
fieldType = identAst.getText();
}
return fieldType;
}
/**
* Holds the names of fields of a type.
*/
private static class FieldFrame {
/** Name of the class, enum or enum constant declaration. */
private String frameName;
/** Parent frame. */
private final FieldFrame parent;
/** Set of frame's children. */
private final Set<FieldFrame> children = Sets.newHashSet();
/** Set of fields. */
private final Set<DetailAST> fields = Sets.newHashSet();
/** Set of equals calls. */
private final Set<DetailAST> methodCalls = Sets.newHashSet();
/** Whether the frame is CLASS_DEF, ENUM_DEF or ENUM_CONST_DEF. */
private boolean classOrEnumOrEnumConstDef;
/**
* Creates new frame.
* @param parent parent frame.
*/
FieldFrame(FieldFrame parent) {
this.parent = parent;
}
/**
* Set the frame name.
* @param frameName value to set.
*/
public void setFrameName(String frameName) {
this.frameName = frameName;
}
/**
* Getter for the frame name.
* @return frame name.
*/
public String getFrameName() {
return frameName;
}
/**
* Getter for the parent frame.
* @return parent frame.
*/
public FieldFrame getParent() {
return parent;
}
/**
* Getter for frame's children.
* @return children of this frame.
*/
public Set<FieldFrame> getChildren() {
return children;
}
/**
* Add child frame to this frame.
* @param child frame to add.
*/
public void addChild(FieldFrame child) {
children.add(child);
}
/**
* Add field to this FieldFrame.
* @param field the ast of the field.
*/
public void addField(DetailAST field) {
fields.add(field);
}
/**
* Sets isClassOrEnum.
* @param value value to set.
*/
public void setClassOrEnumOrEnumConstDef(boolean value) {
classOrEnumOrEnumConstDef = value;
}
/**
* Getter for classOrEnumOrEnumConstDef.
* @return classOrEnumOrEnumConstDef.
*/
public boolean isClassOrEnumOrEnumConstDef() {
return classOrEnumOrEnumConstDef;
}
/**
* Add method call to this frame.
* @param methodCall METHOD_CALL ast.
*/
public void addMethodCall(DetailAST methodCall) {
methodCalls.add(methodCall);
}
/**
* Determines whether this FieldFrame contains the field.
* @param name name of the field to check.
* @return true if this FieldFrame contains instance field field.
*/
public DetailAST findField(String name) {
for (DetailAST field: fields) {
if (getFieldName(field).equals(name)) {
return field;
}
}
return null;
}
/**
* Getter for frame's method calls.
* @return method calls of this frame.
*/
public Set<DetailAST> getMethodCalls() {
return methodCalls;
}
/**
* Get the name of the field.
* @param field to get the name from.
* @return name of the field.
*/
private static String getFieldName(DetailAST field) {
return field.findFirstToken(TokenTypes.IDENT).getText();
}
}
}
|
package com.simpligility.maven.plugins.android.standalonemojos;
import com.simpligility.maven.plugins.android.AbstractAndroidMojo;
import com.simpligility.maven.plugins.android.CommandExecutor;
import com.simpligility.maven.plugins.android.ExecutionException;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import java.util.ArrayList;
import java.util.List;
/**
* Connect external IP addresses to the ADB server.
*
* @author demey.emmanuel@gmail.com
*/
@Mojo( name = "connect", requiresProject = false )
public class ConnectMojo extends AbstractAndroidMojo
{
@Override
public void execute() throws MojoExecutionException, MojoFailureException
{
if ( ips.length > 0 )
{
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
for ( String ip : ips )
{
getLog().debug( "Connecting " + ip );
// It would be better to use the AndroidDebugBridge class
// rather than calling the command line tool
String command = getAndroidSdk().getAdbPath();
// We first have to the put the bridge in tcpip mode or else it will fail to connect
// First make sure everything is clean ...
List<String> parameters = new ArrayList<String>();
parameters.add( "kill-server" );
try
{
executor.setCaptureStdOut( true );
executor.executeCommand( command, parameters );
parameters.clear();
// ... now put in wireless mode ...
String hostport[] = ip.split( ":" );
parameters.add( "tcpip" );
parameters.add( hostport[1] );
executor.setCaptureStdOut( true );
executor.executeCommand( command, parameters );
// ... and finally connect
parameters.clear();
parameters.add( "connect" );
parameters.add( ip );
executor.executeCommand( command, parameters );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( String.format( "Can not connect %s", ip ), e );
}
}
}
}
}
|
package com.synopsys.arc.jenkins.plugins.ownership.nodes;
import com.synopsys.arc.jenkins.plugins.ownership.IOwnershipHelper;
import com.synopsys.arc.jenkins.plugins.ownership.IOwnershipItem;
import com.synopsys.arc.jenkins.plugins.ownership.Messages;
import com.synopsys.arc.jenkins.plugins.ownership.OwnershipDescription;
import com.synopsys.arc.jenkins.plugins.ownership.OwnershipPlugin;
import com.synopsys.arc.jenkins.plugins.ownership.util.ui.OwnershipLayoutFormatter;
import hudson.Extension;
import hudson.model.Descriptor;
import hudson.model.Node;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.SlaveComputer;
import java.util.List;
import javax.annotation.CheckForNull;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.Ancestor;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
/**
* Implements owner property for Jenkins Nodes.
* @author Oleg Nenashev <nenashev@synopsys.com>
* @deprecated Will be removed in future versions
* @since 0.0.3
*/
public class OwnerNodeProperty extends NodeProperty<Node>
implements IOwnershipItem<NodeProperty> {
private OwnershipDescription ownership;
private String nodeName;
@DataBoundConstructor
public OwnerNodeProperty(NodeOwnerWrapper slaveOwnership) {
this(null, (slaveOwnership != null) ? slaveOwnership.getDescription() : null);
}
public OwnerNodeProperty(Node node, OwnershipDescription ownership) {
setNode(node);
//FIXME: remove hack with owner
this.nodeName = (node != null) ? node.getNodeName() : null;
this.ownership = (ownership != null) ? ownership : OwnershipDescription.DISABLED_DESCR;
}
@Override
public OwnershipDescription getOwnership() {
return ownership != null ? ownership : OwnershipDescription.DISABLED_DESCR;
}
public void setOwnershipDescription(OwnershipDescription descr) {
ownership = descr;
getDescriptor().save();
}
@CheckForNull
public Node getNode() {
if (node == null) {
setNode(Jenkins.getInstance().getNode(nodeName));
}
return node;
}
@Override
public NodePropertyDescriptor getDescriptor() {
return super.getDescriptor();
}
@Override
public IOwnershipHelper<NodeProperty> helper() {
return NodeOwnerPropertyHelper.Instance;
}
@Override
public NodeProperty<?> reconfigure(StaplerRequest req, JSONObject form) throws Descriptor.FormException {
return new OwnerNodeProperty(DescriptorImpl.getNodePropertyOwner(req), getOwnership());
}
@Override
public NodeProperty getDescribedItem() {
return this;
}
public OwnershipLayoutFormatter<Node> getLayoutFormatter() {
return OwnershipPlugin.getInstance().getOwnershipLayoutFormatterProvider().getLayoutFormatter(getNode());
}
@Extension
public static class DescriptorImpl extends NodePropertyDescriptor {
/**
* Gets Node, which is being configured by StaplerRequest
* @remarks Workaround for
* @param req StaplerRequest (ex, from NodePropertyDescriptor::newInstance())
* @return Instance of the node, which is being configured (or null)
*
* @since 0.0.5
* @author Oleg Nenashev <nenashev@synopsys.com>
*/
private static Node getNodePropertyOwner(StaplerRequest req)
{
List<Ancestor> ancestors = req.getAncestors();
if (ancestors.isEmpty()) {
assert false : "StaplerRequest is empty";
return null;
}
Object node = ancestors.get(ancestors.size()-1).getObject();
if (SlaveComputer.class.isAssignableFrom(node.getClass())) {
return ((SlaveComputer)node).getNode();
} else {
assert false : "StaplerRequest should have Node ancestor";
return null;
}
}
@Override
public String getDisplayName() {
return null;
}
@Override
public boolean isApplicable( Class<? extends Node> Type ) {
return true;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.