lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | c5bc80adaf9adf9a330e5274f85a0ff923f3e82a | 0 | IWSDevelopers/iws,IWSDevelopers/iws | /*
* =============================================================================
* Copyright 1998-2014, IAESTE Internet Development Team. All rights reserved.
* ----------------------------------------------------------------------------
* Project: IntraWeb Services (iws-client) - net.iaeste.iws.client.exchange.StudentTest
* -----------------------------------------------------------------------------
* This software is provided by the members of the IAESTE Internet Development
* Team (IDT) to IAESTE A.s.b.l. It is for internal use only and may not be
* redistributed. IAESTE A.s.b.l. is not permitted to sell this software.
*
* This software is provided "as is"; the IDT or individuals within the IDT
* cannot be held legally responsible for any problems the software may cause.
* =============================================================================
*/
package net.iaeste.iws.client.exchange;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import net.iaeste.iws.api.Administration;
import net.iaeste.iws.api.Exchange;
import net.iaeste.iws.api.Students;
import net.iaeste.iws.api.constants.IWSConstants;
import net.iaeste.iws.api.constants.IWSErrors;
import net.iaeste.iws.api.dtos.AuthenticationToken;
import net.iaeste.iws.api.dtos.Group;
import net.iaeste.iws.api.dtos.TestData;
import net.iaeste.iws.api.dtos.exchange.Offer;
import net.iaeste.iws.api.dtos.exchange.Student;
import net.iaeste.iws.api.dtos.exchange.StudentApplication;
import net.iaeste.iws.api.enums.FetchType;
import net.iaeste.iws.api.enums.Gender;
import net.iaeste.iws.api.enums.exchange.ApplicationStatus;
import net.iaeste.iws.api.enums.exchange.OfferState;
import net.iaeste.iws.api.requests.CreateUserRequest;
import net.iaeste.iws.api.requests.exchange.FetchOffersRequest;
import net.iaeste.iws.api.requests.exchange.FetchPublishedGroupsRequest;
import net.iaeste.iws.api.requests.exchange.ProcessOfferRequest;
import net.iaeste.iws.api.requests.exchange.PublishOfferRequest;
import net.iaeste.iws.api.requests.student.FetchStudentApplicationsRequest;
import net.iaeste.iws.api.requests.student.FetchStudentsRequest;
import net.iaeste.iws.api.requests.student.ProcessStudentApplicationsRequest;
import net.iaeste.iws.api.requests.student.StudentApplicationRequest;
import net.iaeste.iws.api.requests.student.StudentRequest;
import net.iaeste.iws.api.responses.CreateUserResponse;
import net.iaeste.iws.api.responses.exchange.FetchOffersResponse;
import net.iaeste.iws.api.responses.exchange.FetchPublishedGroupsResponse;
import net.iaeste.iws.api.responses.exchange.OfferResponse;
import net.iaeste.iws.api.responses.exchange.PublishOfferResponse;
import net.iaeste.iws.api.responses.student.FetchStudentApplicationsResponse;
import net.iaeste.iws.api.responses.student.FetchStudentsResponse;
import net.iaeste.iws.api.responses.student.StudentApplicationResponse;
import net.iaeste.iws.api.responses.student.StudentResponse;
import net.iaeste.iws.api.util.Copier;
import net.iaeste.iws.api.util.Date;
import net.iaeste.iws.api.util.DatePeriod;
import net.iaeste.iws.api.util.DateTime;
import net.iaeste.iws.client.AbstractTest;
import net.iaeste.iws.client.AdministrationClient;
import net.iaeste.iws.client.ExchangeClient;
import net.iaeste.iws.client.StudentClient;
import org.junit.Ignore;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Pavel Fiala / last $Author:$
* @version $Revision:$ / $Date:$
* @since 1.7
*/
public final class StudentTest extends AbstractTest {
private final Administration administration = new AdministrationClient();
private final Exchange exchange = new ExchangeClient();
private final Students students = new StudentClient();
private AuthenticationToken austriaToken = null;
private AuthenticationToken croatiaToken = null;
@Override
public void setup() {
token = login("[email protected]", "poland");
austriaToken = login("[email protected]", "austria");
croatiaToken = login("[email protected]", "croatia");
}
@Override
public void tearDown() {
logout(token);
logout(austriaToken);
logout(croatiaToken);
}
@Test
public void testProcessStudentApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001001", "Employer", "PL");
final ProcessOfferRequest offerRequest = new ProcessOfferRequest(offer);
final OfferResponse saveResponse = exchange.processOffer(token, offerRequest);
final String refNo = saveResponse.getOffer().getRefNo();
// verify processResponse
assertThat(saveResponse.isOk(), is(true));
final FetchOffersRequest allOffersRequest = new FetchOffersRequest(FetchType.ALL);
FetchOffersResponse allOffersResponse = exchange.fetchOffers(token, allOffersRequest);
assertThat(allOffersResponse.getOffers().isEmpty(), is(false));
Offer sharedOffer = findOfferFromResponse(saveResponse.getOffer().getRefNo(), allOffersResponse);
assertThat(sharedOffer, is(not(nullValue())));
assertThat(sharedOffer.getStatus(), is(OfferState.NEW));
assertThat(sharedOffer.getNominationDeadline(), is(not(nominationDeadline)));
final Set<String> offersToShare = new HashSet<>(1);
offersToShare.add(sharedOffer.getOfferId());
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferRequest publishRequest1 = new PublishOfferRequest(offersToShare, groupIds, nominationDeadline);
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, publishRequest1);
assertThat(publishResponse1.getError(), is(IWSErrors.SUCCESS));
assertThat(publishResponse1.isOk(), is(true));
final List<String> offersExternalId = new ArrayList<>(1);
offersExternalId.add(sharedOffer.getOfferId());
final FetchPublishedGroupsRequest fetchPublishRequest = new FetchPublishedGroupsRequest(offersExternalId);
final FetchPublishedGroupsResponse fetchPublishResponse1 = exchange.fetchPublishedGroups(token, fetchPublishRequest);
//is it shared to two groups?
assertThat(fetchPublishResponse1.isOk(), is(true));
final List<Group> offerGroupsSharedTo = fetchPublishResponse1.getOffersGroups().get(offersExternalId.get(0));
assertThat(2, is(offerGroupsSharedTo.size()));
allOffersResponse = exchange.fetchOffers(token, allOffersRequest);
assertThat(allOffersResponse.getOffers().isEmpty(), is(false));
sharedOffer = findOfferFromResponse(saveResponse.getOffer().getRefNo(), allOffersResponse);
assertThat(sharedOffer, is(not(nullValue())));
assertThat(sharedOffer.getRefNo(), is(saveResponse.getOffer().getRefNo()));
assertThat("The offer is shared now, the status has to be SHARED", sharedOffer.getStatus(), is(OfferState.SHARED));
assertThat(sharedOffer.getNominationDeadline(), is(nominationDeadline));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat(createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat(fetchStudentsResponse.isOk(), is(true));
assertThat(fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(sharedOffer);
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createStudentApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createStudentApplicationResponse = students.processStudentApplication(austriaToken, createStudentApplicationsRequest);
assertThat(createStudentApplicationResponse.isOk(), is(true));
}
@Test
@Ignore("2014-01-17 Pavel - test fails due to wrong data gets from TestData, see #646")
public void testFetchStudentApplications() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001003", "Employer", "PL");
final ProcessOfferRequest offerRequest = new ProcessOfferRequest(offer);
final OfferResponse saveResponse = exchange.processOffer(token, offerRequest);
final String refNo = saveResponse.getOffer().getRefNo();
// verify processResponse
assertThat(saveResponse.isOk(), is(true));
final FetchOffersRequest allOffersRequest = new FetchOffersRequest(FetchType.ALL);
FetchOffersResponse allOffersResponse = exchange.fetchOffers(token, allOffersRequest);
assertThat(allOffersResponse.getOffers().isEmpty(), is(false));
Offer sharedOffer = findOfferFromResponse(refNo, allOffersResponse);
assertThat(sharedOffer, is(not(nullValue())));
assertThat(sharedOffer.getStatus(), is(OfferState.NEW));
assertThat(sharedOffer.getNominationDeadline(), is(not(nominationDeadline)));
final Set<String> offersToShare = new HashSet<>(1);
offersToShare.add(sharedOffer.getOfferId());
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferRequest publishRequest1 = new PublishOfferRequest(offersToShare, groupIds, nominationDeadline);
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, publishRequest1);
assertThat(publishResponse1.getError(), is(IWSErrors.SUCCESS));
assertThat(publishResponse1.isOk(), is(true));
final List<String> offersExternalId = new ArrayList<>(1);
offersExternalId.add(sharedOffer.getOfferId());
final FetchPublishedGroupsRequest fetchPublishRequest = new FetchPublishedGroupsRequest(offersExternalId);
final FetchPublishedGroupsResponse fetchPublishResponse1 = exchange.fetchPublishedGroups(token, fetchPublishRequest);
//is it shared to two groups?
assertThat(fetchPublishResponse1.isOk(), is(true));
final List<Group> offerGroupsSharedTo = fetchPublishResponse1.getOffersGroups().get(offersExternalId.get(0));
assertThat(2, is(offerGroupsSharedTo.size()));
allOffersResponse = exchange.fetchOffers(token, allOffersRequest);
assertThat(allOffersResponse.getOffers().isEmpty(), is(false));
sharedOffer = findOfferFromResponse(saveResponse.getOffer().getRefNo(), allOffersResponse);
assertThat(sharedOffer, is(not(nullValue())));
assertThat(sharedOffer.getRefNo(), is(saveResponse.getOffer().getRefNo()));
assertThat("The offer is shared now, the status has to be SHARED", sharedOffer.getStatus(), is(OfferState.SHARED));
assertThat(sharedOffer.getNominationDeadline(), is(nominationDeadline));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat(createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat(fetchStudentsResponse.isOk(), is(true));
assertThat(fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(sharedOffer);
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
application.setGender(Gender.FEMALE);
application.setNationality(TestData.prepareCountry("DE"));
final ProcessStudentApplicationsRequest createStudentApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createStudentApplicationResponse = students.processStudentApplication(austriaToken, createStudentApplicationsRequest);
assertThat(createStudentApplicationResponse.isOk(), is(true));
final FetchStudentApplicationsRequest fetchStudentApplicationsRequest = new FetchStudentApplicationsRequest(sharedOffer.getOfferId());
final FetchStudentApplicationsResponse fetchStudentApplicationsResponse = students.fetchStudentApplications(austriaToken, fetchStudentApplicationsRequest);
assertThat(fetchStudentApplicationsResponse.isOk(), is(true));
assertThat(fetchStudentApplicationsResponse.getStudentApplications().size(), is(1));
final StudentApplication fetchedApplication = fetchStudentApplicationsResponse.getStudentApplications().get(0);
assertThat(fetchedApplication.getGender(), is(application.getGender()));
assertThat(fetchedApplication.getGender(), is(application.getGender()));
assertThat(fetchedApplication.getNationality(), is(application.getNationality()));
}
//TODO Kim, have a look at this test please
//@Ignore("2013-21-04 Pavel - failing OfferGroupEntity with id xyz cannot be found even it exists in DB. See #515")
@Test
public void testUpdateStudentApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001002", "Employer", "PL");
final ProcessOfferRequest offerRequest = new ProcessOfferRequest(offer);
final OfferResponse saveResponse = exchange.processOffer(token, offerRequest);
final String refNo = saveResponse.getOffer().getRefNo();
// verify processResponse
assertThat(saveResponse.isOk(), is(true));
final FetchOffersRequest allOffersRequest = new FetchOffersRequest(FetchType.ALL);
FetchOffersResponse allOffersResponse = exchange.fetchOffers(token, allOffersRequest);
assertThat(allOffersResponse.getOffers().isEmpty(), is(false));
Offer sharedOffer = findOfferFromResponse(saveResponse.getOffer().getRefNo(), allOffersResponse);
assertThat(sharedOffer, is(not(nullValue())));
assertThat(sharedOffer.getStatus(), is(OfferState.NEW));
assertThat(sharedOffer.getNominationDeadline(), is(not(nominationDeadline)));
final Set<String> offersToShare = new HashSet<>(1);
offersToShare.add(sharedOffer.getOfferId());
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferRequest publishRequest1 = new PublishOfferRequest(offersToShare, groupIds, nominationDeadline);
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, publishRequest1);
assertThat(publishResponse1.getError(), is(IWSErrors.SUCCESS));
assertThat(publishResponse1.isOk(), is(true));
final List<String> offersExternalId = new ArrayList<>(1);
offersExternalId.add(sharedOffer.getOfferId());
final FetchPublishedGroupsRequest fetchPublishRequest = new FetchPublishedGroupsRequest(offersExternalId);
final FetchPublishedGroupsResponse fetchPublishResponse1 = exchange.fetchPublishedGroups(token, fetchPublishRequest);
//is it shared to two groups?
assertThat(fetchPublishResponse1.isOk(), is(true));
final List<Group> offerGroupsSharedTo = fetchPublishResponse1.getOffersGroups().get(offersExternalId.get(0));
assertThat(2, is(offerGroupsSharedTo.size()));
allOffersResponse = exchange.fetchOffers(token, allOffersRequest);
assertThat(allOffersResponse.getOffers().isEmpty(), is(false));
sharedOffer = findOfferFromResponse(saveResponse.getOffer().getRefNo(), allOffersResponse);
assertThat(sharedOffer, is(not(nullValue())));
assertThat(sharedOffer.getRefNo(), is(saveResponse.getOffer().getRefNo()));
assertThat("The offer is shared now, the status has to be SHARED", sharedOffer.getStatus(), is(OfferState.SHARED));
assertThat(sharedOffer.getNominationDeadline(), is(nominationDeadline));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat(createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat(fetchStudentsResponse.isOk(), is(true));
assertThat(fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
StudentApplication application = new StudentApplication();
application.setOffer(sharedOffer);
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createStudentApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createStudentApplicationResponse = students.processStudentApplication(austriaToken, createStudentApplicationsRequest);
assertThat(createStudentApplicationResponse.isOk(), is(true));
//test updating existing application
application = Copier.copy(createStudentApplicationResponse.getStudentApplication());
application.setUniversity("MyUniversity");
final ProcessStudentApplicationsRequest createStudentApplicationsRequest2 = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createStudentApplicationResponse2 = students.processStudentApplication(austriaToken, createStudentApplicationsRequest2);
assertThat(createStudentApplicationResponse2.isOk(), is(true));
assertThat(createStudentApplicationResponse2.getStudentApplication().getUniversity(), is(application.getUniversity()));
}
//TODO Kim, have a look at this test please
//@Ignore("2013-21-04 Pavel - failing OfferGroupEntity with id xyz cannot be found even it exists in DB. See #515")
@Test
public void testNominatingApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001004", "Employer", "PL");
final OfferResponse saveResponse = exchange.processOffer(token, new ProcessOfferRequest(offer));
assertThat("Offer has been saved", saveResponse.isOk(), is(true));
final Set<String> offersToShare = new HashSet<>(1);
final String offerId = saveResponse.getOffer().getOfferId();
offersToShare.add(offerId);
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been shared to 2 countries", publishResponse1.isOk(), is(true));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat("Student has been saved", createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(saveResponse.getOffer());
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(austriaToken, createApplicationsRequest);
final StudentApplication studentApplication = createApplicationResponse.getStudentApplication();
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
final StudentApplicationRequest nominateStudentRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.NOMINATED);
final StudentApplicationResponse nominateStudentResponse = students.processApplicationStatus(austriaToken, nominateStudentRequest);
assertThat("Student has been nominated by Austria to Poland", nominateStudentResponse.isOk(), is(true));
assertThat("Application state is NOMINATED", nominateStudentResponse.getStudentApplication().getStatus(), is(ApplicationStatus.NOMINATED));
assertThat(nominateStudentResponse.getStudentApplication().getNominatedAt(), not(nullValue()));
final DateTime beforeNominationDate = new DateTime();
final FetchStudentApplicationsRequest fetchApplicationsRequest = new FetchStudentApplicationsRequest(offerId);
final FetchStudentApplicationsResponse fetchApplicationsResponse = students.fetchStudentApplications(austriaToken, fetchApplicationsRequest);
assertThat(fetchApplicationsResponse.isOk(), is(true));
final StudentApplication foundApplication = findApplicationFromResponse(studentApplication.getApplicationId(), fetchApplicationsResponse);
assertThat("Make sure that new application state has been persisted", foundApplication.getStatus(), is(ApplicationStatus.NOMINATED));
assertThat("Nomination date is set", foundApplication.getNominatedAt(), not(nullValue()));
}
@Test
public void testProcessStudent() {
final CreateUserRequest createUserRequest = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest.setStudentAccount(true);
final CreateUserResponse createStudentResponse = administration.createUser(austriaToken, createUserRequest);
assertThat(createStudentResponse.isOk(), is(true));
final Student newStudent = new Student();
newStudent.setUser(createStudentResponse.getUser());
final StudentRequest processStudentRequest = new StudentRequest(newStudent);
final StudentResponse processStudentResponse = students.processStudent(austriaToken, processStudentRequest);
assertThat(processStudentResponse.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat(fetchStudentsResponse.isOk(), is(true));
}
@Test
public void testRejectNominatedApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001005", "Employer", "PL");
final OfferResponse saveResponse = exchange.processOffer(token, new ProcessOfferRequest(offer));
assertThat("Offer has been saved", saveResponse.isOk(), is(true));
final Set<String> offersToShare = new HashSet<>(1);
final String offerId = saveResponse.getOffer().getOfferId();
offersToShare.add(offerId);
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been shared to 2 countries", publishResponse1.isOk(), is(true));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat("Student has been saved", createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(saveResponse.getOffer());
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(austriaToken, createApplicationsRequest);
final StudentApplication studentApplication = createApplicationResponse.getStudentApplication();
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
final StudentApplicationRequest nominateStudentRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.NOMINATED);
final StudentApplicationResponse nominateStudentResponse = students.processApplicationStatus(austriaToken, nominateStudentRequest);
assertThat("Student has been nominated by Austria to Poland", nominateStudentResponse.isOk(), is(true));
assertThat("Application state is NOMINATED", nominateStudentResponse.getStudentApplication().getStatus(), is(ApplicationStatus.NOMINATED));
final StudentApplicationRequest rejectStudentRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.REJECTED);
rejectStudentRequest.setRejectInternalComment("reject internal comment");
rejectStudentRequest.setRejectDescription("reject description");
rejectStudentRequest.setRejectByEmployerReason("reject employer reason");
final StudentApplicationResponse rejectStudentResponse = students.processApplicationStatus(token, rejectStudentRequest);
assertThat("Student has been rejected by Poland", rejectStudentResponse.isOk(), is(true));
final StudentApplication rejectedApplication = rejectStudentResponse.getStudentApplication();
assertThat(rejectedApplication.getRejectByEmployerReason(), is(rejectStudentRequest.getRejectByEmployerReason()));
assertThat(rejectedApplication.getRejectDescription(), is(rejectStudentRequest.getRejectDescription()));
assertThat(rejectedApplication.getRejectInternalComment(), is(rejectStudentRequest.getRejectInternalComment()));
}
@Test
@Ignore("Ignored 2014-01-19 by Kim - Reason: It's failing! Need to commit other work, so wish to see a stable build for the migration as well.")
public void testRejectAppliedApplicationBySendingCountry() {
//Sending country is only allowed to reject applied application
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001065", "Employer", "PL");
final OfferResponse saveResponse = exchange.processOffer(token, new ProcessOfferRequest(offer));
assertThat("Offer has been saved", saveResponse.isOk(), is(true));
final Set<String> offersToShare = new HashSet<>(1);
final String offerId = saveResponse.getOffer().getOfferId();
offersToShare.add(offerId);
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been shared to 2 countries", publishResponse1.isOk(), is(true));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat("Student has been saved", createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(saveResponse.getOffer());
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(austriaToken, createApplicationsRequest);
final StudentApplication studentApplication = createApplicationResponse.getStudentApplication();
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
final StudentApplicationRequest rejectStudentRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.REJECTED_BY_SENDING_COUNTRY);
rejectStudentRequest.setRejectInternalComment("reject internal comment");
rejectStudentRequest.setRejectDescription("reject description");
final StudentApplicationResponse rejectStudentResponse = students.processApplicationStatus(austriaToken, rejectStudentRequest);
assertThat("Student has been rejected by Austria (sending country)", rejectStudentResponse.isOk(), is(true));
final StudentApplication rejectedApplication = rejectStudentResponse.getStudentApplication();
assertThat(rejectedApplication.getRejectDescription(), is(rejectStudentRequest.getRejectDescription()));
assertThat(rejectedApplication.getRejectInternalComment(), is(rejectStudentRequest.getRejectInternalComment()));
}
@Test
public void testRejectApplicationBySendingCountryForClosedOffer() {
//Sending country is only allowed to reject applied application
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001065", "Employer", "PL");
final OfferResponse saveResponse = exchange.processOffer(token, new ProcessOfferRequest(offer));
assertThat("Offer has been saved", saveResponse.isOk(), is(true));
final Set<String> offersToShare = new HashSet<>(1);
final String offerId = saveResponse.getOffer().getOfferId();
offersToShare.add(offerId);
List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been shared to 2 countries", publishResponse1.isOk(), is(true));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat("Student has been saved", createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(saveResponse.getOffer());
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(austriaToken, createApplicationsRequest);
final StudentApplication studentApplication = createApplicationResponse.getStudentApplication();
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
//usnhare offer
groupIds.clear();
final PublishOfferResponse unshareResponse = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been unshared", unshareResponse.isOk(), is(true));
final StudentApplicationRequest rejectStudentRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.REJECTED_BY_SENDING_COUNTRY);
rejectStudentRequest.setRejectInternalComment("reject internal comment");
rejectStudentRequest.setRejectDescription("reject description");
final StudentApplicationResponse rejectStudentResponse = students.processApplicationStatus(austriaToken, rejectStudentRequest);
assertThat("Student has been rejected by Austria (sending country)", rejectStudentResponse.isOk(), is(true));
final StudentApplication rejectedApplication = rejectStudentResponse.getStudentApplication();
assertThat(rejectedApplication.getRejectDescription(), is(rejectStudentRequest.getRejectDescription()));
assertThat(rejectedApplication.getRejectInternalComment(), is(rejectStudentRequest.getRejectInternalComment()));
}
@Test
public void testCancelNominatedApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001006", "Employer", "PL");
final OfferResponse saveResponse = exchange.processOffer(token, new ProcessOfferRequest(offer));
assertThat("Offer has been saved", saveResponse.isOk(), is(true));
final Set<String> offersToShare = new HashSet<>(1);
final String offerId = saveResponse.getOffer().getOfferId();
offersToShare.add(offerId);
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been shared to 2 countries", publishResponse1.isOk(), is(true));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat("Student has been saved", createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(saveResponse.getOffer());
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(austriaToken, createApplicationsRequest);
final StudentApplication studentApplication = createApplicationResponse.getStudentApplication();
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
final StudentApplicationRequest nominateStudentRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.NOMINATED);
final StudentApplicationResponse nominateStudentResponse = students.processApplicationStatus(austriaToken, nominateStudentRequest);
assertThat("Student has been nominated by Austria to Poland", nominateStudentResponse.isOk(), is(true));
assertThat("Application state is NOMINATED", nominateStudentResponse.getStudentApplication().getStatus(), is(ApplicationStatus.NOMINATED));
final StudentApplicationRequest cancelStudentRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.CANCELLED);
final StudentApplicationResponse rejectStudentResponse = students.processApplicationStatus(austriaToken, cancelStudentRequest);
assertThat("Student has been canceled by Austria", rejectStudentResponse.isOk(), is(true));
final StudentApplication rejectedApplication = rejectStudentResponse.getStudentApplication();
assertThat(rejectedApplication.getStatus(), is(ApplicationStatus.CANCELLED));
}
@Test
public void testApplyCancelledApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001007", "Employer", "PL");
final OfferResponse saveResponse = exchange.processOffer(token, new ProcessOfferRequest(offer));
assertThat("Offer has been saved", saveResponse.isOk(), is(true));
final Set<String> offersToShare = new HashSet<>(1);
final String offerId = saveResponse.getOffer().getOfferId();
offersToShare.add(offerId);
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been shared to 2 countries", publishResponse1.isOk(), is(true));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat("Student has been saved", createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(saveResponse.getOffer());
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(austriaToken, createApplicationsRequest);
final StudentApplication studentApplication = createApplicationResponse.getStudentApplication();
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
final StudentApplicationRequest cancelStudentApplicationRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.CANCELLED);
final StudentApplicationResponse cancelStudentApplicationResponse = students.processApplicationStatus(austriaToken, cancelStudentApplicationRequest);
assertThat("Student has been cancelled", cancelStudentApplicationResponse.isOk(), is(true));
assertThat("Application state is CANCELLED", cancelStudentApplicationResponse.getStudentApplication().getStatus(), is(ApplicationStatus.CANCELLED));
final StudentApplicationRequest applyStudentRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.APPLIED);
final StudentApplicationResponse rejectStudentResponse = students.processApplicationStatus(austriaToken, applyStudentRequest);
assertThat("Student has been canceled by Austria", rejectStudentResponse.isOk(), is(true));
final StudentApplication rejectedApplication = rejectStudentResponse.getStudentApplication();
assertThat(rejectedApplication.getStatus(), is(ApplicationStatus.APPLIED));
}
@Test
public void testAcceptAtEmployerApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001008", "Employer", "PL");
final OfferResponse saveResponse = exchange.processOffer(token, new ProcessOfferRequest(offer));
assertThat("Offer has been saved", saveResponse.isOk(), is(true));
final Set<String> offersToShare = new HashSet<>(1);
final String offerId = saveResponse.getOffer().getOfferId();
offersToShare.add(offerId);
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been shared to 2 countries", publishResponse1.isOk(), is(true));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat("Student has been saved", createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(saveResponse.getOffer());
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(austriaToken, createApplicationsRequest);
final StudentApplication studentApplication = createApplicationResponse.getStudentApplication();
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
final StudentApplicationRequest nominateStudentApplicationRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.NOMINATED);
final StudentApplicationResponse nominateStudentApplicationResponse = students.processApplicationStatus(austriaToken, nominateStudentApplicationRequest);
assertThat("Student has been nominated by Austria to Poland", nominateStudentApplicationResponse.isOk(), is(true));
assertThat("Application state is NOMINATED", nominateStudentApplicationResponse.getStudentApplication().getStatus(), is(ApplicationStatus.NOMINATED));
final StudentApplicationRequest forwardStudentApplicationRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.FORWARDED_TO_EMPLOYER);
final StudentApplicationResponse forwardStudentApplicationResponse = students.processApplicationStatus(token, forwardStudentApplicationRequest);
assertThat("Student has been forwarded to employer", forwardStudentApplicationResponse.isOk(), is(true));
assertThat("Application state is FORWARDED_TO_EMPLOYER", forwardStudentApplicationResponse.getStudentApplication().getStatus(), is(ApplicationStatus.FORWARDED_TO_EMPLOYER));
final StudentApplicationRequest acceptStudentApplicationRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.ACCEPTED);
final StudentApplicationResponse acceptStudentApplicationResponse = students.processApplicationStatus(token, acceptStudentApplicationRequest);
assertThat("Student has been accepted", acceptStudentApplicationResponse.isOk(), is(true));
assertThat(acceptStudentApplicationResponse.getStudentApplication().getStatus(), is(ApplicationStatus.ACCEPTED));
}
@Test
public void testCancelAcceptedApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001009", "Employer", "PL");
final OfferResponse saveResponse = exchange.processOffer(token, new ProcessOfferRequest(offer));
assertThat("Offer has been saved", saveResponse.isOk(), is(true));
final Set<String> offersToShare = new HashSet<>(1);
final String offerId = saveResponse.getOffer().getOfferId();
offersToShare.add(offerId);
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been shared to 2 countries", publishResponse1.isOk(), is(true));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat("Student has been saved", createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(saveResponse.getOffer());
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(austriaToken, createApplicationsRequest);
final StudentApplication studentApplication = createApplicationResponse.getStudentApplication();
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
final StudentApplicationRequest nominateStudentApplicationRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.NOMINATED);
final StudentApplicationResponse nominateStudentApplicationResponse = students.processApplicationStatus(austriaToken, nominateStudentApplicationRequest);
assertThat("Student has been nominated by Austria to Poland", nominateStudentApplicationResponse.isOk(), is(true));
assertThat("Application state is NOMINATED", nominateStudentApplicationResponse.getStudentApplication().getStatus(), is(ApplicationStatus.NOMINATED));
final StudentApplicationRequest forwardStudentApplicationRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.FORWARDED_TO_EMPLOYER);
final StudentApplicationResponse forwardStudentApplicationResponse = students.processApplicationStatus(token, forwardStudentApplicationRequest);
assertThat("Student has been forwarded to employer", forwardStudentApplicationResponse.isOk(), is(true));
assertThat("Application state is FORWARDED_TO_EMPLOYER", forwardStudentApplicationResponse.getStudentApplication().getStatus(), is(ApplicationStatus.FORWARDED_TO_EMPLOYER));
final StudentApplicationRequest acceptStudentApplicationRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.ACCEPTED);
final StudentApplicationResponse acceptStudentApplicationResponse = students.processApplicationStatus(token, acceptStudentApplicationRequest);
assertThat("Student has been accepted", acceptStudentApplicationResponse.isOk(), is(true));
assertThat(acceptStudentApplicationResponse.getStudentApplication().getStatus(), is(ApplicationStatus.ACCEPTED));
final StudentApplicationRequest cancelStudentApplicationRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.CANCELLED);
final StudentApplicationResponse cancelStudentApplicationResponse = students.processApplicationStatus(austriaToken, cancelStudentApplicationRequest);
assertThat("Student has been cancelled", cancelStudentApplicationResponse.isOk(), is(true));
assertThat("Application state is CANCELLED", cancelStudentApplicationResponse.getStudentApplication().getStatus(), is(ApplicationStatus.CANCELLED));
}
@Test
public void testFetchSharedDomesticOfferWithApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final String refNo = "AT-2014-000003";
final Offer offer = TestData.prepareMinimalOffer(refNo, "Employer", "PL");
offer.setPrivateComment("austria");
final ProcessOfferRequest offerRequest = new ProcessOfferRequest(offer);
final OfferResponse processResponse = exchange.processOffer(austriaToken, offerRequest);
assertThat("verify that the offer was persisted", processResponse.isOk(), is(true));
assertThat(processResponse.getOffer().getStatus(), is(OfferState.NEW));
final Set<String> offersToShare = new HashSet<>(1);
offersToShare.add(processResponse.getOffer().getOfferId());
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferRequest publishRequest = new PublishOfferRequest(offersToShare, groupIds, nominationDeadline);
final PublishOfferResponse publishResponse = exchange.processPublishOffer(austriaToken, publishRequest);
assertThat("verify that there was no error during sharing the offer", publishResponse.getError(), is(IWSErrors.SUCCESS));
assertThat("verify that the offer was successfully shared with Croatia", publishResponse.isOk(), is(true));
final FetchOffersRequest requestHr1 = new FetchOffersRequest(FetchType.SHARED);
final FetchOffersResponse fetchResponseHr1 = exchange.fetchOffers(croatiaToken, requestHr1);
final Offer readOfferHr1 = findOfferFromResponse(refNo, fetchResponseHr1);
assertThat("Foreign offer was loaded", readOfferHr1, is(not(nullValue())));
assertThat("Foreign offer has correct state", readOfferHr1.getStatus(), is(OfferState.SHARED));
final CreateUserRequest createUserRequest = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest.setStudentAccount(true);
final CreateUserResponse createStudentResponse = administration.createUser(croatiaToken, createUserRequest);
assertThat("Student has been saved", createStudentResponse.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(croatiaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(readOfferHr1);
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("DE"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(croatiaToken, createApplicationsRequest);
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
final FetchOffersRequest requestHr = new FetchOffersRequest(FetchType.SHARED);
final FetchOffersResponse fetchResponseHr = exchange.fetchOffers(croatiaToken, requestHr);
final Offer readOfferHr = findOfferFromResponse(refNo, fetchResponseHr);
assertThat("Foreign offer was loaded", readOfferHr, is(not(nullValue())));
assertThat("Foreign offer has correct state", readOfferHr.getStatus(), is(OfferState.APPLICATIONS));
assertThat("Foreign offer should not see private comment", readOfferHr.getPrivateComment(), is(nullValue()));
final FetchOffersRequest requestAt = new FetchOffersRequest(FetchType.ALL);
final FetchOffersResponse fetchResponseAt = exchange.fetchOffers(austriaToken, requestAt);
final Offer readOfferAt = findOfferFromResponse(refNo, fetchResponseAt);
assertThat("Domestic offer was loaded", readOfferAt, is(not(nullValue())));
assertThat("Domestic offer has correct state", readOfferAt.getStatus(), is(OfferState.SHARED));
assertThat("Domestic offer should see private comment", readOfferAt.getPrivateComment(), is("austria"));
}
private static Offer findOfferFromResponse(final String refno, final FetchOffersResponse response) {
// As the IWS is replacing the new Reference Number with the correct
// year, the only valid information to go on is the running number.
// Hence, we're skipping everything before that
final String refNoLowerCase = refno.toLowerCase(IWSConstants.DEFAULT_LOCALE).substring(8);
Offer offer = null;
for (final Offer found : response.getOffers()) {
final String foundRefNo = found.getRefNo().toLowerCase(IWSConstants.DEFAULT_LOCALE);
if (foundRefNo.contains(refNoLowerCase)) {
offer = found;
}
}
return offer;
}
private static StudentApplication findApplicationFromResponse(final String applicationId, final FetchStudentApplicationsResponse response) {
for (final StudentApplication found : response.getStudentApplications()) {
if (found.getApplicationId().equals(applicationId)) {
return found;
}
}
return null;
}
}
| iws-client/src/test/java/net/iaeste/iws/client/exchange/StudentTest.java | /*
* =============================================================================
* Copyright 1998-2014, IAESTE Internet Development Team. All rights reserved.
* ----------------------------------------------------------------------------
* Project: IntraWeb Services (iws-client) - net.iaeste.iws.client.exchange.StudentTest
* -----------------------------------------------------------------------------
* This software is provided by the members of the IAESTE Internet Development
* Team (IDT) to IAESTE A.s.b.l. It is for internal use only and may not be
* redistributed. IAESTE A.s.b.l. is not permitted to sell this software.
*
* This software is provided "as is"; the IDT or individuals within the IDT
* cannot be held legally responsible for any problems the software may cause.
* =============================================================================
*/
package net.iaeste.iws.client.exchange;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import net.iaeste.iws.api.Administration;
import net.iaeste.iws.api.Exchange;
import net.iaeste.iws.api.Students;
import net.iaeste.iws.api.constants.IWSConstants;
import net.iaeste.iws.api.constants.IWSErrors;
import net.iaeste.iws.api.dtos.AuthenticationToken;
import net.iaeste.iws.api.dtos.Group;
import net.iaeste.iws.api.dtos.TestData;
import net.iaeste.iws.api.dtos.exchange.Offer;
import net.iaeste.iws.api.dtos.exchange.Student;
import net.iaeste.iws.api.dtos.exchange.StudentApplication;
import net.iaeste.iws.api.enums.FetchType;
import net.iaeste.iws.api.enums.Gender;
import net.iaeste.iws.api.enums.exchange.ApplicationStatus;
import net.iaeste.iws.api.enums.exchange.OfferState;
import net.iaeste.iws.api.requests.CreateUserRequest;
import net.iaeste.iws.api.requests.exchange.FetchOffersRequest;
import net.iaeste.iws.api.requests.exchange.FetchPublishedGroupsRequest;
import net.iaeste.iws.api.requests.exchange.ProcessOfferRequest;
import net.iaeste.iws.api.requests.exchange.PublishOfferRequest;
import net.iaeste.iws.api.requests.student.FetchStudentApplicationsRequest;
import net.iaeste.iws.api.requests.student.FetchStudentsRequest;
import net.iaeste.iws.api.requests.student.ProcessStudentApplicationsRequest;
import net.iaeste.iws.api.requests.student.StudentApplicationRequest;
import net.iaeste.iws.api.requests.student.StudentRequest;
import net.iaeste.iws.api.responses.CreateUserResponse;
import net.iaeste.iws.api.responses.exchange.FetchOffersResponse;
import net.iaeste.iws.api.responses.exchange.FetchPublishedGroupsResponse;
import net.iaeste.iws.api.responses.exchange.OfferResponse;
import net.iaeste.iws.api.responses.exchange.PublishOfferResponse;
import net.iaeste.iws.api.responses.student.FetchStudentApplicationsResponse;
import net.iaeste.iws.api.responses.student.FetchStudentsResponse;
import net.iaeste.iws.api.responses.student.StudentApplicationResponse;
import net.iaeste.iws.api.responses.student.StudentResponse;
import net.iaeste.iws.api.util.Copier;
import net.iaeste.iws.api.util.Date;
import net.iaeste.iws.api.util.DatePeriod;
import net.iaeste.iws.api.util.DateTime;
import net.iaeste.iws.client.AbstractTest;
import net.iaeste.iws.client.AdministrationClient;
import net.iaeste.iws.client.ExchangeClient;
import net.iaeste.iws.client.StudentClient;
import org.junit.Ignore;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Pavel Fiala / last $Author:$
* @version $Revision:$ / $Date:$
* @since 1.7
*/
public final class StudentTest extends AbstractTest {
private final Administration administration = new AdministrationClient();
private final Exchange exchange = new ExchangeClient();
private final Students students = new StudentClient();
private AuthenticationToken austriaToken = null;
private AuthenticationToken croatiaToken = null;
@Override
public void setup() {
token = login("[email protected]", "poland");
austriaToken = login("[email protected]", "austria");
croatiaToken = login("[email protected]", "croatia");
}
@Override
public void tearDown() {
logout(token);
logout(austriaToken);
logout(croatiaToken);
}
@Test
public void testProcessStudentApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001001", "Employer", "PL");
final ProcessOfferRequest offerRequest = new ProcessOfferRequest(offer);
final OfferResponse saveResponse = exchange.processOffer(token, offerRequest);
final String refNo = saveResponse.getOffer().getRefNo();
// verify processResponse
assertThat(saveResponse.isOk(), is(true));
final FetchOffersRequest allOffersRequest = new FetchOffersRequest(FetchType.ALL);
FetchOffersResponse allOffersResponse = exchange.fetchOffers(token, allOffersRequest);
assertThat(allOffersResponse.getOffers().isEmpty(), is(false));
Offer sharedOffer = findOfferFromResponse(saveResponse.getOffer().getRefNo(), allOffersResponse);
assertThat(sharedOffer, is(not(nullValue())));
assertThat(sharedOffer.getStatus(), is(OfferState.NEW));
assertThat(sharedOffer.getNominationDeadline(), is(not(nominationDeadline)));
final Set<String> offersToShare = new HashSet<>(1);
offersToShare.add(sharedOffer.getOfferId());
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferRequest publishRequest1 = new PublishOfferRequest(offersToShare, groupIds, nominationDeadline);
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, publishRequest1);
assertThat(publishResponse1.getError(), is(IWSErrors.SUCCESS));
assertThat(publishResponse1.isOk(), is(true));
final List<String> offersExternalId = new ArrayList<>(1);
offersExternalId.add(sharedOffer.getOfferId());
final FetchPublishedGroupsRequest fetchPublishRequest = new FetchPublishedGroupsRequest(offersExternalId);
final FetchPublishedGroupsResponse fetchPublishResponse1 = exchange.fetchPublishedGroups(token, fetchPublishRequest);
//is it shared to two groups?
assertThat(fetchPublishResponse1.isOk(), is(true));
final List<Group> offerGroupsSharedTo = fetchPublishResponse1.getOffersGroups().get(offersExternalId.get(0));
assertThat(2, is(offerGroupsSharedTo.size()));
allOffersResponse = exchange.fetchOffers(token, allOffersRequest);
assertThat(allOffersResponse.getOffers().isEmpty(), is(false));
sharedOffer = findOfferFromResponse(saveResponse.getOffer().getRefNo(), allOffersResponse);
assertThat(sharedOffer, is(not(nullValue())));
assertThat(sharedOffer.getRefNo(), is(saveResponse.getOffer().getRefNo()));
assertThat("The offer is shared now, the status has to be SHARED", sharedOffer.getStatus(), is(OfferState.SHARED));
assertThat(sharedOffer.getNominationDeadline(), is(nominationDeadline));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat(createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat(fetchStudentsResponse.isOk(), is(true));
assertThat(fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(sharedOffer);
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createStudentApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createStudentApplicationResponse = students.processStudentApplication(austriaToken, createStudentApplicationsRequest);
assertThat(createStudentApplicationResponse.isOk(), is(true));
}
@Test
@Ignore("2014-01-17 Pavel - test fails due to wrong data gets from TestData, see #646")
public void testFetchStudentApplications() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001003", "Employer", "PL");
final ProcessOfferRequest offerRequest = new ProcessOfferRequest(offer);
final OfferResponse saveResponse = exchange.processOffer(token, offerRequest);
final String refNo = saveResponse.getOffer().getRefNo();
// verify processResponse
assertThat(saveResponse.isOk(), is(true));
final FetchOffersRequest allOffersRequest = new FetchOffersRequest(FetchType.ALL);
FetchOffersResponse allOffersResponse = exchange.fetchOffers(token, allOffersRequest);
assertThat(allOffersResponse.getOffers().isEmpty(), is(false));
Offer sharedOffer = findOfferFromResponse(refNo, allOffersResponse);
assertThat(sharedOffer, is(not(nullValue())));
assertThat(sharedOffer.getStatus(), is(OfferState.NEW));
assertThat(sharedOffer.getNominationDeadline(), is(not(nominationDeadline)));
final Set<String> offersToShare = new HashSet<>(1);
offersToShare.add(sharedOffer.getOfferId());
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferRequest publishRequest1 = new PublishOfferRequest(offersToShare, groupIds, nominationDeadline);
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, publishRequest1);
assertThat(publishResponse1.getError(), is(IWSErrors.SUCCESS));
assertThat(publishResponse1.isOk(), is(true));
final List<String> offersExternalId = new ArrayList<>(1);
offersExternalId.add(sharedOffer.getOfferId());
final FetchPublishedGroupsRequest fetchPublishRequest = new FetchPublishedGroupsRequest(offersExternalId);
final FetchPublishedGroupsResponse fetchPublishResponse1 = exchange.fetchPublishedGroups(token, fetchPublishRequest);
//is it shared to two groups?
assertThat(fetchPublishResponse1.isOk(), is(true));
final List<Group> offerGroupsSharedTo = fetchPublishResponse1.getOffersGroups().get(offersExternalId.get(0));
assertThat(2, is(offerGroupsSharedTo.size()));
allOffersResponse = exchange.fetchOffers(token, allOffersRequest);
assertThat(allOffersResponse.getOffers().isEmpty(), is(false));
sharedOffer = findOfferFromResponse(saveResponse.getOffer().getRefNo(), allOffersResponse);
assertThat(sharedOffer, is(not(nullValue())));
assertThat(sharedOffer.getRefNo(), is(saveResponse.getOffer().getRefNo()));
assertThat("The offer is shared now, the status has to be SHARED", sharedOffer.getStatus(), is(OfferState.SHARED));
assertThat(sharedOffer.getNominationDeadline(), is(nominationDeadline));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat(createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat(fetchStudentsResponse.isOk(), is(true));
assertThat(fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(sharedOffer);
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
application.setGender(Gender.FEMALE);
application.setNationality(TestData.prepareCountry("DE"));
final ProcessStudentApplicationsRequest createStudentApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createStudentApplicationResponse = students.processStudentApplication(austriaToken, createStudentApplicationsRequest);
assertThat(createStudentApplicationResponse.isOk(), is(true));
final FetchStudentApplicationsRequest fetchStudentApplicationsRequest = new FetchStudentApplicationsRequest(sharedOffer.getOfferId());
final FetchStudentApplicationsResponse fetchStudentApplicationsResponse = students.fetchStudentApplications(austriaToken, fetchStudentApplicationsRequest);
assertThat(fetchStudentApplicationsResponse.isOk(), is(true));
assertThat(fetchStudentApplicationsResponse.getStudentApplications().size(), is(1));
final StudentApplication fetchedApplication = fetchStudentApplicationsResponse.getStudentApplications().get(0);
assertThat(fetchedApplication.getGender(), is(application.getGender()));
assertThat(fetchedApplication.getGender(), is(application.getGender()));
assertThat(fetchedApplication.getNationality(), is(application.getNationality()));
}
//TODO Kim, have a look at this test please
//@Ignore("2013-21-04 Pavel - failing OfferGroupEntity with id xyz cannot be found even it exists in DB. See #515")
@Test
public void testUpdateStudentApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001002", "Employer", "PL");
final ProcessOfferRequest offerRequest = new ProcessOfferRequest(offer);
final OfferResponse saveResponse = exchange.processOffer(token, offerRequest);
final String refNo = saveResponse.getOffer().getRefNo();
// verify processResponse
assertThat(saveResponse.isOk(), is(true));
final FetchOffersRequest allOffersRequest = new FetchOffersRequest(FetchType.ALL);
FetchOffersResponse allOffersResponse = exchange.fetchOffers(token, allOffersRequest);
assertThat(allOffersResponse.getOffers().isEmpty(), is(false));
Offer sharedOffer = findOfferFromResponse(saveResponse.getOffer().getRefNo(), allOffersResponse);
assertThat(sharedOffer, is(not(nullValue())));
assertThat(sharedOffer.getStatus(), is(OfferState.NEW));
assertThat(sharedOffer.getNominationDeadline(), is(not(nominationDeadline)));
final Set<String> offersToShare = new HashSet<>(1);
offersToShare.add(sharedOffer.getOfferId());
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferRequest publishRequest1 = new PublishOfferRequest(offersToShare, groupIds, nominationDeadline);
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, publishRequest1);
assertThat(publishResponse1.getError(), is(IWSErrors.SUCCESS));
assertThat(publishResponse1.isOk(), is(true));
final List<String> offersExternalId = new ArrayList<>(1);
offersExternalId.add(sharedOffer.getOfferId());
final FetchPublishedGroupsRequest fetchPublishRequest = new FetchPublishedGroupsRequest(offersExternalId);
final FetchPublishedGroupsResponse fetchPublishResponse1 = exchange.fetchPublishedGroups(token, fetchPublishRequest);
//is it shared to two groups?
assertThat(fetchPublishResponse1.isOk(), is(true));
final List<Group> offerGroupsSharedTo = fetchPublishResponse1.getOffersGroups().get(offersExternalId.get(0));
assertThat(2, is(offerGroupsSharedTo.size()));
allOffersResponse = exchange.fetchOffers(token, allOffersRequest);
assertThat(allOffersResponse.getOffers().isEmpty(), is(false));
sharedOffer = findOfferFromResponse(saveResponse.getOffer().getRefNo(), allOffersResponse);
assertThat(sharedOffer, is(not(nullValue())));
assertThat(sharedOffer.getRefNo(), is(saveResponse.getOffer().getRefNo()));
assertThat("The offer is shared now, the status has to be SHARED", sharedOffer.getStatus(), is(OfferState.SHARED));
assertThat(sharedOffer.getNominationDeadline(), is(nominationDeadline));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat(createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat(fetchStudentsResponse.isOk(), is(true));
assertThat(fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
StudentApplication application = new StudentApplication();
application.setOffer(sharedOffer);
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createStudentApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createStudentApplicationResponse = students.processStudentApplication(austriaToken, createStudentApplicationsRequest);
assertThat(createStudentApplicationResponse.isOk(), is(true));
//test updating existing application
application = Copier.copy(createStudentApplicationResponse.getStudentApplication());
application.setUniversity("MyUniversity");
final ProcessStudentApplicationsRequest createStudentApplicationsRequest2 = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createStudentApplicationResponse2 = students.processStudentApplication(austriaToken, createStudentApplicationsRequest2);
assertThat(createStudentApplicationResponse2.isOk(), is(true));
assertThat(createStudentApplicationResponse2.getStudentApplication().getUniversity(), is(application.getUniversity()));
}
//TODO Kim, have a look at this test please
//@Ignore("2013-21-04 Pavel - failing OfferGroupEntity with id xyz cannot be found even it exists in DB. See #515")
@Test
public void testNominatingApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001004", "Employer", "PL");
final OfferResponse saveResponse = exchange.processOffer(token, new ProcessOfferRequest(offer));
assertThat("Offer has been saved", saveResponse.isOk(), is(true));
final Set<String> offersToShare = new HashSet<>(1);
final String offerId = saveResponse.getOffer().getOfferId();
offersToShare.add(offerId);
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been shared to 2 countries", publishResponse1.isOk(), is(true));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat("Student has been saved", createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(saveResponse.getOffer());
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(austriaToken, createApplicationsRequest);
final StudentApplication studentApplication = createApplicationResponse.getStudentApplication();
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
final StudentApplicationRequest nominateStudentRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.NOMINATED);
final StudentApplicationResponse nominateStudentResponse = students.processApplicationStatus(austriaToken, nominateStudentRequest);
assertThat("Student has been nominated by Austria to Poland", nominateStudentResponse.isOk(), is(true));
assertThat("Application state is NOMINATED", nominateStudentResponse.getStudentApplication().getStatus(), is(ApplicationStatus.NOMINATED));
assertThat(nominateStudentResponse.getStudentApplication().getNominatedAt(), not(nullValue()));
final DateTime beforeNominationDate = new DateTime();
final FetchStudentApplicationsRequest fetchApplicationsRequest = new FetchStudentApplicationsRequest(offerId);
final FetchStudentApplicationsResponse fetchApplicationsResponse = students.fetchStudentApplications(austriaToken, fetchApplicationsRequest);
assertThat(fetchApplicationsResponse.isOk(), is(true));
final StudentApplication foundApplication = findApplicationFromResponse(studentApplication.getApplicationId(), fetchApplicationsResponse);
assertThat("Make sure that new application state has been persisted", foundApplication.getStatus(), is(ApplicationStatus.NOMINATED));
assertThat("Nomination date is set", foundApplication.getNominatedAt(), not(nullValue()));
}
@Test
public void testProcessStudent() {
final CreateUserRequest createUserRequest = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest.setStudentAccount(true);
final CreateUserResponse createStudentResponse = administration.createUser(austriaToken, createUserRequest);
assertThat(createStudentResponse.isOk(), is(true));
final Student newStudent = new Student();
newStudent.setUser(createStudentResponse.getUser());
final StudentRequest processStudentRequest = new StudentRequest(newStudent);
final StudentResponse processStudentResponse = students.processStudent(austriaToken, processStudentRequest);
assertThat(processStudentResponse.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat(fetchStudentsResponse.isOk(), is(true));
}
@Test
public void testRejectNominatedApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001005", "Employer", "PL");
final OfferResponse saveResponse = exchange.processOffer(token, new ProcessOfferRequest(offer));
assertThat("Offer has been saved", saveResponse.isOk(), is(true));
final Set<String> offersToShare = new HashSet<>(1);
final String offerId = saveResponse.getOffer().getOfferId();
offersToShare.add(offerId);
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been shared to 2 countries", publishResponse1.isOk(), is(true));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat("Student has been saved", createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(saveResponse.getOffer());
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(austriaToken, createApplicationsRequest);
final StudentApplication studentApplication = createApplicationResponse.getStudentApplication();
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
final StudentApplicationRequest nominateStudentRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.NOMINATED);
final StudentApplicationResponse nominateStudentResponse = students.processApplicationStatus(austriaToken, nominateStudentRequest);
assertThat("Student has been nominated by Austria to Poland", nominateStudentResponse.isOk(), is(true));
assertThat("Application state is NOMINATED", nominateStudentResponse.getStudentApplication().getStatus(), is(ApplicationStatus.NOMINATED));
final StudentApplicationRequest rejectStudentRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.REJECTED);
rejectStudentRequest.setRejectInternalComment("reject internal comment");
rejectStudentRequest.setRejectDescription("reject description");
rejectStudentRequest.setRejectByEmployerReason("reject employer reason");
final StudentApplicationResponse rejectStudentResponse = students.processApplicationStatus(token, rejectStudentRequest);
assertThat("Student has been rejected by Poland", rejectStudentResponse.isOk(), is(true));
final StudentApplication rejectedApplication = rejectStudentResponse.getStudentApplication();
assertThat(rejectedApplication.getRejectByEmployerReason(), is(rejectStudentRequest.getRejectByEmployerReason()));
assertThat(rejectedApplication.getRejectDescription(), is(rejectStudentRequest.getRejectDescription()));
assertThat(rejectedApplication.getRejectInternalComment(), is(rejectStudentRequest.getRejectInternalComment()));
}
@Test
public void testRejectAppliedApplicationBySendingCountry() {
//Sending country is only allowed to reject applied application
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001065", "Employer", "PL");
final OfferResponse saveResponse = exchange.processOffer(token, new ProcessOfferRequest(offer));
assertThat("Offer has been saved", saveResponse.isOk(), is(true));
final Set<String> offersToShare = new HashSet<>(1);
final String offerId = saveResponse.getOffer().getOfferId();
offersToShare.add(offerId);
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been shared to 2 countries", publishResponse1.isOk(), is(true));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat("Student has been saved", createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(saveResponse.getOffer());
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(austriaToken, createApplicationsRequest);
final StudentApplication studentApplication = createApplicationResponse.getStudentApplication();
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
final StudentApplicationRequest rejectStudentRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.REJECTED_BY_SENDING_COUNTRY);
rejectStudentRequest.setRejectInternalComment("reject internal comment");
rejectStudentRequest.setRejectDescription("reject description");
final StudentApplicationResponse rejectStudentResponse = students.processApplicationStatus(austriaToken, rejectStudentRequest);
assertThat("Student has been rejected by Austria (sending country)", rejectStudentResponse.isOk(), is(true));
final StudentApplication rejectedApplication = rejectStudentResponse.getStudentApplication();
assertThat(rejectedApplication.getRejectDescription(), is(rejectStudentRequest.getRejectDescription()));
assertThat(rejectedApplication.getRejectInternalComment(), is(rejectStudentRequest.getRejectInternalComment()));
}
@Test
public void testRejectApplicationBySendingCountryForClosedOffer() {
//Sending country is only allowed to reject applied application
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001065", "Employer", "PL");
final OfferResponse saveResponse = exchange.processOffer(token, new ProcessOfferRequest(offer));
assertThat("Offer has been saved", saveResponse.isOk(), is(true));
final Set<String> offersToShare = new HashSet<>(1);
final String offerId = saveResponse.getOffer().getOfferId();
offersToShare.add(offerId);
List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been shared to 2 countries", publishResponse1.isOk(), is(true));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat("Student has been saved", createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(saveResponse.getOffer());
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(austriaToken, createApplicationsRequest);
final StudentApplication studentApplication = createApplicationResponse.getStudentApplication();
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
//usnhare offer
groupIds.clear();
final PublishOfferResponse unshareResponse = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been unshared", unshareResponse.isOk(), is(true));
final StudentApplicationRequest rejectStudentRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.REJECTED_BY_SENDING_COUNTRY);
rejectStudentRequest.setRejectInternalComment("reject internal comment");
rejectStudentRequest.setRejectDescription("reject description");
final StudentApplicationResponse rejectStudentResponse = students.processApplicationStatus(austriaToken, rejectStudentRequest);
assertThat("Student has been rejected by Austria (sending country)", rejectStudentResponse.isOk(), is(true));
final StudentApplication rejectedApplication = rejectStudentResponse.getStudentApplication();
assertThat(rejectedApplication.getRejectDescription(), is(rejectStudentRequest.getRejectDescription()));
assertThat(rejectedApplication.getRejectInternalComment(), is(rejectStudentRequest.getRejectInternalComment()));
}
@Test
public void testCancelNominatedApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001006", "Employer", "PL");
final OfferResponse saveResponse = exchange.processOffer(token, new ProcessOfferRequest(offer));
assertThat("Offer has been saved", saveResponse.isOk(), is(true));
final Set<String> offersToShare = new HashSet<>(1);
final String offerId = saveResponse.getOffer().getOfferId();
offersToShare.add(offerId);
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been shared to 2 countries", publishResponse1.isOk(), is(true));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat("Student has been saved", createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(saveResponse.getOffer());
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(austriaToken, createApplicationsRequest);
final StudentApplication studentApplication = createApplicationResponse.getStudentApplication();
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
final StudentApplicationRequest nominateStudentRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.NOMINATED);
final StudentApplicationResponse nominateStudentResponse = students.processApplicationStatus(austriaToken, nominateStudentRequest);
assertThat("Student has been nominated by Austria to Poland", nominateStudentResponse.isOk(), is(true));
assertThat("Application state is NOMINATED", nominateStudentResponse.getStudentApplication().getStatus(), is(ApplicationStatus.NOMINATED));
final StudentApplicationRequest cancelStudentRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.CANCELLED);
final StudentApplicationResponse rejectStudentResponse = students.processApplicationStatus(austriaToken, cancelStudentRequest);
assertThat("Student has been canceled by Austria", rejectStudentResponse.isOk(), is(true));
final StudentApplication rejectedApplication = rejectStudentResponse.getStudentApplication();
assertThat(rejectedApplication.getStatus(), is(ApplicationStatus.CANCELLED));
}
@Test
public void testApplyCancelledApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001007", "Employer", "PL");
final OfferResponse saveResponse = exchange.processOffer(token, new ProcessOfferRequest(offer));
assertThat("Offer has been saved", saveResponse.isOk(), is(true));
final Set<String> offersToShare = new HashSet<>(1);
final String offerId = saveResponse.getOffer().getOfferId();
offersToShare.add(offerId);
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been shared to 2 countries", publishResponse1.isOk(), is(true));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat("Student has been saved", createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(saveResponse.getOffer());
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(austriaToken, createApplicationsRequest);
final StudentApplication studentApplication = createApplicationResponse.getStudentApplication();
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
final StudentApplicationRequest cancelStudentApplicationRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.CANCELLED);
final StudentApplicationResponse cancelStudentApplicationResponse = students.processApplicationStatus(austriaToken, cancelStudentApplicationRequest);
assertThat("Student has been cancelled", cancelStudentApplicationResponse.isOk(), is(true));
assertThat("Application state is CANCELLED", cancelStudentApplicationResponse.getStudentApplication().getStatus(), is(ApplicationStatus.CANCELLED));
final StudentApplicationRequest applyStudentRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.APPLIED);
final StudentApplicationResponse rejectStudentResponse = students.processApplicationStatus(austriaToken, applyStudentRequest);
assertThat("Student has been canceled by Austria", rejectStudentResponse.isOk(), is(true));
final StudentApplication rejectedApplication = rejectStudentResponse.getStudentApplication();
assertThat(rejectedApplication.getStatus(), is(ApplicationStatus.APPLIED));
}
@Test
public void testAcceptAtEmployerApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001008", "Employer", "PL");
final OfferResponse saveResponse = exchange.processOffer(token, new ProcessOfferRequest(offer));
assertThat("Offer has been saved", saveResponse.isOk(), is(true));
final Set<String> offersToShare = new HashSet<>(1);
final String offerId = saveResponse.getOffer().getOfferId();
offersToShare.add(offerId);
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been shared to 2 countries", publishResponse1.isOk(), is(true));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat("Student has been saved", createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(saveResponse.getOffer());
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(austriaToken, createApplicationsRequest);
final StudentApplication studentApplication = createApplicationResponse.getStudentApplication();
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
final StudentApplicationRequest nominateStudentApplicationRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.NOMINATED);
final StudentApplicationResponse nominateStudentApplicationResponse = students.processApplicationStatus(austriaToken, nominateStudentApplicationRequest);
assertThat("Student has been nominated by Austria to Poland", nominateStudentApplicationResponse.isOk(), is(true));
assertThat("Application state is NOMINATED", nominateStudentApplicationResponse.getStudentApplication().getStatus(), is(ApplicationStatus.NOMINATED));
final StudentApplicationRequest forwardStudentApplicationRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.FORWARDED_TO_EMPLOYER);
final StudentApplicationResponse forwardStudentApplicationResponse = students.processApplicationStatus(token, forwardStudentApplicationRequest);
assertThat("Student has been forwarded to employer", forwardStudentApplicationResponse.isOk(), is(true));
assertThat("Application state is FORWARDED_TO_EMPLOYER", forwardStudentApplicationResponse.getStudentApplication().getStatus(), is(ApplicationStatus.FORWARDED_TO_EMPLOYER));
final StudentApplicationRequest acceptStudentApplicationRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.ACCEPTED);
final StudentApplicationResponse acceptStudentApplicationResponse = students.processApplicationStatus(token, acceptStudentApplicationRequest);
assertThat("Student has been accepted", acceptStudentApplicationResponse.isOk(), is(true));
assertThat(acceptStudentApplicationResponse.getStudentApplication().getStatus(), is(ApplicationStatus.ACCEPTED));
}
@Test
public void testCancelAcceptedApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final Offer offer = TestData.prepareMinimalOffer("PL-2014-001009", "Employer", "PL");
final OfferResponse saveResponse = exchange.processOffer(token, new ProcessOfferRequest(offer));
assertThat("Offer has been saved", saveResponse.isOk(), is(true));
final Set<String> offersToShare = new HashSet<>(1);
final String offerId = saveResponse.getOffer().getOfferId();
offersToShare.add(offerId);
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(austriaToken).getGroupId());
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferResponse publishResponse1 = exchange.processPublishOffer(token, new PublishOfferRequest(offersToShare, groupIds, nominationDeadline));
assertThat("Offer has been shared to 2 countries", publishResponse1.isOk(), is(true));
final CreateUserRequest createUserRequest1 = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest1.setStudentAccount(true);
final CreateUserResponse createStudentResponse1 = administration.createUser(austriaToken, createUserRequest1);
assertThat("Student has been saved", createStudentResponse1.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(austriaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(saveResponse.getOffer());
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("AT"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(austriaToken, createApplicationsRequest);
final StudentApplication studentApplication = createApplicationResponse.getStudentApplication();
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
final StudentApplicationRequest nominateStudentApplicationRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.NOMINATED);
final StudentApplicationResponse nominateStudentApplicationResponse = students.processApplicationStatus(austriaToken, nominateStudentApplicationRequest);
assertThat("Student has been nominated by Austria to Poland", nominateStudentApplicationResponse.isOk(), is(true));
assertThat("Application state is NOMINATED", nominateStudentApplicationResponse.getStudentApplication().getStatus(), is(ApplicationStatus.NOMINATED));
final StudentApplicationRequest forwardStudentApplicationRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.FORWARDED_TO_EMPLOYER);
final StudentApplicationResponse forwardStudentApplicationResponse = students.processApplicationStatus(token, forwardStudentApplicationRequest);
assertThat("Student has been forwarded to employer", forwardStudentApplicationResponse.isOk(), is(true));
assertThat("Application state is FORWARDED_TO_EMPLOYER", forwardStudentApplicationResponse.getStudentApplication().getStatus(), is(ApplicationStatus.FORWARDED_TO_EMPLOYER));
final StudentApplicationRequest acceptStudentApplicationRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.ACCEPTED);
final StudentApplicationResponse acceptStudentApplicationResponse = students.processApplicationStatus(token, acceptStudentApplicationRequest);
assertThat("Student has been accepted", acceptStudentApplicationResponse.isOk(), is(true));
assertThat(acceptStudentApplicationResponse.getStudentApplication().getStatus(), is(ApplicationStatus.ACCEPTED));
final StudentApplicationRequest cancelStudentApplicationRequest = new StudentApplicationRequest(
studentApplication.getApplicationId(),
ApplicationStatus.CANCELLED);
final StudentApplicationResponse cancelStudentApplicationResponse = students.processApplicationStatus(austriaToken, cancelStudentApplicationRequest);
assertThat("Student has been cancelled", cancelStudentApplicationResponse.isOk(), is(true));
assertThat("Application state is CANCELLED", cancelStudentApplicationResponse.getStudentApplication().getStatus(), is(ApplicationStatus.CANCELLED));
}
@Test
public void testFetchSharedDomesticOfferWithApplication() {
final Date nominationDeadline = new Date().plusDays(20);
final String refNo = "AT-2014-000003";
final Offer offer = TestData.prepareMinimalOffer(refNo, "Employer", "PL");
offer.setPrivateComment("austria");
final ProcessOfferRequest offerRequest = new ProcessOfferRequest(offer);
final OfferResponse processResponse = exchange.processOffer(austriaToken, offerRequest);
assertThat("verify that the offer was persisted", processResponse.isOk(), is(true));
assertThat(processResponse.getOffer().getStatus(), is(OfferState.NEW));
final Set<String> offersToShare = new HashSet<>(1);
offersToShare.add(processResponse.getOffer().getOfferId());
final List<String> groupIds = new ArrayList<>(2);
groupIds.add(findNationalGroup(croatiaToken).getGroupId());
final PublishOfferRequest publishRequest = new PublishOfferRequest(offersToShare, groupIds, nominationDeadline);
final PublishOfferResponse publishResponse = exchange.processPublishOffer(austriaToken, publishRequest);
assertThat("verify that there was no error during sharing the offer", publishResponse.getError(), is(IWSErrors.SUCCESS));
assertThat("verify that the offer was successfully shared with Croatia", publishResponse.isOk(), is(true));
final FetchOffersRequest requestHr1 = new FetchOffersRequest(FetchType.SHARED);
final FetchOffersResponse fetchResponseHr1 = exchange.fetchOffers(croatiaToken, requestHr1);
final Offer readOfferHr1 = findOfferFromResponse(refNo, fetchResponseHr1);
assertThat("Foreign offer was loaded", readOfferHr1, is(not(nullValue())));
assertThat("Foreign offer has correct state", readOfferHr1.getStatus(), is(OfferState.SHARED));
final CreateUserRequest createUserRequest = new CreateUserRequest("[email protected]", "password1", "Student1", "Graduate1");
createUserRequest.setStudentAccount(true);
final CreateUserResponse createStudentResponse = administration.createUser(croatiaToken, createUserRequest);
assertThat("Student has been saved", createStudentResponse.isOk(), is(true));
final FetchStudentsRequest fetchStudentsRequest = new FetchStudentsRequest();
final FetchStudentsResponse fetchStudentsResponse = students.fetchStudents(croatiaToken, fetchStudentsRequest);
assertThat("At least one student has been fetched", fetchStudentsResponse.isOk(), is(true));
assertThat("At least one student has been fetched", fetchStudentsResponse.getStudents().isEmpty(), is(false));
final Student student = fetchStudentsResponse.getStudents().get(0);
student.setAvailable(new DatePeriod(new Date(), nominationDeadline));
final StudentApplication application = new StudentApplication();
application.setOffer(readOfferHr1);
application.setStudent(student);
application.setStatus(ApplicationStatus.APPLIED);
application.setHomeAddress(TestData.prepareAddress("DE"));
application.setAddressDuringTerms(TestData.prepareAddress("DE"));
final ProcessStudentApplicationsRequest createApplicationsRequest = new ProcessStudentApplicationsRequest(application);
final StudentApplicationResponse createApplicationResponse = students.processStudentApplication(croatiaToken, createApplicationsRequest);
assertThat("Student application has been created", createApplicationResponse.isOk(), is(true));
final FetchOffersRequest requestHr = new FetchOffersRequest(FetchType.SHARED);
final FetchOffersResponse fetchResponseHr = exchange.fetchOffers(croatiaToken, requestHr);
final Offer readOfferHr = findOfferFromResponse(refNo, fetchResponseHr);
assertThat("Foreign offer was loaded", readOfferHr, is(not(nullValue())));
assertThat("Foreign offer has correct state", readOfferHr.getStatus(), is(OfferState.APPLICATIONS));
assertThat("Foreign offer should not see private comment", readOfferHr.getPrivateComment(), is(nullValue()));
final FetchOffersRequest requestAt = new FetchOffersRequest(FetchType.ALL);
final FetchOffersResponse fetchResponseAt = exchange.fetchOffers(austriaToken, requestAt);
final Offer readOfferAt = findOfferFromResponse(refNo, fetchResponseAt);
assertThat("Domestic offer was loaded", readOfferAt, is(not(nullValue())));
assertThat("Domestic offer has correct state", readOfferAt.getStatus(), is(OfferState.SHARED));
assertThat("Domestic offer should see private comment", readOfferAt.getPrivateComment(), is("austria"));
}
private static Offer findOfferFromResponse(final String refno, final FetchOffersResponse response) {
// As the IWS is replacing the new Reference Number with the correct
// year, the only valid information to go on is the running number.
// Hence, we're skipping everything before that
final String refNoLowerCase = refno.toLowerCase(IWSConstants.DEFAULT_LOCALE).substring(8);
Offer offer = null;
for (final Offer found : response.getOffers()) {
final String foundRefNo = found.getRefNo().toLowerCase(IWSConstants.DEFAULT_LOCALE);
if (foundRefNo.contains(refNoLowerCase)) {
offer = found;
}
}
return offer;
}
private static StudentApplication findApplicationFromResponse(final String applicationId, final FetchStudentApplicationsResponse response) {
for (final StudentApplication found : response.getStudentApplications()) {
if (found.getApplicationId().equals(applicationId)) {
return found;
}
}
return null;
}
}
| Ignoring failing test.
I've quite a few changes. The test is failing due to some other changes elsewhere. So for now, I've set it to Ignored so it can be fixed separately without compromising the build stability.
| iws-client/src/test/java/net/iaeste/iws/client/exchange/StudentTest.java | Ignoring failing test. |
|
Java | apache-2.0 | 9970f96ec009848b4b6302ece54d8f919c3e9c09 | 0 | kevinsawicki/maven-android-plugin,kedzie/maven-android-plugin,psorobka/android-maven-plugin,CJstar/android-maven-plugin,CJstar/android-maven-plugin,greek1979/maven-android-plugin,hgl888/android-maven-plugin,psorobka/android-maven-plugin,secondsun/maven-android-plugin,mitchhentges/android-maven-plugin,repanda/android-maven-plugin,wskplho/android-maven-plugin,b-cuts/android-maven-plugin,kedzie/maven-android-plugin,WonderCsabo/maven-android-plugin,mitchhentges/android-maven-plugin,repanda/android-maven-plugin,xiaojiaqiao/android-maven-plugin,jdegroot/android-maven-plugin,simpligility/android-maven-plugin,Stuey86/android-maven-plugin,hgl888/android-maven-plugin,b-cuts/android-maven-plugin,jdegroot/android-maven-plugin,ashutoshbhide/android-maven-plugin,wskplho/android-maven-plugin,xiaojiaqiao/android-maven-plugin,xiaojiaqiao/android-maven-plugin,Cha0sX/android-maven-plugin,Stuey86/android-maven-plugin,Cha0sX/android-maven-plugin,WonderCsabo/maven-android-plugin,Cha0sX/android-maven-plugin,greek1979/maven-android-plugin,secondsun/maven-android-plugin,secondsun/maven-android-plugin,xieningtao/android-maven-plugin,xieningtao/android-maven-plugin,ashutoshbhide/android-maven-plugin | /*
* Copyright (C) 2009 Jayway AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jayway.maven.plugins.android;
import org.apache.maven.plugin.MojoExecutionException;
import org.codehaus.plexus.util.ReflectionUtils;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
/**
* Excercises the {@link AndroidSdk} class.
*
* @author [email protected]
*/
public class AndroidSdkTest {
private static final String ENV_ANDROID_SDK_11 = System.getenv("ANDROID_SDK_11");
private static final String ENV_ANDROID_SDK_15 = System.getenv("ANDROID_SDK_15");
public static final AndroidSdk SDK_1_1;
static{
Assert.assertNotNull("For running the tests, you must have environment variable ANDROID_SDK_11 set to a valid Android SDK 1.1 directory.", ENV_ANDROID_SDK_11);
SDK_1_1 = constructAndroidSdkWith(new File(ENV_ANDROID_SDK_11), "1.1");
}
public static final AndroidSdk SDK_1_5;
static{
Assert.assertNotNull("For running the tests, you must have environment variable ANDROID_SDK_15 set to a valid Android SDK 1.5 directory.", ENV_ANDROID_SDK_15);
SDK_1_5 = constructAndroidSdkWith(new File(ENV_ANDROID_SDK_15), "1.5");
}
@Test
public void givenLayout1dot1AndToolAdbThenPathIs1dot1Style() {
final String pathForTool = SDK_1_1.getPathForTool("adb");
Assert.assertEquals(ENV_ANDROID_SDK_11 + "/tools/adb", pathForTool);
}
@Test
public void givenLayout1dot1AndToolAndroidThenPathIs1dot1Style() {
final String pathForTool = SDK_1_1.getPathForTool("android");
Assert.assertEquals(ENV_ANDROID_SDK_11 + "/tools/android", pathForTool);
}
@Test
public void givenLayout1dot1AndToolAaptThenPathIs1dot1Style() {
final String pathForTool = SDK_1_1.getPathForTool("aapt");
Assert.assertEquals(ENV_ANDROID_SDK_11 + "/tools/aapt", pathForTool);
}
@Test
public void givenLayout1dot5AndToolAdbThenPathIsCommon() {
final String pathForTool = SDK_1_5.getPathForTool("adb");
Assert.assertEquals(ENV_ANDROID_SDK_15 + "/tools/adb", pathForTool);
}
@Test
public void givenLayout1dot5AndToolAndroidThenPathIsCommon() {
final String pathForTool = SDK_1_5.getPathForTool("android");
Assert.assertEquals(ENV_ANDROID_SDK_15 + "/tools/android", pathForTool);
}
@Test
public void givenLayout1dot5AndToolAaptAndPlatform1dot1ThenPathIsPlatform1dot1() {
final AndroidSdk sdk = constructAndroidSdkWith(new File(ENV_ANDROID_SDK_15), "1.1");
final String pathForTool = sdk.getPathForTool("aapt");
Assert.assertEquals(ENV_ANDROID_SDK_15 + "/platforms/android-1.1/tools/aapt", pathForTool);
}
@Test
public void givenLayout1dot5AndToolAaptAndPlatform1dot5ThenPathIsPlatform1dot5() {
final AndroidSdk sdk = constructAndroidSdkWith(new File(ENV_ANDROID_SDK_15), "1.5");
final String pathForTool = sdk.getPathForTool("aapt");
Assert.assertEquals(ENV_ANDROID_SDK_15 + "/platforms/android-1.5/tools/aapt", pathForTool);
}
@Test(expected = InvalidSdkException.class)
public void givenLayout1dot5AndToolAaptAndPlatform1dot6ThenException() {
constructAndroidSdkWith(new File(ENV_ANDROID_SDK_15), "1.6").getPathForTool("aapt");
}
@Test(expected = InvalidSdkException.class)
public void givenInvalidAndroidSdkPathThenException() throws IOException {
constructAndroidSdkWith(File.createTempFile("maven-android-plugin", "test"), null).getLayout();
}
@Test
public void givenAndroidSdk11PathThenLayoutIs11(){
Assert.assertEquals(constructAndroidSdkWith(new File(ENV_ANDROID_SDK_11), null).getLayout(), AndroidSdk.Layout.LAYOUT_1_1);
}
@Test
public void givenAndroidSdk15PathThenLayoutIs15(){
Assert.assertEquals(constructAndroidSdkWith(new File(ENV_ANDROID_SDK_15), null).getLayout(), AndroidSdk.Layout.LAYOUT_1_5);
}
/**
* Constructs a testable instance of {@link AndroidSdk} with specified values set.
*
* @param path The <code>path</code> value to set inside the <code>AndroidSdk</code>.
* @param platform The <code>platform</code> value to set inside the <code>AndroidSdk</code>.
* @return an instance to test
*/
protected static AndroidSdk constructAndroidSdkWith(File path, String platform) {
final AndroidSdk sdk = new AndroidSdk();
try {
ReflectionUtils.setVariableValueInObject(sdk, "path", path);
ReflectionUtils.setVariableValueInObject(sdk, "platform", platform);
} catch (IllegalAccessException e) {
// Retrow unchecked, so callers won't have to care.
throw new RuntimeException(e);
}
return sdk;
}
}
| src/test/java/com/jayway/maven/plugins/android/AndroidSdkTest.java | /*
* Copyright (C) 2009 Jayway AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jayway.maven.plugins.android;
import org.apache.maven.plugin.MojoExecutionException;
import org.codehaus.plexus.util.ReflectionUtils;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
/**
* Excercises the {@link AndroidSdk} class.
*
* @author [email protected]
*/
public class AndroidSdkTest {
private static final String ENV_ANDROID_SDK_11 = System.getenv("ANDROID_SDK_11");
private static final String ENV_ANDROID_SDK_15 = System.getenv("ANDROID_SDK_15");
public static final AndroidSdk SDK_1_1;
static{
Assert.assertNotNull("For running the tests, you must have environment variable ANDROID_SDK_11 set to a valid Android SDK 1.1 directory.", ENV_ANDROID_SDK_11);
SDK_1_1 = constructAndroidSdkWith(new File(ENV_ANDROID_SDK_11), "1.1");
}
public static final AndroidSdk SDK_1_5;
static{
Assert.assertNotNull("For running the tests, you must have environment variable ANDROID_SDK_15 set to a valid Android SDK 1.5 directory.", ENV_ANDROID_SDK_15);
SDK_1_5 = constructAndroidSdkWith(new File(ENV_ANDROID_SDK_15), "1.5");
}
@Test
public void givenLayout1dot1AndToolAdbThenPathIs1dot1Style() {
final String pathForTool = SDK_1_1.getPathForTool("adb");
Assert.assertEquals(ENV_ANDROID_SDK_11 + "/tools/adb", pathForTool);
}
@Test
public void givenLayout1dot1AndToolAndroidThenPathIs1dot1Style() {
final String pathForTool = SDK_1_1.getPathForTool("android");
Assert.assertEquals(ENV_ANDROID_SDK_11 + "/tools/android", pathForTool);
}
@Test
public void givenLayout1dot1AndToolAaptThenPathIs1dot1Style() {
final String pathForTool = SDK_1_1.getPathForTool("aapt");
Assert.assertEquals(ENV_ANDROID_SDK_11 + "/tools/aapt", pathForTool);
}
@Test
public void givenLayout1dot5AndToolAdbThenPathIsCommon() {
final String pathForTool = SDK_1_5.getPathForTool("adb");
Assert.assertEquals(ENV_ANDROID_SDK_15 + "/tools/adb", pathForTool);
}
@Test
public void givenLayout1dot5AndToolAndroidThenPathIsCommon() {
final String pathForTool = SDK_1_5.getPathForTool("android");
Assert.assertEquals(ENV_ANDROID_SDK_15 + "/tools/android", pathForTool);
}
@Test
public void givenLayout1dot5AndToolAaptAndPlatform1dot1ThenPathIsPlatform1dot1() {
final AndroidSdk sdk = constructAndroidSdkWith(new File(ENV_ANDROID_SDK_15), "1.1");
final String pathForTool = sdk.getPathForTool("aapt");
Assert.assertEquals(ENV_ANDROID_SDK_15 + "/platforms/android-1.1/tools/aapt", pathForTool);
}
@Test
public void givenLayout1dot5AndToolAaptAndPlatform1dot5ThenPathIsPlatform1dot5() {
final AndroidSdk sdk = constructAndroidSdkWith(new File(ENV_ANDROID_SDK_15), "1.5");
final String pathForTool = sdk.getPathForTool("aapt");
Assert.assertEquals(ENV_ANDROID_SDK_15 + "/platforms/android-1.5/tools/aapt", pathForTool);
}
@Test(expected = InvalidSdkException.class)
public void givenLayout1dot5AndToolAaptAndPlatform1dot6ThenException() {
constructAndroidSdkWith(new File(ENV_ANDROID_SDK_15), "1.6").getPathForTool("aapt");
}
/**
* Constructs a testable instance of {@link AndroidSdk} with specified values set.
*
* @param path The <code>path</code> value to set inside the <code>AndroidSdk</code>.
* @param platform The <code>platform</code> value to set inside the <code>AndroidSdk</code>.
* @return an instance to test
*/
protected static AndroidSdk constructAndroidSdkWith(File path, String platform) {
final AndroidSdk sdk = new AndroidSdk();
try {
ReflectionUtils.setVariableValueInObject(sdk, "path", path);
ReflectionUtils.setVariableValueInObject(sdk, "platform", platform);
} catch (IllegalAccessException e) {
// Retrow unchecked, so callers won't have to care.
throw new RuntimeException(e);
}
return sdk;
}
}
| Added tests for AndroidSdk layout detection.
| src/test/java/com/jayway/maven/plugins/android/AndroidSdkTest.java | Added tests for AndroidSdk layout detection. |
|
Java | apache-2.0 | de45cafb0f9eaa3bbac6bde4da065915f2c1c4c2 | 0 | kironapublic/vaadin,asashour/framework,Darsstar/framework,peterl1084/framework,synes/vaadin,fireflyc/vaadin,Legioth/vaadin,Legioth/vaadin,Peppe/vaadin,magi42/vaadin,carrchang/vaadin,shahrzadmn/vaadin,jdahlstrom/vaadin.react,travisfw/vaadin,mittop/vaadin,sitexa/vaadin,Legioth/vaadin,Scarlethue/vaadin,mstahv/framework,synes/vaadin,Darsstar/framework,sitexa/vaadin,asashour/framework,Legioth/vaadin,udayinfy/vaadin,asashour/framework,Peppe/vaadin,magi42/vaadin,oalles/vaadin,peterl1084/framework,synes/vaadin,oalles/vaadin,peterl1084/framework,udayinfy/vaadin,kironapublic/vaadin,carrchang/vaadin,cbmeeks/vaadin,Flamenco/vaadin,bmitc/vaadin,shahrzadmn/vaadin,jdahlstrom/vaadin.react,Scarlethue/vaadin,udayinfy/vaadin,fireflyc/vaadin,Legioth/vaadin,travisfw/vaadin,asashour/framework,Peppe/vaadin,shahrzadmn/vaadin,mittop/vaadin,oalles/vaadin,mstahv/framework,travisfw/vaadin,Darsstar/framework,sitexa/vaadin,fireflyc/vaadin,fireflyc/vaadin,Scarlethue/vaadin,mittop/vaadin,mstahv/framework,asashour/framework,peterl1084/framework,shahrzadmn/vaadin,sitexa/vaadin,cbmeeks/vaadin,udayinfy/vaadin,mittop/vaadin,mstahv/framework,travisfw/vaadin,oalles/vaadin,magi42/vaadin,jdahlstrom/vaadin.react,kironapublic/vaadin,travisfw/vaadin,jdahlstrom/vaadin.react,Flamenco/vaadin,bmitc/vaadin,Peppe/vaadin,mstahv/framework,carrchang/vaadin,Peppe/vaadin,fireflyc/vaadin,sitexa/vaadin,Flamenco/vaadin,bmitc/vaadin,magi42/vaadin,cbmeeks/vaadin,kironapublic/vaadin,Darsstar/framework,Scarlethue/vaadin,synes/vaadin,bmitc/vaadin,carrchang/vaadin,Scarlethue/vaadin,shahrzadmn/vaadin,Flamenco/vaadin,kironapublic/vaadin,peterl1084/framework,jdahlstrom/vaadin.react,udayinfy/vaadin,cbmeeks/vaadin,magi42/vaadin,oalles/vaadin,synes/vaadin,Darsstar/framework | /*
@VaadinApache2LicenseForJavaFiles@
*/
package com.vaadin.terminal.gwt.client.ui;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.dom.client.Style.Visibility;
import com.google.gwt.dom.client.TableCellElement;
import com.google.gwt.dom.client.TableRowElement;
import com.google.gwt.dom.client.TableSectionElement;
import com.google.gwt.dom.client.Touch;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ContextMenuEvent;
import com.google.gwt.event.dom.client.ContextMenuHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.dom.client.ScrollEvent;
import com.google.gwt.event.dom.client.ScrollHandler;
import com.google.gwt.event.dom.client.TouchStartEvent;
import com.google.gwt.event.dom.client.TouchStartHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.BrowserInfo;
import com.vaadin.terminal.gwt.client.Container;
import com.vaadin.terminal.gwt.client.Focusable;
import com.vaadin.terminal.gwt.client.MouseEventDetails;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.RenderSpace;
import com.vaadin.terminal.gwt.client.TooltipInfo;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.VConsole;
import com.vaadin.terminal.gwt.client.VTooltip;
import com.vaadin.terminal.gwt.client.ui.VScrollTable.VScrollTableBody.VScrollTableRow;
import com.vaadin.terminal.gwt.client.ui.dd.DDUtil;
import com.vaadin.terminal.gwt.client.ui.dd.VAbstractDropHandler;
import com.vaadin.terminal.gwt.client.ui.dd.VAcceptCallback;
import com.vaadin.terminal.gwt.client.ui.dd.VDragAndDropManager;
import com.vaadin.terminal.gwt.client.ui.dd.VDragEvent;
import com.vaadin.terminal.gwt.client.ui.dd.VHasDropHandler;
import com.vaadin.terminal.gwt.client.ui.dd.VTransferable;
import com.vaadin.terminal.gwt.client.ui.dd.VerticalDropLocation;
/**
* VScrollTable
*
* VScrollTable is a FlowPanel having two widgets in it: * TableHead component *
* ScrollPanel
*
* TableHead contains table's header and widgets + logic for resizing,
* reordering and hiding columns.
*
* ScrollPanel contains VScrollTableBody object which handles content. To save
* some bandwidth and to improve clients responsiveness with loads of data, in
* VScrollTableBody all rows are not necessary rendered. There are "spacers" in
* VScrollTableBody to use the exact same space as non-rendered rows would use.
* This way we can use seamlessly traditional scrollbars and scrolling to fetch
* more rows instead of "paging".
*
* In VScrollTable we listen to scroll events. On horizontal scrolling we also
* update TableHeads scroll position which has its scrollbars hidden. On
* vertical scroll events we will check if we are reaching the end of area where
* we have rows rendered and
*
* TODO implement unregistering for child components in Cells
*/
public class VScrollTable extends FlowPanel implements Table, ScrollHandler,
VHasDropHandler, FocusHandler, BlurHandler, Focusable, ActionOwner {
public static final String ATTRIBUTE_PAGEBUFFER_FIRST = "pb-ft";
public static final String ATTRIBUTE_PAGEBUFFER_LAST = "pb-l";
private static final String ROW_HEADER_COLUMN_KEY = "0";
public static final String CLASSNAME = "v-table";
public static final String CLASSNAME_SELECTION_FOCUS = CLASSNAME + "-focus";
public static final String ITEM_CLICK_EVENT_ID = "itemClick";
public static final String HEADER_CLICK_EVENT_ID = "handleHeaderClick";
public static final String FOOTER_CLICK_EVENT_ID = "handleFooterClick";
public static final String COLUMN_RESIZE_EVENT_ID = "columnResize";
public static final String COLUMN_REORDER_EVENT_ID = "columnReorder";
private static final double CACHE_RATE_DEFAULT = 2;
/**
* The default multi select mode where simple left clicks only selects one
* item, CTRL+left click selects multiple items and SHIFT-left click selects
* a range of items.
*/
private static final int MULTISELECT_MODE_DEFAULT = 0;
/**
* The simple multiselect mode is what the table used to have before
* ctrl/shift selections were added. That is that when this is set clicking
* on an item selects/deselects the item and no ctrl/shift selections are
* available.
*/
private static final int MULTISELECT_MODE_SIMPLE = 1;
/**
* multiple of pagelength which component will cache when requesting more
* rows
*/
private double cache_rate = CACHE_RATE_DEFAULT;
/**
* fraction of pageLenght which can be scrolled without making new request
*/
private double cache_react_rate = 0.75 * cache_rate;
public static final char ALIGN_CENTER = 'c';
public static final char ALIGN_LEFT = 'b';
public static final char ALIGN_RIGHT = 'e';
private static final int CHARCODE_SPACE = 32;
private int firstRowInViewPort = 0;
private int pageLength = 15;
private int lastRequestedFirstvisible = 0; // to detect "serverside scroll"
protected boolean showRowHeaders = false;
private String[] columnOrder;
protected ApplicationConnection client;
protected String paintableId;
private boolean immediate;
private boolean nullSelectionAllowed = true;
private int selectMode = Table.SELECT_MODE_NONE;
private final HashSet<String> selectedRowKeys = new HashSet<String>();
/*
* When scrolling and selecting at the same time, the selections are not in
* sync with the server while retrieving new rows (until key is released).
*/
private HashSet<Object> unSyncedselectionsBeforeRowFetch;
/*
* These are used when jumping between pages when pressing Home and End
*/
private boolean selectLastItemInNextRender = false;
private boolean selectFirstItemInNextRender = false;
private boolean focusFirstItemInNextRender = false;
private boolean focusLastItemInNextRender = false;
/*
* The currently focused row
*/
private VScrollTableRow focusedRow;
/*
* Helper to store selection range start in when using the keyboard
*/
private VScrollTableRow selectionRangeStart;
/*
* Flag for notifying when the selection has changed and should be sent to
* the server
*/
private boolean selectionChanged = false;
/*
* The speed (in pixels) which the scrolling scrolls vertically/horizontally
*/
private int scrollingVelocity = 10;
private Timer scrollingVelocityTimer = null;
private String[] bodyActionKeys;
private boolean enableDebug = false;
/**
* Represents a select range of rows
*/
private class SelectionRange {
private VScrollTableRow startRow;
private final int length;
/**
* Constuctor.
*/
public SelectionRange(VScrollTableRow row1, VScrollTableRow row2) {
VScrollTableRow endRow;
if (row2.isBefore(row1)) {
startRow = row2;
endRow = row1;
} else {
startRow = row1;
endRow = row2;
}
length = endRow.getIndex() - startRow.getIndex() + 1;
}
public SelectionRange(VScrollTableRow row, int length) {
startRow = row;
this.length = length;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return startRow.getKey() + "-" + length;
}
private boolean inRange(VScrollTableRow row) {
return row.getIndex() >= startRow.getIndex()
&& row.getIndex() < startRow.getIndex() + length;
}
public Collection<SelectionRange> split(VScrollTableRow row) {
assert row.isAttached();
ArrayList<SelectionRange> ranges = new ArrayList<SelectionRange>(2);
int endOfFirstRange = row.getIndex() - 1;
if (!(endOfFirstRange - startRow.getIndex() < 0)) {
// create range of first part unless its length is < 1
ranges.add(new SelectionRange(startRow, endOfFirstRange
- startRow.getIndex() + 1));
}
int startOfSecondRange = row.getIndex() + 1;
if (!(getEndIndex() - startOfSecondRange < 0)) {
// create range of second part unless its length is < 1
VScrollTableRow startOfRange = scrollBody
.getRowByRowIndex(startOfSecondRange);
ranges.add(new SelectionRange(startOfRange, getEndIndex()
- startOfSecondRange + 1));
}
return ranges;
}
private int getEndIndex() {
return startRow.getIndex() + length - 1;
}
};
private final HashSet<SelectionRange> selectedRowRanges = new HashSet<SelectionRange>();
private boolean initializedAndAttached = false;
/**
* Flag to indicate if a column width recalculation is needed due update.
*/
private boolean headerChangedDuringUpdate = false;
protected final TableHead tHead = new TableHead();
private final TableFooter tFoot = new TableFooter();
private final FocusableScrollPanel scrollBodyPanel = new FocusableScrollPanel(
true);
private KeyPressHandler navKeyPressHandler = new KeyPressHandler() {
public void onKeyPress(KeyPressEvent keyPressEvent) {
// This is used for Firefox only, since Firefox auto-repeat
// works correctly only if we use a key press handler, other
// browsers handle it correctly when using a key down handler
if (!BrowserInfo.get().isGecko()) {
return;
}
NativeEvent event = keyPressEvent.getNativeEvent();
if (!enabled) {
// Cancel default keyboard events on a disabled Table
// (prevents scrolling)
event.preventDefault();
} else if (hasFocus) {
// Key code in Firefox/onKeyPress is present only for
// special keys, otherwise 0 is returned
int keyCode = event.getKeyCode();
if (keyCode == 0 && event.getCharCode() == ' ') {
// Provide a keyCode for space to be compatible with
// FireFox keypress event
keyCode = CHARCODE_SPACE;
}
if (handleNavigation(keyCode,
event.getCtrlKey() || event.getMetaKey(),
event.getShiftKey())) {
event.preventDefault();
}
startScrollingVelocityTimer();
}
}
};
private KeyUpHandler navKeyUpHandler = new KeyUpHandler() {
public void onKeyUp(KeyUpEvent keyUpEvent) {
NativeEvent event = keyUpEvent.getNativeEvent();
int keyCode = event.getKeyCode();
if (!isFocusable()) {
cancelScrollingVelocityTimer();
} else if (isNavigationKey(keyCode)) {
if (keyCode == getNavigationDownKey()
|| keyCode == getNavigationUpKey()) {
/*
* in multiselect mode the server may still have value from
* previous page. Clear it unless doing multiselection or
* just moving focus.
*/
if (!event.getShiftKey() && !event.getCtrlKey()) {
instructServerToForgetPreviousSelections();
}
sendSelectedRows();
}
cancelScrollingVelocityTimer();
navKeyDown = false;
}
}
};
private KeyDownHandler navKeyDownHandler = new KeyDownHandler() {
public void onKeyDown(KeyDownEvent keyDownEvent) {
NativeEvent event = keyDownEvent.getNativeEvent();
// This is not used for Firefox
if (BrowserInfo.get().isGecko()) {
return;
}
if (!enabled) {
// Cancel default keyboard events on a disabled Table
// (prevents scrolling)
event.preventDefault();
} else if (hasFocus) {
if (handleNavigation(event.getKeyCode(), event.getCtrlKey()
|| event.getMetaKey(), event.getShiftKey())) {
navKeyDown = true;
event.preventDefault();
}
startScrollingVelocityTimer();
}
}
};
private int totalRows;
private Set<String> collapsedColumns;
private final RowRequestHandler rowRequestHandler;
private VScrollTableBody scrollBody;
private int firstvisible = 0;
private boolean sortAscending;
private String sortColumn;
private String oldSortColumn;
private boolean columnReordering;
/**
* This map contains captions and icon urls for actions like: * "33_c" ->
* "Edit" * "33_i" -> "http://dom.com/edit.png"
*/
private final HashMap<Object, String> actionMap = new HashMap<Object, String>();
private String[] visibleColOrder;
private boolean initialContentReceived = false;
private Element scrollPositionElement;
private boolean enabled;
private boolean showColHeaders;
private boolean showColFooters;
/** flag to indicate that table body has changed */
private boolean isNewBody = true;
/*
* Read from the "recalcWidths" -attribute. When it is true, the table will
* recalculate the widths for columns - desirable in some cases. For #1983,
* marked experimental.
*/
boolean recalcWidths = false;
private final ArrayList<Panel> lazyUnregistryBag = new ArrayList<Panel>();
private String height;
private String width = "";
private boolean rendering = false;
private boolean hasFocus = false;
private int dragmode;
private int multiselectmode;
private int tabIndex;
private TouchScrollDelegate touchScrollDelegate;
private int lastRenderedHeight;
/**
* Values (serverCacheFirst+serverCacheLast) sent by server that tells which
* rows (indexes) are in the server side cache (page buffer). -1 means
* unknown. The server side cache row MUST MATCH the client side cache rows.
*
* If the client side cache contains additional rows with e.g. buttons, it
* will cause out of sync when such a button is pressed.
*
* If the server side cache contains additional rows with e.g. buttons,
* scrolling in the client will cause empty buttons to be rendered
* (cached=true request for non-existing components)
*/
private int serverCacheFirst = -1;
private int serverCacheLast = -1;
/**
* Used to recall the position of an open context menu if we need to close
* and reopen it during a row update.
*/
private class ContextMenuDetails {
String rowKey;
int left;
int top;
ContextMenuDetails(String rowKey, int left, int top) {
this.rowKey = rowKey;
this.left = left;
this.top = top;
}
}
ContextMenuDetails contextMenu;
public VScrollTable() {
setMultiSelectMode(MULTISELECT_MODE_DEFAULT);
scrollBodyPanel.setStyleName(CLASSNAME + "-body-wrapper");
scrollBodyPanel.addFocusHandler(this);
scrollBodyPanel.addBlurHandler(this);
scrollBodyPanel.addScrollHandler(this);
scrollBodyPanel.setStyleName(CLASSNAME + "-body");
/*
* Firefox auto-repeat works correctly only if we use a key press
* handler, other browsers handle it correctly when using a key down
* handler
*/
if (BrowserInfo.get().isGecko()) {
scrollBodyPanel.addKeyPressHandler(navKeyPressHandler);
} else {
scrollBodyPanel.addKeyDownHandler(navKeyDownHandler);
}
scrollBodyPanel.addKeyUpHandler(navKeyUpHandler);
scrollBodyPanel.sinkEvents(Event.TOUCHEVENTS);
scrollBodyPanel.addDomHandler(new TouchStartHandler() {
public void onTouchStart(TouchStartEvent event) {
getTouchScrollDelegate().onTouchStart(event);
}
}, TouchStartEvent.getType());
scrollBodyPanel.sinkEvents(Event.ONCONTEXTMENU);
scrollBodyPanel.addDomHandler(new ContextMenuHandler() {
public void onContextMenu(ContextMenuEvent event) {
handleBodyContextMenu(event);
}
}, ContextMenuEvent.getType());
setStyleName(CLASSNAME);
add(tHead);
add(scrollBodyPanel);
add(tFoot);
rowRequestHandler = new RowRequestHandler();
}
protected TouchScrollDelegate getTouchScrollDelegate() {
if (touchScrollDelegate == null) {
touchScrollDelegate = new TouchScrollDelegate(
scrollBodyPanel.getElement());
touchScrollDelegate.setScrollHandler(this);
}
return touchScrollDelegate;
}
private void handleBodyContextMenu(ContextMenuEvent event) {
if (enabled && bodyActionKeys != null) {
int left = Util.getTouchOrMouseClientX(event.getNativeEvent());
int top = Util.getTouchOrMouseClientY(event.getNativeEvent());
top += Window.getScrollTop();
left += Window.getScrollLeft();
client.getContextMenu().showAt(this, left, top);
// Only prevent browser context menu if there are action handlers
// registered
event.stopPropagation();
event.preventDefault();
}
}
/**
* Fires a column resize event which sends the resize information to the
* server.
*
* @param columnId
* The columnId of the column which was resized
* @param originalWidth
* The width in pixels of the column before the resize event
* @param newWidth
* The width in pixels of the column after the resize event
*/
private void fireColumnResizeEvent(String columnId, int originalWidth,
int newWidth) {
client.updateVariable(paintableId, "columnResizeEventColumn", columnId,
false);
client.updateVariable(paintableId, "columnResizeEventPrev",
originalWidth, false);
client.updateVariable(paintableId, "columnResizeEventCurr", newWidth,
immediate);
}
/**
* Non-immediate variable update of column widths for a collection of
* columns.
*
* @param columns
* the columns to trigger the events for.
*/
private void sendColumnWidthUpdates(Collection<HeaderCell> columns) {
String[] newSizes = new String[columns.size()];
int ix = 0;
for (HeaderCell cell : columns) {
newSizes[ix++] = cell.getColKey() + ":" + cell.getWidth();
}
client.updateVariable(paintableId, "columnWidthUpdates", newSizes,
false);
}
/**
* Moves the focus one step down
*
* @return Returns true if succeeded
*/
private boolean moveFocusDown() {
return moveFocusDown(0);
}
/**
* Moves the focus down by 1+offset rows
*
* @return Returns true if succeeded, else false if the selection could not
* be move downwards
*/
private boolean moveFocusDown(int offset) {
if (isSelectable()) {
if (focusedRow == null && scrollBody.iterator().hasNext()) {
// FIXME should focus first visible from top, not first rendered
// ??
return setRowFocus((VScrollTableRow) scrollBody.iterator()
.next());
} else {
VScrollTableRow next = getNextRow(focusedRow, offset);
if (next != null) {
return setRowFocus(next);
}
}
}
return false;
}
/**
* Moves the selection one step up
*
* @return Returns true if succeeded
*/
private boolean moveFocusUp() {
return moveFocusUp(0);
}
/**
* Moves the focus row upwards
*
* @return Returns true if succeeded, else false if the selection could not
* be move upwards
*
*/
private boolean moveFocusUp(int offset) {
if (isSelectable()) {
if (focusedRow == null && scrollBody.iterator().hasNext()) {
// FIXME logic is exactly the same as in moveFocusDown, should
// be the opposite??
return setRowFocus((VScrollTableRow) scrollBody.iterator()
.next());
} else {
VScrollTableRow prev = getPreviousRow(focusedRow, offset);
if (prev != null) {
return setRowFocus(prev);
} else {
VConsole.log("no previous available");
}
}
}
return false;
}
/**
* Selects a row where the current selection head is
*
* @param ctrlSelect
* Is the selection a ctrl+selection
* @param shiftSelect
* Is the selection a shift+selection
* @return Returns truw
*/
private void selectFocusedRow(boolean ctrlSelect, boolean shiftSelect) {
if (focusedRow != null) {
// Arrows moves the selection and clears previous selections
if (isSelectable() && !ctrlSelect && !shiftSelect) {
deselectAll();
focusedRow.toggleSelection();
selectionRangeStart = focusedRow;
} else if (isSelectable() && ctrlSelect && !shiftSelect) {
// Ctrl+arrows moves selection head
selectionRangeStart = focusedRow;
// No selection, only selection head is moved
} else if (isMultiSelectModeAny() && !ctrlSelect && shiftSelect) {
// Shift+arrows selection selects a range
focusedRow.toggleShiftSelection(shiftSelect);
}
}
}
/**
* Sends the selection to the server if changed since the last update/visit.
*/
protected void sendSelectedRows() {
sendSelectedRows(immediate);
}
/**
* Sends the selection to the server if it has been changed since the last
* update/visit.
*
* @param immediately
* set to true to immediately send the rows
*/
protected void sendSelectedRows(boolean immediately) {
// Don't send anything if selection has not changed
if (!selectionChanged) {
return;
}
// Reset selection changed flag
selectionChanged = false;
// Note: changing the immediateness of this might require changes to
// "clickEvent" immediateness also.
if (isMultiSelectModeDefault()) {
// Convert ranges to a set of strings
Set<String> ranges = new HashSet<String>();
for (SelectionRange range : selectedRowRanges) {
ranges.add(range.toString());
}
// Send the selected row ranges
client.updateVariable(paintableId, "selectedRanges",
ranges.toArray(new String[selectedRowRanges.size()]), false);
// clean selectedRowKeys so that they don't contain excess values
for (Iterator<String> iterator = selectedRowKeys.iterator(); iterator
.hasNext();) {
String key = iterator.next();
VScrollTableRow renderedRowByKey = getRenderedRowByKey(key);
if (renderedRowByKey != null) {
for (SelectionRange range : selectedRowRanges) {
if (range.inRange(renderedRowByKey)) {
iterator.remove();
}
}
} else {
// orphaned selected key, must be in a range, ignore
iterator.remove();
}
}
}
// Send the selected rows
client.updateVariable(paintableId, "selected",
selectedRowKeys.toArray(new String[selectedRowKeys.size()]),
immediately);
}
/**
* Get the key that moves the selection head upwards. By default it is the
* up arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationUpKey() {
return KeyCodes.KEY_UP;
}
/**
* Get the key that moves the selection head downwards. By default it is the
* down arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationDownKey() {
return KeyCodes.KEY_DOWN;
}
/**
* Get the key that scrolls to the left in the table. By default it is the
* left arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationLeftKey() {
return KeyCodes.KEY_LEFT;
}
/**
* Get the key that scroll to the right on the table. By default it is the
* right arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationRightKey() {
return KeyCodes.KEY_RIGHT;
}
/**
* Get the key that selects an item in the table. By default it is the space
* bar key but by overriding this you can change the key to whatever you
* want.
*
* @return
*/
protected int getNavigationSelectKey() {
return CHARCODE_SPACE;
}
/**
* Get the key the moves the selection one page up in the table. By default
* this is the Page Up key but by overriding this you can change the key to
* whatever you want.
*
* @return
*/
protected int getNavigationPageUpKey() {
return KeyCodes.KEY_PAGEUP;
}
/**
* Get the key the moves the selection one page down in the table. By
* default this is the Page Down key but by overriding this you can change
* the key to whatever you want.
*
* @return
*/
protected int getNavigationPageDownKey() {
return KeyCodes.KEY_PAGEDOWN;
}
/**
* Get the key the moves the selection to the beginning of the table. By
* default this is the Home key but by overriding this you can change the
* key to whatever you want.
*
* @return
*/
protected int getNavigationStartKey() {
return KeyCodes.KEY_HOME;
}
/**
* Get the key the moves the selection to the end of the table. By default
* this is the End key but by overriding this you can change the key to
* whatever you want.
*
* @return
*/
protected int getNavigationEndKey() {
return KeyCodes.KEY_END;
}
/*
* (non-Javadoc)
*
* @see
* com.vaadin.terminal.gwt.client.Paintable#updateFromUIDL(com.vaadin.terminal
* .gwt.client.UIDL, com.vaadin.terminal.gwt.client.ApplicationConnection)
*/
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
rendering = true;
// On the first rendering, add a handler to clear saved context menu
// details when the menu closes. See #8526.
if (this.client == null) {
client.getContextMenu().addCloseHandler(
new CloseHandler<PopupPanel>() {
public void onClose(CloseEvent<PopupPanel> event) {
contextMenu = null;
}
});
}
// If a row has an open context menu, it will be closed as the row is
// detached. Retain a reference here so we can restore the menu if
// required.
ContextMenuDetails savedContextMenu = contextMenu;
if (uidl.hasAttribute(ATTRIBUTE_PAGEBUFFER_FIRST)) {
serverCacheFirst = uidl.getIntAttribute(ATTRIBUTE_PAGEBUFFER_FIRST);
serverCacheLast = uidl.getIntAttribute(ATTRIBUTE_PAGEBUFFER_LAST);
} else {
serverCacheFirst = -1;
serverCacheLast = -1;
}
/*
* We need to do this before updateComponent since updateComponent calls
* this.setHeight() which will calculate a new body height depending on
* the space available.
*/
if (uidl.hasAttribute("colfooters")) {
showColFooters = uidl.getBooleanAttribute("colfooters");
}
tFoot.setVisible(showColFooters);
if (client.updateComponent(this, uidl, true)) {
rendering = false;
return;
}
enabled = !uidl.hasAttribute("disabled");
if (BrowserInfo.get().isIE8() && !enabled) {
/*
* The disabled shim will not cover the table body if it is relative
* in IE8. See #7324
*/
scrollBodyPanel.getElement().getStyle()
.setPosition(Position.STATIC);
} else if (BrowserInfo.get().isIE8()) {
scrollBodyPanel.getElement().getStyle()
.setPosition(Position.RELATIVE);
}
this.client = client;
paintableId = uidl.getStringAttribute("id");
immediate = uidl.getBooleanAttribute("immediate");
int previousTotalRows = totalRows;
updateTotalRows(uidl);
boolean totalRowsChanged = (totalRows != previousTotalRows);
updateDragMode(uidl);
updateSelectionProperties(uidl);
if (uidl.hasAttribute("alb")) {
bodyActionKeys = uidl.getStringArrayAttribute("alb");
} else {
// Need to clear the actions if the action handlers have been
// removed
bodyActionKeys = null;
}
setCacheRateFromUIDL(uidl);
recalcWidths = uidl.hasAttribute("recalcWidths");
if (recalcWidths) {
tHead.clear();
tFoot.clear();
}
updatePageLength(uidl);
updateFirstVisibleAndScrollIfNeeded(uidl);
showRowHeaders = uidl.getBooleanAttribute("rowheaders");
showColHeaders = uidl.getBooleanAttribute("colheaders");
updateSortingProperties(uidl);
boolean keyboardSelectionOverRowFetchInProgress = selectSelectedRows(uidl);
updateActionMap(uidl);
updateColumnProperties(uidl);
UIDL ac = uidl.getChildByTagName("-ac");
if (ac == null) {
if (dropHandler != null) {
// remove dropHandler if not present anymore
dropHandler = null;
}
} else {
if (dropHandler == null) {
dropHandler = new VScrollTableDropHandler();
}
dropHandler.updateAcceptRules(ac);
}
UIDL partialRowAdditions = uidl.getChildByTagName("prows");
UIDL partialRowUpdates = uidl.getChildByTagName("urows");
if (partialRowUpdates != null || partialRowAdditions != null) {
// we may have pending cache row fetch, cancel it. See #2136
rowRequestHandler.cancel();
updateRowsInBody(partialRowUpdates);
addAndRemoveRows(partialRowAdditions);
} else {
UIDL rowData = uidl.getChildByTagName("rows");
if (rowData != null) {
// we may have pending cache row fetch, cancel it. See #2136
rowRequestHandler.cancel();
if (!recalcWidths && initializedAndAttached) {
updateBody(rowData, uidl.getIntAttribute("firstrow"),
uidl.getIntAttribute("rows"));
if (headerChangedDuringUpdate) {
triggerLazyColumnAdjustment(true);
} else if (!isScrollPositionVisible()
|| totalRowsChanged
|| lastRenderedHeight != scrollBody
.getOffsetHeight()) {
// webkits may still bug with their disturbing scrollbar
// bug, see #3457
// Run overflow fix for the scrollable area
// #6698 - If there's a scroll going on, don't abort it
// by changing overflows as the length of the contents
// *shouldn't* have changed (unless the number of rows
// or the height of the widget has also changed)
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel
.getElement());
}
});
}
} else {
initializeRows(uidl, rowData);
}
}
}
// If a row had an open context menu before the update, and after the
// update there's a row with the same key as that row, restore the
// context menu. See #8526.
if (enabled && savedContextMenu != null) {
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (row.isVisible()
&& row.getKey().equals(savedContextMenu.rowKey)) {
contextMenu = savedContextMenu;
client.getContextMenu().showAt(row, savedContextMenu.left,
savedContextMenu.top);
}
}
}
if (!isSelectable()) {
scrollBody.addStyleName(CLASSNAME + "-body-noselection");
} else {
scrollBody.removeStyleName(CLASSNAME + "-body-noselection");
}
hideScrollPositionAnnotation();
purgeUnregistryBag();
// selection is no in sync with server, avoid excessive server visits by
// clearing to flag used during the normal operation
if (!keyboardSelectionOverRowFetchInProgress) {
selectionChanged = false;
}
/*
* This is called when the Home or page up button has been pressed in
* selectable mode and the next selected row was not yet rendered in the
* client
*/
if (selectFirstItemInNextRender || focusFirstItemInNextRender) {
selectFirstRenderedRowInViewPort(focusFirstItemInNextRender);
selectFirstItemInNextRender = focusFirstItemInNextRender = false;
}
/*
* This is called when the page down or end button has been pressed in
* selectable mode and the next selected row was not yet rendered in the
* client
*/
if (selectLastItemInNextRender || focusLastItemInNextRender) {
selectLastRenderedRowInViewPort(focusLastItemInNextRender);
selectLastItemInNextRender = focusLastItemInNextRender = false;
}
multiselectPending = false;
if (focusedRow != null) {
if (!focusedRow.isAttached() && !rowRequestHandler.isRunning()) {
// focused row has been orphaned, can't focus
focusRowFromBody();
}
}
tabIndex = uidl.hasAttribute("tabindex") ? uidl
.getIntAttribute("tabindex") : 0;
setProperTabIndex();
resizeSortedColumnForSortIndicator();
// Remember this to detect situations where overflow hack might be
// needed during scrolling
lastRenderedHeight = scrollBody.getOffsetHeight();
rendering = false;
headerChangedDuringUpdate = false;
}
private void initializeRows(UIDL uidl, UIDL rowData) {
if (scrollBody != null) {
scrollBody.removeFromParent();
lazyUnregistryBag.add(scrollBody);
}
scrollBody = createScrollBody();
scrollBody.renderInitialRows(rowData, uidl.getIntAttribute("firstrow"),
uidl.getIntAttribute("rows"));
scrollBodyPanel.add(scrollBody);
// New body starts scrolled to the left, make sure the header and footer
// are also scrolled to the left
tHead.setHorizontalScrollPosition(0);
tFoot.setHorizontalScrollPosition(0);
initialContentReceived = true;
if (isAttached()) {
sizeInit();
}
scrollBody.restoreRowVisibility();
}
private void updateColumnProperties(UIDL uidl) {
updateColumnOrder(uidl);
updateCollapsedColumns(uidl);
UIDL vc = uidl.getChildByTagName("visiblecolumns");
if (vc != null) {
tHead.updateCellsFromUIDL(vc);
tFoot.updateCellsFromUIDL(vc);
}
updateHeader(uidl.getStringArrayAttribute("vcolorder"));
updateFooter(uidl.getStringArrayAttribute("vcolorder"));
}
private void updateCollapsedColumns(UIDL uidl) {
if (uidl.hasVariable("collapsedcolumns")) {
tHead.setColumnCollapsingAllowed(true);
collapsedColumns = uidl
.getStringArrayVariableAsSet("collapsedcolumns");
} else {
tHead.setColumnCollapsingAllowed(false);
}
}
private void updateColumnOrder(UIDL uidl) {
if (uidl.hasVariable("columnorder")) {
columnReordering = true;
columnOrder = uidl.getStringArrayVariable("columnorder");
} else {
columnReordering = false;
columnOrder = null;
}
}
private boolean selectSelectedRows(UIDL uidl) {
boolean keyboardSelectionOverRowFetchInProgress = false;
if (uidl.hasVariable("selected")) {
final Set<String> selectedKeys = uidl
.getStringArrayVariableAsSet("selected");
if (scrollBody != null) {
Iterator<Widget> iterator = scrollBody.iterator();
while (iterator.hasNext()) {
/*
* Make the focus reflect to the server side state unless we
* are currently selecting multiple rows with keyboard.
*/
VScrollTableRow row = (VScrollTableRow) iterator.next();
boolean selected = selectedKeys.contains(row.getKey());
if (!selected
&& unSyncedselectionsBeforeRowFetch != null
&& unSyncedselectionsBeforeRowFetch.contains(row
.getKey())) {
selected = true;
keyboardSelectionOverRowFetchInProgress = true;
}
if (selected != row.isSelected()) {
row.toggleSelection();
if (!isSingleSelectMode() && !selected) {
// Update selection range in case a row is
// unselected from the middle of a range - #8076
removeRowFromUnsentSelectionRanges(row);
}
}
}
}
}
unSyncedselectionsBeforeRowFetch = null;
return keyboardSelectionOverRowFetchInProgress;
}
private void updateSortingProperties(UIDL uidl) {
oldSortColumn = sortColumn;
if (uidl.hasVariable("sortascending")) {
sortAscending = uidl.getBooleanVariable("sortascending");
sortColumn = uidl.getStringVariable("sortcolumn");
}
}
private void resizeSortedColumnForSortIndicator() {
// Force recalculation of the captionContainer element inside the header
// cell to accomodate for the size of the sort arrow.
HeaderCell sortedHeader = tHead.getHeaderCell(sortColumn);
if (sortedHeader != null) {
tHead.resizeCaptionContainer(sortedHeader);
}
// Also recalculate the width of the captionContainer element in the
// previously sorted header, since this now has more room.
HeaderCell oldSortedHeader = tHead.getHeaderCell(oldSortColumn);
if (oldSortedHeader != null) {
tHead.resizeCaptionContainer(oldSortedHeader);
}
}
private void updateFirstVisibleAndScrollIfNeeded(UIDL uidl) {
firstvisible = uidl.hasVariable("firstvisible") ? uidl
.getIntVariable("firstvisible") : 0;
if (firstvisible != lastRequestedFirstvisible && scrollBody != null) {
// received 'surprising' firstvisible from server: scroll there
firstRowInViewPort = firstvisible;
scrollBodyPanel
.setScrollPosition(measureRowHeightOffset(firstvisible));
}
}
protected int measureRowHeightOffset(int rowIx) {
return (int) (rowIx * scrollBody.getRowHeight());
}
private void updatePageLength(UIDL uidl) {
int oldPageLength = pageLength;
if (uidl.hasAttribute("pagelength")) {
pageLength = uidl.getIntAttribute("pagelength");
} else {
// pagelenght is "0" meaning scrolling is turned off
pageLength = totalRows;
}
if (oldPageLength != pageLength && initializedAndAttached) {
// page length changed, need to update size
sizeInit();
}
}
private void updateSelectionProperties(UIDL uidl) {
setMultiSelectMode(uidl.hasAttribute("multiselectmode") ? uidl
.getIntAttribute("multiselectmode") : MULTISELECT_MODE_DEFAULT);
nullSelectionAllowed = uidl.hasAttribute("nsa") ? uidl
.getBooleanAttribute("nsa") : true;
if (uidl.hasAttribute("selectmode")) {
if (uidl.getBooleanAttribute("readonly")) {
selectMode = Table.SELECT_MODE_NONE;
} else if (uidl.getStringAttribute("selectmode").equals("multi")) {
selectMode = Table.SELECT_MODE_MULTI;
} else if (uidl.getStringAttribute("selectmode").equals("single")) {
selectMode = Table.SELECT_MODE_SINGLE;
} else {
selectMode = Table.SELECT_MODE_NONE;
}
}
}
private void updateDragMode(UIDL uidl) {
dragmode = uidl.hasAttribute("dragmode") ? uidl
.getIntAttribute("dragmode") : 0;
if (BrowserInfo.get().isIE()) {
if (dragmode > 0) {
getElement().setPropertyJSO("onselectstart",
getPreventTextSelectionIEHack());
} else {
getElement().setPropertyJSO("onselectstart", null);
}
}
}
protected void updateTotalRows(UIDL uidl) {
int newTotalRows = uidl.getIntAttribute("totalrows");
if (newTotalRows != getTotalRows()) {
if (scrollBody != null) {
if (getTotalRows() == 0) {
tHead.clear();
tFoot.clear();
}
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
setTotalRows(newTotalRows);
}
}
protected void setTotalRows(int newTotalRows) {
totalRows = newTotalRows;
}
protected int getTotalRows() {
return totalRows;
}
private void focusRowFromBody() {
if (selectedRowKeys.size() == 1) {
// try to focus a row currently selected and in viewport
String selectedRowKey = selectedRowKeys.iterator().next();
if (selectedRowKey != null) {
VScrollTableRow renderedRow = getRenderedRowByKey(selectedRowKey);
if (renderedRow == null || !renderedRow.isInViewPort()) {
setRowFocus(scrollBody.getRowByRowIndex(firstRowInViewPort));
} else {
setRowFocus(renderedRow);
}
}
} else {
// multiselect mode
setRowFocus(scrollBody.getRowByRowIndex(firstRowInViewPort));
}
}
protected VScrollTableBody createScrollBody() {
return new VScrollTableBody();
}
/**
* Selects the last row visible in the table
*
* @param focusOnly
* Should the focus only be moved to the last row
*/
private void selectLastRenderedRowInViewPort(boolean focusOnly) {
int index = firstRowInViewPort + getFullyVisibleRowCount();
VScrollTableRow lastRowInViewport = scrollBody.getRowByRowIndex(index);
if (lastRowInViewport == null) {
// this should not happen in normal situations (white space at the
// end of viewport). Select the last rendered as a fallback.
lastRowInViewport = scrollBody.getRowByRowIndex(scrollBody
.getLastRendered());
if (lastRowInViewport == null) {
return; // empty table
}
}
setRowFocus(lastRowInViewport);
if (!focusOnly) {
selectFocusedRow(false, multiselectPending);
sendSelectedRows();
}
}
/**
* Selects the first row visible in the table
*
* @param focusOnly
* Should the focus only be moved to the first row
*/
private void selectFirstRenderedRowInViewPort(boolean focusOnly) {
int index = firstRowInViewPort;
VScrollTableRow firstInViewport = scrollBody.getRowByRowIndex(index);
if (firstInViewport == null) {
// this should not happen in normal situations
return;
}
setRowFocus(firstInViewport);
if (!focusOnly) {
selectFocusedRow(false, multiselectPending);
sendSelectedRows();
}
}
private void setCacheRateFromUIDL(UIDL uidl) {
setCacheRate(uidl.hasAttribute("cr") ? uidl.getDoubleAttribute("cr")
: CACHE_RATE_DEFAULT);
}
private void setCacheRate(double d) {
if (cache_rate != d) {
cache_rate = d;
cache_react_rate = 0.75 * d;
}
}
/**
* Unregisters Paintables in "trashed" HasWidgets (IScrollTableBodys or
* IScrollTableRows). This is done lazily as Table must survive from
* "subtreecaching" logic.
*/
private void purgeUnregistryBag() {
for (Iterator<Panel> iterator = lazyUnregistryBag.iterator(); iterator
.hasNext();) {
client.unregisterChildPaintables(iterator.next());
}
lazyUnregistryBag.clear();
}
private void updateActionMap(UIDL mainUidl) {
UIDL actionsUidl = mainUidl.getChildByTagName("actions");
if (actionsUidl == null) {
return;
}
final Iterator<?> it = actionsUidl.getChildIterator();
while (it.hasNext()) {
final UIDL action = (UIDL) it.next();
final String key = action.getStringAttribute("key");
final String caption = action.getStringAttribute("caption");
actionMap.put(key + "_c", caption);
if (action.hasAttribute("icon")) {
// TODO need some uri handling ??
actionMap.put(key + "_i", client.translateVaadinUri(action
.getStringAttribute("icon")));
} else {
actionMap.remove(key + "_i");
}
}
}
public String getActionCaption(String actionKey) {
return actionMap.get(actionKey + "_c");
}
public String getActionIcon(String actionKey) {
return actionMap.get(actionKey + "_i");
}
private void updateHeader(String[] strings) {
if (strings == null) {
return;
}
int visibleCols = strings.length;
int colIndex = 0;
if (showRowHeaders) {
tHead.enableColumn(ROW_HEADER_COLUMN_KEY, colIndex);
visibleCols++;
visibleColOrder = new String[visibleCols];
visibleColOrder[colIndex] = ROW_HEADER_COLUMN_KEY;
colIndex++;
} else {
visibleColOrder = new String[visibleCols];
tHead.removeCell(ROW_HEADER_COLUMN_KEY);
}
int i;
for (i = 0; i < strings.length; i++) {
final String cid = strings[i];
visibleColOrder[colIndex] = cid;
tHead.enableColumn(cid, colIndex);
colIndex++;
}
tHead.setVisible(showColHeaders);
setContainerHeight();
}
/**
* Updates footers.
* <p>
* Update headers whould be called before this method is called!
* </p>
*
* @param strings
*/
private void updateFooter(String[] strings) {
if (strings == null) {
return;
}
// Add dummy column if row headers are present
int colIndex = 0;
if (showRowHeaders) {
tFoot.enableColumn(ROW_HEADER_COLUMN_KEY, colIndex);
colIndex++;
} else {
tFoot.removeCell(ROW_HEADER_COLUMN_KEY);
}
int i;
for (i = 0; i < strings.length; i++) {
final String cid = strings[i];
tFoot.enableColumn(cid, colIndex);
colIndex++;
}
tFoot.setVisible(showColFooters);
}
/**
* @param uidl
* which contains row data
* @param firstRow
* first row in data set
* @param reqRows
* amount of rows in data set
*/
private void updateBody(UIDL uidl, int firstRow, int reqRows) {
if (uidl == null || reqRows < 1) {
// container is empty, remove possibly existing rows
if (firstRow <= 0) {
while (scrollBody.getLastRendered() > scrollBody.firstRendered) {
scrollBody.unlinkRow(false);
}
scrollBody.unlinkRow(false);
}
return;
}
scrollBody.renderRows(uidl, firstRow, reqRows);
discardRowsOutsideCacheWindow();
}
private void updateRowsInBody(UIDL partialRowUpdates) {
if (partialRowUpdates == null) {
return;
}
int firstRowIx = partialRowUpdates.getIntAttribute("firsturowix");
int count = partialRowUpdates.getIntAttribute("numurows");
scrollBody.unlinkRows(firstRowIx, count);
scrollBody.insertRows(partialRowUpdates, firstRowIx, count);
}
/**
* Updates the internal cache by unlinking rows that fall outside of the
* caching window.
*/
protected void discardRowsOutsideCacheWindow() {
int firstRowToKeep = (int) (firstRowInViewPort - pageLength
* cache_rate);
int lastRowToKeep = (int) (firstRowInViewPort + pageLength + pageLength
* cache_rate);
debug("Client side calculated cache rows to keep: " + firstRowToKeep
+ "-" + lastRowToKeep);
if (serverCacheFirst != -1) {
firstRowToKeep = serverCacheFirst;
lastRowToKeep = serverCacheLast;
debug("Server cache rows that override: " + serverCacheFirst + "-"
+ serverCacheLast);
if (firstRowToKeep < scrollBody.getFirstRendered()
|| lastRowToKeep > scrollBody.getLastRendered()) {
debug("*** Server wants us to keep " + serverCacheFirst + "-"
+ serverCacheLast + " but we only have rows "
+ scrollBody.getFirstRendered() + "-"
+ scrollBody.getLastRendered() + " rendered!");
}
}
discardRowsOutsideOf(firstRowToKeep, lastRowToKeep);
scrollBody.fixSpacers();
scrollBody.restoreRowVisibility();
}
private void discardRowsOutsideOf(int optimalFirstRow, int optimalLastRow) {
/*
* firstDiscarded and lastDiscarded are only calculated for debug
* purposes
*/
int firstDiscarded = -1, lastDiscarded = -1;
boolean cont = true;
while (cont && scrollBody.getLastRendered() > optimalFirstRow
&& scrollBody.getFirstRendered() < optimalFirstRow) {
if (firstDiscarded == -1) {
firstDiscarded = scrollBody.getFirstRendered();
}
// removing row from start
cont = scrollBody.unlinkRow(true);
}
if (firstDiscarded != -1) {
lastDiscarded = scrollBody.getFirstRendered() - 1;
debug("Discarded rows " + firstDiscarded + "-" + lastDiscarded);
}
firstDiscarded = lastDiscarded = -1;
cont = true;
while (cont && scrollBody.getLastRendered() > optimalLastRow) {
if (lastDiscarded == -1) {
lastDiscarded = scrollBody.getLastRendered();
}
// removing row from the end
cont = scrollBody.unlinkRow(false);
}
if (lastDiscarded != -1) {
firstDiscarded = scrollBody.getLastRendered() + 1;
debug("Discarded rows " + firstDiscarded + "-" + lastDiscarded);
}
debug("Now in cache: " + scrollBody.getFirstRendered() + "-"
+ scrollBody.getLastRendered());
}
/**
* Inserts rows in the table body or removes them from the table body based
* on the commands in the UIDL.
*
* @param partialRowAdditions
* the UIDL containing row updates.
*/
protected void addAndRemoveRows(UIDL partialRowAdditions) {
if (partialRowAdditions == null) {
return;
}
if (partialRowAdditions.hasAttribute("hide")) {
scrollBody.unlinkAndReindexRows(
partialRowAdditions.getIntAttribute("firstprowix"),
partialRowAdditions.getIntAttribute("numprows"));
scrollBody.ensureCacheFilled();
} else {
if (partialRowAdditions.hasAttribute("delbelow")) {
scrollBody.insertRowsDeleteBelow(partialRowAdditions,
partialRowAdditions.getIntAttribute("firstprowix"),
partialRowAdditions.getIntAttribute("numprows"));
} else {
scrollBody.insertAndReindexRows(partialRowAdditions,
partialRowAdditions.getIntAttribute("firstprowix"),
partialRowAdditions.getIntAttribute("numprows"));
}
}
discardRowsOutsideCacheWindow();
}
/**
* Gives correct column index for given column key ("cid" in UIDL).
*
* @param colKey
* @return column index of visible columns, -1 if column not visible
*/
private int getColIndexByKey(String colKey) {
// return 0 if asked for rowHeaders
if (ROW_HEADER_COLUMN_KEY.equals(colKey)) {
return 0;
}
for (int i = 0; i < visibleColOrder.length; i++) {
if (visibleColOrder[i].equals(colKey)) {
return i;
}
}
return -1;
}
private boolean isMultiSelectModeSimple() {
return selectMode == Table.SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_SIMPLE;
}
private boolean isSingleSelectMode() {
return selectMode == Table.SELECT_MODE_SINGLE;
}
private boolean isMultiSelectModeAny() {
return selectMode == Table.SELECT_MODE_MULTI;
}
private boolean isMultiSelectModeDefault() {
return selectMode == Table.SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT;
}
private void setMultiSelectMode(int multiselectmode) {
if (BrowserInfo.get().isTouchDevice()) {
// Always use the simple mode for touch devices that do not have
// shift/ctrl keys
this.multiselectmode = MULTISELECT_MODE_SIMPLE;
} else {
this.multiselectmode = multiselectmode;
}
}
protected boolean isSelectable() {
return selectMode > Table.SELECT_MODE_NONE;
}
private boolean isCollapsedColumn(String colKey) {
if (collapsedColumns == null) {
return false;
}
if (collapsedColumns.contains(colKey)) {
return true;
}
return false;
}
private String getColKeyByIndex(int index) {
return tHead.getHeaderCell(index).getColKey();
}
private void setColWidth(int colIndex, int w, boolean isDefinedWidth) {
final HeaderCell hcell = tHead.getHeaderCell(colIndex);
// Make sure that the column grows to accommodate the sort indicator if
// necessary.
if (w < hcell.getMinWidth()) {
w = hcell.getMinWidth();
}
// Set header column width
hcell.setWidth(w, isDefinedWidth);
// Ensure indicators have been taken into account
tHead.resizeCaptionContainer(hcell);
// Set body column width
scrollBody.setColWidth(colIndex, w);
// Set footer column width
FooterCell fcell = tFoot.getFooterCell(colIndex);
fcell.setWidth(w, isDefinedWidth);
}
private int getColWidth(String colKey) {
return tHead.getHeaderCell(colKey).getWidth();
}
/**
* Get a rendered row by its key
*
* @param key
* The key to search with
* @return
*/
protected VScrollTableRow getRenderedRowByKey(String key) {
if (scrollBody != null) {
final Iterator<Widget> it = scrollBody.iterator();
VScrollTableRow r = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (r.getKey().equals(key)) {
return r;
}
}
}
return null;
}
/**
* Returns the next row to the given row
*
* @param row
* The row to calculate from
*
* @return The next row or null if no row exists
*/
private VScrollTableRow getNextRow(VScrollTableRow row, int offset) {
final Iterator<Widget> it = scrollBody.iterator();
VScrollTableRow r = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (r == row) {
r = null;
while (offset >= 0 && it.hasNext()) {
r = (VScrollTableRow) it.next();
offset--;
}
return r;
}
}
return null;
}
/**
* Returns the previous row from the given row
*
* @param row
* The row to calculate from
* @return The previous row or null if no row exists
*/
private VScrollTableRow getPreviousRow(VScrollTableRow row, int offset) {
final Iterator<Widget> it = scrollBody.iterator();
final Iterator<Widget> offsetIt = scrollBody.iterator();
VScrollTableRow r = null;
VScrollTableRow prev = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (offset < 0) {
prev = (VScrollTableRow) offsetIt.next();
}
if (r == row) {
return prev;
}
offset--;
}
return null;
}
protected void reOrderColumn(String columnKey, int newIndex) {
final int oldIndex = getColIndexByKey(columnKey);
// Change header order
tHead.moveCell(oldIndex, newIndex);
// Change body order
scrollBody.moveCol(oldIndex, newIndex);
// Change footer order
tFoot.moveCell(oldIndex, newIndex);
/*
* Build new columnOrder and update it to server Note that columnOrder
* also contains collapsed columns so we cannot directly build it from
* cells vector Loop the old columnOrder and append in order to new
* array unless on moved columnKey. On new index also put the moved key
* i == index on columnOrder, j == index on newOrder
*/
final String oldKeyOnNewIndex = visibleColOrder[newIndex];
if (showRowHeaders) {
newIndex--; // columnOrder don't have rowHeader
}
// add back hidden rows,
for (int i = 0; i < columnOrder.length; i++) {
if (columnOrder[i].equals(oldKeyOnNewIndex)) {
break; // break loop at target
}
if (isCollapsedColumn(columnOrder[i])) {
newIndex++;
}
}
// finally we can build the new columnOrder for server
final String[] newOrder = new String[columnOrder.length];
for (int i = 0, j = 0; j < newOrder.length; i++) {
if (j == newIndex) {
newOrder[j] = columnKey;
j++;
}
if (i == columnOrder.length) {
break;
}
if (columnOrder[i].equals(columnKey)) {
continue;
}
newOrder[j] = columnOrder[i];
j++;
}
columnOrder = newOrder;
// also update visibleColumnOrder
int i = showRowHeaders ? 1 : 0;
for (int j = 0; j < newOrder.length; j++) {
final String cid = newOrder[j];
if (!isCollapsedColumn(cid)) {
visibleColOrder[i++] = cid;
}
}
client.updateVariable(paintableId, "columnorder", columnOrder, false);
if (client.hasEventListeners(this, COLUMN_REORDER_EVENT_ID)) {
client.sendPendingVariableChanges();
}
}
@Override
protected void onAttach() {
super.onAttach();
if (initialContentReceived) {
sizeInit();
}
}
@Override
protected void onDetach() {
rowRequestHandler.cancel();
super.onDetach();
// ensure that scrollPosElement will be detached
if (scrollPositionElement != null) {
final Element parent = DOM.getParent(scrollPositionElement);
if (parent != null) {
DOM.removeChild(parent, scrollPositionElement);
}
}
}
/**
* Run only once when component is attached and received its initial
* content. This function:
*
* * Syncs headers and bodys "natural widths and saves the values.
*
* * Sets proper width and height
*
* * Makes deferred request to get some cache rows
*/
private void sizeInit() {
/*
* We will use browsers table rendering algorithm to find proper column
* widths. If content and header take less space than available, we will
* divide extra space relatively to each column which has not width set.
*
* Overflow pixels are added to last column.
*/
Iterator<Widget> headCells = tHead.iterator();
Iterator<Widget> footCells = tFoot.iterator();
int i = 0;
int totalExplicitColumnsWidths = 0;
int total = 0;
float expandRatioDivider = 0;
final int[] widths = new int[tHead.visibleCells.size()];
tHead.enableBrowserIntelligence();
tFoot.enableBrowserIntelligence();
// first loop: collect natural widths
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
final FooterCell fCell = (FooterCell) footCells.next();
int w = hCell.getWidth();
if (hCell.isDefinedWidth()) {
// server has defined column width explicitly
totalExplicitColumnsWidths += w;
} else {
if (hCell.getExpandRatio() > 0) {
expandRatioDivider += hCell.getExpandRatio();
w = 0;
} else {
// get and store greater of header width and column width,
// and
// store it as a minimumn natural col width
int headerWidth = hCell.getNaturalColumnWidth(i);
int footerWidth = fCell.getNaturalColumnWidth(i);
w = headerWidth > footerWidth ? headerWidth : footerWidth;
}
hCell.setNaturalMinimumColumnWidth(w);
fCell.setNaturalMinimumColumnWidth(w);
}
widths[i] = w;
total += w;
i++;
}
tHead.disableBrowserIntelligence();
tFoot.disableBrowserIntelligence();
boolean willHaveScrollbarz = willHaveScrollbars();
// fix "natural" width if width not set
if (width == null || "".equals(width)) {
int w = total;
w += scrollBody.getCellExtraWidth() * visibleColOrder.length;
if (willHaveScrollbarz) {
w += Util.getNativeScrollbarSize();
}
setContentWidth(w);
}
int availW = scrollBody.getAvailableWidth();
if (BrowserInfo.get().isIE()) {
// Hey IE, are you really sure about this?
availW = scrollBody.getAvailableWidth();
}
availW -= scrollBody.getCellExtraWidth() * visibleColOrder.length;
if (willHaveScrollbarz) {
availW -= Util.getNativeScrollbarSize();
}
// TODO refactor this code to be the same as in resize timer
boolean needsReLayout = false;
if (availW > total) {
// natural size is smaller than available space
final int extraSpace = availW - total;
final int totalWidthR = total - totalExplicitColumnsWidths;
int checksum = 0;
needsReLayout = true;
if (extraSpace == 1) {
// We cannot divide one single pixel so we give it the first
// undefined column
headCells = tHead.iterator();
i = 0;
checksum = availW;
while (headCells.hasNext()) {
HeaderCell hc = (HeaderCell) headCells.next();
if (!hc.isDefinedWidth()) {
widths[i]++;
break;
}
i++;
}
} else if (expandRatioDivider > 0) {
// visible columns have some active expand ratios, excess
// space is divided according to them
headCells = tHead.iterator();
i = 0;
while (headCells.hasNext()) {
HeaderCell hCell = (HeaderCell) headCells.next();
if (hCell.getExpandRatio() > 0) {
int w = widths[i];
final int newSpace = Math.round((extraSpace * (hCell
.getExpandRatio() / expandRatioDivider)));
w += newSpace;
widths[i] = w;
}
checksum += widths[i];
i++;
}
} else if (totalWidthR > 0) {
// no expand ratios defined, we will share extra space
// relatively to "natural widths" among those without
// explicit width
headCells = tHead.iterator();
i = 0;
while (headCells.hasNext()) {
HeaderCell hCell = (HeaderCell) headCells.next();
if (!hCell.isDefinedWidth()) {
int w = widths[i];
final int newSpace = Math.round((float) extraSpace
* (float) w / totalWidthR);
w += newSpace;
widths[i] = w;
}
checksum += widths[i];
i++;
}
}
if (extraSpace > 0 && checksum != availW) {
/*
* There might be in some cases a rounding error of 1px when
* extra space is divided so if there is one then we give the
* first undefined column 1 more pixel
*/
headCells = tHead.iterator();
i = 0;
while (headCells.hasNext()) {
HeaderCell hc = (HeaderCell) headCells.next();
if (!hc.isDefinedWidth()) {
widths[i] += availW - checksum;
break;
}
i++;
}
}
} else {
// bodys size will be more than available and scrollbar will appear
}
// last loop: set possibly modified values or reset if new tBody
i = 0;
headCells = tHead.iterator();
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
if (isNewBody || hCell.getWidth() == -1) {
final int w = widths[i];
setColWidth(i, w, false);
}
i++;
}
initializedAndAttached = true;
if (needsReLayout) {
scrollBody.reLayoutComponents();
}
updatePageLength();
/*
* Fix "natural" height if height is not set. This must be after width
* fixing so the components' widths have been adjusted.
*/
if (height == null || "".equals(height)) {
/*
* We must force an update of the row height as this point as it
* might have been (incorrectly) calculated earlier
*/
int bodyHeight;
if (pageLength == totalRows) {
/*
* A hack to support variable height rows when paging is off.
* Generally this is not supported by scrolltable. We want to
* show all rows so the bodyHeight should be equal to the table
* height.
*/
// int bodyHeight = scrollBody.getOffsetHeight();
bodyHeight = scrollBody.getRequiredHeight();
} else {
bodyHeight = (int) Math.round(scrollBody.getRowHeight(true)
* pageLength);
}
boolean needsSpaceForHorizontalSrollbar = (total > availW);
if (needsSpaceForHorizontalSrollbar) {
bodyHeight += Util.getNativeScrollbarSize();
}
scrollBodyPanel.setHeight(bodyHeight + "px");
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
isNewBody = false;
if (firstvisible > 0) {
// FIXME #7607
// Originally deferred due to Firefox oddities which should not
// occur any more. Currently deferring breaks Webkit scrolling with
// relative-height tables, but not deferring instead breaks tables
// with explicit page length.
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
scrollBodyPanel
.setScrollPosition(measureRowHeightOffset(firstvisible));
firstRowInViewPort = firstvisible;
}
});
}
if (enabled) {
// Do we need cache rows
if (scrollBody.getLastRendered() + 1 < firstRowInViewPort
+ pageLength + (int) cache_react_rate * pageLength) {
if (totalRows - 1 > scrollBody.getLastRendered()) {
// fetch cache rows
int firstInNewSet = scrollBody.getLastRendered() + 1;
rowRequestHandler.setReqFirstRow(firstInNewSet);
int lastInNewSet = (int) (firstRowInViewPort + pageLength + cache_rate
* pageLength);
if (lastInNewSet > totalRows - 1) {
lastInNewSet = totalRows - 1;
}
rowRequestHandler.setReqRows(lastInNewSet - firstInNewSet
+ 1);
rowRequestHandler.deferRowFetch(1);
}
}
}
/*
* Ensures the column alignments are correct at initial loading. <br/>
* (child components widths are correct)
*/
scrollBody.reLayoutComponents();
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
});
}
/**
* Note, this method is not official api although declared as protected.
* Extend at you own risk.
*
* @return true if content area will have scrollbars visible.
*/
protected boolean willHaveScrollbars() {
if (!(height != null && !height.equals(""))) {
if (pageLength < totalRows) {
return true;
}
} else {
int fakeheight = (int) Math.round(scrollBody.getRowHeight()
* totalRows);
int availableHeight = scrollBodyPanel.getElement().getPropertyInt(
"clientHeight");
if (fakeheight > availableHeight) {
return true;
}
}
return false;
}
private void announceScrollPosition() {
if (scrollPositionElement == null) {
scrollPositionElement = DOM.createDiv();
scrollPositionElement.setClassName(CLASSNAME + "-scrollposition");
scrollPositionElement.getStyle().setPosition(Position.ABSOLUTE);
scrollPositionElement.getStyle().setDisplay(Display.NONE);
getElement().appendChild(scrollPositionElement);
}
Style style = scrollPositionElement.getStyle();
style.setMarginLeft(getElement().getOffsetWidth() / 2 - 80, Unit.PX);
style.setMarginTop(-scrollBodyPanel.getOffsetHeight(), Unit.PX);
// indexes go from 1-totalRows, as rowheaders in index-mode indicate
int last = (firstRowInViewPort + pageLength);
if (last > totalRows) {
last = totalRows;
}
scrollPositionElement.setInnerHTML("<span>" + (firstRowInViewPort + 1)
+ " – " + (last) + "..." + "</span>");
style.setDisplay(Display.BLOCK);
}
private void hideScrollPositionAnnotation() {
if (scrollPositionElement != null) {
DOM.setStyleAttribute(scrollPositionElement, "display", "none");
}
}
private boolean isScrollPositionVisible() {
return scrollPositionElement != null
&& !scrollPositionElement.getStyle().getDisplay()
.equals(Display.NONE.toString());
}
private class RowRequestHandler extends Timer {
private int reqFirstRow = 0;
private int reqRows = 0;
private boolean isRunning = false;
public void deferRowFetch() {
deferRowFetch(250);
}
public boolean isRunning() {
return isRunning;
}
public void deferRowFetch(int msec) {
isRunning = true;
if (reqRows > 0 && reqFirstRow < totalRows) {
schedule(msec);
// tell scroll position to user if currently "visible" rows are
// not rendered
if (totalRows > pageLength
&& ((firstRowInViewPort + pageLength > scrollBody
.getLastRendered()) || (firstRowInViewPort < scrollBody
.getFirstRendered()))) {
announceScrollPosition();
} else {
hideScrollPositionAnnotation();
}
}
}
public void setReqFirstRow(int reqFirstRow) {
if (reqFirstRow < 0) {
reqFirstRow = 0;
} else if (reqFirstRow >= totalRows) {
reqFirstRow = totalRows - 1;
}
this.reqFirstRow = reqFirstRow;
}
public void setReqRows(int reqRows) {
this.reqRows = reqRows;
}
@Override
public void run() {
if (client.hasActiveRequest() || navKeyDown) {
// if client connection is busy, don't bother loading it more
VConsole.log("Postponed rowfetch");
schedule(250);
} else {
int firstToBeRendered = scrollBody.firstRendered;
if (reqFirstRow < firstToBeRendered) {
firstToBeRendered = reqFirstRow;
} else if (firstRowInViewPort - (int) (cache_rate * pageLength) > firstToBeRendered) {
firstToBeRendered = firstRowInViewPort
- (int) (cache_rate * pageLength);
if (firstToBeRendered < 0) {
firstToBeRendered = 0;
}
}
int lastToBeRendered = scrollBody.lastRendered;
if (reqFirstRow + reqRows - 1 > lastToBeRendered) {
lastToBeRendered = reqFirstRow + reqRows - 1;
} else if (firstRowInViewPort + pageLength + pageLength
* cache_rate < lastToBeRendered) {
lastToBeRendered = (firstRowInViewPort + pageLength + (int) (pageLength * cache_rate));
if (lastToBeRendered >= totalRows) {
lastToBeRendered = totalRows - 1;
}
// due Safari 3.1 bug (see #2607), verify reqrows, original
// problem unknown, but this should catch the issue
if (reqFirstRow + reqRows - 1 > lastToBeRendered) {
reqRows = lastToBeRendered - reqFirstRow;
}
}
client.updateVariable(paintableId, "firstToBeRendered",
firstToBeRendered, false);
client.updateVariable(paintableId, "lastToBeRendered",
lastToBeRendered, false);
// remember which firstvisible we requested, in case the server
// has
// a differing opinion
lastRequestedFirstvisible = firstRowInViewPort;
client.updateVariable(paintableId, "firstvisible",
firstRowInViewPort, false);
client.updateVariable(paintableId, "reqfirstrow", reqFirstRow,
false);
client.updateVariable(paintableId, "reqrows", reqRows, true);
if (selectionChanged) {
unSyncedselectionsBeforeRowFetch = new HashSet<Object>(
selectedRowKeys);
}
isRunning = false;
}
}
public int getReqFirstRow() {
return reqFirstRow;
}
/**
* Sends request to refresh content at this position.
*/
public void refreshContent() {
isRunning = true;
int first = (int) (firstRowInViewPort - pageLength * cache_rate);
int reqRows = (int) (2 * pageLength * cache_rate + pageLength);
if (first < 0) {
reqRows = reqRows + first;
first = 0;
}
setReqFirstRow(first);
setReqRows(reqRows);
run();
}
}
public class HeaderCell extends Widget {
Element td = DOM.createTD();
Element captionContainer = DOM.createDiv();
Element sortIndicator = DOM.createDiv();
Element colResizeWidget = DOM.createDiv();
Element floatingCopyOfHeaderCell;
private boolean sortable = false;
private final String cid;
private boolean dragging;
private int dragStartX;
private int colIndex;
private int originalWidth;
private boolean isResizing;
private int headerX;
private boolean moved;
private int closestSlot;
private int width = -1;
private int naturalWidth = -1;
private char align = ALIGN_LEFT;
boolean definedWidth = false;
private float expandRatio = 0;
private boolean sorted;
public void setSortable(boolean b) {
sortable = b;
}
/**
* Makes room for the sorting indicator in case the column that the
* header cell belongs to is sorted. This is done by resizing the width
* of the caption container element by the correct amount
*/
public void resizeCaptionContainer(int rightSpacing) {
int captionContainerWidth = width
- colResizeWidget.getOffsetWidth() - rightSpacing;
if (BrowserInfo.get().isIE6() || td.getClassName().contains("-asc")
|| td.getClassName().contains("-desc")) {
// Leave room for the sort indicator
captionContainerWidth -= sortIndicator.getOffsetWidth();
}
if (captionContainerWidth < 0) {
rightSpacing += captionContainerWidth;
captionContainerWidth = 0;
}
captionContainer.getStyle().setPropertyPx("width",
captionContainerWidth);
// Apply/Remove spacing if defined
if (rightSpacing > 0) {
colResizeWidget.getStyle().setMarginLeft(rightSpacing, Unit.PX);
} else {
colResizeWidget.getStyle().clearMarginLeft();
}
}
public void setNaturalMinimumColumnWidth(int w) {
naturalWidth = w;
}
public HeaderCell(String colId, String headerText) {
cid = colId;
DOM.setElementProperty(colResizeWidget, "className", CLASSNAME
+ "-resizer");
setText(headerText);
DOM.appendChild(td, colResizeWidget);
DOM.setElementProperty(sortIndicator, "className", CLASSNAME
+ "-sort-indicator");
DOM.appendChild(td, sortIndicator);
DOM.setElementProperty(captionContainer, "className", CLASSNAME
+ "-caption-container");
// ensure no clipping initially (problem on column additions)
DOM.setStyleAttribute(captionContainer, "overflow", "visible");
DOM.appendChild(td, captionContainer);
DOM.sinkEvents(td, Event.MOUSEEVENTS | Event.ONDBLCLICK
| Event.ONCONTEXTMENU | Event.TOUCHEVENTS);
setElement(td);
setAlign(ALIGN_LEFT);
}
public void disableAutoWidthCalculation() {
definedWidth = true;
expandRatio = 0;
}
public void setWidth(int w, boolean ensureDefinedWidth) {
if (ensureDefinedWidth) {
definedWidth = true;
// on column resize expand ratio becomes zero
expandRatio = 0;
}
if (width == -1) {
// go to default mode, clip content if necessary
DOM.setStyleAttribute(captionContainer, "overflow", "");
}
width = w;
if (w == -1) {
DOM.setStyleAttribute(captionContainer, "width", "");
setWidth("");
} else {
tHead.resizeCaptionContainer(this);
/*
* if we already have tBody, set the header width properly, if
* not defer it. IE will fail with complex float in table header
* unless TD width is not explicitly set.
*/
if (scrollBody != null) {
int tdWidth = width + scrollBody.getCellExtraWidth();
setWidth(tdWidth + "px");
} else {
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
int tdWidth = width
+ scrollBody.getCellExtraWidth();
setWidth(tdWidth + "px");
}
});
}
}
}
public void setUndefinedWidth() {
definedWidth = false;
setWidth(-1, false);
}
/**
* Detects if width is fixed by developer on server side or resized to
* current width by user.
*
* @return true if defined, false if "natural" width
*/
public boolean isDefinedWidth() {
return definedWidth && width >= 0;
}
public int getWidth() {
return width;
}
public void setText(String headerText) {
DOM.setInnerHTML(captionContainer, headerText);
}
public String getColKey() {
return cid;
}
private void setSorted(boolean sorted) {
this.sorted = sorted;
if (sorted) {
if (sortAscending) {
this.setStyleName(CLASSNAME + "-header-cell-asc");
} else {
this.setStyleName(CLASSNAME + "-header-cell-desc");
}
} else {
this.setStyleName(CLASSNAME + "-header-cell");
}
}
/**
* Handle column reordering.
*/
@Override
public void onBrowserEvent(Event event) {
if (enabled && event != null) {
if (isResizing
|| event.getEventTarget().cast() == colResizeWidget) {
if (dragging
&& (event.getTypeInt() == Event.ONMOUSEUP || event
.getTypeInt() == Event.ONTOUCHEND)) {
// Handle releasing column header on spacer #5318
handleCaptionEvent(event);
} else {
onResizeEvent(event);
}
} else {
/*
* Ensure focus before handling caption event. Otherwise
* variables changed from caption event may be before
* variables from other components that fire variables when
* they lose focus.
*/
if (event.getTypeInt() == Event.ONMOUSEDOWN
|| event.getTypeInt() == Event.ONTOUCHSTART) {
scrollBodyPanel.setFocus(true);
}
handleCaptionEvent(event);
boolean stopPropagation = true;
if (event.getTypeInt() == Event.ONCONTEXTMENU
&& !client.hasEventListeners(VScrollTable.this,
HEADER_CLICK_EVENT_ID)) {
// Prevent showing the browser's context menu only when
// there is a header click listener.
stopPropagation = false;
}
if (stopPropagation) {
event.stopPropagation();
event.preventDefault();
}
}
}
}
private void createFloatingCopy() {
floatingCopyOfHeaderCell = DOM.createDiv();
DOM.setInnerHTML(floatingCopyOfHeaderCell, DOM.getInnerHTML(td));
floatingCopyOfHeaderCell = DOM
.getChild(floatingCopyOfHeaderCell, 2);
DOM.setElementProperty(floatingCopyOfHeaderCell, "className",
CLASSNAME + "-header-drag");
// otherwise might wrap or be cut if narrow column
DOM.setStyleAttribute(floatingCopyOfHeaderCell, "width", "auto");
updateFloatingCopysPosition(DOM.getAbsoluteLeft(td),
DOM.getAbsoluteTop(td));
DOM.appendChild(RootPanel.get().getElement(),
floatingCopyOfHeaderCell);
}
private void updateFloatingCopysPosition(int x, int y) {
x -= DOM.getElementPropertyInt(floatingCopyOfHeaderCell,
"offsetWidth") / 2;
DOM.setStyleAttribute(floatingCopyOfHeaderCell, "left", x + "px");
if (y > 0) {
DOM.setStyleAttribute(floatingCopyOfHeaderCell, "top", (y + 7)
+ "px");
}
}
private void hideFloatingCopy() {
DOM.removeChild(RootPanel.get().getElement(),
floatingCopyOfHeaderCell);
floatingCopyOfHeaderCell = null;
}
/**
* Fires a header click event after the user has clicked a column header
* cell
*
* @param event
* The click event
*/
private void fireHeaderClickedEvent(Event event) {
if (client.hasEventListeners(VScrollTable.this,
HEADER_CLICK_EVENT_ID)) {
MouseEventDetails details = new MouseEventDetails(event);
client.updateVariable(paintableId, "headerClickEvent",
details.toString(), false);
client.updateVariable(paintableId, "headerClickCID", cid, true);
}
}
protected void handleCaptionEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONTOUCHSTART:
case Event.ONMOUSEDOWN:
if (columnReordering
&& Util.isTouchEventOrLeftMouseButton(event)) {
if (event.getTypeInt() == Event.ONTOUCHSTART) {
/*
* prevent using this event in e.g. scrolling
*/
event.stopPropagation();
}
dragging = true;
moved = false;
colIndex = getColIndexByKey(cid);
DOM.setCapture(getElement());
headerX = tHead.getAbsoluteLeft();
event.preventDefault(); // prevent selecting text &&
// generated touch events
}
break;
case Event.ONMOUSEUP:
case Event.ONTOUCHEND:
case Event.ONTOUCHCANCEL:
if (columnReordering
&& Util.isTouchEventOrLeftMouseButton(event)) {
dragging = false;
DOM.releaseCapture(getElement());
if (moved) {
hideFloatingCopy();
tHead.removeSlotFocus();
if (closestSlot != colIndex
&& closestSlot != (colIndex + 1)) {
if (closestSlot > colIndex) {
reOrderColumn(cid, closestSlot - 1);
} else {
reOrderColumn(cid, closestSlot);
}
}
}
if (Util.isTouchEvent(event)) {
/*
* Prevent using in e.g. scrolling and prevent generated
* events.
*/
event.preventDefault();
event.stopPropagation();
}
}
if (!moved) {
// mouse event was a click to header -> sort column
if (sortable && Util.isTouchEventOrLeftMouseButton(event)) {
if (sortColumn.equals(cid)) {
// just toggle order
client.updateVariable(paintableId, "sortascending",
!sortAscending, false);
} else {
// set table sorted by this column
client.updateVariable(paintableId, "sortcolumn",
cid, false);
}
// get also cache columns at the same request
scrollBodyPanel.setScrollPosition(0);
firstvisible = 0;
rowRequestHandler.setReqFirstRow(0);
rowRequestHandler.setReqRows((int) (2 * pageLength
* cache_rate + pageLength));
rowRequestHandler.deferRowFetch(); // some validation +
// defer 250ms
rowRequestHandler.cancel(); // instead of waiting
rowRequestHandler.run(); // run immediately
}
fireHeaderClickedEvent(event);
if (Util.isTouchEvent(event)) {
/*
* Prevent using in e.g. scrolling and prevent generated
* events.
*/
event.preventDefault();
event.stopPropagation();
}
break;
}
break;
case Event.ONDBLCLICK:
fireHeaderClickedEvent(event);
break;
case Event.ONTOUCHMOVE:
case Event.ONMOUSEMOVE:
if (dragging && Util.isTouchEventOrLeftMouseButton(event)) {
if (event.getTypeInt() == Event.ONTOUCHMOVE) {
/*
* prevent using this event in e.g. scrolling
*/
event.stopPropagation();
}
if (!moved) {
createFloatingCopy();
moved = true;
}
final int clientX = Util.getTouchOrMouseClientX(event);
final int x = clientX + tHead.hTableWrapper.getScrollLeft();
int slotX = headerX;
closestSlot = colIndex;
int closestDistance = -1;
int start = 0;
if (showRowHeaders) {
start++;
}
final int visibleCellCount = tHead.getVisibleCellCount();
for (int i = start; i <= visibleCellCount; i++) {
if (i > 0) {
final String colKey = getColKeyByIndex(i - 1);
slotX += getColWidth(colKey);
}
final int dist = Math.abs(x - slotX);
if (closestDistance == -1 || dist < closestDistance) {
closestDistance = dist;
closestSlot = i;
}
}
tHead.focusSlot(closestSlot);
updateFloatingCopysPosition(clientX, -1);
}
break;
default:
break;
}
}
private void onResizeEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
if (!Util.isTouchEventOrLeftMouseButton(event)) {
return;
}
isResizing = true;
DOM.setCapture(getElement());
dragStartX = DOM.eventGetClientX(event);
colIndex = getColIndexByKey(cid);
originalWidth = getWidth();
DOM.eventPreventDefault(event);
break;
case Event.ONMOUSEUP:
if (!Util.isTouchEventOrLeftMouseButton(event)) {
return;
}
isResizing = false;
DOM.releaseCapture(getElement());
tHead.disableAutoColumnWidthCalculation(this);
// Ensure last header cell is taking into account possible
// column selector
HeaderCell lastCell = tHead.getHeaderCell(tHead
.getVisibleCellCount() - 1);
tHead.resizeCaptionContainer(lastCell);
triggerLazyColumnAdjustment(true);
fireColumnResizeEvent(cid, originalWidth, getColWidth(cid));
break;
case Event.ONMOUSEMOVE:
if (!Util.isTouchEventOrLeftMouseButton(event)) {
return;
}
if (isResizing) {
final int deltaX = DOM.eventGetClientX(event) - dragStartX;
if (deltaX == 0) {
return;
}
tHead.disableAutoColumnWidthCalculation(this);
int newWidth = originalWidth + deltaX;
if (newWidth < getMinWidth()) {
newWidth = getMinWidth();
}
setColWidth(colIndex, newWidth, true);
triggerLazyColumnAdjustment(false);
forceRealignColumnHeaders();
}
break;
default:
break;
}
}
public int getMinWidth() {
int cellExtraWidth = 0;
if (scrollBody != null) {
cellExtraWidth += scrollBody.getCellExtraWidth();
}
return cellExtraWidth + sortIndicator.getOffsetWidth();
}
public String getCaption() {
return DOM.getInnerText(captionContainer);
}
public boolean isEnabled() {
return getParent() != null;
}
public void setAlign(char c) {
final String ALIGN_PREFIX = CLASSNAME + "-caption-container-align-";
if (align != c) {
captionContainer.removeClassName(ALIGN_PREFIX + "center");
captionContainer.removeClassName(ALIGN_PREFIX + "right");
captionContainer.removeClassName(ALIGN_PREFIX + "left");
switch (c) {
case ALIGN_CENTER:
captionContainer.addClassName(ALIGN_PREFIX + "center");
break;
case ALIGN_RIGHT:
captionContainer.addClassName(ALIGN_PREFIX + "right");
break;
default:
captionContainer.addClassName(ALIGN_PREFIX + "left");
break;
}
}
align = c;
}
public char getAlign() {
return align;
}
/**
* Detects the natural minimum width for the column of this header cell.
* If column is resized by user or the width is defined by server the
* actual width is returned. Else the natural min width is returned.
*
* @param columnIndex
* column index hint, if -1 (unknown) it will be detected
*
* @return
*/
public int getNaturalColumnWidth(int columnIndex) {
if (isDefinedWidth()) {
return width;
} else {
if (naturalWidth < 0) {
// This is recently revealed column. Try to detect a proper
// value (greater of header and data
// cols)
int hw = captionContainer.getOffsetWidth()
+ scrollBody.getCellExtraWidth();
if (BrowserInfo.get().isGecko()
|| BrowserInfo.get().isIE7()) {
hw += sortIndicator.getOffsetWidth();
}
if (columnIndex < 0) {
columnIndex = 0;
for (Iterator<Widget> it = tHead.iterator(); it
.hasNext(); columnIndex++) {
if (it.next() == this) {
break;
}
}
}
final int cw = scrollBody.getColWidth(columnIndex);
naturalWidth = (hw > cw ? hw : cw);
}
return naturalWidth;
}
}
public void setExpandRatio(float floatAttribute) {
if (floatAttribute != expandRatio) {
triggerLazyColumnAdjustment(false);
}
expandRatio = floatAttribute;
}
public float getExpandRatio() {
return expandRatio;
}
public boolean isSorted() {
return sorted;
}
}
/**
* HeaderCell that is header cell for row headers.
*
* Reordering disabled and clicking on it resets sorting.
*/
public class RowHeadersHeaderCell extends HeaderCell {
RowHeadersHeaderCell() {
super(ROW_HEADER_COLUMN_KEY, "");
this.setStyleName(CLASSNAME + "-header-cell-rowheader");
}
@Override
protected void handleCaptionEvent(Event event) {
// NOP: RowHeaders cannot be reordered
// TODO It'd be nice to reset sorting here
}
}
public class TableHead extends Panel implements ActionOwner {
private static final int WRAPPER_WIDTH = 900000;
ArrayList<Widget> visibleCells = new ArrayList<Widget>();
HashMap<String, HeaderCell> availableCells = new HashMap<String, HeaderCell>();
Element div = DOM.createDiv();
Element hTableWrapper = DOM.createDiv();
Element hTableContainer = DOM.createDiv();
Element table = DOM.createTable();
Element headerTableBody = DOM.createTBody();
Element tr = DOM.createTR();
private final Element columnSelector = DOM.createDiv();
private int focusedSlot = -1;
public TableHead() {
if (BrowserInfo.get().isIE()) {
table.setPropertyInt("cellSpacing", 0);
}
DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden");
DOM.setElementProperty(hTableWrapper, "className", CLASSNAME
+ "-header");
// TODO move styles to CSS
DOM.setElementProperty(columnSelector, "className", CLASSNAME
+ "-column-selector");
DOM.setStyleAttribute(columnSelector, "display", "none");
DOM.appendChild(table, headerTableBody);
DOM.appendChild(headerTableBody, tr);
DOM.appendChild(hTableContainer, table);
DOM.appendChild(hTableWrapper, hTableContainer);
DOM.appendChild(div, hTableWrapper);
DOM.appendChild(div, columnSelector);
setElement(div);
setStyleName(CLASSNAME + "-header-wrap");
DOM.sinkEvents(columnSelector, Event.ONCLICK);
availableCells.put(ROW_HEADER_COLUMN_KEY,
new RowHeadersHeaderCell());
}
public void resizeCaptionContainer(HeaderCell cell) {
HeaderCell lastcell = getHeaderCell(visibleCells.size() - 1);
// Measure column widths
int columnTotalWidth = 0;
for (Widget w : visibleCells) {
columnTotalWidth += w.getOffsetWidth();
}
if (cell == lastcell
&& columnSelector.getOffsetWidth() > 0
&& columnTotalWidth >= div.getOffsetWidth()
- columnSelector.getOffsetWidth()
&& !hasVerticalScrollbar()) {
// Ensure column caption is visible when placed under the column
// selector widget by shifting and resizing the caption.
int offset = 0;
int diff = div.getOffsetWidth() - columnTotalWidth;
if (diff < columnSelector.getOffsetWidth() && diff > 0) {
// If the difference is less than the column selectors width
// then just offset by the
// difference
offset = columnSelector.getOffsetWidth() - diff;
} else {
// Else offset by the whole column selector
offset = columnSelector.getOffsetWidth();
}
lastcell.resizeCaptionContainer(offset);
} else {
cell.resizeCaptionContainer(0);
}
}
@Override
public void clear() {
for (String cid : availableCells.keySet()) {
removeCell(cid);
}
availableCells.clear();
availableCells.put(ROW_HEADER_COLUMN_KEY,
new RowHeadersHeaderCell());
}
public void updateCellsFromUIDL(UIDL uidl) {
Iterator<?> it = uidl.getChildIterator();
HashSet<String> updated = new HashSet<String>();
boolean refreshContentWidths = false;
while (it.hasNext()) {
final UIDL col = (UIDL) it.next();
final String cid = col.getStringAttribute("cid");
updated.add(cid);
String caption = buildCaptionHtmlSnippet(col);
HeaderCell c = getHeaderCell(cid);
if (c == null) {
c = new HeaderCell(cid, caption);
availableCells.put(cid, c);
if (initializedAndAttached) {
// we will need a column width recalculation
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
} else {
c.setText(caption);
}
if (col.hasAttribute("sortable")) {
c.setSortable(true);
if (cid.equals(sortColumn)) {
c.setSorted(true);
} else {
c.setSorted(false);
}
} else {
c.setSortable(false);
}
if (col.hasAttribute("align")) {
c.setAlign(col.getStringAttribute("align").charAt(0));
} else {
c.setAlign(ALIGN_LEFT);
}
if (col.hasAttribute("width")) {
final String widthStr = col.getStringAttribute("width");
// Make sure to accomodate for the sort indicator if
// necessary.
int width = Integer.parseInt(widthStr);
if (width < c.getMinWidth()) {
width = c.getMinWidth();
}
if (width != c.getWidth() && scrollBody != null) {
// Do a more thorough update if a column is resized from
// the server *after* the header has been properly
// initialized
final int colIx = getColIndexByKey(c.cid);
final int newWidth = width;
Scheduler.get().scheduleDeferred(
new ScheduledCommand() {
public void execute() {
setColWidth(colIx, newWidth, true);
}
});
refreshContentWidths = true;
} else {
c.setWidth(width, true);
}
} else if (recalcWidths) {
c.setUndefinedWidth();
}
if (col.hasAttribute("er")) {
c.setExpandRatio(col.getFloatAttribute("er"));
}
if (col.hasAttribute("collapsed")) {
// ensure header is properly removed from parent (case when
// collapsing happens via servers side api)
if (c.isAttached()) {
c.removeFromParent();
headerChangedDuringUpdate = true;
}
}
}
if (refreshContentWidths) {
// Recalculate the column sizings if any column has changed
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
public void execute() {
triggerLazyColumnAdjustment(true);
}
});
}
// check for orphaned header cells
for (Iterator<String> cit = availableCells.keySet().iterator(); cit
.hasNext();) {
String cid = cit.next();
if (!updated.contains(cid)) {
removeCell(cid);
cit.remove();
// we will need a column width recalculation, since columns
// with expand ratios should expand to fill the void.
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
}
}
public void enableColumn(String cid, int index) {
final HeaderCell c = getHeaderCell(cid);
if (!c.isEnabled() || getHeaderCell(index) != c) {
setHeaderCell(index, c);
if (initializedAndAttached) {
headerChangedDuringUpdate = true;
}
}
}
public int getVisibleCellCount() {
return visibleCells.size();
}
public void setHorizontalScrollPosition(int scrollLeft) {
if (BrowserInfo.get().isIE6()) {
hTableWrapper.getStyle().setPosition(Position.RELATIVE);
hTableWrapper.getStyle().setLeft(-scrollLeft, Unit.PX);
} else {
hTableWrapper.setScrollLeft(scrollLeft);
}
}
public void setColumnCollapsingAllowed(boolean cc) {
if (cc) {
columnSelector.getStyle().setDisplay(Display.BLOCK);
} else {
columnSelector.getStyle().setDisplay(Display.NONE);
}
}
public void disableBrowserIntelligence() {
hTableContainer.getStyle().setWidth(WRAPPER_WIDTH, Unit.PX);
}
public void enableBrowserIntelligence() {
hTableContainer.getStyle().clearWidth();
}
public void setHeaderCell(int index, HeaderCell cell) {
if (cell.isEnabled()) {
// we're moving the cell
DOM.removeChild(tr, cell.getElement());
orphan(cell);
visibleCells.remove(cell);
}
if (index < visibleCells.size()) {
// insert to right slot
DOM.insertChild(tr, cell.getElement(), index);
adopt(cell);
visibleCells.add(index, cell);
} else if (index == visibleCells.size()) {
// simply append
DOM.appendChild(tr, cell.getElement());
adopt(cell);
visibleCells.add(cell);
} else {
throw new RuntimeException(
"Header cells must be appended in order");
}
}
public HeaderCell getHeaderCell(int index) {
if (index >= 0 && index < visibleCells.size()) {
return (HeaderCell) visibleCells.get(index);
} else {
return null;
}
}
/**
* Get's HeaderCell by it's column Key.
*
* Note that this returns HeaderCell even if it is currently collapsed.
*
* @param cid
* Column key of accessed HeaderCell
* @return HeaderCell
*/
public HeaderCell getHeaderCell(String cid) {
return availableCells.get(cid);
}
public void moveCell(int oldIndex, int newIndex) {
final HeaderCell hCell = getHeaderCell(oldIndex);
final Element cell = hCell.getElement();
visibleCells.remove(oldIndex);
DOM.removeChild(tr, cell);
DOM.insertChild(tr, cell, newIndex);
visibleCells.add(newIndex, hCell);
}
public Iterator<Widget> iterator() {
return visibleCells.iterator();
}
@Override
public boolean remove(Widget w) {
if (visibleCells.contains(w)) {
visibleCells.remove(w);
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
return true;
}
return false;
}
public void removeCell(String colKey) {
final HeaderCell c = getHeaderCell(colKey);
remove(c);
}
private void focusSlot(int index) {
removeSlotFocus();
if (index > 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, index - 1)),
"className", CLASSNAME + "-resizer " + CLASSNAME
+ "-focus-slot-right");
} else {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, index)),
"className", CLASSNAME + "-resizer " + CLASSNAME
+ "-focus-slot-left");
}
focusedSlot = index;
}
private void removeSlotFocus() {
if (focusedSlot < 0) {
return;
}
if (focusedSlot == 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, focusedSlot)),
"className", CLASSNAME + "-resizer");
} else if (focusedSlot > 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, focusedSlot - 1)),
"className", CLASSNAME + "-resizer");
}
focusedSlot = -1;
}
@Override
public void onBrowserEvent(Event event) {
if (enabled) {
if (event.getEventTarget().cast() == columnSelector) {
final int left = DOM.getAbsoluteLeft(columnSelector);
final int top = DOM.getAbsoluteTop(columnSelector)
+ DOM.getElementPropertyInt(columnSelector,
"offsetHeight");
client.getContextMenu().showAt(this, left, top);
}
}
}
@Override
protected void onDetach() {
super.onDetach();
if (client != null) {
client.getContextMenu().ensureHidden(this);
}
}
class VisibleColumnAction extends Action {
String colKey;
private boolean collapsed;
private VScrollTableRow currentlyFocusedRow;
public VisibleColumnAction(String colKey) {
super(VScrollTable.TableHead.this);
this.colKey = colKey;
caption = tHead.getHeaderCell(colKey).getCaption();
currentlyFocusedRow = focusedRow;
}
@Override
public void execute() {
client.getContextMenu().hide();
// toggle selected column
if (collapsedColumns.contains(colKey)) {
collapsedColumns.remove(colKey);
} else {
tHead.removeCell(colKey);
collapsedColumns.add(colKey);
triggerLazyColumnAdjustment(true);
}
// update variable to server
client.updateVariable(paintableId, "collapsedcolumns",
collapsedColumns.toArray(new String[collapsedColumns
.size()]), false);
// let rowRequestHandler determine proper rows
rowRequestHandler.refreshContent();
lazyRevertFocusToRow(currentlyFocusedRow);
}
public void setCollapsed(boolean b) {
collapsed = b;
}
/**
* Override default method to distinguish on/off columns
*/
@Override
public String getHTML() {
final StringBuffer buf = new StringBuffer();
if (collapsed) {
buf.append("<span class=\"v-off\">");
} else {
buf.append("<span class=\"v-on\">");
}
buf.append(super.getHTML());
buf.append("</span>");
return buf.toString();
}
}
/*
* Returns columns as Action array for column select popup
*/
public Action[] getActions() {
Object[] cols;
if (columnReordering && columnOrder != null) {
cols = columnOrder;
} else {
// if columnReordering is disabled, we need different way to get
// all available columns
cols = visibleColOrder;
cols = new Object[visibleColOrder.length
+ collapsedColumns.size()];
int i;
for (i = 0; i < visibleColOrder.length; i++) {
cols[i] = visibleColOrder[i];
}
for (final Iterator<String> it = collapsedColumns.iterator(); it
.hasNext();) {
cols[i++] = it.next();
}
}
final Action[] actions = new Action[cols.length];
for (int i = 0; i < cols.length; i++) {
final String cid = (String) cols[i];
final HeaderCell c = getHeaderCell(cid);
final VisibleColumnAction a = new VisibleColumnAction(
c.getColKey());
a.setCaption(c.getCaption());
if (!c.isEnabled()) {
a.setCollapsed(true);
}
actions[i] = a;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
/**
* Returns column alignments for visible columns
*/
public char[] getColumnAlignments() {
final Iterator<Widget> it = visibleCells.iterator();
final char[] aligns = new char[visibleCells.size()];
int colIndex = 0;
while (it.hasNext()) {
aligns[colIndex++] = ((HeaderCell) it.next()).getAlign();
}
return aligns;
}
/**
* Disables the automatic calculation of all column widths by forcing
* the widths to be "defined" thus turning off expand ratios and such.
*/
public void disableAutoColumnWidthCalculation(HeaderCell source) {
for (HeaderCell cell : availableCells.values()) {
cell.disableAutoWidthCalculation();
}
// fire column resize events for all columns but the source of the
// resize action, since an event will fire separately for this.
ArrayList<HeaderCell> columns = new ArrayList<HeaderCell>(
availableCells.values());
columns.remove(source);
sendColumnWidthUpdates(columns);
forceRealignColumnHeaders();
}
}
/**
* A cell in the footer
*/
public class FooterCell extends Widget {
private final Element td = DOM.createTD();
private final Element captionContainer = DOM.createDiv();
private char align = ALIGN_LEFT;
private int width = -1;
private float expandRatio = 0;
private final String cid;
boolean definedWidth = false;
private int naturalWidth = -1;
public FooterCell(String colId, String headerText) {
cid = colId;
setText(headerText);
DOM.setElementProperty(captionContainer, "className", CLASSNAME
+ "-footer-container");
// ensure no clipping initially (problem on column additions)
DOM.setStyleAttribute(captionContainer, "overflow", "visible");
DOM.sinkEvents(captionContainer, Event.MOUSEEVENTS);
DOM.appendChild(td, captionContainer);
DOM.sinkEvents(td, Event.MOUSEEVENTS | Event.ONDBLCLICK
| Event.ONCONTEXTMENU);
setElement(td);
}
/**
* Sets the text of the footer
*
* @param footerText
* The text in the footer
*/
public void setText(String footerText) {
DOM.setInnerHTML(captionContainer, footerText);
}
/**
* Set alignment of the text in the cell
*
* @param c
* The alignment which can be ALIGN_CENTER, ALIGN_LEFT,
* ALIGN_RIGHT
*/
public void setAlign(char c) {
if (align != c) {
switch (c) {
case ALIGN_CENTER:
DOM.setStyleAttribute(captionContainer, "textAlign",
"center");
break;
case ALIGN_RIGHT:
DOM.setStyleAttribute(captionContainer, "textAlign",
"right");
break;
default:
DOM.setStyleAttribute(captionContainer, "textAlign", "");
break;
}
}
align = c;
}
/**
* Get the alignment of the text int the cell
*
* @return Returns either ALIGN_CENTER, ALIGN_LEFT or ALIGN_RIGHT
*/
public char getAlign() {
return align;
}
/**
* Sets the width of the cell
*
* @param w
* The width of the cell
* @param ensureDefinedWidth
* Ensures the the given width is not recalculated
*/
public void setWidth(int w, boolean ensureDefinedWidth) {
if (ensureDefinedWidth) {
definedWidth = true;
// on column resize expand ratio becomes zero
expandRatio = 0;
}
if (width == w) {
return;
}
if (width == -1) {
// go to default mode, clip content if necessary
DOM.setStyleAttribute(captionContainer, "overflow", "");
}
width = w;
if (w == -1) {
DOM.setStyleAttribute(captionContainer, "width", "");
setWidth("");
} else {
/*
* Reduce width with one pixel for the right border since the
* footers does not have any spacers between them.
*/
int borderWidths = 1;
// Set the container width (check for negative value)
if (w - borderWidths >= 0) {
captionContainer.getStyle().setPropertyPx("width",
w - borderWidths);
} else {
captionContainer.getStyle().setPropertyPx("width", 0);
}
/*
* if we already have tBody, set the header width properly, if
* not defer it. IE will fail with complex float in table header
* unless TD width is not explicitly set.
*/
if (scrollBody != null) {
/*
* Reduce with one since footer does not have any spacers,
* instead a 1 pixel border.
*/
int tdWidth = width + scrollBody.getCellExtraWidth()
- borderWidths;
setWidth(tdWidth + "px");
} else {
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
int borderWidths = 1;
int tdWidth = width
+ scrollBody.getCellExtraWidth()
- borderWidths;
setWidth(tdWidth + "px");
}
});
}
}
}
/**
* Sets the width to undefined
*/
public void setUndefinedWidth() {
setWidth(-1, false);
}
/**
* Detects if width is fixed by developer on server side or resized to
* current width by user.
*
* @return true if defined, false if "natural" width
*/
public boolean isDefinedWidth() {
return definedWidth && width >= 0;
}
/**
* Returns the pixels width of the footer cell
*
* @return The width in pixels
*/
public int getWidth() {
return width;
}
/**
* Sets the expand ratio of the cell
*
* @param floatAttribute
* The expand ratio
*/
public void setExpandRatio(float floatAttribute) {
expandRatio = floatAttribute;
}
/**
* Returns the expand ration of the cell
*
* @return The expand ratio
*/
public float getExpandRatio() {
return expandRatio;
}
/**
* Is the cell enabled?
*
* @return True if enabled else False
*/
public boolean isEnabled() {
return getParent() != null;
}
/**
* Handle column clicking
*/
@Override
public void onBrowserEvent(Event event) {
if (enabled && event != null) {
handleCaptionEvent(event);
if (DOM.eventGetType(event) == Event.ONMOUSEUP) {
scrollBodyPanel.setFocus(true);
}
boolean stopPropagation = true;
if (event.getTypeInt() == Event.ONCONTEXTMENU
&& !client.hasEventListeners(VScrollTable.this,
FOOTER_CLICK_EVENT_ID)) {
// Show browser context menu if a footer click listener is
// not present
stopPropagation = false;
}
if (stopPropagation) {
event.stopPropagation();
event.preventDefault();
}
}
}
/**
* Handles a event on the captions
*
* @param event
* The event to handle
*/
protected void handleCaptionEvent(Event event) {
if (event.getTypeInt() == Event.ONMOUSEUP
|| event.getTypeInt() == Event.ONDBLCLICK) {
fireFooterClickedEvent(event);
}
}
/**
* Fires a footer click event after the user has clicked a column footer
* cell
*
* @param event
* The click event
*/
private void fireFooterClickedEvent(Event event) {
if (client.hasEventListeners(VScrollTable.this,
FOOTER_CLICK_EVENT_ID)) {
MouseEventDetails details = new MouseEventDetails(event);
client.updateVariable(paintableId, "footerClickEvent",
details.toString(), false);
client.updateVariable(paintableId, "footerClickCID", cid, true);
}
}
/**
* Returns the column key of the column
*
* @return The column key
*/
public String getColKey() {
return cid;
}
/**
* Detects the natural minimum width for the column of this header cell.
* If column is resized by user or the width is defined by server the
* actual width is returned. Else the natural min width is returned.
*
* @param columnIndex
* column index hint, if -1 (unknown) it will be detected
*
* @return
*/
public int getNaturalColumnWidth(int columnIndex) {
if (isDefinedWidth()) {
return width;
} else {
if (naturalWidth < 0) {
// This is recently revealed column. Try to detect a proper
// value (greater of header and data
// cols)
final int hw = ((Element) getElement().getLastChild())
.getOffsetWidth() + scrollBody.getCellExtraWidth();
if (columnIndex < 0) {
columnIndex = 0;
for (Iterator<Widget> it = tHead.iterator(); it
.hasNext(); columnIndex++) {
if (it.next() == this) {
break;
}
}
}
final int cw = scrollBody.getColWidth(columnIndex);
naturalWidth = (hw > cw ? hw : cw);
}
return naturalWidth;
}
}
public void setNaturalMinimumColumnWidth(int w) {
naturalWidth = w;
}
}
/**
* HeaderCell that is header cell for row headers.
*
* Reordering disabled and clicking on it resets sorting.
*/
public class RowHeadersFooterCell extends FooterCell {
RowHeadersFooterCell() {
super(ROW_HEADER_COLUMN_KEY, "");
}
@Override
protected void handleCaptionEvent(Event event) {
// NOP: RowHeaders cannot be reordered
// TODO It'd be nice to reset sorting here
}
}
/**
* The footer of the table which can be seen in the bottom of the Table.
*/
public class TableFooter extends Panel {
private static final int WRAPPER_WIDTH = 900000;
ArrayList<Widget> visibleCells = new ArrayList<Widget>();
HashMap<String, FooterCell> availableCells = new HashMap<String, FooterCell>();
Element div = DOM.createDiv();
Element hTableWrapper = DOM.createDiv();
Element hTableContainer = DOM.createDiv();
Element table = DOM.createTable();
Element headerTableBody = DOM.createTBody();
Element tr = DOM.createTR();
public TableFooter() {
DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden");
DOM.setElementProperty(hTableWrapper, "className", CLASSNAME
+ "-footer");
DOM.appendChild(table, headerTableBody);
DOM.appendChild(headerTableBody, tr);
DOM.appendChild(hTableContainer, table);
DOM.appendChild(hTableWrapper, hTableContainer);
DOM.appendChild(div, hTableWrapper);
setElement(div);
setStyleName(CLASSNAME + "-footer-wrap");
availableCells.put(ROW_HEADER_COLUMN_KEY,
new RowHeadersFooterCell());
}
@Override
public void clear() {
for (String cid : availableCells.keySet()) {
removeCell(cid);
}
availableCells.clear();
availableCells.put(ROW_HEADER_COLUMN_KEY,
new RowHeadersFooterCell());
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.user.client.ui.Panel#remove(com.google.gwt.user.client
* .ui.Widget)
*/
@Override
public boolean remove(Widget w) {
if (visibleCells.contains(w)) {
visibleCells.remove(w);
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see com.google.gwt.user.client.ui.HasWidgets#iterator()
*/
public Iterator<Widget> iterator() {
return visibleCells.iterator();
}
/**
* Gets a footer cell which represents the given columnId
*
* @param cid
* The columnId
*
* @return The cell
*/
public FooterCell getFooterCell(String cid) {
return availableCells.get(cid);
}
/**
* Gets a footer cell by using a column index
*
* @param index
* The index of the column
* @return The Cell
*/
public FooterCell getFooterCell(int index) {
if (index < visibleCells.size()) {
return (FooterCell) visibleCells.get(index);
} else {
return null;
}
}
/**
* Updates the cells contents when updateUIDL request is received
*
* @param uidl
* The UIDL
*/
public void updateCellsFromUIDL(UIDL uidl) {
Iterator<?> columnIterator = uidl.getChildIterator();
HashSet<String> updated = new HashSet<String>();
while (columnIterator.hasNext()) {
final UIDL col = (UIDL) columnIterator.next();
final String cid = col.getStringAttribute("cid");
updated.add(cid);
String caption = col.hasAttribute("fcaption") ? col
.getStringAttribute("fcaption") : "";
FooterCell c = getFooterCell(cid);
if (c == null) {
c = new FooterCell(cid, caption);
availableCells.put(cid, c);
if (initializedAndAttached) {
// we will need a column width recalculation
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
} else {
c.setText(caption);
}
if (col.hasAttribute("align")) {
c.setAlign(col.getStringAttribute("align").charAt(0));
} else {
c.setAlign(ALIGN_LEFT);
}
if (col.hasAttribute("width")) {
if (scrollBody == null) {
// Already updated by setColWidth called from
// TableHeads.updateCellsFromUIDL in case of a server
// side resize
final String width = col.getStringAttribute("width");
c.setWidth(Integer.parseInt(width), true);
}
} else if (recalcWidths) {
c.setUndefinedWidth();
}
if (col.hasAttribute("er")) {
c.setExpandRatio(col.getFloatAttribute("er"));
}
if (col.hasAttribute("collapsed")) {
// ensure header is properly removed from parent (case when
// collapsing happens via servers side api)
if (c.isAttached()) {
c.removeFromParent();
headerChangedDuringUpdate = true;
}
}
}
// check for orphaned header cells
for (Iterator<String> cit = availableCells.keySet().iterator(); cit
.hasNext();) {
String cid = cit.next();
if (!updated.contains(cid)) {
removeCell(cid);
cit.remove();
}
}
}
/**
* Set a footer cell for a specified column index
*
* @param index
* The index
* @param cell
* The footer cell
*/
public void setFooterCell(int index, FooterCell cell) {
if (cell.isEnabled()) {
// we're moving the cell
DOM.removeChild(tr, cell.getElement());
orphan(cell);
visibleCells.remove(cell);
}
if (index < visibleCells.size()) {
// insert to right slot
DOM.insertChild(tr, cell.getElement(), index);
adopt(cell);
visibleCells.add(index, cell);
} else if (index == visibleCells.size()) {
// simply append
DOM.appendChild(tr, cell.getElement());
adopt(cell);
visibleCells.add(cell);
} else {
throw new RuntimeException(
"Header cells must be appended in order");
}
}
/**
* Remove a cell by using the columnId
*
* @param colKey
* The columnId to remove
*/
public void removeCell(String colKey) {
final FooterCell c = getFooterCell(colKey);
remove(c);
}
/**
* Enable a column (Sets the footer cell)
*
* @param cid
* The columnId
* @param index
* The index of the column
*/
public void enableColumn(String cid, int index) {
final FooterCell c = getFooterCell(cid);
if (!c.isEnabled() || getFooterCell(index) != c) {
setFooterCell(index, c);
if (initializedAndAttached) {
headerChangedDuringUpdate = true;
}
}
}
/**
* Disable browser measurement of the table width
*/
public void disableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", WRAPPER_WIDTH
+ "px");
}
/**
* Enable browser measurement of the table width
*/
public void enableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", "");
}
/**
* Set the horizontal position in the cell in the footer. This is done
* when a horizontal scrollbar is present.
*
* @param scrollLeft
* The value of the leftScroll
*/
public void setHorizontalScrollPosition(int scrollLeft) {
if (BrowserInfo.get().isIE6()) {
hTableWrapper.getStyle().setProperty("position", "relative");
hTableWrapper.getStyle().setPropertyPx("left", -scrollLeft);
} else {
hTableWrapper.setScrollLeft(scrollLeft);
}
}
/**
* Swap cells when the column are dragged
*
* @param oldIndex
* The old index of the cell
* @param newIndex
* The new index of the cell
*/
public void moveCell(int oldIndex, int newIndex) {
final FooterCell hCell = getFooterCell(oldIndex);
final Element cell = hCell.getElement();
visibleCells.remove(oldIndex);
DOM.removeChild(tr, cell);
DOM.insertChild(tr, cell, newIndex);
visibleCells.add(newIndex, hCell);
}
}
/**
* This Panel can only contain VScrollTableRow type of widgets. This
* "simulates" very large table, keeping spacers which take room of
* unrendered rows.
*
*/
public class VScrollTableBody extends Panel {
public static final int DEFAULT_ROW_HEIGHT = 24;
private double rowHeight = -1;
private final LinkedList<Widget> renderedRows = new LinkedList<Widget>();
/**
* Due some optimizations row height measuring is deferred and initial
* set of rows is rendered detached. Flag set on when table body has
* been attached in dom and rowheight has been measured.
*/
private boolean tBodyMeasurementsDone = false;
Element preSpacer = DOM.createDiv();
Element postSpacer = DOM.createDiv();
Element container = DOM.createDiv();
TableSectionElement tBodyElement = Document.get().createTBodyElement();
Element table = DOM.createTable();
private int firstRendered;
private int lastRendered;
private char[] aligns;
protected VScrollTableBody() {
constructDOM();
setElement(container);
}
public VScrollTableRow getRowByRowIndex(int indexInTable) {
int internalIndex = indexInTable - firstRendered;
if (internalIndex >= 0 && internalIndex < renderedRows.size()) {
return (VScrollTableRow) renderedRows.get(internalIndex);
} else {
return null;
}
}
/**
* @return the height of scrollable body, subpixels ceiled.
*/
public int getRequiredHeight() {
return preSpacer.getOffsetHeight() + postSpacer.getOffsetHeight()
+ Util.getRequiredHeight(table);
}
private void constructDOM() {
DOM.setElementProperty(table, "className", CLASSNAME + "-table");
if (BrowserInfo.get().isIE()) {
table.setPropertyInt("cellSpacing", 0);
}
DOM.setElementProperty(preSpacer, "className", CLASSNAME
+ "-row-spacer");
DOM.setElementProperty(postSpacer, "className", CLASSNAME
+ "-row-spacer");
table.appendChild(tBodyElement);
DOM.appendChild(container, preSpacer);
DOM.appendChild(container, table);
DOM.appendChild(container, postSpacer);
if (BrowserInfo.get().isTouchDevice()) {
NodeList<Node> childNodes = container.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Element item = (Element) childNodes.getItem(i);
item.getStyle().setProperty("webkitTransform",
"translate3d(0,0,0)");
}
}
}
public int getAvailableWidth() {
int availW = scrollBodyPanel.getOffsetWidth() - getBorderWidth();
return availW;
}
public void renderInitialRows(UIDL rowData, int firstIndex, int rows) {
firstRendered = firstIndex;
lastRendered = firstIndex + rows - 1;
final Iterator<?> it = rowData.getChildIterator();
aligns = tHead.getColumnAlignments();
while (it.hasNext()) {
final VScrollTableRow row = createRow((UIDL) it.next(), aligns);
addRow(row);
}
if (isAttached()) {
fixSpacers();
}
}
public void renderRows(UIDL rowData, int firstIndex, int rows) {
// FIXME REVIEW
aligns = tHead.getColumnAlignments();
final Iterator<?> it = rowData.getChildIterator();
if (firstIndex == lastRendered + 1) {
while (it.hasNext()) {
final VScrollTableRow row = prepareRow((UIDL) it.next());
addRow(row);
lastRendered++;
}
fixSpacers();
} else if (firstIndex + rows == firstRendered) {
final VScrollTableRow[] rowArray = new VScrollTableRow[rows];
int i = rows;
while (it.hasNext()) {
i--;
rowArray[i] = prepareRow((UIDL) it.next());
}
for (i = 0; i < rows; i++) {
addRowBeforeFirstRendered(rowArray[i]);
firstRendered--;
}
} else {
// completely new set of rows
while (lastRendered + 1 > firstRendered) {
unlinkRow(false);
}
final VScrollTableRow row = prepareRow((UIDL) it.next());
firstRendered = firstIndex;
lastRendered = firstIndex - 1;
addRow(row);
lastRendered++;
setContainerHeight();
fixSpacers();
while (it.hasNext()) {
addRow(prepareRow((UIDL) it.next()));
lastRendered++;
}
fixSpacers();
}
// this may be a new set of rows due content change,
// ensure we have proper cache rows
ensureCacheFilled();
}
/**
* Ensure we have the correct set of rows on client side, e.g. if the
* content on the server side has changed, or the client scroll position
* has changed since the last request.
*/
protected void ensureCacheFilled() {
int reactFirstRow = (int) (firstRowInViewPort - pageLength
* cache_react_rate);
int reactLastRow = (int) (firstRowInViewPort + pageLength + pageLength
* cache_react_rate);
if (reactFirstRow < 0) {
reactFirstRow = 0;
}
if (reactLastRow >= totalRows) {
reactLastRow = totalRows - 1;
}
if (lastRendered < reactFirstRow || firstRendered > reactLastRow) {
/*
* #8040 - scroll position is completely changed since the
* latest request, so request a new set of rows.
*
* TODO: We should probably check whether the fetched rows match
* the current scroll position right when they arrive, so as to
* not waste time rendering a set of rows that will never be
* visible...
*/
rowRequestHandler.setReqFirstRow(reactFirstRow);
rowRequestHandler.setReqRows(reactLastRow - reactFirstRow + 1);
rowRequestHandler.deferRowFetch(1);
} else if (lastRendered < reactLastRow) {
// get some cache rows below visible area
rowRequestHandler.setReqFirstRow(lastRendered + 1);
rowRequestHandler.setReqRows(reactLastRow - lastRendered);
rowRequestHandler.deferRowFetch(1);
} else if (firstRendered > reactFirstRow) {
/*
* Branch for fetching cache above visible area.
*
* If cache needed for both before and after visible area, this
* will be rendered after-cache is received and rendered. So in
* some rare situations the table may make two cache visits to
* server.
*/
rowRequestHandler.setReqFirstRow(reactFirstRow);
rowRequestHandler.setReqRows(firstRendered - reactFirstRow);
rowRequestHandler.deferRowFetch(1);
}
}
/**
* Inserts rows as provided in the rowData starting at firstIndex.
*
* @param rowData
* @param firstIndex
* @param rows
* the number of rows
* @return a list of the rows added.
*/
protected List<VScrollTableRow> insertRows(UIDL rowData,
int firstIndex, int rows) {
aligns = tHead.getColumnAlignments();
final Iterator<?> it = rowData.getChildIterator();
List<VScrollTableRow> insertedRows = new ArrayList<VScrollTableRow>();
if (firstIndex == lastRendered + 1) {
while (it.hasNext()) {
final VScrollTableRow row = prepareRow((UIDL) it.next());
addRow(row);
insertedRows.add(row);
lastRendered++;
}
fixSpacers();
} else if (firstIndex + rows == firstRendered) {
final VScrollTableRow[] rowArray = new VScrollTableRow[rows];
int i = rows;
while (it.hasNext()) {
i--;
rowArray[i] = prepareRow((UIDL) it.next());
}
for (i = 0; i < rows; i++) {
addRowBeforeFirstRendered(rowArray[i]);
insertedRows.add(rowArray[i]);
firstRendered--;
}
} else {
// insert in the middle
int ix = firstIndex;
while (it.hasNext()) {
VScrollTableRow row = prepareRow((UIDL) it.next());
insertRowAt(row, ix);
insertedRows.add(row);
lastRendered++;
ix++;
}
fixSpacers();
}
return insertedRows;
}
protected List<VScrollTableRow> insertAndReindexRows(UIDL rowData,
int firstIndex, int rows) {
List<VScrollTableRow> inserted = insertRows(rowData, firstIndex,
rows);
int actualIxOfFirstRowAfterInserted = firstIndex + rows
- firstRendered;
for (int ix = actualIxOfFirstRowAfterInserted; ix < renderedRows
.size(); ix++) {
VScrollTableRow r = (VScrollTableRow) renderedRows.get(ix);
r.setIndex(r.getIndex() + rows);
}
setContainerHeight();
return inserted;
}
protected void insertRowsDeleteBelow(UIDL rowData, int firstIndex,
int rows) {
unlinkAllRowsStartingAt(firstIndex);
insertRows(rowData, firstIndex, rows);
setContainerHeight();
}
/**
* This method is used to instantiate new rows for this table. It
* automatically sets correct widths to rows cells and assigns correct
* client reference for child widgets.
*
* This method can be called only after table has been initialized
*
* @param uidl
*/
private VScrollTableRow prepareRow(UIDL uidl) {
final VScrollTableRow row = createRow(uidl, aligns);
row.initCellWidths();
return row;
}
protected VScrollTableRow createRow(UIDL uidl, char[] aligns2) {
if (uidl.hasAttribute("gen_html")) {
// This is a generated row.
return new VScrollTableGeneratedRow(uidl, aligns2);
}
return new VScrollTableRow(uidl, aligns2);
}
private void addRowBeforeFirstRendered(VScrollTableRow row) {
row.setIndex(firstRendered - 1);
if (row.isSelected()) {
row.addStyleName("v-selected");
}
tBodyElement.insertBefore(row.getElement(),
tBodyElement.getFirstChild());
adopt(row);
renderedRows.add(0, row);
}
private void addRow(VScrollTableRow row) {
row.setIndex(firstRendered + renderedRows.size());
if (row.isSelected()) {
row.addStyleName("v-selected");
}
tBodyElement.appendChild(row.getElement());
adopt(row);
renderedRows.add(row);
}
private void insertRowAt(VScrollTableRow row, int index) {
row.setIndex(index);
if (row.isSelected()) {
row.addStyleName("v-selected");
}
if (index > 0) {
VScrollTableRow sibling = getRowByRowIndex(index - 1);
tBodyElement
.insertAfter(row.getElement(), sibling.getElement());
} else {
VScrollTableRow sibling = getRowByRowIndex(index);
tBodyElement.insertBefore(row.getElement(),
sibling.getElement());
}
adopt(row);
int actualIx = index - firstRendered;
renderedRows.add(actualIx, row);
}
public Iterator<Widget> iterator() {
return renderedRows.iterator();
}
/**
* @return false if couldn't remove row
*/
protected boolean unlinkRow(boolean fromBeginning) {
if (lastRendered - firstRendered < 0) {
return false;
}
int actualIx;
if (fromBeginning) {
actualIx = 0;
firstRendered++;
} else {
actualIx = renderedRows.size() - 1;
lastRendered--;
}
if (actualIx >= 0) {
unlinkRowAtActualIndex(actualIx);
fixSpacers();
return true;
}
return false;
}
protected void unlinkRows(int firstIndex, int count) {
if (count < 1) {
return;
}
if (firstRendered > firstIndex
&& firstRendered < firstIndex + count) {
firstIndex = firstRendered;
}
int lastIndex = firstIndex + count - 1;
if (lastRendered < lastIndex) {
lastIndex = lastRendered;
}
for (int ix = lastIndex; ix >= firstIndex; ix--) {
unlinkRowAtActualIndex(actualIndex(ix));
lastRendered--;
}
fixSpacers();
}
protected void unlinkAndReindexRows(int firstIndex, int count) {
unlinkRows(firstIndex, count);
int actualFirstIx = firstIndex - firstRendered;
for (int ix = actualFirstIx; ix < renderedRows.size(); ix++) {
VScrollTableRow r = (VScrollTableRow) renderedRows.get(ix);
r.setIndex(r.getIndex() - count);
}
setContainerHeight();
}
protected void unlinkAllRowsStartingAt(int index) {
if (firstRendered > index) {
index = firstRendered;
}
for (int ix = renderedRows.size() - 1; ix >= index; ix--) {
unlinkRowAtActualIndex(actualIndex(ix));
lastRendered--;
}
fixSpacers();
}
private int actualIndex(int index) {
return index - firstRendered;
}
private void unlinkRowAtActualIndex(int index) {
final VScrollTableRow toBeRemoved = (VScrollTableRow) renderedRows
.get(index);
// Unregister row tooltip
client.registerTooltip(VScrollTable.this, toBeRemoved.getElement(),
null);
for (int i = 0; i < toBeRemoved.getElement().getChildCount(); i++) {
// Unregister cell tooltips
Element td = toBeRemoved.getElement().getChild(i).cast();
client.registerTooltip(VScrollTable.this, td, null);
}
lazyUnregistryBag.add(toBeRemoved);
tBodyElement.removeChild(toBeRemoved.getElement());
orphan(toBeRemoved);
renderedRows.remove(index);
}
@Override
public boolean remove(Widget w) {
throw new UnsupportedOperationException();
}
@Override
protected void onAttach() {
super.onAttach();
setContainerHeight();
}
/**
* Fix container blocks height according to totalRows to avoid
* "bouncing" when scrolling
*/
private void setContainerHeight() {
fixSpacers();
DOM.setStyleAttribute(container, "height",
measureRowHeightOffset(totalRows) + "px");
}
private void fixSpacers() {
int prepx = measureRowHeightOffset(firstRendered);
if (prepx < 0) {
prepx = 0;
}
preSpacer.getStyle().setPropertyPx("height", prepx);
int postpx = measureRowHeightOffset(totalRows - 1)
- measureRowHeightOffset(lastRendered);
if (postpx < 0) {
postpx = 0;
}
postSpacer.getStyle().setPropertyPx("height", postpx);
}
public double getRowHeight() {
return getRowHeight(false);
}
public double getRowHeight(boolean forceUpdate) {
if (tBodyMeasurementsDone && !forceUpdate) {
return rowHeight;
} else {
if (tBodyElement.getRows().getLength() > 0) {
int tableHeight = getTableHeight();
int rowCount = tBodyElement.getRows().getLength();
rowHeight = tableHeight / (double) rowCount;
} else {
if (isAttached()) {
// measure row height by adding a dummy row
VScrollTableRow scrollTableRow = new VScrollTableRow();
tBodyElement.appendChild(scrollTableRow.getElement());
getRowHeight(forceUpdate);
tBodyElement.removeChild(scrollTableRow.getElement());
} else {
// TODO investigate if this can never happen anymore
return DEFAULT_ROW_HEIGHT;
}
}
tBodyMeasurementsDone = true;
return rowHeight;
}
}
public int getTableHeight() {
return table.getOffsetHeight();
}
/**
* Returns the width available for column content.
*
* @param columnIndex
* @return
*/
public int getColWidth(int columnIndex) {
if (tBodyMeasurementsDone) {
if (renderedRows.isEmpty()) {
// no rows yet rendered
return 0;
}
for (Widget row : renderedRows) {
if (!(row instanceof VScrollTableGeneratedRow)) {
TableRowElement tr = row.getElement().cast();
Element wrapperdiv = tr.getCells().getItem(columnIndex)
.getFirstChildElement().cast();
return wrapperdiv.getOffsetWidth();
}
}
return 0;
} else {
return 0;
}
}
/**
* Sets the content width of a column.
*
* Due IE limitation, we must set the width to a wrapper elements inside
* table cells (with overflow hidden, which does not work on td
* elements).
*
* To get this work properly crossplatform, we will also set the width
* of td.
*
* @param colIndex
* @param w
*/
public void setColWidth(int colIndex, int w) {
for (Widget row : renderedRows) {
((VScrollTableRow) row).setCellWidth(colIndex, w);
}
}
private int cellExtraWidth = -1;
/**
* Method to return the space used for cell paddings + border.
*/
private int getCellExtraWidth() {
if (cellExtraWidth < 0) {
detectExtrawidth();
}
return cellExtraWidth;
}
private void detectExtrawidth() {
NodeList<TableRowElement> rows = tBodyElement.getRows();
if (rows.getLength() == 0) {
/* need to temporary add empty row and detect */
VScrollTableRow scrollTableRow = new VScrollTableRow();
tBodyElement.appendChild(scrollTableRow.getElement());
detectExtrawidth();
tBodyElement.removeChild(scrollTableRow.getElement());
} else {
boolean noCells = false;
TableRowElement item = rows.getItem(0);
TableCellElement firstTD = item.getCells().getItem(0);
if (firstTD == null) {
// content is currently empty, we need to add a fake cell
// for measuring
noCells = true;
VScrollTableRow next = (VScrollTableRow) iterator().next();
boolean sorted = tHead.getHeaderCell(0) != null ? tHead
.getHeaderCell(0).isSorted() : false;
next.addCell(null, "", ALIGN_LEFT, "", true, sorted);
firstTD = item.getCells().getItem(0);
}
com.google.gwt.dom.client.Element wrapper = firstTD
.getFirstChildElement();
cellExtraWidth = firstTD.getOffsetWidth()
- wrapper.getOffsetWidth();
if (noCells) {
firstTD.getParentElement().removeChild(firstTD);
}
}
}
private void reLayoutComponents() {
for (Widget w : this) {
VScrollTableRow r = (VScrollTableRow) w;
for (Widget widget : r) {
client.handleComponentRelativeSize(widget);
}
}
}
public int getLastRendered() {
return lastRendered;
}
public int getFirstRendered() {
return firstRendered;
}
public void moveCol(int oldIndex, int newIndex) {
// loop all rows and move given index to its new place
final Iterator<?> rows = iterator();
while (rows.hasNext()) {
final VScrollTableRow row = (VScrollTableRow) rows.next();
final Element td = DOM.getChild(row.getElement(), oldIndex);
if (td != null) {
DOM.removeChild(row.getElement(), td);
DOM.insertChild(row.getElement(), td, newIndex);
}
}
}
/**
* Restore row visibility which is set to "none" when the row is
* rendered (due a performance optimization).
*/
private void restoreRowVisibility() {
for (Widget row : renderedRows) {
row.getElement().getStyle().setProperty("visibility", "");
}
}
public class VScrollTableRow extends Panel implements ActionOwner,
Container {
private static final int TOUCHSCROLL_TIMEOUT = 100;
private static final int DRAGMODE_MULTIROW = 2;
protected ArrayList<Widget> childWidgets = new ArrayList<Widget>();
private boolean selected = false;
protected final int rowKey;
private List<UIDL> pendingComponentPaints;
private String[] actionKeys = null;
private final TableRowElement rowElement;
private boolean mDown;
private int index;
private Event touchStart;
private static final String ROW_CLASSNAME_EVEN = CLASSNAME + "-row";
private static final String ROW_CLASSNAME_ODD = CLASSNAME
+ "-row-odd";
private static final int TOUCH_CONTEXT_MENU_TIMEOUT = 500;
private Timer contextTouchTimeout;
private int touchStartY;
private int touchStartX;
private VScrollTableRow(int rowKey) {
this.rowKey = rowKey;
rowElement = Document.get().createTRElement();
setElement(rowElement);
DOM.sinkEvents(getElement(), Event.MOUSEEVENTS
| Event.TOUCHEVENTS | Event.ONDBLCLICK
| Event.ONCONTEXTMENU | VTooltip.TOOLTIP_EVENTS);
}
public VScrollTableRow(UIDL uidl, char[] aligns) {
this(uidl.getIntAttribute("key"));
/*
* Rendering the rows as hidden improves Firefox and Safari
* performance drastically.
*/
getElement().getStyle().setProperty("visibility", "hidden");
String rowStyle = uidl.getStringAttribute("rowstyle");
if (rowStyle != null) {
addStyleName(CLASSNAME + "-row-" + rowStyle);
}
String rowDescription = uidl.getStringAttribute("rowdescr");
if (rowDescription != null && !rowDescription.equals("")) {
TooltipInfo info = new TooltipInfo(rowDescription);
client.registerTooltip(VScrollTable.this, rowElement, info);
} else {
// Remove possibly previously set tooltip
client.registerTooltip(VScrollTable.this, rowElement, null);
}
tHead.getColumnAlignments();
int col = 0;
int visibleColumnIndex = -1;
// row header
if (showRowHeaders) {
boolean sorted = tHead.getHeaderCell(col).isSorted();
addCell(uidl, buildCaptionHtmlSnippet(uidl), aligns[col++],
"rowheader", true, sorted);
visibleColumnIndex++;
}
if (uidl.hasAttribute("al")) {
actionKeys = uidl.getStringArrayAttribute("al");
}
addCellsFromUIDL(uidl, aligns, col, visibleColumnIndex);
if (uidl.hasAttribute("selected") && !isSelected()) {
toggleSelection();
}
}
/**
* Add a dummy row, used for measurements if Table is empty.
*/
public VScrollTableRow() {
this(0);
addStyleName(CLASSNAME + "-row");
addCell(null, "_", 'b', "", true, false);
}
protected void initCellWidths() {
final int cells = tHead.getVisibleCellCount();
for (int i = 0; i < cells; i++) {
int w = VScrollTable.this.getColWidth(getColKeyByIndex(i));
if (w < 0) {
w = 0;
}
setCellWidth(i, w);
}
}
protected void setCellWidth(int cellIx, int width) {
final Element cell = DOM.getChild(getElement(), cellIx);
cell.getFirstChildElement().getStyle()
.setPropertyPx("width", width);
cell.getStyle().setPropertyPx("width", width);
}
protected void addCellsFromUIDL(UIDL uidl, char[] aligns, int col,
int visibleColumnIndex) {
final Iterator<?> cells = uidl.getChildIterator();
while (cells.hasNext()) {
final Object cell = cells.next();
visibleColumnIndex++;
String columnId = visibleColOrder[visibleColumnIndex];
String style = "";
if (uidl.hasAttribute("style-" + columnId)) {
style = uidl.getStringAttribute("style-" + columnId);
}
String description = null;
if (uidl.hasAttribute("descr-" + columnId)) {
description = uidl.getStringAttribute("descr-"
+ columnId);
}
boolean sorted = tHead.getHeaderCell(col).isSorted();
if (cell instanceof String) {
addCell(uidl, cell.toString(), aligns[col++], style,
isRenderHtmlInCells(), sorted, description);
} else {
final Paintable cellContent = client
.getPaintable((UIDL) cell);
addCell(uidl, (Widget) cellContent, aligns[col++],
style, sorted);
paintComponent(cellContent, (UIDL) cell);
}
}
}
/**
* Overriding this and returning true causes all text cells to be
* rendered as HTML.
*
* @return always returns false in the default implementation
*/
protected boolean isRenderHtmlInCells() {
return false;
}
/**
* Detects whether row is visible in tables viewport.
*
* @return
*/
public boolean isInViewPort() {
int absoluteTop = getAbsoluteTop();
int scrollPosition = scrollBodyPanel.getScrollPosition();
if (absoluteTop < scrollPosition) {
return false;
}
int maxVisible = scrollPosition
+ scrollBodyPanel.getOffsetHeight() - getOffsetHeight();
if (absoluteTop > maxVisible) {
return false;
}
return true;
}
/**
* Makes a check based on indexes whether the row is before the
* compared row.
*
* @param row1
* @return true if this rows index is smaller than in the row1
*/
public boolean isBefore(VScrollTableRow row1) {
return getIndex() < row1.getIndex();
}
/**
* Sets the index of the row in the whole table. Currently used just
* to set even/odd classname
*
* @param indexInWholeTable
*/
private void setIndex(int indexInWholeTable) {
index = indexInWholeTable;
boolean isOdd = indexInWholeTable % 2 == 0;
// Inverted logic to be backwards compatible with earlier 6.4.
// It is very strange because rows 1,3,5 are considered "even"
// and 2,4,6 "odd".
//
// First remove any old styles so that both styles aren't
// applied when indexes are updated.
removeStyleName(ROW_CLASSNAME_ODD);
removeStyleName(ROW_CLASSNAME_EVEN);
if (!isOdd) {
addStyleName(ROW_CLASSNAME_ODD);
} else {
addStyleName(ROW_CLASSNAME_EVEN);
}
}
public int getIndex() {
return index;
}
protected void paintComponent(Paintable p, UIDL uidl) {
if (isAttached()) {
p.updateFromUIDL(uidl, client);
} else {
if (pendingComponentPaints == null) {
pendingComponentPaints = new LinkedList<UIDL>();
}
pendingComponentPaints.add(uidl);
}
}
@Override
protected void onAttach() {
super.onAttach();
if (pendingComponentPaints != null) {
for (UIDL uidl : pendingComponentPaints) {
Paintable paintable = client.getPaintable(uidl);
paintable.updateFromUIDL(uidl, client);
}
pendingComponentPaints.clear();
}
}
@Override
protected void onDetach() {
super.onDetach();
client.getContextMenu().ensureHidden(this);
}
public String getKey() {
return String.valueOf(rowKey);
}
public void addCell(UIDL rowUidl, String text, char align,
String style, boolean textIsHTML, boolean sorted) {
addCell(rowUidl, text, align, style, textIsHTML, sorted, null);
}
public void addCell(UIDL rowUidl, String text, char align,
String style, boolean textIsHTML, boolean sorted,
String description) {
// String only content is optimized by not using Label widget
final TableCellElement td = DOM.createTD().cast();
initCellWithText(text, align, style, textIsHTML, sorted,
description, td);
}
protected void initCellWithText(String text, char align,
String style, boolean textIsHTML, boolean sorted,
String description, final TableCellElement td) {
final Element container = DOM.createDiv();
String className = CLASSNAME + "-cell-content";
if (style != null && !style.equals("")) {
className += " " + CLASSNAME + "-cell-content-" + style;
}
if (sorted) {
className += " " + CLASSNAME + "-cell-content-sorted";
}
td.setClassName(className);
container.setClassName(CLASSNAME + "-cell-wrapper");
if (textIsHTML) {
container.setInnerHTML(text);
} else {
container.setInnerText(text);
}
if (align != ALIGN_LEFT) {
switch (align) {
case ALIGN_CENTER:
container.getStyle().setProperty("textAlign", "center");
break;
case ALIGN_RIGHT:
default:
container.getStyle().setProperty("textAlign", "right");
break;
}
}
if (description != null && !description.equals("")) {
TooltipInfo info = new TooltipInfo(description);
client.registerTooltip(VScrollTable.this, td, info);
} else {
// Remove possibly previously set tooltip
client.registerTooltip(VScrollTable.this, td, null);
}
td.appendChild(container);
getElement().appendChild(td);
}
public void addCell(UIDL rowUidl, Widget w, char align,
String style, boolean sorted) {
final TableCellElement td = DOM.createTD().cast();
initCellWithWidget(w, align, style, sorted, td);
}
protected void initCellWithWidget(Widget w, char align,
String style, boolean sorted, final TableCellElement td) {
final Element container = DOM.createDiv();
String className = CLASSNAME + "-cell-content";
if (style != null && !style.equals("")) {
className += " " + CLASSNAME + "-cell-content-" + style;
}
if (sorted) {
className += " " + CLASSNAME + "-cell-content-sorted";
}
td.setClassName(className);
container.setClassName(CLASSNAME + "-cell-wrapper");
// TODO most components work with this, but not all (e.g.
// Select)
// Old comment: make widget cells respect align.
// text-align:center for IE, margin: auto for others
if (align != ALIGN_LEFT) {
switch (align) {
case ALIGN_CENTER:
container.getStyle().setProperty("textAlign", "center");
break;
case ALIGN_RIGHT:
default:
container.getStyle().setProperty("textAlign", "right");
break;
}
}
td.appendChild(container);
getElement().appendChild(td);
// ensure widget not attached to another element (possible tBody
// change)
w.removeFromParent();
container.appendChild(w.getElement());
adopt(w);
childWidgets.add(w);
}
public Iterator<Widget> iterator() {
return childWidgets.iterator();
}
@Override
public boolean remove(Widget w) {
if (childWidgets.contains(w)) {
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()),
w.getElement());
childWidgets.remove(w);
return true;
} else {
return false;
}
}
/**
* If there are registered click listeners, sends a click event and
* returns true. Otherwise, does nothing and returns false.
*
* @param event
* @param targetTdOrTr
* @param immediate
* Whether the event is sent immediately
* @return Whether a click event was sent
*/
private boolean handleClickEvent(Event event, Element targetTdOrTr,
boolean immediate) {
if (!client.hasEventListeners(VScrollTable.this,
ITEM_CLICK_EVENT_ID)) {
// Don't send an event if nobody is listening
return false;
}
// This row was clicked
client.updateVariable(paintableId, "clickedKey", "" + rowKey,
false);
if (getElement() == targetTdOrTr.getParentElement()) {
// A specific column was clicked
int childIndex = DOM.getChildIndex(getElement(),
targetTdOrTr);
String colKey = null;
colKey = tHead.getHeaderCell(childIndex).getColKey();
client.updateVariable(paintableId, "clickedColKey", colKey,
false);
}
MouseEventDetails details = new MouseEventDetails(event);
client.updateVariable(paintableId, "clickEvent",
details.toString(), immediate);
return true;
}
private void handleTooltips(final Event event, Element target) {
if (target.hasTagName("TD")) {
// Table cell (td)
Element container = target.getFirstChildElement().cast();
Element widget = container.getFirstChildElement().cast();
boolean containsWidget = false;
for (Widget w : childWidgets) {
if (widget == w.getElement()) {
containsWidget = true;
break;
}
}
if (!containsWidget) {
// Only text nodes has tooltips
if (client.getTooltipTitleInfo(VScrollTable.this,
target) != null) {
// Cell has description, use it
client.handleTooltipEvent(event, VScrollTable.this,
target);
} else {
// Cell might have row description, use row
// description
client.handleTooltipEvent(event, VScrollTable.this,
target.getParentElement());
}
}
} else {
// Table row (tr)
client.handleTooltipEvent(event, VScrollTable.this, target);
}
}
/*
* React on click that occur on content cells only
*/
@Override
public void onBrowserEvent(final Event event) {
if (enabled) {
final int type = event.getTypeInt();
final Element targetTdOrTr = getEventTargetTdOrTr(event);
if (type == Event.ONCONTEXTMENU) {
showContextMenu(event);
if (enabled
&& (actionKeys != null || client
.hasEventListeners(VScrollTable.this,
ITEM_CLICK_EVENT_ID))) {
/*
* Prevent browser context menu only if there are
* action handlers or item click listeners
* registered
*/
event.stopPropagation();
event.preventDefault();
}
return;
}
boolean targetCellOrRowFound = targetTdOrTr != null;
if (targetCellOrRowFound) {
handleTooltips(event, targetTdOrTr);
}
switch (type) {
case Event.ONDBLCLICK:
if (targetCellOrRowFound) {
handleClickEvent(event, targetTdOrTr, true);
}
break;
case Event.ONMOUSEUP:
if (targetCellOrRowFound) {
mDown = false;
/*
* Queue here, send at the same time as the
* corresponding value change event - see #7127
*/
boolean clickEventSent = handleClickEvent(event,
targetTdOrTr, false);
if (event.getButton() == Event.BUTTON_LEFT
&& isSelectable()) {
// Ctrl+Shift click
if ((event.getCtrlKey() || event.getMetaKey())
&& event.getShiftKey()
&& isMultiSelectModeDefault()) {
toggleShiftSelection(false);
setRowFocus(this);
// Ctrl click
} else if ((event.getCtrlKey() || event
.getMetaKey())
&& isMultiSelectModeDefault()) {
boolean wasSelected = isSelected();
toggleSelection();
setRowFocus(this);
/*
* next possible range select must start on
* this row
*/
selectionRangeStart = this;
if (wasSelected) {
removeRowFromUnsentSelectionRanges(this);
}
} else if ((event.getCtrlKey() || event
.getMetaKey()) && isSingleSelectMode()) {
// Ctrl (or meta) click (Single selection)
if (!isSelected()
|| (isSelected() && nullSelectionAllowed)) {
if (!isSelected()) {
deselectAll();
}
toggleSelection();
setRowFocus(this);
}
} else if (event.getShiftKey()
&& isMultiSelectModeDefault()) {
// Shift click
toggleShiftSelection(true);
} else {
// click
boolean currentlyJustThisRowSelected = selectedRowKeys
.size() == 1
&& selectedRowKeys
.contains(getKey());
if (!currentlyJustThisRowSelected) {
if (isSingleSelectMode()
|| isMultiSelectModeDefault()) {
/*
* For default multi select mode
* (ctrl/shift) and for single
* select mode we need to clear the
* previous selection before
* selecting a new one when the user
* clicks on a row. Only in
* multiselect/simple mode the old
* selection should remain after a
* normal click.
*/
deselectAll();
}
toggleSelection();
} else if ((isSingleSelectMode() || isMultiSelectModeSimple())
&& nullSelectionAllowed) {
toggleSelection();
}/*
* else NOP to avoid excessive server
* visits (selection is removed with
* CTRL/META click)
*/
selectionRangeStart = this;
setRowFocus(this);
}
// Remove IE text selection hack
if (BrowserInfo.get().isIE()) {
((Element) event.getEventTarget().cast())
.setPropertyJSO("onselectstart",
null);
}
// Queue value change
sendSelectedRows(false);
}
/*
* Send queued click and value change events if any
* If a click event is sent, send value change with
* it regardless of the immediate flag, see #7127
*/
if (immediate || clickEventSent) {
client.sendPendingVariableChanges();
}
}
break;
case Event.ONTOUCHEND:
case Event.ONTOUCHCANCEL:
if (touchStart != null) {
/*
* Touch has not been handled as neither context or
* drag start, handle it as a click.
*/
Util.simulateClickFromTouchEvent(touchStart, this);
touchStart = null;
}
if (contextTouchTimeout != null) {
contextTouchTimeout.cancel();
}
break;
case Event.ONTOUCHMOVE:
if (isSignificantMove(event)) {
/*
* TODO figure out scroll delegate don't eat events
* if row is selected. Null check for active
* delegate is as a workaround.
*/
if (dragmode != 0
&& touchStart != null
&& (TouchScrollDelegate
.getActiveScrollDelegate() == null)) {
startRowDrag(touchStart, type, targetTdOrTr);
}
if (contextTouchTimeout != null) {
contextTouchTimeout.cancel();
}
/*
* Avoid clicks and drags by clearing touch start
* flag.
*/
touchStart = null;
}
break;
case Event.ONTOUCHSTART:
touchStart = event;
Touch touch = event.getChangedTouches().get(0);
// save position to fields, touches in events are same
// isntance during the operation.
touchStartX = touch.getClientX();
touchStartY = touch.getClientY();
/*
* Prevent simulated mouse events.
*/
touchStart.preventDefault();
if (dragmode != 0 || actionKeys != null) {
new Timer() {
@Override
public void run() {
TouchScrollDelegate activeScrollDelegate = TouchScrollDelegate
.getActiveScrollDelegate();
/*
* If there's a scroll delegate, check if
* we're actually scrolling and handle it.
* If no delegate, do nothing here and let
* the row handle potential drag'n'drop or
* context menu.
*/
if (activeScrollDelegate != null) {
if (activeScrollDelegate.isMoved()) {
/*
* Prevent the row from handling
* touch move/end events (the
* delegate handles those) and from
* doing drag'n'drop or opening a
* context menu.
*/
touchStart = null;
} else {
/*
* Scrolling hasn't started, so
* cancel delegate and let the row
* handle potential drag'n'drop or
* context menu.
*/
activeScrollDelegate
.stopScrolling();
}
}
}
}.schedule(TOUCHSCROLL_TIMEOUT);
if (contextTouchTimeout == null
&& actionKeys != null) {
contextTouchTimeout = new Timer() {
@Override
public void run() {
if (touchStart != null) {
showContextMenu(touchStart);
touchStart = null;
}
}
};
}
if (contextTouchTimeout != null) {
contextTouchTimeout.cancel();
contextTouchTimeout
.schedule(TOUCH_CONTEXT_MENU_TIMEOUT);
}
}
break;
case Event.ONMOUSEDOWN:
if (targetCellOrRowFound) {
setRowFocus(this);
ensureFocus();
if (dragmode != 0
&& (event.getButton() == NativeEvent.BUTTON_LEFT)) {
startRowDrag(event, type, targetTdOrTr);
} else if (event.getCtrlKey()
|| event.getShiftKey()
|| event.getMetaKey()
&& isMultiSelectModeDefault()) {
// Prevent default text selection in Firefox
event.preventDefault();
// Prevent default text selection in IE
if (BrowserInfo.get().isIE()) {
((Element) event.getEventTarget().cast())
.setPropertyJSO(
"onselectstart",
getPreventTextSelectionIEHack());
}
event.stopPropagation();
}
}
break;
case Event.ONMOUSEOUT:
if (targetCellOrRowFound) {
mDown = false;
}
break;
default:
break;
}
}
super.onBrowserEvent(event);
}
private boolean isSignificantMove(Event event) {
if (touchStart == null) {
// no touch start
return false;
}
/*
* TODO calculate based on real distance instead of separate
* axis checks
*/
Touch touch = event.getChangedTouches().get(0);
if (Math.abs(touch.getClientX() - touchStartX) > TouchScrollDelegate.SIGNIFICANT_MOVE_THRESHOLD) {
return true;
}
if (Math.abs(touch.getClientY() - touchStartY) > TouchScrollDelegate.SIGNIFICANT_MOVE_THRESHOLD) {
return true;
}
return false;
}
protected void startRowDrag(Event event, final int type,
Element targetTdOrTr) {
mDown = true;
VTransferable transferable = new VTransferable();
transferable.setDragSource(VScrollTable.this);
transferable.setData("itemId", "" + rowKey);
NodeList<TableCellElement> cells = rowElement.getCells();
for (int i = 0; i < cells.getLength(); i++) {
if (cells.getItem(i).isOrHasChild(targetTdOrTr)) {
HeaderCell headerCell = tHead.getHeaderCell(i);
transferable.setData("propertyId", headerCell.cid);
break;
}
}
VDragEvent ev = VDragAndDropManager.get().startDrag(
transferable, event, true);
if (dragmode == DRAGMODE_MULTIROW && isMultiSelectModeAny()
&& selectedRowKeys.contains("" + rowKey)) {
ev.createDragImage(
(Element) scrollBody.tBodyElement.cast(), true);
Element dragImage = ev.getDragImage();
int i = 0;
for (Iterator<Widget> iterator = scrollBody.iterator(); iterator
.hasNext();) {
VScrollTableRow next = (VScrollTableRow) iterator
.next();
Element child = (Element) dragImage.getChild(i++);
if (!selectedRowKeys.contains("" + next.rowKey)) {
child.getStyle().setVisibility(Visibility.HIDDEN);
}
}
} else {
ev.createDragImage(getElement(), true);
}
if (type == Event.ONMOUSEDOWN) {
event.preventDefault();
}
event.stopPropagation();
}
/**
* Finds the TD that the event interacts with. Returns null if the
* target of the event should not be handled. If the event target is
* the row directly this method returns the TR element instead of
* the TD.
*
* @param event
* @return TD or TR element that the event targets (the actual event
* target is this element or a child of it)
*/
private Element getEventTargetTdOrTr(Event event) {
final Element eventTarget = event.getEventTarget().cast();
Widget widget = Util.findWidget(eventTarget, null);
final Element thisTrElement = getElement();
if (widget != this) {
/*
* This is a workaround to make Labels, read only TextFields
* and Embedded in a Table clickable (see #2688). It is
* really not a fix as it does not work with a custom read
* only components (not extending VLabel/VEmbedded).
*/
while (widget != null && widget.getParent() != this) {
widget = widget.getParent();
}
if (!(widget instanceof VLabel)
&& !(widget instanceof VEmbedded)
&& !(widget instanceof VTextField && ((VTextField) widget)
.isReadOnly())) {
return null;
}
}
if (eventTarget == thisTrElement) {
// This was a click on the TR element
return thisTrElement;
}
// Iterate upwards until we find the TR element
Element element = eventTarget;
while (element != null
&& element.getParentElement().cast() != thisTrElement) {
element = element.getParentElement().cast();
}
return element;
}
public void showContextMenu(Event event) {
if (enabled && actionKeys != null) {
// Show context menu if there are registered action handlers
int left = Util.getTouchOrMouseClientX(event);
int top = Util.getTouchOrMouseClientY(event);
top += Window.getScrollTop();
left += Window.getScrollLeft();
contextMenu = new ContextMenuDetails(getKey(), left, top);
client.getContextMenu().showAt(this, left, top);
}
}
/**
* Has the row been selected?
*
* @return Returns true if selected, else false
*/
public boolean isSelected() {
return selected;
}
/**
* Toggle the selection of the row
*/
public void toggleSelection() {
selected = !selected;
selectionChanged = true;
if (selected) {
selectedRowKeys.add(String.valueOf(rowKey));
addStyleName("v-selected");
} else {
removeStyleName("v-selected");
selectedRowKeys.remove(String.valueOf(rowKey));
}
}
/**
* Is called when a user clicks an item when holding SHIFT key down.
* This will select a new range from the last focused row
*
* @param deselectPrevious
* Should the previous selected range be deselected
*/
private void toggleShiftSelection(boolean deselectPrevious) {
/*
* Ensures that we are in multiselect mode and that we have a
* previous selection which was not a deselection
*/
if (isSingleSelectMode()) {
// No previous selection found
deselectAll();
toggleSelection();
return;
}
// Set the selectable range
VScrollTableRow endRow = this;
VScrollTableRow startRow = selectionRangeStart;
if (startRow == null) {
startRow = focusedRow;
// If start row is null then we have a multipage selection
// from
// above
if (startRow == null) {
startRow = (VScrollTableRow) scrollBody.iterator()
.next();
setRowFocus(endRow);
}
}
// Deselect previous items if so desired
if (deselectPrevious) {
deselectAll();
}
// we'll ensure GUI state from top down even though selection
// was the opposite way
if (!startRow.isBefore(endRow)) {
VScrollTableRow tmp = startRow;
startRow = endRow;
endRow = tmp;
}
SelectionRange range = new SelectionRange(startRow, endRow);
for (Widget w : scrollBody) {
VScrollTableRow row = (VScrollTableRow) w;
if (range.inRange(row)) {
if (!row.isSelected()) {
row.toggleSelection();
}
selectedRowKeys.add(row.getKey());
}
}
// Add range
if (startRow != endRow) {
selectedRowRanges.add(range);
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.terminal.gwt.client.ui.IActionOwner#getActions ()
*/
public Action[] getActions() {
if (actionKeys == null) {
return new Action[] {};
}
final Action[] actions = new Action[actionKeys.length];
for (int i = 0; i < actions.length; i++) {
final String actionKey = actionKeys[i];
final TreeAction a = new TreeAction(this,
String.valueOf(rowKey), actionKey) {
@Override
public void execute() {
super.execute();
lazyRevertFocusToRow(VScrollTableRow.this);
}
};
a.setCaption(getActionCaption(actionKey));
a.setIconUrl(getActionIcon(actionKey));
actions[i] = a;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
public RenderSpace getAllocatedSpace(Widget child) {
int w = 0;
int i = getColIndexOf(child);
HeaderCell headerCell = tHead.getHeaderCell(i);
if (headerCell != null) {
if (initializedAndAttached) {
w = headerCell.getWidth();
} else {
// header offset width is not absolutely correct value,
// but a best guess (expecting similar content in all
// columns ->
// if one component is relative width so are others)
w = headerCell.getOffsetWidth() - getCellExtraWidth();
}
}
return new RenderSpace(w, 0) {
@Override
public int getHeight() {
return (int) getRowHeight();
}
};
}
private int getColIndexOf(Widget child) {
com.google.gwt.dom.client.Element widgetCell = child
.getElement().getParentElement().getParentElement();
NodeList<TableCellElement> cells = rowElement.getCells();
for (int i = 0; i < cells.getLength(); i++) {
if (cells.getItem(i) == widgetCell) {
return i;
}
}
return -1;
}
public boolean hasChildComponent(Widget component) {
return childWidgets.contains(component);
}
public void replaceChildComponent(Widget oldComponent,
Widget newComponent) {
com.google.gwt.dom.client.Element parentElement = oldComponent
.getElement().getParentElement();
int index = childWidgets.indexOf(oldComponent);
oldComponent.removeFromParent();
parentElement.appendChild(newComponent.getElement());
childWidgets.add(index, newComponent);
adopt(newComponent);
}
public boolean requestLayout(Set<Paintable> children) {
// row size should never change and system wouldn't event
// survive as this is a kind of fake paitable
return true;
}
public void updateCaption(Paintable component, UIDL uidl) {
// NOP, not rendered
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// Should never be called,
// Component container interface faked here to get layouts
// render properly
}
}
protected class VScrollTableGeneratedRow extends VScrollTableRow {
private boolean spanColumns;
private boolean htmlContentAllowed;
public VScrollTableGeneratedRow(UIDL uidl, char[] aligns) {
super(uidl, aligns);
addStyleName("v-table-generated-row");
}
public boolean isSpanColumns() {
return spanColumns;
}
@Override
protected void initCellWidths() {
if (spanColumns) {
setSpannedColumnWidthAfterDOMFullyInited();
} else {
super.initCellWidths();
}
}
private void setSpannedColumnWidthAfterDOMFullyInited() {
// Defer setting width on spanned columns to make sure that
// they are added to the DOM before trying to calculate
// widths.
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
public void execute() {
if (showRowHeaders) {
setCellWidth(0, tHead.getHeaderCell(0).getWidth());
calcAndSetSpanWidthOnCell(1);
} else {
calcAndSetSpanWidthOnCell(0);
}
}
});
}
@Override
protected boolean isRenderHtmlInCells() {
return htmlContentAllowed;
}
@Override
protected void addCellsFromUIDL(UIDL uidl, char[] aligns, int col,
int visibleColumnIndex) {
htmlContentAllowed = uidl.getBooleanAttribute("gen_html");
spanColumns = uidl.getBooleanAttribute("gen_span");
final Iterator<?> cells = uidl.getChildIterator();
if (spanColumns) {
int colCount = uidl.getChildCount();
if (cells.hasNext()) {
final Object cell = cells.next();
if (cell instanceof String) {
addSpannedCell(uidl, cell.toString(), aligns[0],
"", htmlContentAllowed, false, null,
colCount);
} else {
addSpannedCell(uidl, (Widget) cell, aligns[0], "",
false, colCount);
}
}
} else {
super.addCellsFromUIDL(uidl, aligns, col,
visibleColumnIndex);
}
}
private void addSpannedCell(UIDL rowUidl, Widget w, char align,
String style, boolean sorted, int colCount) {
TableCellElement td = DOM.createTD().cast();
td.setColSpan(colCount);
initCellWithWidget(w, align, style, sorted, td);
}
private void addSpannedCell(UIDL rowUidl, String text, char align,
String style, boolean textIsHTML, boolean sorted,
String description, int colCount) {
// String only content is optimized by not using Label widget
final TableCellElement td = DOM.createTD().cast();
td.setColSpan(colCount);
initCellWithText(text, align, style, textIsHTML, sorted,
description, td);
}
@Override
protected void setCellWidth(int cellIx, int width) {
if (isSpanColumns()) {
if (showRowHeaders) {
if (cellIx == 0) {
super.setCellWidth(0, width);
} else {
// We need to recalculate the spanning TDs width for
// every cellIx in order to support column resizing.
calcAndSetSpanWidthOnCell(1);
}
} else {
// Same as above.
calcAndSetSpanWidthOnCell(0);
}
} else {
super.setCellWidth(cellIx, width);
}
}
private void calcAndSetSpanWidthOnCell(final int cellIx) {
int spanWidth = 0;
for (int ix = (showRowHeaders ? 1 : 0); ix < tHead
.getVisibleCellCount(); ix++) {
spanWidth += tHead.getHeaderCell(ix).getOffsetWidth();
}
Util.setWidthExcludingPaddingAndBorder((Element) getElement()
.getChild(cellIx), spanWidth, 13, false);
}
}
/**
* Ensure the component has a focus.
*
* TODO the current implementation simply always calls focus for the
* component. In case the Table at some point implements focus/blur
* listeners, this method needs to be evolved to conditionally call
* focus only if not currently focused.
*/
protected void ensureFocus() {
if (!hasFocus) {
scrollBodyPanel.setFocus(true);
}
}
}
/**
* Deselects all items
*/
public void deselectAll() {
for (Widget w : scrollBody) {
VScrollTableRow row = (VScrollTableRow) w;
if (row.isSelected()) {
row.toggleSelection();
}
}
// still ensure all selects are removed from (not necessary rendered)
selectedRowKeys.clear();
selectedRowRanges.clear();
// also notify server that it clears all previous selections (the client
// side does not know about the invisible ones)
instructServerToForgetPreviousSelections();
}
/**
* Used in multiselect mode when the client side knows that all selections
* are in the next request.
*/
private void instructServerToForgetPreviousSelections() {
client.updateVariable(paintableId, "clearSelections", true, false);
}
/**
* Determines the pagelength when the table height is fixed.
*/
public void updatePageLength() {
// Only update if visible and enabled
if (!isVisible() || !enabled) {
return;
}
if (scrollBody == null) {
return;
}
if (height == null || height.equals("")) {
return;
}
int rowHeight = (int) Math.round(scrollBody.getRowHeight());
int bodyH = scrollBodyPanel.getOffsetHeight();
int rowsAtOnce = bodyH / rowHeight;
boolean anotherPartlyVisible = ((bodyH % rowHeight) != 0);
if (anotherPartlyVisible) {
rowsAtOnce++;
}
if (pageLength != rowsAtOnce) {
pageLength = rowsAtOnce;
client.updateVariable(paintableId, "pagelength", pageLength, false);
if (!rendering) {
int currentlyVisible = scrollBody.lastRendered
- scrollBody.firstRendered;
if (currentlyVisible < pageLength
&& currentlyVisible < totalRows) {
// shake scrollpanel to fill empty space
scrollBodyPanel.setScrollPosition(scrollTop + 1);
scrollBodyPanel.setScrollPosition(scrollTop - 1);
}
}
}
}
@Override
public void setWidth(String width) {
if (this.width.equals(width)) {
return;
}
if (!isVisible()) {
/*
* Do not update size when the table is hidden as all column widths
* will be set to zero and they won't be recalculated when the table
* is set visible again (until the size changes again)
*/
return;
}
this.width = width;
if (width != null && !"".equals(width)) {
super.setWidth(width);
int innerPixels = getOffsetWidth() - getBorderWidth();
if (innerPixels < 0) {
innerPixels = 0;
}
setContentWidth(innerPixels);
// readjust undefined width columns
triggerLazyColumnAdjustment(false);
} else {
// Undefined width
super.setWidth("");
// Readjust size of table
sizeInit();
// readjust undefined width columns
triggerLazyColumnAdjustment(false);
}
/*
* setting width may affect wheter the component has scrollbars -> needs
* scrolling or not
*/
setProperTabIndex();
}
private static final int LAZY_COLUMN_ADJUST_TIMEOUT = 300;
private final Timer lazyAdjustColumnWidths = new Timer() {
/**
* Check for column widths, and available width, to see if we can fix
* column widths "optimally". Doing this lazily to avoid expensive
* calculation when resizing is not yet finished.
*/
@Override
public void run() {
if (scrollBody == null) {
// Try again later if we get here before scrollBody has been
// initalized
triggerLazyColumnAdjustment(false);
return;
}
Iterator<Widget> headCells = tHead.iterator();
int usedMinimumWidth = 0;
int totalExplicitColumnsWidths = 0;
float expandRatioDivider = 0;
int colIndex = 0;
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
if (hCell.isDefinedWidth()) {
totalExplicitColumnsWidths += hCell.getWidth();
usedMinimumWidth += hCell.getWidth();
} else {
usedMinimumWidth += hCell.getNaturalColumnWidth(colIndex);
expandRatioDivider += hCell.getExpandRatio();
}
colIndex++;
}
int availW = scrollBody.getAvailableWidth();
// Hey IE, are you really sure about this?
availW = scrollBody.getAvailableWidth();
int visibleCellCount = tHead.getVisibleCellCount();
availW -= scrollBody.getCellExtraWidth() * visibleCellCount;
if (willHaveScrollbars()) {
availW -= Util.getNativeScrollbarSize();
}
int extraSpace = availW - usedMinimumWidth;
if (extraSpace < 0) {
extraSpace = 0;
}
int totalUndefinedNaturalWidths = usedMinimumWidth
- totalExplicitColumnsWidths;
// we have some space that can be divided optimally
HeaderCell hCell;
colIndex = 0;
headCells = tHead.iterator();
int checksum = 0;
while (headCells.hasNext()) {
hCell = (HeaderCell) headCells.next();
if (!hCell.isDefinedWidth()) {
int w = hCell.getNaturalColumnWidth(colIndex);
int newSpace;
if (expandRatioDivider > 0) {
// divide excess space by expand ratios
newSpace = Math.round((w + extraSpace
* hCell.getExpandRatio() / expandRatioDivider));
} else {
if (totalUndefinedNaturalWidths != 0) {
// divide relatively to natural column widths
newSpace = Math.round(w + (float) extraSpace
* (float) w / totalUndefinedNaturalWidths);
} else {
newSpace = w;
}
}
checksum += newSpace;
setColWidth(colIndex, newSpace, false);
} else {
checksum += hCell.getWidth();
}
colIndex++;
}
if (extraSpace > 0 && checksum != availW) {
/*
* There might be in some cases a rounding error of 1px when
* extra space is divided so if there is one then we give the
* first undefined column 1 more pixel
*/
headCells = tHead.iterator();
colIndex = 0;
while (headCells.hasNext()) {
HeaderCell hc = (HeaderCell) headCells.next();
if (!hc.isDefinedWidth()) {
setColWidth(colIndex,
hc.getWidth() + availW - checksum, false);
break;
}
colIndex++;
}
}
if ((height == null || "".equals(height))
&& totalRows == pageLength) {
// fix body height (may vary if lazy loading is offhorizontal
// scrollbar appears/disappears)
int bodyHeight = scrollBody.getRequiredHeight();
boolean needsSpaceForHorizontalScrollbar = (availW < usedMinimumWidth);
if (needsSpaceForHorizontalScrollbar) {
bodyHeight += Util.getNativeScrollbarSize();
}
int heightBefore = getOffsetHeight();
scrollBodyPanel.setHeight(bodyHeight + "px");
if (heightBefore != getOffsetHeight()) {
Util.notifyParentOfSizeChange(VScrollTable.this, false);
}
}
scrollBody.reLayoutComponents();
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
});
forceRealignColumnHeaders();
}
};
private void forceRealignColumnHeaders() {
if (BrowserInfo.get().isIE()) {
/*
* IE does not fire onscroll event if scroll position is reverted to
* 0 due to the content element size growth. Ensure headers are in
* sync with content manually. Safe to use null event as we don't
* actually use the event object in listener.
*/
onScroll(null);
}
}
/**
* helper to set pixel size of head and body part
*
* @param pixels
*/
private void setContentWidth(int pixels) {
tHead.setWidth(pixels + "px");
scrollBodyPanel.setWidth(pixels + "px");
tFoot.setWidth(pixels + "px");
}
private int borderWidth = -1;
/**
* @return border left + border right
*/
private int getBorderWidth() {
if (borderWidth < 0) {
borderWidth = Util.measureHorizontalPaddingAndBorder(
scrollBodyPanel.getElement(), 2);
if (borderWidth < 0) {
borderWidth = 0;
}
}
return borderWidth;
}
/**
* Ensures scrollable area is properly sized. This method is used when fixed
* size is used.
*/
private int containerHeight;
private void setContainerHeight() {
if (height != null && !"".equals(height)) {
containerHeight = getOffsetHeight();
containerHeight -= showColHeaders ? tHead.getOffsetHeight() : 0;
containerHeight -= tFoot.getOffsetHeight();
containerHeight -= getContentAreaBorderHeight();
if (containerHeight < 0) {
containerHeight = 0;
}
scrollBodyPanel.setHeight(containerHeight + "px");
}
}
private int contentAreaBorderHeight = -1;
private int scrollLeft;
private int scrollTop;
private VScrollTableDropHandler dropHandler;
private boolean navKeyDown;
private boolean multiselectPending;
/**
* @return border top + border bottom of the scrollable area of table
*/
private int getContentAreaBorderHeight() {
if (contentAreaBorderHeight < 0) {
if (BrowserInfo.get().isIE7() || BrowserInfo.get().isIE6()) {
contentAreaBorderHeight = Util
.measureVerticalBorder(scrollBodyPanel.getElement());
} else {
DOM.setStyleAttribute(scrollBodyPanel.getElement(), "overflow",
"hidden");
int oh = scrollBodyPanel.getOffsetHeight();
int ch = scrollBodyPanel.getElement().getPropertyInt(
"clientHeight");
contentAreaBorderHeight = oh - ch;
DOM.setStyleAttribute(scrollBodyPanel.getElement(), "overflow",
"auto");
}
}
return contentAreaBorderHeight;
}
@Override
public void setHeight(String height) {
this.height = height;
super.setHeight(height);
setContainerHeight();
if (initializedAndAttached) {
updatePageLength();
}
if (!rendering) {
// Webkit may sometimes get an odd rendering bug (white space
// between header and body), see bug #3875. Running
// overflow hack here to shake body element a bit.
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
/*
* setting height may affect wheter the component has scrollbars ->
* needs scrolling or not
*/
setProperTabIndex();
}
/*
* Overridden due Table might not survive of visibility change (scroll pos
* lost). Example ITabPanel just set contained components invisible and back
* when changing tabs.
*/
@Override
public void setVisible(boolean visible) {
if (isVisible() != visible) {
super.setVisible(visible);
if (initializedAndAttached) {
if (visible) {
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
scrollBodyPanel
.setScrollPosition(measureRowHeightOffset(firstRowInViewPort));
}
});
}
}
}
}
/**
* Helper function to build html snippet for column or row headers
*
* @param uidl
* possibly with values caption and icon
* @return html snippet containing possibly an icon + caption text
*/
protected String buildCaptionHtmlSnippet(UIDL uidl) {
String s = uidl.hasAttribute("caption") ? uidl
.getStringAttribute("caption") : "";
if (uidl.hasAttribute("icon")) {
s = "<img src=\""
+ Util.escapeAttribute(client.translateVaadinUri(uidl
.getStringAttribute("icon")))
+ "\" alt=\"icon\" class=\"v-icon\">" + s;
}
return s;
}
/**
* This method has logic which rows needs to be requested from server when
* user scrolls
*/
public void onScroll(ScrollEvent event) {
scrollLeft = scrollBodyPanel.getElement().getScrollLeft();
scrollTop = scrollBodyPanel.getScrollPosition();
/*
* #6970 - IE sometimes fires scroll events for a detached table.
*
* FIXME initializedAndAttached should probably be renamed - its name
* doesn't seem to reflect its semantics. onDetach() doesn't set it to
* false, and changing that might break something else, so we need to
* check isAttached() separately.
*/
if (!initializedAndAttached || !isAttached()) {
return;
}
if (!enabled) {
scrollBodyPanel
.setScrollPosition(measureRowHeightOffset(firstRowInViewPort));
return;
}
rowRequestHandler.cancel();
if (BrowserInfo.get().isSafari() && event != null && scrollTop == 0) {
// due to the webkitoverflowworkaround, top may sometimes report 0
// for webkit, although it really is not. Expecting to have the
// correct
// value available soon.
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
onScroll(null);
}
});
return;
}
// fix headers horizontal scrolling
tHead.setHorizontalScrollPosition(scrollLeft);
// fix footers horizontal scrolling
tFoot.setHorizontalScrollPosition(scrollLeft);
firstRowInViewPort = calcFirstRowInViewPort();
if (firstRowInViewPort > totalRows - pageLength) {
firstRowInViewPort = totalRows - pageLength;
}
int postLimit = (int) (firstRowInViewPort + (pageLength - 1) + pageLength
* cache_react_rate);
if (postLimit > totalRows - 1) {
postLimit = totalRows - 1;
}
int preLimit = (int) (firstRowInViewPort - pageLength
* cache_react_rate);
if (preLimit < 0) {
preLimit = 0;
}
final int lastRendered = scrollBody.getLastRendered();
final int firstRendered = scrollBody.getFirstRendered();
if (postLimit <= lastRendered && preLimit >= firstRendered) {
// we're within no-react area, no need to request more rows
// remember which firstvisible we requested, in case the server has
// a differing opinion
lastRequestedFirstvisible = firstRowInViewPort;
client.updateVariable(paintableId, "firstvisible",
firstRowInViewPort, false);
return;
}
if (firstRowInViewPort - pageLength * cache_rate > lastRendered
|| firstRowInViewPort + pageLength + pageLength * cache_rate < firstRendered) {
// need a totally new set of rows
rowRequestHandler
.setReqFirstRow((firstRowInViewPort - (int) (pageLength * cache_rate)));
int last = firstRowInViewPort + (int) (cache_rate * pageLength)
+ pageLength - 1;
if (last >= totalRows) {
last = totalRows - 1;
}
rowRequestHandler.setReqRows(last
- rowRequestHandler.getReqFirstRow() + 1);
rowRequestHandler.deferRowFetch();
return;
}
if (preLimit < firstRendered) {
// need some rows to the beginning of the rendered area
rowRequestHandler
.setReqFirstRow((int) (firstRowInViewPort - pageLength
* cache_rate));
rowRequestHandler.setReqRows(firstRendered
- rowRequestHandler.getReqFirstRow());
rowRequestHandler.deferRowFetch();
return;
}
if (postLimit > lastRendered) {
// need some rows to the end of the rendered area
rowRequestHandler.setReqFirstRow(lastRendered + 1);
rowRequestHandler.setReqRows((int) ((firstRowInViewPort
+ pageLength + pageLength * cache_rate) - lastRendered));
rowRequestHandler.deferRowFetch();
}
}
protected int calcFirstRowInViewPort() {
return (int) Math.ceil(scrollTop / scrollBody.getRowHeight());
}
public VScrollTableDropHandler getDropHandler() {
return dropHandler;
}
private static class TableDDDetails {
int overkey = -1;
VerticalDropLocation dropLocation;
String colkey;
@Override
public boolean equals(Object obj) {
if (obj instanceof TableDDDetails) {
TableDDDetails other = (TableDDDetails) obj;
return dropLocation == other.dropLocation
&& overkey == other.overkey
&& ((colkey != null && colkey.equals(other.colkey)) || (colkey == null && other.colkey == null));
}
return false;
}
// @Override
// public int hashCode() {
// return overkey;
// }
}
public class VScrollTableDropHandler extends VAbstractDropHandler {
private static final String ROWSTYLEBASE = "v-table-row-drag-";
private TableDDDetails dropDetails;
private TableDDDetails lastEmphasized;
@Override
public void dragEnter(VDragEvent drag) {
updateDropDetails(drag);
super.dragEnter(drag);
}
private void updateDropDetails(VDragEvent drag) {
dropDetails = new TableDDDetails();
Element elementOver = drag.getElementOver();
VScrollTableRow row = Util.findWidget(elementOver, getRowClass());
if (row != null) {
dropDetails.overkey = row.rowKey;
Element tr = row.getElement();
Element element = elementOver;
while (element != null && element.getParentElement() != tr) {
element = (Element) element.getParentElement();
}
int childIndex = DOM.getChildIndex(tr, element);
dropDetails.colkey = tHead.getHeaderCell(childIndex)
.getColKey();
dropDetails.dropLocation = DDUtil.getVerticalDropLocation(
row.getElement(), drag.getCurrentGwtEvent(), 0.2);
}
drag.getDropDetails().put("itemIdOver", dropDetails.overkey + "");
drag.getDropDetails().put(
"detail",
dropDetails.dropLocation != null ? dropDetails.dropLocation
.toString() : null);
}
private Class<? extends Widget> getRowClass() {
// get the row type this way to make dd work in derived
// implementations
return scrollBody.iterator().next().getClass();
}
@Override
public void dragOver(VDragEvent drag) {
TableDDDetails oldDetails = dropDetails;
updateDropDetails(drag);
if (!oldDetails.equals(dropDetails)) {
deEmphasis();
final TableDDDetails newDetails = dropDetails;
VAcceptCallback cb = new VAcceptCallback() {
public void accepted(VDragEvent event) {
if (newDetails.equals(dropDetails)) {
dragAccepted(event);
}
/*
* Else new target slot already defined, ignore
*/
}
};
validate(cb, drag);
}
}
@Override
public void dragLeave(VDragEvent drag) {
deEmphasis();
super.dragLeave(drag);
}
@Override
public boolean drop(VDragEvent drag) {
deEmphasis();
return super.drop(drag);
}
private void deEmphasis() {
UIObject.setStyleName(getElement(), CLASSNAME + "-drag", false);
if (lastEmphasized == null) {
return;
}
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (lastEmphasized != null
&& row.rowKey == lastEmphasized.overkey) {
String stylename = ROWSTYLEBASE
+ lastEmphasized.dropLocation.toString()
.toLowerCase();
VScrollTableRow.setStyleName(row.getElement(), stylename,
false);
lastEmphasized = null;
return;
}
}
}
/**
* TODO needs different drop modes ?? (on cells, on rows), now only
* supports rows
*/
private void emphasis(TableDDDetails details) {
deEmphasis();
UIObject.setStyleName(getElement(), CLASSNAME + "-drag", true);
// iterate old and new emphasized row
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (details != null && details.overkey == row.rowKey) {
String stylename = ROWSTYLEBASE
+ details.dropLocation.toString().toLowerCase();
VScrollTableRow.setStyleName(row.getElement(), stylename,
true);
lastEmphasized = details;
return;
}
}
}
@Override
protected void dragAccepted(VDragEvent drag) {
emphasis(dropDetails);
}
@Override
public Paintable getPaintable() {
return VScrollTable.this;
}
public ApplicationConnection getApplicationConnection() {
return client;
}
}
protected VScrollTableRow getFocusedRow() {
return focusedRow;
}
/**
* Moves the selection head to a specific row
*
* @param row
* The row to where the selection head should move
* @return Returns true if focus was moved successfully, else false
*/
protected boolean setRowFocus(VScrollTableRow row) {
if (!isSelectable()) {
return false;
}
// Remove previous selection
if (focusedRow != null && focusedRow != row) {
focusedRow.removeStyleName(CLASSNAME_SELECTION_FOCUS);
}
if (row != null) {
// Apply focus style to new selection
row.addStyleName(CLASSNAME_SELECTION_FOCUS);
/*
* Trying to set focus on already focused row
*/
if (row == focusedRow) {
return false;
}
// Set new focused row
focusedRow = row;
ensureRowIsVisible(row);
return true;
}
return false;
}
/**
* Ensures that the row is visible
*
* @param row
* The row to ensure is visible
*/
private void ensureRowIsVisible(VScrollTableRow row) {
if (BrowserInfo.get().isTouchDevice()) {
// Skip due to android devices that have broken scrolltop will may
// get odd scrolling here.
return;
}
Util.scrollIntoViewVertically(row.getElement());
}
/**
* Handles the keyboard events handled by the table
*
* @param event
* The keyboard event received
* @return true iff the navigation event was handled
*/
protected boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {
if (keycode == KeyCodes.KEY_TAB || keycode == KeyCodes.KEY_SHIFT) {
// Do not handle tab key
return false;
}
// Down navigation
if (!isSelectable() && keycode == getNavigationDownKey()) {
scrollBodyPanel.setScrollPosition(scrollBodyPanel
.getScrollPosition() + scrollingVelocity);
return true;
} else if (keycode == getNavigationDownKey()) {
if (isMultiSelectModeAny() && moveFocusDown()) {
selectFocusedRow(ctrl, shift);
} else if (isSingleSelectMode() && !shift && moveFocusDown()) {
selectFocusedRow(ctrl, shift);
}
return true;
}
// Up navigation
if (!isSelectable() && keycode == getNavigationUpKey()) {
scrollBodyPanel.setScrollPosition(scrollBodyPanel
.getScrollPosition() - scrollingVelocity);
return true;
} else if (keycode == getNavigationUpKey()) {
if (isMultiSelectModeAny() && moveFocusUp()) {
selectFocusedRow(ctrl, shift);
} else if (isSingleSelectMode() && !shift && moveFocusUp()) {
selectFocusedRow(ctrl, shift);
}
return true;
}
if (keycode == getNavigationLeftKey()) {
// Left navigation
scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
.getHorizontalScrollPosition() - scrollingVelocity);
return true;
} else if (keycode == getNavigationRightKey()) {
// Right navigation
scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
.getHorizontalScrollPosition() + scrollingVelocity);
return true;
}
// Select navigation
if (isSelectable() && keycode == getNavigationSelectKey()) {
if (isSingleSelectMode()) {
boolean wasSelected = focusedRow.isSelected();
deselectAll();
if (!wasSelected || !nullSelectionAllowed) {
focusedRow.toggleSelection();
}
} else {
focusedRow.toggleSelection();
removeRowFromUnsentSelectionRanges(focusedRow);
}
sendSelectedRows();
return true;
}
// Page Down navigation
if (keycode == getNavigationPageDownKey()) {
if (isSelectable()) {
/*
* If selectable we plagiate MSW behaviour: first scroll to the
* end of current view. If at the end, scroll down one page
* length and keep the selected row in the bottom part of
* visible area.
*/
if (!isFocusAtTheEndOfTable()) {
VScrollTableRow lastVisibleRowInViewPort = scrollBody
.getRowByRowIndex(firstRowInViewPort
+ getFullyVisibleRowCount() - 1);
if (lastVisibleRowInViewPort != null
&& lastVisibleRowInViewPort != focusedRow) {
// focused row is not at the end of the table, move
// focus and select the last visible row
setRowFocus(lastVisibleRowInViewPort);
selectFocusedRow(ctrl, shift);
sendSelectedRows();
} else {
int indexOfToBeFocused = focusedRow.getIndex()
+ getFullyVisibleRowCount();
if (indexOfToBeFocused >= totalRows) {
indexOfToBeFocused = totalRows - 1;
}
VScrollTableRow toBeFocusedRow = scrollBody
.getRowByRowIndex(indexOfToBeFocused);
if (toBeFocusedRow != null) {
/*
* if the next focused row is rendered
*/
setRowFocus(toBeFocusedRow);
selectFocusedRow(ctrl, shift);
// TODO needs scrollintoview ?
sendSelectedRows();
} else {
// scroll down by pixels and return, to wait for
// new rows, then select the last item in the
// viewport
selectLastItemInNextRender = true;
multiselectPending = shift;
scrollByPagelenght(1);
}
}
}
} else {
/* No selections, go page down by scrolling */
scrollByPagelenght(1);
}
return true;
}
// Page Up navigation
if (keycode == getNavigationPageUpKey()) {
if (isSelectable()) {
/*
* If selectable we plagiate MSW behaviour: first scroll to the
* end of current view. If at the end, scroll down one page
* length and keep the selected row in the bottom part of
* visible area.
*/
if (!isFocusAtTheBeginningOfTable()) {
VScrollTableRow firstVisibleRowInViewPort = scrollBody
.getRowByRowIndex(firstRowInViewPort);
if (firstVisibleRowInViewPort != null
&& firstVisibleRowInViewPort != focusedRow) {
// focus is not at the beginning of the table, move
// focus and select the first visible row
setRowFocus(firstVisibleRowInViewPort);
selectFocusedRow(ctrl, shift);
sendSelectedRows();
} else {
int indexOfToBeFocused = focusedRow.getIndex()
- getFullyVisibleRowCount();
if (indexOfToBeFocused < 0) {
indexOfToBeFocused = 0;
}
VScrollTableRow toBeFocusedRow = scrollBody
.getRowByRowIndex(indexOfToBeFocused);
if (toBeFocusedRow != null) { // if the next focused row
// is rendered
setRowFocus(toBeFocusedRow);
selectFocusedRow(ctrl, shift);
// TODO needs scrollintoview ?
sendSelectedRows();
} else {
// unless waiting for the next rowset already
// scroll down by pixels and return, to wait for
// new rows, then select the last item in the
// viewport
selectFirstItemInNextRender = true;
multiselectPending = shift;
scrollByPagelenght(-1);
}
}
}
} else {
/* No selections, go page up by scrolling */
scrollByPagelenght(-1);
}
return true;
}
// Goto start navigation
if (keycode == getNavigationStartKey()) {
scrollBodyPanel.setScrollPosition(0);
if (isSelectable()) {
if (focusedRow != null && focusedRow.getIndex() == 0) {
return false;
} else {
VScrollTableRow rowByRowIndex = (VScrollTableRow) scrollBody
.iterator().next();
if (rowByRowIndex.getIndex() == 0) {
setRowFocus(rowByRowIndex);
selectFocusedRow(ctrl, shift);
sendSelectedRows();
} else {
// first row of table will come in next row fetch
if (ctrl) {
focusFirstItemInNextRender = true;
} else {
selectFirstItemInNextRender = true;
multiselectPending = shift;
}
}
}
}
return true;
}
// Goto end navigation
if (keycode == getNavigationEndKey()) {
scrollBodyPanel.setScrollPosition(scrollBody.getOffsetHeight());
if (isSelectable()) {
final int lastRendered = scrollBody.getLastRendered();
if (lastRendered + 1 == totalRows) {
VScrollTableRow rowByRowIndex = scrollBody
.getRowByRowIndex(lastRendered);
if (focusedRow != rowByRowIndex) {
setRowFocus(rowByRowIndex);
selectFocusedRow(ctrl, shift);
sendSelectedRows();
}
} else {
if (ctrl) {
focusLastItemInNextRender = true;
} else {
selectLastItemInNextRender = true;
multiselectPending = shift;
}
}
}
return true;
}
return false;
}
private boolean isFocusAtTheBeginningOfTable() {
return focusedRow.getIndex() == 0;
}
private boolean isFocusAtTheEndOfTable() {
return focusedRow.getIndex() + 1 >= totalRows;
}
private int getFullyVisibleRowCount() {
return (int) (scrollBodyPanel.getOffsetHeight() / scrollBody
.getRowHeight());
}
private void scrollByPagelenght(int i) {
int pixels = i * scrollBodyPanel.getOffsetHeight();
int newPixels = scrollBodyPanel.getScrollPosition() + pixels;
if (newPixels < 0) {
newPixels = 0;
} // else if too high, NOP (all know browsers accept illegally big
// values here)
scrollBodyPanel.setScrollPosition(newPixels);
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
* .dom.client.FocusEvent)
*/
public void onFocus(FocusEvent event) {
if (isFocusable()) {
hasFocus = true;
// Focus a row if no row is in focus
if (focusedRow == null) {
focusRowFromBody();
} else {
setRowFocus(focusedRow);
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
* .dom.client.BlurEvent)
*/
public void onBlur(BlurEvent event) {
hasFocus = false;
navKeyDown = false;
if (BrowserInfo.get().isIE()) {
// IE sometimes moves focus to a clicked table cell...
Element focusedElement = Util.getIEFocusedElement();
if (Util.getPaintableForElement(client, getParent(), focusedElement) == this) {
// ..in that case, steal the focus back to the focus handler
// but not if focus is in a child component instead (#7965)
focus();
return;
}
}
if (isFocusable()) {
// Unfocus any row
setRowFocus(null);
}
}
/**
* Removes a key from a range if the key is found in a selected range
*
* @param key
* The key to remove
*/
private void removeRowFromUnsentSelectionRanges(VScrollTableRow row) {
Collection<SelectionRange> newRanges = null;
for (Iterator<SelectionRange> iterator = selectedRowRanges.iterator(); iterator
.hasNext();) {
SelectionRange range = iterator.next();
if (range.inRange(row)) {
// Split the range if given row is in range
Collection<SelectionRange> splitranges = range.split(row);
if (newRanges == null) {
newRanges = new ArrayList<SelectionRange>();
}
newRanges.addAll(splitranges);
iterator.remove();
}
}
if (newRanges != null) {
selectedRowRanges.addAll(newRanges);
}
}
/**
* Can the Table be focused?
*
* @return True if the table can be focused, else false
*/
public boolean isFocusable() {
if (scrollBody != null && enabled) {
return !(!hasHorizontalScrollbar() && !hasVerticalScrollbar() && !isSelectable());
}
return false;
}
private boolean hasHorizontalScrollbar() {
return scrollBody.getOffsetWidth() > scrollBodyPanel.getOffsetWidth();
}
private boolean hasVerticalScrollbar() {
return scrollBody.getOffsetHeight() > scrollBodyPanel.getOffsetHeight();
}
/*
* (non-Javadoc)
*
* @see com.vaadin.terminal.gwt.client.Focusable#focus()
*/
public void focus() {
if (isFocusable()) {
scrollBodyPanel.focus();
}
}
/**
* Sets the proper tabIndex for scrollBodyPanel (the focusable elemen in the
* component).
*
* If the component has no explicit tabIndex a zero is given (default
* tabbing order based on dom hierarchy) or -1 if the component does not
* need to gain focus. The component needs no focus if it has no scrollabars
* (not scrollable) and not selectable. Note that in the future shortcut
* actions may need focus.
*
*/
private void setProperTabIndex() {
int storedScrollTop = 0;
int storedScrollLeft = 0;
if (BrowserInfo.get().getOperaVersion() >= 11) {
// Workaround for Opera scroll bug when changing tabIndex (#6222)
storedScrollTop = scrollBodyPanel.getScrollPosition();
storedScrollLeft = scrollBodyPanel.getHorizontalScrollPosition();
}
if (tabIndex == 0 && !isFocusable()) {
scrollBodyPanel.setTabIndex(-1);
} else {
scrollBodyPanel.setTabIndex(tabIndex);
}
if (BrowserInfo.get().getOperaVersion() >= 11) {
// Workaround for Opera scroll bug when changing tabIndex (#6222)
scrollBodyPanel.setScrollPosition(storedScrollTop);
scrollBodyPanel.setHorizontalScrollPosition(storedScrollLeft);
}
}
public void startScrollingVelocityTimer() {
if (scrollingVelocityTimer == null) {
scrollingVelocityTimer = new Timer() {
@Override
public void run() {
scrollingVelocity++;
}
};
scrollingVelocityTimer.scheduleRepeating(100);
}
}
public void cancelScrollingVelocityTimer() {
if (scrollingVelocityTimer != null) {
// Remove velocityTimer if it exists and the Table is disabled
scrollingVelocityTimer.cancel();
scrollingVelocityTimer = null;
scrollingVelocity = 10;
}
}
/**
*
* @param keyCode
* @return true if the given keyCode is used by the table for navigation
*/
private boolean isNavigationKey(int keyCode) {
return keyCode == getNavigationUpKey()
|| keyCode == getNavigationLeftKey()
|| keyCode == getNavigationRightKey()
|| keyCode == getNavigationDownKey()
|| keyCode == getNavigationPageUpKey()
|| keyCode == getNavigationPageDownKey()
|| keyCode == getNavigationEndKey()
|| keyCode == getNavigationStartKey();
}
public void lazyRevertFocusToRow(final VScrollTableRow currentlyFocusedRow) {
Scheduler.get().scheduleFinally(new ScheduledCommand() {
public void execute() {
if (currentlyFocusedRow != null) {
setRowFocus(currentlyFocusedRow);
} else {
VConsole.log("no row?");
focusRowFromBody();
}
scrollBody.ensureFocus();
}
});
}
public Action[] getActions() {
if (bodyActionKeys == null) {
return new Action[] {};
}
final Action[] actions = new Action[bodyActionKeys.length];
for (int i = 0; i < actions.length; i++) {
final String actionKey = bodyActionKeys[i];
Action bodyAction = new TreeAction(this, null, actionKey);
bodyAction.setCaption(getActionCaption(actionKey));
bodyAction.setIconUrl(getActionIcon(actionKey));
actions[i] = bodyAction;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
/**
* Add this to the element mouse down event by using element.setPropertyJSO
* ("onselectstart",applyDisableTextSelectionIEHack()); Remove it then again
* when the mouse is depressed in the mouse up event.
*
* @return Returns the JSO preventing text selection
*/
private static native JavaScriptObject getPreventTextSelectionIEHack()
/*-{
return function(){ return false; };
}-*/;
protected void triggerLazyColumnAdjustment(boolean now) {
lazyAdjustColumnWidths.cancel();
if (now) {
lazyAdjustColumnWidths.run();
} else {
lazyAdjustColumnWidths.schedule(LAZY_COLUMN_ADJUST_TIMEOUT);
}
}
private void debug(String msg) {
if (enableDebug) {
VConsole.error(msg);
}
}
}
| src/com/vaadin/terminal/gwt/client/ui/VScrollTable.java | /*
@VaadinApache2LicenseForJavaFiles@
*/
package com.vaadin.terminal.gwt.client.ui;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.dom.client.Style.Visibility;
import com.google.gwt.dom.client.TableCellElement;
import com.google.gwt.dom.client.TableRowElement;
import com.google.gwt.dom.client.TableSectionElement;
import com.google.gwt.dom.client.Touch;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ContextMenuEvent;
import com.google.gwt.event.dom.client.ContextMenuHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.dom.client.ScrollEvent;
import com.google.gwt.event.dom.client.ScrollHandler;
import com.google.gwt.event.dom.client.TouchStartEvent;
import com.google.gwt.event.dom.client.TouchStartHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.BrowserInfo;
import com.vaadin.terminal.gwt.client.Container;
import com.vaadin.terminal.gwt.client.Focusable;
import com.vaadin.terminal.gwt.client.MouseEventDetails;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.RenderSpace;
import com.vaadin.terminal.gwt.client.TooltipInfo;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.VConsole;
import com.vaadin.terminal.gwt.client.VTooltip;
import com.vaadin.terminal.gwt.client.ui.VScrollTable.VScrollTableBody.VScrollTableRow;
import com.vaadin.terminal.gwt.client.ui.dd.DDUtil;
import com.vaadin.terminal.gwt.client.ui.dd.VAbstractDropHandler;
import com.vaadin.terminal.gwt.client.ui.dd.VAcceptCallback;
import com.vaadin.terminal.gwt.client.ui.dd.VDragAndDropManager;
import com.vaadin.terminal.gwt.client.ui.dd.VDragEvent;
import com.vaadin.terminal.gwt.client.ui.dd.VHasDropHandler;
import com.vaadin.terminal.gwt.client.ui.dd.VTransferable;
import com.vaadin.terminal.gwt.client.ui.dd.VerticalDropLocation;
/**
* VScrollTable
*
* VScrollTable is a FlowPanel having two widgets in it: * TableHead component *
* ScrollPanel
*
* TableHead contains table's header and widgets + logic for resizing,
* reordering and hiding columns.
*
* ScrollPanel contains VScrollTableBody object which handles content. To save
* some bandwidth and to improve clients responsiveness with loads of data, in
* VScrollTableBody all rows are not necessary rendered. There are "spacers" in
* VScrollTableBody to use the exact same space as non-rendered rows would use.
* This way we can use seamlessly traditional scrollbars and scrolling to fetch
* more rows instead of "paging".
*
* In VScrollTable we listen to scroll events. On horizontal scrolling we also
* update TableHeads scroll position which has its scrollbars hidden. On
* vertical scroll events we will check if we are reaching the end of area where
* we have rows rendered and
*
* TODO implement unregistering for child components in Cells
*/
public class VScrollTable extends FlowPanel implements Table, ScrollHandler,
VHasDropHandler, FocusHandler, BlurHandler, Focusable, ActionOwner {
public static final String ATTRIBUTE_PAGEBUFFER_FIRST = "pb-ft";
public static final String ATTRIBUTE_PAGEBUFFER_LAST = "pb-l";
private static final String ROW_HEADER_COLUMN_KEY = "0";
public static final String CLASSNAME = "v-table";
public static final String CLASSNAME_SELECTION_FOCUS = CLASSNAME + "-focus";
public static final String ITEM_CLICK_EVENT_ID = "itemClick";
public static final String HEADER_CLICK_EVENT_ID = "handleHeaderClick";
public static final String FOOTER_CLICK_EVENT_ID = "handleFooterClick";
public static final String COLUMN_RESIZE_EVENT_ID = "columnResize";
public static final String COLUMN_REORDER_EVENT_ID = "columnReorder";
private static final double CACHE_RATE_DEFAULT = 2;
/**
* The default multi select mode where simple left clicks only selects one
* item, CTRL+left click selects multiple items and SHIFT-left click selects
* a range of items.
*/
private static final int MULTISELECT_MODE_DEFAULT = 0;
/**
* The simple multiselect mode is what the table used to have before
* ctrl/shift selections were added. That is that when this is set clicking
* on an item selects/deselects the item and no ctrl/shift selections are
* available.
*/
private static final int MULTISELECT_MODE_SIMPLE = 1;
/**
* multiple of pagelength which component will cache when requesting more
* rows
*/
private double cache_rate = CACHE_RATE_DEFAULT;
/**
* fraction of pageLenght which can be scrolled without making new request
*/
private double cache_react_rate = 0.75 * cache_rate;
public static final char ALIGN_CENTER = 'c';
public static final char ALIGN_LEFT = 'b';
public static final char ALIGN_RIGHT = 'e';
private static final int CHARCODE_SPACE = 32;
private int firstRowInViewPort = 0;
private int pageLength = 15;
private int lastRequestedFirstvisible = 0; // to detect "serverside scroll"
protected boolean showRowHeaders = false;
private String[] columnOrder;
protected ApplicationConnection client;
protected String paintableId;
private boolean immediate;
private boolean nullSelectionAllowed = true;
private int selectMode = Table.SELECT_MODE_NONE;
private final HashSet<String> selectedRowKeys = new HashSet<String>();
/*
* When scrolling and selecting at the same time, the selections are not in
* sync with the server while retrieving new rows (until key is released).
*/
private HashSet<Object> unSyncedselectionsBeforeRowFetch;
/*
* These are used when jumping between pages when pressing Home and End
*/
private boolean selectLastItemInNextRender = false;
private boolean selectFirstItemInNextRender = false;
private boolean focusFirstItemInNextRender = false;
private boolean focusLastItemInNextRender = false;
/*
* The currently focused row
*/
private VScrollTableRow focusedRow;
/*
* Helper to store selection range start in when using the keyboard
*/
private VScrollTableRow selectionRangeStart;
/*
* Flag for notifying when the selection has changed and should be sent to
* the server
*/
private boolean selectionChanged = false;
/*
* The speed (in pixels) which the scrolling scrolls vertically/horizontally
*/
private int scrollingVelocity = 10;
private Timer scrollingVelocityTimer = null;
private String[] bodyActionKeys;
private boolean enableDebug = false;
/**
* Represents a select range of rows
*/
private class SelectionRange {
private VScrollTableRow startRow;
private final int length;
/**
* Constuctor.
*/
public SelectionRange(VScrollTableRow row1, VScrollTableRow row2) {
VScrollTableRow endRow;
if (row2.isBefore(row1)) {
startRow = row2;
endRow = row1;
} else {
startRow = row1;
endRow = row2;
}
length = endRow.getIndex() - startRow.getIndex() + 1;
}
public SelectionRange(VScrollTableRow row, int length) {
startRow = row;
this.length = length;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return startRow.getKey() + "-" + length;
}
private boolean inRange(VScrollTableRow row) {
return row.getIndex() >= startRow.getIndex()
&& row.getIndex() < startRow.getIndex() + length;
}
public Collection<SelectionRange> split(VScrollTableRow row) {
assert row.isAttached();
ArrayList<SelectionRange> ranges = new ArrayList<SelectionRange>(2);
int endOfFirstRange = row.getIndex() - 1;
if (!(endOfFirstRange - startRow.getIndex() < 0)) {
// create range of first part unless its length is < 1
ranges.add(new SelectionRange(startRow, endOfFirstRange
- startRow.getIndex() + 1));
}
int startOfSecondRange = row.getIndex() + 1;
if (!(getEndIndex() - startOfSecondRange < 0)) {
// create range of second part unless its length is < 1
VScrollTableRow startOfRange = scrollBody
.getRowByRowIndex(startOfSecondRange);
ranges.add(new SelectionRange(startOfRange, getEndIndex()
- startOfSecondRange + 1));
}
return ranges;
}
private int getEndIndex() {
return startRow.getIndex() + length - 1;
}
};
private final HashSet<SelectionRange> selectedRowRanges = new HashSet<SelectionRange>();
private boolean initializedAndAttached = false;
/**
* Flag to indicate if a column width recalculation is needed due update.
*/
private boolean headerChangedDuringUpdate = false;
protected final TableHead tHead = new TableHead();
private final TableFooter tFoot = new TableFooter();
private final FocusableScrollPanel scrollBodyPanel = new FocusableScrollPanel(
true);
private KeyPressHandler navKeyPressHandler = new KeyPressHandler() {
public void onKeyPress(KeyPressEvent keyPressEvent) {
// This is used for Firefox only, since Firefox auto-repeat
// works correctly only if we use a key press handler, other
// browsers handle it correctly when using a key down handler
if (!BrowserInfo.get().isGecko()) {
return;
}
NativeEvent event = keyPressEvent.getNativeEvent();
if (!enabled) {
// Cancel default keyboard events on a disabled Table
// (prevents scrolling)
event.preventDefault();
} else if (hasFocus) {
// Key code in Firefox/onKeyPress is present only for
// special keys, otherwise 0 is returned
int keyCode = event.getKeyCode();
if (keyCode == 0 && event.getCharCode() == ' ') {
// Provide a keyCode for space to be compatible with
// FireFox keypress event
keyCode = CHARCODE_SPACE;
}
if (handleNavigation(keyCode,
event.getCtrlKey() || event.getMetaKey(),
event.getShiftKey())) {
event.preventDefault();
}
startScrollingVelocityTimer();
}
}
};
private KeyUpHandler navKeyUpHandler = new KeyUpHandler() {
public void onKeyUp(KeyUpEvent keyUpEvent) {
NativeEvent event = keyUpEvent.getNativeEvent();
int keyCode = event.getKeyCode();
if (!isFocusable()) {
cancelScrollingVelocityTimer();
} else if (isNavigationKey(keyCode)) {
if (keyCode == getNavigationDownKey()
|| keyCode == getNavigationUpKey()) {
/*
* in multiselect mode the server may still have value from
* previous page. Clear it unless doing multiselection or
* just moving focus.
*/
if (!event.getShiftKey() && !event.getCtrlKey()) {
instructServerToForgetPreviousSelections();
}
sendSelectedRows();
}
cancelScrollingVelocityTimer();
navKeyDown = false;
}
}
};
private KeyDownHandler navKeyDownHandler = new KeyDownHandler() {
public void onKeyDown(KeyDownEvent keyDownEvent) {
NativeEvent event = keyDownEvent.getNativeEvent();
// This is not used for Firefox
if (BrowserInfo.get().isGecko()) {
return;
}
if (!enabled) {
// Cancel default keyboard events on a disabled Table
// (prevents scrolling)
event.preventDefault();
} else if (hasFocus) {
if (handleNavigation(event.getKeyCode(), event.getCtrlKey()
|| event.getMetaKey(), event.getShiftKey())) {
navKeyDown = true;
event.preventDefault();
}
startScrollingVelocityTimer();
}
}
};
private int totalRows;
private Set<String> collapsedColumns;
private final RowRequestHandler rowRequestHandler;
private VScrollTableBody scrollBody;
private int firstvisible = 0;
private boolean sortAscending;
private String sortColumn;
private String oldSortColumn;
private boolean columnReordering;
/**
* This map contains captions and icon urls for actions like: * "33_c" ->
* "Edit" * "33_i" -> "http://dom.com/edit.png"
*/
private final HashMap<Object, String> actionMap = new HashMap<Object, String>();
private String[] visibleColOrder;
private boolean initialContentReceived = false;
private Element scrollPositionElement;
private boolean enabled;
private boolean showColHeaders;
private boolean showColFooters;
/** flag to indicate that table body has changed */
private boolean isNewBody = true;
/*
* Read from the "recalcWidths" -attribute. When it is true, the table will
* recalculate the widths for columns - desirable in some cases. For #1983,
* marked experimental.
*/
boolean recalcWidths = false;
private final ArrayList<Panel> lazyUnregistryBag = new ArrayList<Panel>();
private String height;
private String width = "";
private boolean rendering = false;
private boolean hasFocus = false;
private int dragmode;
private int multiselectmode;
private int tabIndex;
private TouchScrollDelegate touchScrollDelegate;
private int lastRenderedHeight;
/**
* Values (serverCacheFirst+serverCacheLast) sent by server that tells which
* rows (indexes) are in the server side cache (page buffer). -1 means
* unknown. The server side cache row MUST MATCH the client side cache rows.
*
* If the client side cache contains additional rows with e.g. buttons, it
* will cause out of sync when such a button is pressed.
*
* If the server side cache contains additional rows with e.g. buttons,
* scrolling in the client will cause empty buttons to be rendered
* (cached=true request for non-existing components)
*/
private int serverCacheFirst = -1;
private int serverCacheLast = -1;
/**
* Used to recall the position of an open context menu if we need to close
* and reopen it during a row update.
*/
private class ContextMenuDetails {
String rowKey;
int left;
int top;
ContextMenuDetails(String rowKey, int left, int top) {
this.rowKey = rowKey;
this.left = left;
this.top = top;
}
}
ContextMenuDetails contextMenu;
public VScrollTable() {
setMultiSelectMode(MULTISELECT_MODE_DEFAULT);
scrollBodyPanel.setStyleName(CLASSNAME + "-body-wrapper");
scrollBodyPanel.addFocusHandler(this);
scrollBodyPanel.addBlurHandler(this);
scrollBodyPanel.addScrollHandler(this);
scrollBodyPanel.setStyleName(CLASSNAME + "-body");
/*
* Firefox auto-repeat works correctly only if we use a key press
* handler, other browsers handle it correctly when using a key down
* handler
*/
if (BrowserInfo.get().isGecko()) {
scrollBodyPanel.addKeyPressHandler(navKeyPressHandler);
} else {
scrollBodyPanel.addKeyDownHandler(navKeyDownHandler);
}
scrollBodyPanel.addKeyUpHandler(navKeyUpHandler);
scrollBodyPanel.sinkEvents(Event.TOUCHEVENTS);
scrollBodyPanel.addDomHandler(new TouchStartHandler() {
public void onTouchStart(TouchStartEvent event) {
getTouchScrollDelegate().onTouchStart(event);
}
}, TouchStartEvent.getType());
scrollBodyPanel.sinkEvents(Event.ONCONTEXTMENU);
scrollBodyPanel.addDomHandler(new ContextMenuHandler() {
public void onContextMenu(ContextMenuEvent event) {
handleBodyContextMenu(event);
}
}, ContextMenuEvent.getType());
setStyleName(CLASSNAME);
add(tHead);
add(scrollBodyPanel);
add(tFoot);
rowRequestHandler = new RowRequestHandler();
}
protected TouchScrollDelegate getTouchScrollDelegate() {
if (touchScrollDelegate == null) {
touchScrollDelegate = new TouchScrollDelegate(
scrollBodyPanel.getElement());
touchScrollDelegate.setScrollHandler(this);
}
return touchScrollDelegate;
}
private void handleBodyContextMenu(ContextMenuEvent event) {
if (enabled && bodyActionKeys != null) {
int left = Util.getTouchOrMouseClientX(event.getNativeEvent());
int top = Util.getTouchOrMouseClientY(event.getNativeEvent());
top += Window.getScrollTop();
left += Window.getScrollLeft();
client.getContextMenu().showAt(this, left, top);
// Only prevent browser context menu if there are action handlers
// registered
event.stopPropagation();
event.preventDefault();
}
}
/**
* Fires a column resize event which sends the resize information to the
* server.
*
* @param columnId
* The columnId of the column which was resized
* @param originalWidth
* The width in pixels of the column before the resize event
* @param newWidth
* The width in pixels of the column after the resize event
*/
private void fireColumnResizeEvent(String columnId, int originalWidth,
int newWidth) {
client.updateVariable(paintableId, "columnResizeEventColumn", columnId,
false);
client.updateVariable(paintableId, "columnResizeEventPrev",
originalWidth, false);
client.updateVariable(paintableId, "columnResizeEventCurr", newWidth,
immediate);
}
/**
* Non-immediate variable update of column widths for a collection of
* columns.
*
* @param columns
* the columns to trigger the events for.
*/
private void sendColumnWidthUpdates(Collection<HeaderCell> columns) {
String[] newSizes = new String[columns.size()];
int ix = 0;
for (HeaderCell cell : columns) {
newSizes[ix++] = cell.getColKey() + ":" + cell.getWidth();
}
client.updateVariable(paintableId, "columnWidthUpdates", newSizes,
false);
}
/**
* Moves the focus one step down
*
* @return Returns true if succeeded
*/
private boolean moveFocusDown() {
return moveFocusDown(0);
}
/**
* Moves the focus down by 1+offset rows
*
* @return Returns true if succeeded, else false if the selection could not
* be move downwards
*/
private boolean moveFocusDown(int offset) {
if (isSelectable()) {
if (focusedRow == null && scrollBody.iterator().hasNext()) {
// FIXME should focus first visible from top, not first rendered
// ??
return setRowFocus((VScrollTableRow) scrollBody.iterator()
.next());
} else {
VScrollTableRow next = getNextRow(focusedRow, offset);
if (next != null) {
return setRowFocus(next);
}
}
}
return false;
}
/**
* Moves the selection one step up
*
* @return Returns true if succeeded
*/
private boolean moveFocusUp() {
return moveFocusUp(0);
}
/**
* Moves the focus row upwards
*
* @return Returns true if succeeded, else false if the selection could not
* be move upwards
*
*/
private boolean moveFocusUp(int offset) {
if (isSelectable()) {
if (focusedRow == null && scrollBody.iterator().hasNext()) {
// FIXME logic is exactly the same as in moveFocusDown, should
// be the opposite??
return setRowFocus((VScrollTableRow) scrollBody.iterator()
.next());
} else {
VScrollTableRow prev = getPreviousRow(focusedRow, offset);
if (prev != null) {
return setRowFocus(prev);
} else {
VConsole.log("no previous available");
}
}
}
return false;
}
/**
* Selects a row where the current selection head is
*
* @param ctrlSelect
* Is the selection a ctrl+selection
* @param shiftSelect
* Is the selection a shift+selection
* @return Returns truw
*/
private void selectFocusedRow(boolean ctrlSelect, boolean shiftSelect) {
if (focusedRow != null) {
// Arrows moves the selection and clears previous selections
if (isSelectable() && !ctrlSelect && !shiftSelect) {
deselectAll();
focusedRow.toggleSelection();
selectionRangeStart = focusedRow;
} else if (isSelectable() && ctrlSelect && !shiftSelect) {
// Ctrl+arrows moves selection head
selectionRangeStart = focusedRow;
// No selection, only selection head is moved
} else if (isMultiSelectModeAny() && !ctrlSelect && shiftSelect) {
// Shift+arrows selection selects a range
focusedRow.toggleShiftSelection(shiftSelect);
}
}
}
/**
* Sends the selection to the server if changed since the last update/visit.
*/
protected void sendSelectedRows() {
sendSelectedRows(immediate);
}
/**
* Sends the selection to the server if it has been changed since the last
* update/visit.
*
* @param immediately
* set to true to immediately send the rows
*/
protected void sendSelectedRows(boolean immediately) {
// Don't send anything if selection has not changed
if (!selectionChanged) {
return;
}
// Reset selection changed flag
selectionChanged = false;
// Note: changing the immediateness of this might require changes to
// "clickEvent" immediateness also.
if (isMultiSelectModeDefault()) {
// Convert ranges to a set of strings
Set<String> ranges = new HashSet<String>();
for (SelectionRange range : selectedRowRanges) {
ranges.add(range.toString());
}
// Send the selected row ranges
client.updateVariable(paintableId, "selectedRanges",
ranges.toArray(new String[selectedRowRanges.size()]), false);
// clean selectedRowKeys so that they don't contain excess values
for (Iterator<String> iterator = selectedRowKeys.iterator(); iterator
.hasNext();) {
String key = iterator.next();
VScrollTableRow renderedRowByKey = getRenderedRowByKey(key);
if (renderedRowByKey != null) {
for (SelectionRange range : selectedRowRanges) {
if (range.inRange(renderedRowByKey)) {
iterator.remove();
}
}
} else {
// orphaned selected key, must be in a range, ignore
iterator.remove();
}
}
}
// Send the selected rows
client.updateVariable(paintableId, "selected",
selectedRowKeys.toArray(new String[selectedRowKeys.size()]),
immediately);
}
/**
* Get the key that moves the selection head upwards. By default it is the
* up arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationUpKey() {
return KeyCodes.KEY_UP;
}
/**
* Get the key that moves the selection head downwards. By default it is the
* down arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationDownKey() {
return KeyCodes.KEY_DOWN;
}
/**
* Get the key that scrolls to the left in the table. By default it is the
* left arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationLeftKey() {
return KeyCodes.KEY_LEFT;
}
/**
* Get the key that scroll to the right on the table. By default it is the
* right arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationRightKey() {
return KeyCodes.KEY_RIGHT;
}
/**
* Get the key that selects an item in the table. By default it is the space
* bar key but by overriding this you can change the key to whatever you
* want.
*
* @return
*/
protected int getNavigationSelectKey() {
return CHARCODE_SPACE;
}
/**
* Get the key the moves the selection one page up in the table. By default
* this is the Page Up key but by overriding this you can change the key to
* whatever you want.
*
* @return
*/
protected int getNavigationPageUpKey() {
return KeyCodes.KEY_PAGEUP;
}
/**
* Get the key the moves the selection one page down in the table. By
* default this is the Page Down key but by overriding this you can change
* the key to whatever you want.
*
* @return
*/
protected int getNavigationPageDownKey() {
return KeyCodes.KEY_PAGEDOWN;
}
/**
* Get the key the moves the selection to the beginning of the table. By
* default this is the Home key but by overriding this you can change the
* key to whatever you want.
*
* @return
*/
protected int getNavigationStartKey() {
return KeyCodes.KEY_HOME;
}
/**
* Get the key the moves the selection to the end of the table. By default
* this is the End key but by overriding this you can change the key to
* whatever you want.
*
* @return
*/
protected int getNavigationEndKey() {
return KeyCodes.KEY_END;
}
/*
* (non-Javadoc)
*
* @see
* com.vaadin.terminal.gwt.client.Paintable#updateFromUIDL(com.vaadin.terminal
* .gwt.client.UIDL, com.vaadin.terminal.gwt.client.ApplicationConnection)
*/
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
rendering = true;
// On the first rendering, add a handler to clear saved context menu
// details when the menu closes. See #8526.
if (this.client == null) {
client.getContextMenu().addCloseHandler(
new CloseHandler<PopupPanel>() {
public void onClose(CloseEvent<PopupPanel> event) {
contextMenu = null;
}
});
}
// If a row has an open context menu, it will be closed as the row is
// detached. Retain a reference here so we can restore the menu if
// required.
ContextMenuDetails savedContextMenu = contextMenu;
if (uidl.hasAttribute(ATTRIBUTE_PAGEBUFFER_FIRST)) {
serverCacheFirst = uidl.getIntAttribute(ATTRIBUTE_PAGEBUFFER_FIRST);
serverCacheLast = uidl.getIntAttribute(ATTRIBUTE_PAGEBUFFER_LAST);
} else {
serverCacheFirst = -1;
serverCacheLast = -1;
}
/*
* We need to do this before updateComponent since updateComponent calls
* this.setHeight() which will calculate a new body height depending on
* the space available.
*/
if (uidl.hasAttribute("colfooters")) {
showColFooters = uidl.getBooleanAttribute("colfooters");
}
tFoot.setVisible(showColFooters);
if (client.updateComponent(this, uidl, true)) {
rendering = false;
return;
}
enabled = !uidl.hasAttribute("disabled");
if (BrowserInfo.get().isIE8() && !enabled) {
/*
* The disabled shim will not cover the table body if it is relative
* in IE8. See #7324
*/
scrollBodyPanel.getElement().getStyle()
.setPosition(Position.STATIC);
} else if (BrowserInfo.get().isIE8()) {
scrollBodyPanel.getElement().getStyle()
.setPosition(Position.RELATIVE);
}
this.client = client;
paintableId = uidl.getStringAttribute("id");
immediate = uidl.getBooleanAttribute("immediate");
int previousTotalRows = totalRows;
updateTotalRows(uidl);
boolean totalRowsChanged = (totalRows != previousTotalRows);
updateDragMode(uidl);
updateSelectionProperties(uidl);
if (uidl.hasAttribute("alb")) {
bodyActionKeys = uidl.getStringArrayAttribute("alb");
} else {
// Need to clear the actions if the action handlers have been
// removed
bodyActionKeys = null;
}
setCacheRateFromUIDL(uidl);
recalcWidths = uidl.hasAttribute("recalcWidths");
if (recalcWidths) {
tHead.clear();
tFoot.clear();
}
updatePageLength(uidl);
updateFirstVisibleAndScrollIfNeeded(uidl);
showRowHeaders = uidl.getBooleanAttribute("rowheaders");
showColHeaders = uidl.getBooleanAttribute("colheaders");
updateSortingProperties(uidl);
boolean keyboardSelectionOverRowFetchInProgress = selectSelectedRows(uidl);
updateActionMap(uidl);
updateColumnProperties(uidl);
UIDL ac = uidl.getChildByTagName("-ac");
if (ac == null) {
if (dropHandler != null) {
// remove dropHandler if not present anymore
dropHandler = null;
}
} else {
if (dropHandler == null) {
dropHandler = new VScrollTableDropHandler();
}
dropHandler.updateAcceptRules(ac);
}
UIDL partialRowAdditions = uidl.getChildByTagName("prows");
UIDL partialRowUpdates = uidl.getChildByTagName("urows");
if (partialRowUpdates != null || partialRowAdditions != null) {
// we may have pending cache row fetch, cancel it. See #2136
rowRequestHandler.cancel();
updateRowsInBody(partialRowUpdates);
addAndRemoveRows(partialRowAdditions);
} else {
UIDL rowData = uidl.getChildByTagName("rows");
if (rowData != null) {
// we may have pending cache row fetch, cancel it. See #2136
rowRequestHandler.cancel();
if (!recalcWidths && initializedAndAttached) {
updateBody(rowData, uidl.getIntAttribute("firstrow"),
uidl.getIntAttribute("rows"));
if (headerChangedDuringUpdate) {
triggerLazyColumnAdjustment(true);
} else if (!isScrollPositionVisible()
|| totalRowsChanged
|| lastRenderedHeight != scrollBody
.getOffsetHeight()) {
// webkits may still bug with their disturbing scrollbar
// bug, see #3457
// Run overflow fix for the scrollable area
// #6698 - If there's a scroll going on, don't abort it
// by changing overflows as the length of the contents
// *shouldn't* have changed (unless the number of rows
// or the height of the widget has also changed)
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel
.getElement());
}
});
}
} else {
initializeRows(uidl, rowData);
}
}
}
// If a row had an open context menu before the update, and after the
// update there's a row with the same key as that row, restore the
// context menu. See #8526.
if (enabled && savedContextMenu != null) {
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (row.isVisible()
&& row.getKey().equals(savedContextMenu.rowKey)) {
contextMenu = savedContextMenu;
client.getContextMenu().showAt(row, savedContextMenu.left,
savedContextMenu.top);
}
}
}
if (!isSelectable()) {
scrollBody.addStyleName(CLASSNAME + "-body-noselection");
} else {
scrollBody.removeStyleName(CLASSNAME + "-body-noselection");
}
hideScrollPositionAnnotation();
purgeUnregistryBag();
// selection is no in sync with server, avoid excessive server visits by
// clearing to flag used during the normal operation
if (!keyboardSelectionOverRowFetchInProgress) {
selectionChanged = false;
}
/*
* This is called when the Home or page up button has been pressed in
* selectable mode and the next selected row was not yet rendered in the
* client
*/
if (selectFirstItemInNextRender || focusFirstItemInNextRender) {
selectFirstRenderedRowInViewPort(focusFirstItemInNextRender);
selectFirstItemInNextRender = focusFirstItemInNextRender = false;
}
/*
* This is called when the page down or end button has been pressed in
* selectable mode and the next selected row was not yet rendered in the
* client
*/
if (selectLastItemInNextRender || focusLastItemInNextRender) {
selectLastRenderedRowInViewPort(focusLastItemInNextRender);
selectLastItemInNextRender = focusLastItemInNextRender = false;
}
multiselectPending = false;
if (focusedRow != null) {
if (!focusedRow.isAttached() && !rowRequestHandler.isRunning()) {
// focused row has been orphaned, can't focus
focusRowFromBody();
}
}
tabIndex = uidl.hasAttribute("tabindex") ? uidl
.getIntAttribute("tabindex") : 0;
setProperTabIndex();
resizeSortedColumnForSortIndicator();
// Remember this to detect situations where overflow hack might be
// needed during scrolling
lastRenderedHeight = scrollBody.getOffsetHeight();
rendering = false;
headerChangedDuringUpdate = false;
}
private void initializeRows(UIDL uidl, UIDL rowData) {
if (scrollBody != null) {
scrollBody.removeFromParent();
lazyUnregistryBag.add(scrollBody);
}
scrollBody = createScrollBody();
scrollBody.renderInitialRows(rowData, uidl.getIntAttribute("firstrow"),
uidl.getIntAttribute("rows"));
scrollBodyPanel.add(scrollBody);
// New body starts scrolled to the left, make sure the header and footer
// are also scrolled to the left
tHead.setHorizontalScrollPosition(0);
tFoot.setHorizontalScrollPosition(0);
initialContentReceived = true;
if (isAttached()) {
sizeInit();
}
scrollBody.restoreRowVisibility();
}
private void updateColumnProperties(UIDL uidl) {
updateColumnOrder(uidl);
updateCollapsedColumns(uidl);
UIDL vc = uidl.getChildByTagName("visiblecolumns");
if (vc != null) {
tHead.updateCellsFromUIDL(vc);
tFoot.updateCellsFromUIDL(vc);
}
updateHeader(uidl.getStringArrayAttribute("vcolorder"));
updateFooter(uidl.getStringArrayAttribute("vcolorder"));
}
private void updateCollapsedColumns(UIDL uidl) {
if (uidl.hasVariable("collapsedcolumns")) {
tHead.setColumnCollapsingAllowed(true);
collapsedColumns = uidl
.getStringArrayVariableAsSet("collapsedcolumns");
} else {
tHead.setColumnCollapsingAllowed(false);
}
}
private void updateColumnOrder(UIDL uidl) {
if (uidl.hasVariable("columnorder")) {
columnReordering = true;
columnOrder = uidl.getStringArrayVariable("columnorder");
} else {
columnReordering = false;
columnOrder = null;
}
}
private boolean selectSelectedRows(UIDL uidl) {
boolean keyboardSelectionOverRowFetchInProgress = false;
if (uidl.hasVariable("selected")) {
final Set<String> selectedKeys = uidl
.getStringArrayVariableAsSet("selected");
if (scrollBody != null) {
Iterator<Widget> iterator = scrollBody.iterator();
while (iterator.hasNext()) {
/*
* Make the focus reflect to the server side state unless we
* are currently selecting multiple rows with keyboard.
*/
VScrollTableRow row = (VScrollTableRow) iterator.next();
boolean selected = selectedKeys.contains(row.getKey());
if (!selected
&& unSyncedselectionsBeforeRowFetch != null
&& unSyncedselectionsBeforeRowFetch.contains(row
.getKey())) {
selected = true;
keyboardSelectionOverRowFetchInProgress = true;
}
if (selected != row.isSelected()) {
row.toggleSelection();
if (!isSingleSelectMode() && !selected) {
// Update selection range in case a row is
// unselected from the middle of a range - #8076
removeRowFromUnsentSelectionRanges(row);
}
}
}
}
}
unSyncedselectionsBeforeRowFetch = null;
return keyboardSelectionOverRowFetchInProgress;
}
private void updateSortingProperties(UIDL uidl) {
oldSortColumn = sortColumn;
if (uidl.hasVariable("sortascending")) {
sortAscending = uidl.getBooleanVariable("sortascending");
sortColumn = uidl.getStringVariable("sortcolumn");
}
}
private void resizeSortedColumnForSortIndicator() {
// Force recalculation of the captionContainer element inside the header
// cell to accomodate for the size of the sort arrow.
HeaderCell sortedHeader = tHead.getHeaderCell(sortColumn);
if (sortedHeader != null) {
tHead.resizeCaptionContainer(sortedHeader);
}
// Also recalculate the width of the captionContainer element in the
// previously sorted header, since this now has more room.
HeaderCell oldSortedHeader = tHead.getHeaderCell(oldSortColumn);
if (oldSortedHeader != null) {
tHead.resizeCaptionContainer(oldSortedHeader);
}
}
private void updateFirstVisibleAndScrollIfNeeded(UIDL uidl) {
firstvisible = uidl.hasVariable("firstvisible") ? uidl
.getIntVariable("firstvisible") : 0;
if (firstvisible != lastRequestedFirstvisible && scrollBody != null) {
// received 'surprising' firstvisible from server: scroll there
firstRowInViewPort = firstvisible;
scrollBodyPanel
.setScrollPosition(measureRowHeightOffset(firstvisible));
}
}
protected int measureRowHeightOffset(int rowIx) {
return (int) (rowIx * scrollBody.getRowHeight());
}
private void updatePageLength(UIDL uidl) {
int oldPageLength = pageLength;
if (uidl.hasAttribute("pagelength")) {
pageLength = uidl.getIntAttribute("pagelength");
} else {
// pagelenght is "0" meaning scrolling is turned off
pageLength = totalRows;
}
if (oldPageLength != pageLength && initializedAndAttached) {
// page length changed, need to update size
sizeInit();
}
}
private void updateSelectionProperties(UIDL uidl) {
setMultiSelectMode(uidl.hasAttribute("multiselectmode") ? uidl
.getIntAttribute("multiselectmode") : MULTISELECT_MODE_DEFAULT);
nullSelectionAllowed = uidl.hasAttribute("nsa") ? uidl
.getBooleanAttribute("nsa") : true;
if (uidl.hasAttribute("selectmode")) {
if (uidl.getBooleanAttribute("readonly")) {
selectMode = Table.SELECT_MODE_NONE;
} else if (uidl.getStringAttribute("selectmode").equals("multi")) {
selectMode = Table.SELECT_MODE_MULTI;
} else if (uidl.getStringAttribute("selectmode").equals("single")) {
selectMode = Table.SELECT_MODE_SINGLE;
} else {
selectMode = Table.SELECT_MODE_NONE;
}
}
}
private void updateDragMode(UIDL uidl) {
dragmode = uidl.hasAttribute("dragmode") ? uidl
.getIntAttribute("dragmode") : 0;
if (BrowserInfo.get().isIE()) {
if (dragmode > 0) {
getElement().setPropertyJSO("onselectstart",
getPreventTextSelectionIEHack());
} else {
getElement().setPropertyJSO("onselectstart", null);
}
}
}
protected void updateTotalRows(UIDL uidl) {
int newTotalRows = uidl.getIntAttribute("totalrows");
if (newTotalRows != getTotalRows()) {
if (scrollBody != null) {
if (getTotalRows() == 0) {
tHead.clear();
tFoot.clear();
}
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
setTotalRows(newTotalRows);
}
}
protected void setTotalRows(int newTotalRows) {
totalRows = newTotalRows;
}
protected int getTotalRows() {
return totalRows;
}
private void focusRowFromBody() {
if (selectedRowKeys.size() == 1) {
// try to focus a row currently selected and in viewport
String selectedRowKey = selectedRowKeys.iterator().next();
if (selectedRowKey != null) {
VScrollTableRow renderedRow = getRenderedRowByKey(selectedRowKey);
if (renderedRow == null || !renderedRow.isInViewPort()) {
setRowFocus(scrollBody.getRowByRowIndex(firstRowInViewPort));
} else {
setRowFocus(renderedRow);
}
}
} else {
// multiselect mode
setRowFocus(scrollBody.getRowByRowIndex(firstRowInViewPort));
}
}
protected VScrollTableBody createScrollBody() {
return new VScrollTableBody();
}
/**
* Selects the last row visible in the table
*
* @param focusOnly
* Should the focus only be moved to the last row
*/
private void selectLastRenderedRowInViewPort(boolean focusOnly) {
int index = firstRowInViewPort + getFullyVisibleRowCount();
VScrollTableRow lastRowInViewport = scrollBody.getRowByRowIndex(index);
if (lastRowInViewport == null) {
// this should not happen in normal situations (white space at the
// end of viewport). Select the last rendered as a fallback.
lastRowInViewport = scrollBody.getRowByRowIndex(scrollBody
.getLastRendered());
if (lastRowInViewport == null) {
return; // empty table
}
}
setRowFocus(lastRowInViewport);
if (!focusOnly) {
selectFocusedRow(false, multiselectPending);
sendSelectedRows();
}
}
/**
* Selects the first row visible in the table
*
* @param focusOnly
* Should the focus only be moved to the first row
*/
private void selectFirstRenderedRowInViewPort(boolean focusOnly) {
int index = firstRowInViewPort;
VScrollTableRow firstInViewport = scrollBody.getRowByRowIndex(index);
if (firstInViewport == null) {
// this should not happen in normal situations
return;
}
setRowFocus(firstInViewport);
if (!focusOnly) {
selectFocusedRow(false, multiselectPending);
sendSelectedRows();
}
}
private void setCacheRateFromUIDL(UIDL uidl) {
setCacheRate(uidl.hasAttribute("cr") ? uidl.getDoubleAttribute("cr")
: CACHE_RATE_DEFAULT);
}
private void setCacheRate(double d) {
if (cache_rate != d) {
cache_rate = d;
cache_react_rate = 0.75 * d;
}
}
/**
* Unregisters Paintables in "trashed" HasWidgets (IScrollTableBodys or
* IScrollTableRows). This is done lazily as Table must survive from
* "subtreecaching" logic.
*/
private void purgeUnregistryBag() {
for (Iterator<Panel> iterator = lazyUnregistryBag.iterator(); iterator
.hasNext();) {
client.unregisterChildPaintables(iterator.next());
}
lazyUnregistryBag.clear();
}
private void updateActionMap(UIDL mainUidl) {
UIDL actionsUidl = mainUidl.getChildByTagName("actions");
if (actionsUidl == null) {
return;
}
final Iterator<?> it = actionsUidl.getChildIterator();
while (it.hasNext()) {
final UIDL action = (UIDL) it.next();
final String key = action.getStringAttribute("key");
final String caption = action.getStringAttribute("caption");
actionMap.put(key + "_c", caption);
if (action.hasAttribute("icon")) {
// TODO need some uri handling ??
actionMap.put(key + "_i", client.translateVaadinUri(action
.getStringAttribute("icon")));
} else {
actionMap.remove(key + "_i");
}
}
}
public String getActionCaption(String actionKey) {
return actionMap.get(actionKey + "_c");
}
public String getActionIcon(String actionKey) {
return actionMap.get(actionKey + "_i");
}
private void updateHeader(String[] strings) {
if (strings == null) {
return;
}
int visibleCols = strings.length;
int colIndex = 0;
if (showRowHeaders) {
tHead.enableColumn(ROW_HEADER_COLUMN_KEY, colIndex);
visibleCols++;
visibleColOrder = new String[visibleCols];
visibleColOrder[colIndex] = ROW_HEADER_COLUMN_KEY;
colIndex++;
} else {
visibleColOrder = new String[visibleCols];
tHead.removeCell(ROW_HEADER_COLUMN_KEY);
}
int i;
for (i = 0; i < strings.length; i++) {
final String cid = strings[i];
visibleColOrder[colIndex] = cid;
tHead.enableColumn(cid, colIndex);
colIndex++;
}
tHead.setVisible(showColHeaders);
setContainerHeight();
}
/**
* Updates footers.
* <p>
* Update headers whould be called before this method is called!
* </p>
*
* @param strings
*/
private void updateFooter(String[] strings) {
if (strings == null) {
return;
}
// Add dummy column if row headers are present
int colIndex = 0;
if (showRowHeaders) {
tFoot.enableColumn(ROW_HEADER_COLUMN_KEY, colIndex);
colIndex++;
} else {
tFoot.removeCell(ROW_HEADER_COLUMN_KEY);
}
int i;
for (i = 0; i < strings.length; i++) {
final String cid = strings[i];
tFoot.enableColumn(cid, colIndex);
colIndex++;
}
tFoot.setVisible(showColFooters);
}
/**
* @param uidl
* which contains row data
* @param firstRow
* first row in data set
* @param reqRows
* amount of rows in data set
*/
private void updateBody(UIDL uidl, int firstRow, int reqRows) {
if (uidl == null || reqRows < 1) {
// container is empty, remove possibly existing rows
if (firstRow <= 0) {
while (scrollBody.getLastRendered() > scrollBody.firstRendered) {
scrollBody.unlinkRow(false);
}
scrollBody.unlinkRow(false);
}
return;
}
scrollBody.renderRows(uidl, firstRow, reqRows);
discardRowsOutsideCacheWindow();
}
private void updateRowsInBody(UIDL partialRowUpdates) {
if (partialRowUpdates == null) {
return;
}
int firstRowIx = partialRowUpdates.getIntAttribute("firsturowix");
int count = partialRowUpdates.getIntAttribute("numurows");
scrollBody.unlinkRows(firstRowIx, count);
scrollBody.insertRows(partialRowUpdates, firstRowIx, count);
}
/**
* Updates the internal cache by unlinking rows that fall outside of the
* caching window.
*/
protected void discardRowsOutsideCacheWindow() {
int firstRowToKeep = (int) (firstRowInViewPort - pageLength
* cache_rate);
int lastRowToKeep = (int) (firstRowInViewPort + pageLength + pageLength
* cache_rate);
debug("Client side calculated cache rows to keep: " + firstRowToKeep
+ "-" + lastRowToKeep);
if (serverCacheFirst != -1) {
firstRowToKeep = serverCacheFirst;
lastRowToKeep = serverCacheLast;
debug("Server cache rows that override: " + serverCacheFirst + "-"
+ serverCacheLast);
if (firstRowToKeep < scrollBody.getFirstRendered()
|| lastRowToKeep > scrollBody.getLastRendered()) {
debug("*** Server wants us to keep " + serverCacheFirst + "-"
+ serverCacheLast + " but we only have rows "
+ scrollBody.getFirstRendered() + "-"
+ scrollBody.getLastRendered() + " rendered!");
}
}
discardRowsOutsideOf(firstRowToKeep, lastRowToKeep);
scrollBody.fixSpacers();
scrollBody.restoreRowVisibility();
}
private void discardRowsOutsideOf(int optimalFirstRow, int optimalLastRow) {
/*
* firstDiscarded and lastDiscarded are only calculated for debug
* purposes
*/
int firstDiscarded = -1, lastDiscarded = -1;
boolean cont = true;
while (cont && scrollBody.getLastRendered() > optimalFirstRow
&& scrollBody.getFirstRendered() < optimalFirstRow) {
if (firstDiscarded == -1) {
firstDiscarded = scrollBody.getFirstRendered();
}
// removing row from start
cont = scrollBody.unlinkRow(true);
}
if (firstDiscarded != -1) {
lastDiscarded = scrollBody.getFirstRendered() - 1;
debug("Discarded rows " + firstDiscarded + "-" + lastDiscarded);
}
firstDiscarded = lastDiscarded = -1;
cont = true;
while (cont && scrollBody.getLastRendered() > optimalLastRow) {
if (lastDiscarded == -1) {
lastDiscarded = scrollBody.getLastRendered();
}
// removing row from the end
cont = scrollBody.unlinkRow(false);
}
if (lastDiscarded != -1) {
firstDiscarded = scrollBody.getLastRendered() + 1;
debug("Discarded rows " + firstDiscarded + "-" + lastDiscarded);
}
debug("Now in cache: " + scrollBody.getFirstRendered() + "-"
+ scrollBody.getLastRendered());
}
/**
* Inserts rows in the table body or removes them from the table body based
* on the commands in the UIDL.
*
* @param partialRowAdditions
* the UIDL containing row updates.
*/
protected void addAndRemoveRows(UIDL partialRowAdditions) {
if (partialRowAdditions == null) {
return;
}
if (partialRowAdditions.hasAttribute("hide")) {
scrollBody.unlinkAndReindexRows(
partialRowAdditions.getIntAttribute("firstprowix"),
partialRowAdditions.getIntAttribute("numprows"));
scrollBody.ensureCacheFilled();
} else {
if (partialRowAdditions.hasAttribute("delbelow")) {
scrollBody.insertRowsDeleteBelow(partialRowAdditions,
partialRowAdditions.getIntAttribute("firstprowix"),
partialRowAdditions.getIntAttribute("numprows"));
} else {
scrollBody.insertAndReindexRows(partialRowAdditions,
partialRowAdditions.getIntAttribute("firstprowix"),
partialRowAdditions.getIntAttribute("numprows"));
}
}
discardRowsOutsideCacheWindow();
}
/**
* Gives correct column index for given column key ("cid" in UIDL).
*
* @param colKey
* @return column index of visible columns, -1 if column not visible
*/
private int getColIndexByKey(String colKey) {
// return 0 if asked for rowHeaders
if (ROW_HEADER_COLUMN_KEY.equals(colKey)) {
return 0;
}
for (int i = 0; i < visibleColOrder.length; i++) {
if (visibleColOrder[i].equals(colKey)) {
return i;
}
}
return -1;
}
private boolean isMultiSelectModeSimple() {
return selectMode == Table.SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_SIMPLE;
}
private boolean isSingleSelectMode() {
return selectMode == Table.SELECT_MODE_SINGLE;
}
private boolean isMultiSelectModeAny() {
return selectMode == Table.SELECT_MODE_MULTI;
}
private boolean isMultiSelectModeDefault() {
return selectMode == Table.SELECT_MODE_MULTI
&& multiselectmode == MULTISELECT_MODE_DEFAULT;
}
private void setMultiSelectMode(int multiselectmode) {
if (BrowserInfo.get().isTouchDevice()) {
// Always use the simple mode for touch devices that do not have
// shift/ctrl keys
this.multiselectmode = MULTISELECT_MODE_SIMPLE;
} else {
this.multiselectmode = multiselectmode;
}
}
protected boolean isSelectable() {
return selectMode > Table.SELECT_MODE_NONE;
}
private boolean isCollapsedColumn(String colKey) {
if (collapsedColumns == null) {
return false;
}
if (collapsedColumns.contains(colKey)) {
return true;
}
return false;
}
private String getColKeyByIndex(int index) {
return tHead.getHeaderCell(index).getColKey();
}
private void setColWidth(int colIndex, int w, boolean isDefinedWidth) {
final HeaderCell hcell = tHead.getHeaderCell(colIndex);
// Make sure that the column grows to accommodate the sort indicator if
// necessary.
if (w < hcell.getMinWidth()) {
w = hcell.getMinWidth();
}
// Set header column width
hcell.setWidth(w, isDefinedWidth);
// Ensure indicators have been taken into account
tHead.resizeCaptionContainer(hcell);
// Set body column width
scrollBody.setColWidth(colIndex, w);
// Set footer column width
FooterCell fcell = tFoot.getFooterCell(colIndex);
fcell.setWidth(w, isDefinedWidth);
}
private int getColWidth(String colKey) {
return tHead.getHeaderCell(colKey).getWidth();
}
/**
* Get a rendered row by its key
*
* @param key
* The key to search with
* @return
*/
protected VScrollTableRow getRenderedRowByKey(String key) {
if (scrollBody != null) {
final Iterator<Widget> it = scrollBody.iterator();
VScrollTableRow r = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (r.getKey().equals(key)) {
return r;
}
}
}
return null;
}
/**
* Returns the next row to the given row
*
* @param row
* The row to calculate from
*
* @return The next row or null if no row exists
*/
private VScrollTableRow getNextRow(VScrollTableRow row, int offset) {
final Iterator<Widget> it = scrollBody.iterator();
VScrollTableRow r = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (r == row) {
r = null;
while (offset >= 0 && it.hasNext()) {
r = (VScrollTableRow) it.next();
offset--;
}
return r;
}
}
return null;
}
/**
* Returns the previous row from the given row
*
* @param row
* The row to calculate from
* @return The previous row or null if no row exists
*/
private VScrollTableRow getPreviousRow(VScrollTableRow row, int offset) {
final Iterator<Widget> it = scrollBody.iterator();
final Iterator<Widget> offsetIt = scrollBody.iterator();
VScrollTableRow r = null;
VScrollTableRow prev = null;
while (it.hasNext()) {
r = (VScrollTableRow) it.next();
if (offset < 0) {
prev = (VScrollTableRow) offsetIt.next();
}
if (r == row) {
return prev;
}
offset--;
}
return null;
}
protected void reOrderColumn(String columnKey, int newIndex) {
final int oldIndex = getColIndexByKey(columnKey);
// Change header order
tHead.moveCell(oldIndex, newIndex);
// Change body order
scrollBody.moveCol(oldIndex, newIndex);
// Change footer order
tFoot.moveCell(oldIndex, newIndex);
/*
* Build new columnOrder and update it to server Note that columnOrder
* also contains collapsed columns so we cannot directly build it from
* cells vector Loop the old columnOrder and append in order to new
* array unless on moved columnKey. On new index also put the moved key
* i == index on columnOrder, j == index on newOrder
*/
final String oldKeyOnNewIndex = visibleColOrder[newIndex];
if (showRowHeaders) {
newIndex--; // columnOrder don't have rowHeader
}
// add back hidden rows,
for (int i = 0; i < columnOrder.length; i++) {
if (columnOrder[i].equals(oldKeyOnNewIndex)) {
break; // break loop at target
}
if (isCollapsedColumn(columnOrder[i])) {
newIndex++;
}
}
// finally we can build the new columnOrder for server
final String[] newOrder = new String[columnOrder.length];
for (int i = 0, j = 0; j < newOrder.length; i++) {
if (j == newIndex) {
newOrder[j] = columnKey;
j++;
}
if (i == columnOrder.length) {
break;
}
if (columnOrder[i].equals(columnKey)) {
continue;
}
newOrder[j] = columnOrder[i];
j++;
}
columnOrder = newOrder;
// also update visibleColumnOrder
int i = showRowHeaders ? 1 : 0;
for (int j = 0; j < newOrder.length; j++) {
final String cid = newOrder[j];
if (!isCollapsedColumn(cid)) {
visibleColOrder[i++] = cid;
}
}
client.updateVariable(paintableId, "columnorder", columnOrder, false);
if (client.hasEventListeners(this, COLUMN_REORDER_EVENT_ID)) {
client.sendPendingVariableChanges();
}
}
@Override
protected void onAttach() {
super.onAttach();
if (initialContentReceived) {
sizeInit();
}
}
@Override
protected void onDetach() {
rowRequestHandler.cancel();
super.onDetach();
// ensure that scrollPosElement will be detached
if (scrollPositionElement != null) {
final Element parent = DOM.getParent(scrollPositionElement);
if (parent != null) {
DOM.removeChild(parent, scrollPositionElement);
}
}
}
/**
* Run only once when component is attached and received its initial
* content. This function:
*
* * Syncs headers and bodys "natural widths and saves the values.
*
* * Sets proper width and height
*
* * Makes deferred request to get some cache rows
*/
private void sizeInit() {
/*
* We will use browsers table rendering algorithm to find proper column
* widths. If content and header take less space than available, we will
* divide extra space relatively to each column which has not width set.
*
* Overflow pixels are added to last column.
*/
Iterator<Widget> headCells = tHead.iterator();
Iterator<Widget> footCells = tFoot.iterator();
int i = 0;
int totalExplicitColumnsWidths = 0;
int total = 0;
float expandRatioDivider = 0;
final int[] widths = new int[tHead.visibleCells.size()];
tHead.enableBrowserIntelligence();
tFoot.enableBrowserIntelligence();
// first loop: collect natural widths
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
final FooterCell fCell = (FooterCell) footCells.next();
int w = hCell.getWidth();
if (hCell.isDefinedWidth()) {
// server has defined column width explicitly
totalExplicitColumnsWidths += w;
} else {
if (hCell.getExpandRatio() > 0) {
expandRatioDivider += hCell.getExpandRatio();
w = 0;
} else {
// get and store greater of header width and column width,
// and
// store it as a minimumn natural col width
int headerWidth = hCell.getNaturalColumnWidth(i);
int footerWidth = fCell.getNaturalColumnWidth(i);
w = headerWidth > footerWidth ? headerWidth : footerWidth;
}
hCell.setNaturalMinimumColumnWidth(w);
fCell.setNaturalMinimumColumnWidth(w);
}
widths[i] = w;
total += w;
i++;
}
tHead.disableBrowserIntelligence();
tFoot.disableBrowserIntelligence();
boolean willHaveScrollbarz = willHaveScrollbars();
// fix "natural" width if width not set
if (width == null || "".equals(width)) {
int w = total;
w += scrollBody.getCellExtraWidth() * visibleColOrder.length;
if (willHaveScrollbarz) {
w += Util.getNativeScrollbarSize();
}
setContentWidth(w);
}
int availW = scrollBody.getAvailableWidth();
if (BrowserInfo.get().isIE()) {
// Hey IE, are you really sure about this?
availW = scrollBody.getAvailableWidth();
}
availW -= scrollBody.getCellExtraWidth() * visibleColOrder.length;
if (willHaveScrollbarz) {
availW -= Util.getNativeScrollbarSize();
}
// TODO refactor this code to be the same as in resize timer
boolean needsReLayout = false;
if (availW > total) {
// natural size is smaller than available space
final int extraSpace = availW - total;
final int totalWidthR = total - totalExplicitColumnsWidths;
int checksum = 0;
needsReLayout = true;
if (extraSpace == 1) {
// We cannot divide one single pixel so we give it the first
// undefined column
headCells = tHead.iterator();
i = 0;
checksum = availW;
while (headCells.hasNext()) {
HeaderCell hc = (HeaderCell) headCells.next();
if (!hc.isDefinedWidth()) {
widths[i]++;
break;
}
i++;
}
} else if (expandRatioDivider > 0) {
// visible columns have some active expand ratios, excess
// space is divided according to them
headCells = tHead.iterator();
i = 0;
while (headCells.hasNext()) {
HeaderCell hCell = (HeaderCell) headCells.next();
if (hCell.getExpandRatio() > 0) {
int w = widths[i];
final int newSpace = Math.round((extraSpace * (hCell
.getExpandRatio() / expandRatioDivider)));
w += newSpace;
widths[i] = w;
}
checksum += widths[i];
i++;
}
} else if (totalWidthR > 0) {
// no expand ratios defined, we will share extra space
// relatively to "natural widths" among those without
// explicit width
headCells = tHead.iterator();
i = 0;
while (headCells.hasNext()) {
HeaderCell hCell = (HeaderCell) headCells.next();
if (!hCell.isDefinedWidth()) {
int w = widths[i];
final int newSpace = Math.round((float) extraSpace
* (float) w / totalWidthR);
w += newSpace;
widths[i] = w;
}
checksum += widths[i];
i++;
}
}
if (extraSpace > 0 && checksum != availW) {
/*
* There might be in some cases a rounding error of 1px when
* extra space is divided so if there is one then we give the
* first undefined column 1 more pixel
*/
headCells = tHead.iterator();
i = 0;
while (headCells.hasNext()) {
HeaderCell hc = (HeaderCell) headCells.next();
if (!hc.isDefinedWidth()) {
widths[i] += availW - checksum;
break;
}
i++;
}
}
} else {
// bodys size will be more than available and scrollbar will appear
}
// last loop: set possibly modified values or reset if new tBody
i = 0;
headCells = tHead.iterator();
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
if (isNewBody || hCell.getWidth() == -1) {
final int w = widths[i];
setColWidth(i, w, false);
}
i++;
}
initializedAndAttached = true;
if (needsReLayout) {
scrollBody.reLayoutComponents();
}
updatePageLength();
/*
* Fix "natural" height if height is not set. This must be after width
* fixing so the components' widths have been adjusted.
*/
if (height == null || "".equals(height)) {
/*
* We must force an update of the row height as this point as it
* might have been (incorrectly) calculated earlier
*/
int bodyHeight;
if (pageLength == totalRows) {
/*
* A hack to support variable height rows when paging is off.
* Generally this is not supported by scrolltable. We want to
* show all rows so the bodyHeight should be equal to the table
* height.
*/
// int bodyHeight = scrollBody.getOffsetHeight();
bodyHeight = scrollBody.getRequiredHeight();
} else {
bodyHeight = (int) Math.round(scrollBody.getRowHeight(true)
* pageLength);
}
boolean needsSpaceForHorizontalSrollbar = (total > availW);
if (needsSpaceForHorizontalSrollbar) {
bodyHeight += Util.getNativeScrollbarSize();
}
scrollBodyPanel.setHeight(bodyHeight + "px");
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
isNewBody = false;
if (firstvisible > 0) {
// FIXME #7607
// Originally deferred due to Firefox oddities which should not
// occur any more. Currently deferring breaks Webkit scrolling with
// relative-height tables, but not deferring instead breaks tables
// with explicit page length.
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
scrollBodyPanel
.setScrollPosition(measureRowHeightOffset(firstvisible));
firstRowInViewPort = firstvisible;
}
});
}
if (enabled) {
// Do we need cache rows
if (scrollBody.getLastRendered() + 1 < firstRowInViewPort
+ pageLength + (int) cache_react_rate * pageLength) {
if (totalRows - 1 > scrollBody.getLastRendered()) {
// fetch cache rows
int firstInNewSet = scrollBody.getLastRendered() + 1;
rowRequestHandler.setReqFirstRow(firstInNewSet);
int lastInNewSet = (int) (firstRowInViewPort + pageLength + cache_rate
* pageLength);
if (lastInNewSet > totalRows - 1) {
lastInNewSet = totalRows - 1;
}
rowRequestHandler.setReqRows(lastInNewSet - firstInNewSet
+ 1);
rowRequestHandler.deferRowFetch(1);
}
}
}
/*
* Ensures the column alignments are correct at initial loading. <br/>
* (child components widths are correct)
*/
scrollBody.reLayoutComponents();
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
});
}
/**
* Note, this method is not official api although declared as protected.
* Extend at you own risk.
*
* @return true if content area will have scrollbars visible.
*/
protected boolean willHaveScrollbars() {
if (!(height != null && !height.equals(""))) {
if (pageLength < totalRows) {
return true;
}
} else {
int fakeheight = (int) Math.round(scrollBody.getRowHeight()
* totalRows);
int availableHeight = scrollBodyPanel.getElement().getPropertyInt(
"clientHeight");
if (fakeheight > availableHeight) {
return true;
}
}
return false;
}
private void announceScrollPosition() {
if (scrollPositionElement == null) {
scrollPositionElement = DOM.createDiv();
scrollPositionElement.setClassName(CLASSNAME + "-scrollposition");
scrollPositionElement.getStyle().setPosition(Position.ABSOLUTE);
scrollPositionElement.getStyle().setDisplay(Display.NONE);
getElement().appendChild(scrollPositionElement);
}
Style style = scrollPositionElement.getStyle();
style.setMarginLeft(getElement().getOffsetWidth() / 2 - 80, Unit.PX);
style.setMarginTop(-scrollBodyPanel.getOffsetHeight(), Unit.PX);
// indexes go from 1-totalRows, as rowheaders in index-mode indicate
int last = (firstRowInViewPort + pageLength);
if (last > totalRows) {
last = totalRows;
}
scrollPositionElement.setInnerHTML("<span>" + (firstRowInViewPort + 1)
+ " – " + (last) + "..." + "</span>");
style.setDisplay(Display.BLOCK);
}
private void hideScrollPositionAnnotation() {
if (scrollPositionElement != null) {
DOM.setStyleAttribute(scrollPositionElement, "display", "none");
}
}
private boolean isScrollPositionVisible() {
return scrollPositionElement != null
&& !scrollPositionElement.getStyle().getDisplay()
.equals(Display.NONE.toString());
}
private class RowRequestHandler extends Timer {
private int reqFirstRow = 0;
private int reqRows = 0;
private boolean isRunning = false;
public void deferRowFetch() {
deferRowFetch(250);
}
public boolean isRunning() {
return isRunning;
}
public void deferRowFetch(int msec) {
isRunning = true;
if (reqRows > 0 && reqFirstRow < totalRows) {
schedule(msec);
// tell scroll position to user if currently "visible" rows are
// not rendered
if (totalRows > pageLength
&& ((firstRowInViewPort + pageLength > scrollBody
.getLastRendered()) || (firstRowInViewPort < scrollBody
.getFirstRendered()))) {
announceScrollPosition();
} else {
hideScrollPositionAnnotation();
}
}
}
public void setReqFirstRow(int reqFirstRow) {
if (reqFirstRow < 0) {
reqFirstRow = 0;
} else if (reqFirstRow >= totalRows) {
reqFirstRow = totalRows - 1;
}
this.reqFirstRow = reqFirstRow;
}
public void setReqRows(int reqRows) {
this.reqRows = reqRows;
}
@Override
public void run() {
if (client.hasActiveRequest() || navKeyDown) {
// if client connection is busy, don't bother loading it more
VConsole.log("Postponed rowfetch");
schedule(250);
} else {
int firstToBeRendered = scrollBody.firstRendered;
if (reqFirstRow < firstToBeRendered) {
firstToBeRendered = reqFirstRow;
} else if (firstRowInViewPort - (int) (cache_rate * pageLength) > firstToBeRendered) {
firstToBeRendered = firstRowInViewPort
- (int) (cache_rate * pageLength);
if (firstToBeRendered < 0) {
firstToBeRendered = 0;
}
}
int lastToBeRendered = scrollBody.lastRendered;
if (reqFirstRow + reqRows - 1 > lastToBeRendered) {
lastToBeRendered = reqFirstRow + reqRows - 1;
} else if (firstRowInViewPort + pageLength + pageLength
* cache_rate < lastToBeRendered) {
lastToBeRendered = (firstRowInViewPort + pageLength + (int) (pageLength * cache_rate));
if (lastToBeRendered >= totalRows) {
lastToBeRendered = totalRows - 1;
}
// due Safari 3.1 bug (see #2607), verify reqrows, original
// problem unknown, but this should catch the issue
if (reqFirstRow + reqRows - 1 > lastToBeRendered) {
reqRows = lastToBeRendered - reqFirstRow;
}
}
client.updateVariable(paintableId, "firstToBeRendered",
firstToBeRendered, false);
client.updateVariable(paintableId, "lastToBeRendered",
lastToBeRendered, false);
// remember which firstvisible we requested, in case the server
// has
// a differing opinion
lastRequestedFirstvisible = firstRowInViewPort;
client.updateVariable(paintableId, "firstvisible",
firstRowInViewPort, false);
client.updateVariable(paintableId, "reqfirstrow", reqFirstRow,
false);
client.updateVariable(paintableId, "reqrows", reqRows, true);
if (selectionChanged) {
unSyncedselectionsBeforeRowFetch = new HashSet<Object>(
selectedRowKeys);
}
isRunning = false;
}
}
public int getReqFirstRow() {
return reqFirstRow;
}
/**
* Sends request to refresh content at this position.
*/
public void refreshContent() {
isRunning = true;
int first = (int) (firstRowInViewPort - pageLength * cache_rate);
int reqRows = (int) (2 * pageLength * cache_rate + pageLength);
if (first < 0) {
reqRows = reqRows + first;
first = 0;
}
setReqFirstRow(first);
setReqRows(reqRows);
run();
}
}
public class HeaderCell extends Widget {
Element td = DOM.createTD();
Element captionContainer = DOM.createDiv();
Element sortIndicator = DOM.createDiv();
Element colResizeWidget = DOM.createDiv();
Element floatingCopyOfHeaderCell;
private boolean sortable = false;
private final String cid;
private boolean dragging;
private int dragStartX;
private int colIndex;
private int originalWidth;
private boolean isResizing;
private int headerX;
private boolean moved;
private int closestSlot;
private int width = -1;
private int naturalWidth = -1;
private char align = ALIGN_LEFT;
boolean definedWidth = false;
private float expandRatio = 0;
private boolean sorted;
public void setSortable(boolean b) {
sortable = b;
}
/**
* Makes room for the sorting indicator in case the column that the
* header cell belongs to is sorted. This is done by resizing the width
* of the caption container element by the correct amount
*/
public void resizeCaptionContainer(int rightSpacing) {
int captionContainerWidth = width
- colResizeWidget.getOffsetWidth() - rightSpacing;
if (BrowserInfo.get().isIE6() || td.getClassName().contains("-asc")
|| td.getClassName().contains("-desc")) {
// Leave room for the sort indicator
captionContainerWidth -= sortIndicator.getOffsetWidth();
}
if (captionContainerWidth < 0) {
rightSpacing += captionContainerWidth;
captionContainerWidth = 0;
}
captionContainer.getStyle().setPropertyPx("width",
captionContainerWidth);
// Apply/Remove spacing if defined
if (rightSpacing > 0) {
colResizeWidget.getStyle().setMarginLeft(rightSpacing, Unit.PX);
} else {
colResizeWidget.getStyle().clearMarginLeft();
}
}
public void setNaturalMinimumColumnWidth(int w) {
naturalWidth = w;
}
public HeaderCell(String colId, String headerText) {
cid = colId;
DOM.setElementProperty(colResizeWidget, "className", CLASSNAME
+ "-resizer");
setText(headerText);
DOM.appendChild(td, colResizeWidget);
DOM.setElementProperty(sortIndicator, "className", CLASSNAME
+ "-sort-indicator");
DOM.appendChild(td, sortIndicator);
DOM.setElementProperty(captionContainer, "className", CLASSNAME
+ "-caption-container");
// ensure no clipping initially (problem on column additions)
DOM.setStyleAttribute(captionContainer, "overflow", "visible");
DOM.appendChild(td, captionContainer);
DOM.sinkEvents(td, Event.MOUSEEVENTS | Event.ONDBLCLICK
| Event.ONCONTEXTMENU | Event.TOUCHEVENTS);
setElement(td);
setAlign(ALIGN_LEFT);
}
public void disableAutoWidthCalculation() {
definedWidth = true;
expandRatio = 0;
}
public void setWidth(int w, boolean ensureDefinedWidth) {
if (ensureDefinedWidth) {
definedWidth = true;
// on column resize expand ratio becomes zero
expandRatio = 0;
}
if (width == -1) {
// go to default mode, clip content if necessary
DOM.setStyleAttribute(captionContainer, "overflow", "");
}
width = w;
if (w == -1) {
DOM.setStyleAttribute(captionContainer, "width", "");
setWidth("");
} else {
tHead.resizeCaptionContainer(this);
/*
* if we already have tBody, set the header width properly, if
* not defer it. IE will fail with complex float in table header
* unless TD width is not explicitly set.
*/
if (scrollBody != null) {
int tdWidth = width + scrollBody.getCellExtraWidth();
setWidth(tdWidth + "px");
} else {
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
int tdWidth = width
+ scrollBody.getCellExtraWidth();
setWidth(tdWidth + "px");
}
});
}
}
}
public void setUndefinedWidth() {
definedWidth = false;
setWidth(-1, false);
}
/**
* Detects if width is fixed by developer on server side or resized to
* current width by user.
*
* @return true if defined, false if "natural" width
*/
public boolean isDefinedWidth() {
return definedWidth && width >= 0;
}
public int getWidth() {
return width;
}
public void setText(String headerText) {
DOM.setInnerHTML(captionContainer, headerText);
}
public String getColKey() {
return cid;
}
private void setSorted(boolean sorted) {
this.sorted = sorted;
if (sorted) {
if (sortAscending) {
this.setStyleName(CLASSNAME + "-header-cell-asc");
} else {
this.setStyleName(CLASSNAME + "-header-cell-desc");
}
} else {
this.setStyleName(CLASSNAME + "-header-cell");
}
}
/**
* Handle column reordering.
*/
@Override
public void onBrowserEvent(Event event) {
if (enabled && event != null) {
if (isResizing
|| event.getEventTarget().cast() == colResizeWidget) {
if (dragging
&& (event.getTypeInt() == Event.ONMOUSEUP || event
.getTypeInt() == Event.ONTOUCHEND)) {
// Handle releasing column header on spacer #5318
handleCaptionEvent(event);
} else {
onResizeEvent(event);
}
} else {
/*
* Ensure focus before handling caption event. Otherwise
* variables changed from caption event may be before
* variables from other components that fire variables when
* they lose focus.
*/
if (event.getTypeInt() == Event.ONMOUSEDOWN
|| event.getTypeInt() == Event.ONTOUCHSTART) {
scrollBodyPanel.setFocus(true);
}
handleCaptionEvent(event);
boolean stopPropagation = true;
if (event.getTypeInt() == Event.ONCONTEXTMENU
&& !client.hasEventListeners(VScrollTable.this,
HEADER_CLICK_EVENT_ID)) {
// Prevent showing the browser's context menu only when
// there is a header click listener.
stopPropagation = false;
}
if (stopPropagation) {
event.stopPropagation();
event.preventDefault();
}
}
}
}
private void createFloatingCopy() {
floatingCopyOfHeaderCell = DOM.createDiv();
DOM.setInnerHTML(floatingCopyOfHeaderCell, DOM.getInnerHTML(td));
floatingCopyOfHeaderCell = DOM
.getChild(floatingCopyOfHeaderCell, 2);
DOM.setElementProperty(floatingCopyOfHeaderCell, "className",
CLASSNAME + "-header-drag");
// otherwise might wrap or be cut if narrow column
DOM.setStyleAttribute(floatingCopyOfHeaderCell, "width", "auto");
updateFloatingCopysPosition(DOM.getAbsoluteLeft(td),
DOM.getAbsoluteTop(td));
DOM.appendChild(RootPanel.get().getElement(),
floatingCopyOfHeaderCell);
}
private void updateFloatingCopysPosition(int x, int y) {
x -= DOM.getElementPropertyInt(floatingCopyOfHeaderCell,
"offsetWidth") / 2;
DOM.setStyleAttribute(floatingCopyOfHeaderCell, "left", x + "px");
if (y > 0) {
DOM.setStyleAttribute(floatingCopyOfHeaderCell, "top", (y + 7)
+ "px");
}
}
private void hideFloatingCopy() {
DOM.removeChild(RootPanel.get().getElement(),
floatingCopyOfHeaderCell);
floatingCopyOfHeaderCell = null;
}
/**
* Fires a header click event after the user has clicked a column header
* cell
*
* @param event
* The click event
*/
private void fireHeaderClickedEvent(Event event) {
if (client.hasEventListeners(VScrollTable.this,
HEADER_CLICK_EVENT_ID)) {
MouseEventDetails details = new MouseEventDetails(event);
client.updateVariable(paintableId, "headerClickEvent",
details.toString(), false);
client.updateVariable(paintableId, "headerClickCID", cid, true);
}
}
protected void handleCaptionEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONTOUCHSTART:
case Event.ONMOUSEDOWN:
if (columnReordering
&& Util.isTouchEventOrLeftMouseButton(event)) {
if (event.getTypeInt() == Event.ONTOUCHSTART) {
/*
* prevent using this event in e.g. scrolling
*/
event.stopPropagation();
}
dragging = true;
moved = false;
colIndex = getColIndexByKey(cid);
DOM.setCapture(getElement());
headerX = tHead.getAbsoluteLeft();
event.preventDefault(); // prevent selecting text &&
// generated touch events
}
break;
case Event.ONMOUSEUP:
case Event.ONTOUCHEND:
case Event.ONTOUCHCANCEL:
if (columnReordering
&& Util.isTouchEventOrLeftMouseButton(event)) {
dragging = false;
DOM.releaseCapture(getElement());
if (moved) {
hideFloatingCopy();
tHead.removeSlotFocus();
if (closestSlot != colIndex
&& closestSlot != (colIndex + 1)) {
if (closestSlot > colIndex) {
reOrderColumn(cid, closestSlot - 1);
} else {
reOrderColumn(cid, closestSlot);
}
}
}
if (Util.isTouchEvent(event)) {
/*
* Prevent using in e.g. scrolling and prevent generated
* events.
*/
event.preventDefault();
event.stopPropagation();
}
}
if (!moved) {
// mouse event was a click to header -> sort column
if (sortable && Util.isTouchEventOrLeftMouseButton(event)) {
if (sortColumn.equals(cid)) {
// just toggle order
client.updateVariable(paintableId, "sortascending",
!sortAscending, false);
} else {
// set table sorted by this column
client.updateVariable(paintableId, "sortcolumn",
cid, false);
}
// get also cache columns at the same request
scrollBodyPanel.setScrollPosition(0);
firstvisible = 0;
rowRequestHandler.setReqFirstRow(0);
rowRequestHandler.setReqRows((int) (2 * pageLength
* cache_rate + pageLength));
rowRequestHandler.deferRowFetch(); // some validation +
// defer 250ms
rowRequestHandler.cancel(); // instead of waiting
rowRequestHandler.run(); // run immediately
}
fireHeaderClickedEvent(event);
if (Util.isTouchEvent(event)) {
/*
* Prevent using in e.g. scrolling and prevent generated
* events.
*/
event.preventDefault();
event.stopPropagation();
}
break;
}
break;
case Event.ONDBLCLICK:
fireHeaderClickedEvent(event);
break;
case Event.ONTOUCHMOVE:
case Event.ONMOUSEMOVE:
if (dragging && Util.isTouchEventOrLeftMouseButton(event)) {
if (event.getTypeInt() == Event.ONTOUCHMOVE) {
/*
* prevent using this event in e.g. scrolling
*/
event.stopPropagation();
}
if (!moved) {
createFloatingCopy();
moved = true;
}
final int clientX = Util.getTouchOrMouseClientX(event);
final int x = clientX + tHead.hTableWrapper.getScrollLeft();
int slotX = headerX;
closestSlot = colIndex;
int closestDistance = -1;
int start = 0;
if (showRowHeaders) {
start++;
}
final int visibleCellCount = tHead.getVisibleCellCount();
for (int i = start; i <= visibleCellCount; i++) {
if (i > 0) {
final String colKey = getColKeyByIndex(i - 1);
slotX += getColWidth(colKey);
}
final int dist = Math.abs(x - slotX);
if (closestDistance == -1 || dist < closestDistance) {
closestDistance = dist;
closestSlot = i;
}
}
tHead.focusSlot(closestSlot);
updateFloatingCopysPosition(clientX, -1);
}
break;
default:
break;
}
}
private void onResizeEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
if (!Util.isTouchEventOrLeftMouseButton(event)) {
return;
}
isResizing = true;
DOM.setCapture(getElement());
dragStartX = DOM.eventGetClientX(event);
colIndex = getColIndexByKey(cid);
originalWidth = getWidth();
DOM.eventPreventDefault(event);
break;
case Event.ONMOUSEUP:
if (!Util.isTouchEventOrLeftMouseButton(event)) {
return;
}
isResizing = false;
DOM.releaseCapture(getElement());
tHead.disableAutoColumnWidthCalculation(this);
// Ensure last header cell is taking into account possible
// column selector
HeaderCell lastCell = tHead.getHeaderCell(tHead
.getVisibleCellCount() - 1);
tHead.resizeCaptionContainer(lastCell);
triggerLazyColumnAdjustment(true);
fireColumnResizeEvent(cid, originalWidth, getColWidth(cid));
break;
case Event.ONMOUSEMOVE:
if (!Util.isTouchEventOrLeftMouseButton(event)) {
return;
}
if (isResizing) {
final int deltaX = DOM.eventGetClientX(event) - dragStartX;
if (deltaX == 0) {
return;
}
tHead.disableAutoColumnWidthCalculation(this);
int newWidth = originalWidth + deltaX;
if (newWidth < getMinWidth()) {
newWidth = getMinWidth();
}
setColWidth(colIndex, newWidth, true);
triggerLazyColumnAdjustment(false);
forceRealignColumnHeaders();
}
break;
default:
break;
}
}
public int getMinWidth() {
int cellExtraWidth = 0;
if (scrollBody != null) {
cellExtraWidth += scrollBody.getCellExtraWidth();
}
return cellExtraWidth + sortIndicator.getOffsetWidth();
}
public String getCaption() {
return DOM.getInnerText(captionContainer);
}
public boolean isEnabled() {
return getParent() != null;
}
public void setAlign(char c) {
final String ALIGN_PREFIX = CLASSNAME + "-caption-container-align-";
if (align != c) {
captionContainer.removeClassName(ALIGN_PREFIX + "center");
captionContainer.removeClassName(ALIGN_PREFIX + "right");
captionContainer.removeClassName(ALIGN_PREFIX + "left");
switch (c) {
case ALIGN_CENTER:
captionContainer.addClassName(ALIGN_PREFIX + "center");
break;
case ALIGN_RIGHT:
captionContainer.addClassName(ALIGN_PREFIX + "right");
break;
default:
captionContainer.addClassName(ALIGN_PREFIX + "left");
break;
}
}
align = c;
}
public char getAlign() {
return align;
}
/**
* Detects the natural minimum width for the column of this header cell.
* If column is resized by user or the width is defined by server the
* actual width is returned. Else the natural min width is returned.
*
* @param columnIndex
* column index hint, if -1 (unknown) it will be detected
*
* @return
*/
public int getNaturalColumnWidth(int columnIndex) {
if (isDefinedWidth()) {
return width;
} else {
if (naturalWidth < 0) {
// This is recently revealed column. Try to detect a proper
// value (greater of header and data
// cols)
int hw = captionContainer.getOffsetWidth()
+ scrollBody.getCellExtraWidth();
if (BrowserInfo.get().isGecko()
|| BrowserInfo.get().isIE7()) {
hw += sortIndicator.getOffsetWidth();
}
if (columnIndex < 0) {
columnIndex = 0;
for (Iterator<Widget> it = tHead.iterator(); it
.hasNext(); columnIndex++) {
if (it.next() == this) {
break;
}
}
}
final int cw = scrollBody.getColWidth(columnIndex);
naturalWidth = (hw > cw ? hw : cw);
}
return naturalWidth;
}
}
public void setExpandRatio(float floatAttribute) {
if (floatAttribute != expandRatio) {
triggerLazyColumnAdjustment(false);
}
expandRatio = floatAttribute;
}
public float getExpandRatio() {
return expandRatio;
}
public boolean isSorted() {
return sorted;
}
}
/**
* HeaderCell that is header cell for row headers.
*
* Reordering disabled and clicking on it resets sorting.
*/
public class RowHeadersHeaderCell extends HeaderCell {
RowHeadersHeaderCell() {
super(ROW_HEADER_COLUMN_KEY, "");
this.setStyleName(CLASSNAME + "-header-cell-rowheader");
}
@Override
protected void handleCaptionEvent(Event event) {
// NOP: RowHeaders cannot be reordered
// TODO It'd be nice to reset sorting here
}
}
public class TableHead extends Panel implements ActionOwner {
private static final int WRAPPER_WIDTH = 900000;
ArrayList<Widget> visibleCells = new ArrayList<Widget>();
HashMap<String, HeaderCell> availableCells = new HashMap<String, HeaderCell>();
Element div = DOM.createDiv();
Element hTableWrapper = DOM.createDiv();
Element hTableContainer = DOM.createDiv();
Element table = DOM.createTable();
Element headerTableBody = DOM.createTBody();
Element tr = DOM.createTR();
private final Element columnSelector = DOM.createDiv();
private int focusedSlot = -1;
public TableHead() {
if (BrowserInfo.get().isIE()) {
table.setPropertyInt("cellSpacing", 0);
}
DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden");
DOM.setElementProperty(hTableWrapper, "className", CLASSNAME
+ "-header");
// TODO move styles to CSS
DOM.setElementProperty(columnSelector, "className", CLASSNAME
+ "-column-selector");
DOM.setStyleAttribute(columnSelector, "display", "none");
DOM.appendChild(table, headerTableBody);
DOM.appendChild(headerTableBody, tr);
DOM.appendChild(hTableContainer, table);
DOM.appendChild(hTableWrapper, hTableContainer);
DOM.appendChild(div, hTableWrapper);
DOM.appendChild(div, columnSelector);
setElement(div);
setStyleName(CLASSNAME + "-header-wrap");
DOM.sinkEvents(columnSelector, Event.ONCLICK);
availableCells.put(ROW_HEADER_COLUMN_KEY,
new RowHeadersHeaderCell());
}
public void resizeCaptionContainer(HeaderCell cell) {
HeaderCell lastcell = getHeaderCell(visibleCells.size() - 1);
// Measure column widths
int columnTotalWidth = 0;
for (Widget w : visibleCells) {
columnTotalWidth += w.getOffsetWidth();
}
if (cell == lastcell
&& columnSelector.getOffsetWidth() > 0
&& columnTotalWidth >= div.getOffsetWidth()
- columnSelector.getOffsetWidth()
&& !hasVerticalScrollbar()) {
// Ensure column caption is visible when placed under the column
// selector widget by shifting and resizing the caption.
int offset = 0;
int diff = div.getOffsetWidth() - columnTotalWidth;
if (diff < columnSelector.getOffsetWidth() && diff > 0) {
// If the difference is less than the column selectors width
// then just offset by the
// difference
offset = columnSelector.getOffsetWidth() - diff;
} else {
// Else offset by the whole column selector
offset = columnSelector.getOffsetWidth();
}
lastcell.resizeCaptionContainer(offset);
} else {
cell.resizeCaptionContainer(0);
}
}
@Override
public void clear() {
for (String cid : availableCells.keySet()) {
removeCell(cid);
}
availableCells.clear();
availableCells.put(ROW_HEADER_COLUMN_KEY,
new RowHeadersHeaderCell());
}
public void updateCellsFromUIDL(UIDL uidl) {
Iterator<?> it = uidl.getChildIterator();
HashSet<String> updated = new HashSet<String>();
boolean refreshContentWidths = false;
while (it.hasNext()) {
final UIDL col = (UIDL) it.next();
final String cid = col.getStringAttribute("cid");
updated.add(cid);
String caption = buildCaptionHtmlSnippet(col);
HeaderCell c = getHeaderCell(cid);
if (c == null) {
c = new HeaderCell(cid, caption);
availableCells.put(cid, c);
if (initializedAndAttached) {
// we will need a column width recalculation
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
} else {
c.setText(caption);
}
if (col.hasAttribute("sortable")) {
c.setSortable(true);
if (cid.equals(sortColumn)) {
c.setSorted(true);
} else {
c.setSorted(false);
}
} else {
c.setSortable(false);
}
if (col.hasAttribute("align")) {
c.setAlign(col.getStringAttribute("align").charAt(0));
} else {
c.setAlign(ALIGN_LEFT);
}
if (col.hasAttribute("width")) {
final String widthStr = col.getStringAttribute("width");
// Make sure to accomodate for the sort indicator if
// necessary.
int width = Integer.parseInt(widthStr);
if (width < c.getMinWidth()) {
width = c.getMinWidth();
}
if (width != c.getWidth() && scrollBody != null) {
// Do a more thorough update if a column is resized from
// the server *after* the header has been properly
// initialized
final int colIx = getColIndexByKey(c.cid);
final int newWidth = width;
Scheduler.get().scheduleDeferred(
new ScheduledCommand() {
public void execute() {
setColWidth(colIx, newWidth, true);
}
});
refreshContentWidths = true;
} else {
c.setWidth(width, true);
}
} else if (recalcWidths) {
c.setUndefinedWidth();
}
if (col.hasAttribute("er")) {
c.setExpandRatio(col.getFloatAttribute("er"));
}
if (col.hasAttribute("collapsed")) {
// ensure header is properly removed from parent (case when
// collapsing happens via servers side api)
if (c.isAttached()) {
c.removeFromParent();
headerChangedDuringUpdate = true;
}
}
}
if (refreshContentWidths) {
// Recalculate the column sizings if any column has changed
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
public void execute() {
triggerLazyColumnAdjustment(true);
}
});
}
// check for orphaned header cells
for (Iterator<String> cit = availableCells.keySet().iterator(); cit
.hasNext();) {
String cid = cit.next();
if (!updated.contains(cid)) {
removeCell(cid);
cit.remove();
// we will need a column width recalculation, since columns
// with expand ratios should expand to fill the void.
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
}
}
public void enableColumn(String cid, int index) {
final HeaderCell c = getHeaderCell(cid);
if (!c.isEnabled() || getHeaderCell(index) != c) {
setHeaderCell(index, c);
if (initializedAndAttached) {
headerChangedDuringUpdate = true;
}
}
}
public int getVisibleCellCount() {
return visibleCells.size();
}
public void setHorizontalScrollPosition(int scrollLeft) {
if (BrowserInfo.get().isIE6()) {
hTableWrapper.getStyle().setPosition(Position.RELATIVE);
hTableWrapper.getStyle().setLeft(-scrollLeft, Unit.PX);
} else {
hTableWrapper.setScrollLeft(scrollLeft);
}
}
public void setColumnCollapsingAllowed(boolean cc) {
if (cc) {
columnSelector.getStyle().setDisplay(Display.BLOCK);
} else {
columnSelector.getStyle().setDisplay(Display.NONE);
}
}
public void disableBrowserIntelligence() {
hTableContainer.getStyle().setWidth(WRAPPER_WIDTH, Unit.PX);
}
public void enableBrowserIntelligence() {
hTableContainer.getStyle().clearWidth();
}
public void setHeaderCell(int index, HeaderCell cell) {
if (cell.isEnabled()) {
// we're moving the cell
DOM.removeChild(tr, cell.getElement());
orphan(cell);
visibleCells.remove(cell);
}
if (index < visibleCells.size()) {
// insert to right slot
DOM.insertChild(tr, cell.getElement(), index);
adopt(cell);
visibleCells.add(index, cell);
} else if (index == visibleCells.size()) {
// simply append
DOM.appendChild(tr, cell.getElement());
adopt(cell);
visibleCells.add(cell);
} else {
throw new RuntimeException(
"Header cells must be appended in order");
}
}
public HeaderCell getHeaderCell(int index) {
if (index >= 0 && index < visibleCells.size()) {
return (HeaderCell) visibleCells.get(index);
} else {
return null;
}
}
/**
* Get's HeaderCell by it's column Key.
*
* Note that this returns HeaderCell even if it is currently collapsed.
*
* @param cid
* Column key of accessed HeaderCell
* @return HeaderCell
*/
public HeaderCell getHeaderCell(String cid) {
return availableCells.get(cid);
}
public void moveCell(int oldIndex, int newIndex) {
final HeaderCell hCell = getHeaderCell(oldIndex);
final Element cell = hCell.getElement();
visibleCells.remove(oldIndex);
DOM.removeChild(tr, cell);
DOM.insertChild(tr, cell, newIndex);
visibleCells.add(newIndex, hCell);
}
public Iterator<Widget> iterator() {
return visibleCells.iterator();
}
@Override
public boolean remove(Widget w) {
if (visibleCells.contains(w)) {
visibleCells.remove(w);
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
return true;
}
return false;
}
public void removeCell(String colKey) {
final HeaderCell c = getHeaderCell(colKey);
remove(c);
}
private void focusSlot(int index) {
removeSlotFocus();
if (index > 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, index - 1)),
"className", CLASSNAME + "-resizer " + CLASSNAME
+ "-focus-slot-right");
} else {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, index)),
"className", CLASSNAME + "-resizer " + CLASSNAME
+ "-focus-slot-left");
}
focusedSlot = index;
}
private void removeSlotFocus() {
if (focusedSlot < 0) {
return;
}
if (focusedSlot == 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, focusedSlot)),
"className", CLASSNAME + "-resizer");
} else if (focusedSlot > 0) {
DOM.setElementProperty(
DOM.getFirstChild(DOM.getChild(tr, focusedSlot - 1)),
"className", CLASSNAME + "-resizer");
}
focusedSlot = -1;
}
@Override
public void onBrowserEvent(Event event) {
if (enabled) {
if (event.getEventTarget().cast() == columnSelector) {
final int left = DOM.getAbsoluteLeft(columnSelector);
final int top = DOM.getAbsoluteTop(columnSelector)
+ DOM.getElementPropertyInt(columnSelector,
"offsetHeight");
client.getContextMenu().showAt(this, left, top);
}
}
}
@Override
protected void onDetach() {
super.onDetach();
if (client != null) {
client.getContextMenu().ensureHidden(this);
}
}
class VisibleColumnAction extends Action {
String colKey;
private boolean collapsed;
private VScrollTableRow currentlyFocusedRow;
public VisibleColumnAction(String colKey) {
super(VScrollTable.TableHead.this);
this.colKey = colKey;
caption = tHead.getHeaderCell(colKey).getCaption();
currentlyFocusedRow = focusedRow;
}
@Override
public void execute() {
client.getContextMenu().hide();
// toggle selected column
if (collapsedColumns.contains(colKey)) {
collapsedColumns.remove(colKey);
} else {
tHead.removeCell(colKey);
collapsedColumns.add(colKey);
triggerLazyColumnAdjustment(true);
}
// update variable to server
client.updateVariable(paintableId, "collapsedcolumns",
collapsedColumns.toArray(new String[collapsedColumns
.size()]), false);
// let rowRequestHandler determine proper rows
rowRequestHandler.refreshContent();
lazyRevertFocusToRow(currentlyFocusedRow);
}
public void setCollapsed(boolean b) {
collapsed = b;
}
/**
* Override default method to distinguish on/off columns
*/
@Override
public String getHTML() {
final StringBuffer buf = new StringBuffer();
if (collapsed) {
buf.append("<span class=\"v-off\">");
} else {
buf.append("<span class=\"v-on\">");
}
buf.append(super.getHTML());
buf.append("</span>");
return buf.toString();
}
}
/*
* Returns columns as Action array for column select popup
*/
public Action[] getActions() {
Object[] cols;
if (columnReordering && columnOrder != null) {
cols = columnOrder;
} else {
// if columnReordering is disabled, we need different way to get
// all available columns
cols = visibleColOrder;
cols = new Object[visibleColOrder.length
+ collapsedColumns.size()];
int i;
for (i = 0; i < visibleColOrder.length; i++) {
cols[i] = visibleColOrder[i];
}
for (final Iterator<String> it = collapsedColumns.iterator(); it
.hasNext();) {
cols[i++] = it.next();
}
}
final Action[] actions = new Action[cols.length];
for (int i = 0; i < cols.length; i++) {
final String cid = (String) cols[i];
final HeaderCell c = getHeaderCell(cid);
final VisibleColumnAction a = new VisibleColumnAction(
c.getColKey());
a.setCaption(c.getCaption());
if (!c.isEnabled()) {
a.setCollapsed(true);
}
actions[i] = a;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
/**
* Returns column alignments for visible columns
*/
public char[] getColumnAlignments() {
final Iterator<Widget> it = visibleCells.iterator();
final char[] aligns = new char[visibleCells.size()];
int colIndex = 0;
while (it.hasNext()) {
aligns[colIndex++] = ((HeaderCell) it.next()).getAlign();
}
return aligns;
}
/**
* Disables the automatic calculation of all column widths by forcing
* the widths to be "defined" thus turning off expand ratios and such.
*/
public void disableAutoColumnWidthCalculation(HeaderCell source) {
for (HeaderCell cell : availableCells.values()) {
cell.disableAutoWidthCalculation();
}
// fire column resize events for all columns but the source of the
// resize action, since an event will fire separately for this.
ArrayList<HeaderCell> columns = new ArrayList<HeaderCell>(
availableCells.values());
columns.remove(source);
sendColumnWidthUpdates(columns);
forceRealignColumnHeaders();
}
}
/**
* A cell in the footer
*/
public class FooterCell extends Widget {
private final Element td = DOM.createTD();
private final Element captionContainer = DOM.createDiv();
private char align = ALIGN_LEFT;
private int width = -1;
private float expandRatio = 0;
private final String cid;
boolean definedWidth = false;
private int naturalWidth = -1;
public FooterCell(String colId, String headerText) {
cid = colId;
setText(headerText);
DOM.setElementProperty(captionContainer, "className", CLASSNAME
+ "-footer-container");
// ensure no clipping initially (problem on column additions)
DOM.setStyleAttribute(captionContainer, "overflow", "visible");
DOM.sinkEvents(captionContainer, Event.MOUSEEVENTS);
DOM.appendChild(td, captionContainer);
DOM.sinkEvents(td, Event.MOUSEEVENTS | Event.ONDBLCLICK
| Event.ONCONTEXTMENU);
setElement(td);
}
/**
* Sets the text of the footer
*
* @param footerText
* The text in the footer
*/
public void setText(String footerText) {
DOM.setInnerHTML(captionContainer, footerText);
}
/**
* Set alignment of the text in the cell
*
* @param c
* The alignment which can be ALIGN_CENTER, ALIGN_LEFT,
* ALIGN_RIGHT
*/
public void setAlign(char c) {
if (align != c) {
switch (c) {
case ALIGN_CENTER:
DOM.setStyleAttribute(captionContainer, "textAlign",
"center");
break;
case ALIGN_RIGHT:
DOM.setStyleAttribute(captionContainer, "textAlign",
"right");
break;
default:
DOM.setStyleAttribute(captionContainer, "textAlign", "");
break;
}
}
align = c;
}
/**
* Get the alignment of the text int the cell
*
* @return Returns either ALIGN_CENTER, ALIGN_LEFT or ALIGN_RIGHT
*/
public char getAlign() {
return align;
}
/**
* Sets the width of the cell
*
* @param w
* The width of the cell
* @param ensureDefinedWidth
* Ensures the the given width is not recalculated
*/
public void setWidth(int w, boolean ensureDefinedWidth) {
if (ensureDefinedWidth) {
definedWidth = true;
// on column resize expand ratio becomes zero
expandRatio = 0;
}
if (width == w) {
return;
}
if (width == -1) {
// go to default mode, clip content if necessary
DOM.setStyleAttribute(captionContainer, "overflow", "");
}
width = w;
if (w == -1) {
DOM.setStyleAttribute(captionContainer, "width", "");
setWidth("");
} else {
/*
* Reduce width with one pixel for the right border since the
* footers does not have any spacers between them.
*/
int borderWidths = 1;
// Set the container width (check for negative value)
if (w - borderWidths >= 0) {
captionContainer.getStyle().setPropertyPx("width",
w - borderWidths);
} else {
captionContainer.getStyle().setPropertyPx("width", 0);
}
/*
* if we already have tBody, set the header width properly, if
* not defer it. IE will fail with complex float in table header
* unless TD width is not explicitly set.
*/
if (scrollBody != null) {
/*
* Reduce with one since footer does not have any spacers,
* instead a 1 pixel border.
*/
int tdWidth = width + scrollBody.getCellExtraWidth()
- borderWidths;
setWidth(tdWidth + "px");
} else {
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
int borderWidths = 1;
int tdWidth = width
+ scrollBody.getCellExtraWidth()
- borderWidths;
setWidth(tdWidth + "px");
}
});
}
}
}
/**
* Sets the width to undefined
*/
public void setUndefinedWidth() {
setWidth(-1, false);
}
/**
* Detects if width is fixed by developer on server side or resized to
* current width by user.
*
* @return true if defined, false if "natural" width
*/
public boolean isDefinedWidth() {
return definedWidth && width >= 0;
}
/**
* Returns the pixels width of the footer cell
*
* @return The width in pixels
*/
public int getWidth() {
return width;
}
/**
* Sets the expand ratio of the cell
*
* @param floatAttribute
* The expand ratio
*/
public void setExpandRatio(float floatAttribute) {
expandRatio = floatAttribute;
}
/**
* Returns the expand ration of the cell
*
* @return The expand ratio
*/
public float getExpandRatio() {
return expandRatio;
}
/**
* Is the cell enabled?
*
* @return True if enabled else False
*/
public boolean isEnabled() {
return getParent() != null;
}
/**
* Handle column clicking
*/
@Override
public void onBrowserEvent(Event event) {
if (enabled && event != null) {
handleCaptionEvent(event);
if (DOM.eventGetType(event) == Event.ONMOUSEUP) {
scrollBodyPanel.setFocus(true);
}
boolean stopPropagation = true;
if (event.getTypeInt() == Event.ONCONTEXTMENU
&& !client.hasEventListeners(VScrollTable.this,
FOOTER_CLICK_EVENT_ID)) {
// Show browser context menu if a footer click listener is
// not present
stopPropagation = false;
}
if (stopPropagation) {
event.stopPropagation();
event.preventDefault();
}
}
}
/**
* Handles a event on the captions
*
* @param event
* The event to handle
*/
protected void handleCaptionEvent(Event event) {
if (event.getTypeInt() == Event.ONMOUSEUP
|| event.getTypeInt() == Event.ONDBLCLICK) {
fireFooterClickedEvent(event);
}
}
/**
* Fires a footer click event after the user has clicked a column footer
* cell
*
* @param event
* The click event
*/
private void fireFooterClickedEvent(Event event) {
if (client.hasEventListeners(VScrollTable.this,
FOOTER_CLICK_EVENT_ID)) {
MouseEventDetails details = new MouseEventDetails(event);
client.updateVariable(paintableId, "footerClickEvent",
details.toString(), false);
client.updateVariable(paintableId, "footerClickCID", cid, true);
}
}
/**
* Returns the column key of the column
*
* @return The column key
*/
public String getColKey() {
return cid;
}
/**
* Detects the natural minimum width for the column of this header cell.
* If column is resized by user or the width is defined by server the
* actual width is returned. Else the natural min width is returned.
*
* @param columnIndex
* column index hint, if -1 (unknown) it will be detected
*
* @return
*/
public int getNaturalColumnWidth(int columnIndex) {
if (isDefinedWidth()) {
return width;
} else {
if (naturalWidth < 0) {
// This is recently revealed column. Try to detect a proper
// value (greater of header and data
// cols)
final int hw = ((Element) getElement().getLastChild())
.getOffsetWidth() + scrollBody.getCellExtraWidth();
if (columnIndex < 0) {
columnIndex = 0;
for (Iterator<Widget> it = tHead.iterator(); it
.hasNext(); columnIndex++) {
if (it.next() == this) {
break;
}
}
}
final int cw = scrollBody.getColWidth(columnIndex);
naturalWidth = (hw > cw ? hw : cw);
}
return naturalWidth;
}
}
public void setNaturalMinimumColumnWidth(int w) {
naturalWidth = w;
}
}
/**
* HeaderCell that is header cell for row headers.
*
* Reordering disabled and clicking on it resets sorting.
*/
public class RowHeadersFooterCell extends FooterCell {
RowHeadersFooterCell() {
super(ROW_HEADER_COLUMN_KEY, "");
}
@Override
protected void handleCaptionEvent(Event event) {
// NOP: RowHeaders cannot be reordered
// TODO It'd be nice to reset sorting here
}
}
/**
* The footer of the table which can be seen in the bottom of the Table.
*/
public class TableFooter extends Panel {
private static final int WRAPPER_WIDTH = 900000;
ArrayList<Widget> visibleCells = new ArrayList<Widget>();
HashMap<String, FooterCell> availableCells = new HashMap<String, FooterCell>();
Element div = DOM.createDiv();
Element hTableWrapper = DOM.createDiv();
Element hTableContainer = DOM.createDiv();
Element table = DOM.createTable();
Element headerTableBody = DOM.createTBody();
Element tr = DOM.createTR();
public TableFooter() {
DOM.setStyleAttribute(hTableWrapper, "overflow", "hidden");
DOM.setElementProperty(hTableWrapper, "className", CLASSNAME
+ "-footer");
DOM.appendChild(table, headerTableBody);
DOM.appendChild(headerTableBody, tr);
DOM.appendChild(hTableContainer, table);
DOM.appendChild(hTableWrapper, hTableContainer);
DOM.appendChild(div, hTableWrapper);
setElement(div);
setStyleName(CLASSNAME + "-footer-wrap");
availableCells.put(ROW_HEADER_COLUMN_KEY,
new RowHeadersFooterCell());
}
@Override
public void clear() {
for (String cid : availableCells.keySet()) {
removeCell(cid);
}
availableCells.clear();
availableCells.put(ROW_HEADER_COLUMN_KEY,
new RowHeadersFooterCell());
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.user.client.ui.Panel#remove(com.google.gwt.user.client
* .ui.Widget)
*/
@Override
public boolean remove(Widget w) {
if (visibleCells.contains(w)) {
visibleCells.remove(w);
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()), w.getElement());
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see com.google.gwt.user.client.ui.HasWidgets#iterator()
*/
public Iterator<Widget> iterator() {
return visibleCells.iterator();
}
/**
* Gets a footer cell which represents the given columnId
*
* @param cid
* The columnId
*
* @return The cell
*/
public FooterCell getFooterCell(String cid) {
return availableCells.get(cid);
}
/**
* Gets a footer cell by using a column index
*
* @param index
* The index of the column
* @return The Cell
*/
public FooterCell getFooterCell(int index) {
if (index < visibleCells.size()) {
return (FooterCell) visibleCells.get(index);
} else {
return null;
}
}
/**
* Updates the cells contents when updateUIDL request is received
*
* @param uidl
* The UIDL
*/
public void updateCellsFromUIDL(UIDL uidl) {
Iterator<?> columnIterator = uidl.getChildIterator();
HashSet<String> updated = new HashSet<String>();
while (columnIterator.hasNext()) {
final UIDL col = (UIDL) columnIterator.next();
final String cid = col.getStringAttribute("cid");
updated.add(cid);
String caption = col.hasAttribute("fcaption") ? col
.getStringAttribute("fcaption") : "";
FooterCell c = getFooterCell(cid);
if (c == null) {
c = new FooterCell(cid, caption);
availableCells.put(cid, c);
if (initializedAndAttached) {
// we will need a column width recalculation
initializedAndAttached = false;
initialContentReceived = false;
isNewBody = true;
}
} else {
c.setText(caption);
}
if (col.hasAttribute("align")) {
c.setAlign(col.getStringAttribute("align").charAt(0));
} else {
c.setAlign(ALIGN_LEFT);
}
if (col.hasAttribute("width")) {
if (scrollBody == null) {
// Already updated by setColWidth called from
// TableHeads.updateCellsFromUIDL in case of a server
// side resize
final String width = col.getStringAttribute("width");
c.setWidth(Integer.parseInt(width), true);
}
} else if (recalcWidths) {
c.setUndefinedWidth();
}
if (col.hasAttribute("er")) {
c.setExpandRatio(col.getFloatAttribute("er"));
}
if (col.hasAttribute("collapsed")) {
// ensure header is properly removed from parent (case when
// collapsing happens via servers side api)
if (c.isAttached()) {
c.removeFromParent();
headerChangedDuringUpdate = true;
}
}
}
// check for orphaned header cells
for (Iterator<String> cit = availableCells.keySet().iterator(); cit
.hasNext();) {
String cid = cit.next();
if (!updated.contains(cid)) {
removeCell(cid);
cit.remove();
}
}
}
/**
* Set a footer cell for a specified column index
*
* @param index
* The index
* @param cell
* The footer cell
*/
public void setFooterCell(int index, FooterCell cell) {
if (cell.isEnabled()) {
// we're moving the cell
DOM.removeChild(tr, cell.getElement());
orphan(cell);
visibleCells.remove(cell);
}
if (index < visibleCells.size()) {
// insert to right slot
DOM.insertChild(tr, cell.getElement(), index);
adopt(cell);
visibleCells.add(index, cell);
} else if (index == visibleCells.size()) {
// simply append
DOM.appendChild(tr, cell.getElement());
adopt(cell);
visibleCells.add(cell);
} else {
throw new RuntimeException(
"Header cells must be appended in order");
}
}
/**
* Remove a cell by using the columnId
*
* @param colKey
* The columnId to remove
*/
public void removeCell(String colKey) {
final FooterCell c = getFooterCell(colKey);
remove(c);
}
/**
* Enable a column (Sets the footer cell)
*
* @param cid
* The columnId
* @param index
* The index of the column
*/
public void enableColumn(String cid, int index) {
final FooterCell c = getFooterCell(cid);
if (!c.isEnabled() || getFooterCell(index) != c) {
setFooterCell(index, c);
if (initializedAndAttached) {
headerChangedDuringUpdate = true;
}
}
}
/**
* Disable browser measurement of the table width
*/
public void disableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", WRAPPER_WIDTH
+ "px");
}
/**
* Enable browser measurement of the table width
*/
public void enableBrowserIntelligence() {
DOM.setStyleAttribute(hTableContainer, "width", "");
}
/**
* Set the horizontal position in the cell in the footer. This is done
* when a horizontal scrollbar is present.
*
* @param scrollLeft
* The value of the leftScroll
*/
public void setHorizontalScrollPosition(int scrollLeft) {
if (BrowserInfo.get().isIE6()) {
hTableWrapper.getStyle().setProperty("position", "relative");
hTableWrapper.getStyle().setPropertyPx("left", -scrollLeft);
} else {
hTableWrapper.setScrollLeft(scrollLeft);
}
}
/**
* Swap cells when the column are dragged
*
* @param oldIndex
* The old index of the cell
* @param newIndex
* The new index of the cell
*/
public void moveCell(int oldIndex, int newIndex) {
final FooterCell hCell = getFooterCell(oldIndex);
final Element cell = hCell.getElement();
visibleCells.remove(oldIndex);
DOM.removeChild(tr, cell);
DOM.insertChild(tr, cell, newIndex);
visibleCells.add(newIndex, hCell);
}
}
/**
* This Panel can only contain VScrollTableRow type of widgets. This
* "simulates" very large table, keeping spacers which take room of
* unrendered rows.
*
*/
public class VScrollTableBody extends Panel {
public static final int DEFAULT_ROW_HEIGHT = 24;
private double rowHeight = -1;
private final LinkedList<Widget> renderedRows = new LinkedList<Widget>();
/**
* Due some optimizations row height measuring is deferred and initial
* set of rows is rendered detached. Flag set on when table body has
* been attached in dom and rowheight has been measured.
*/
private boolean tBodyMeasurementsDone = false;
Element preSpacer = DOM.createDiv();
Element postSpacer = DOM.createDiv();
Element container = DOM.createDiv();
TableSectionElement tBodyElement = Document.get().createTBodyElement();
Element table = DOM.createTable();
private int firstRendered;
private int lastRendered;
private char[] aligns;
protected VScrollTableBody() {
constructDOM();
setElement(container);
}
public VScrollTableRow getRowByRowIndex(int indexInTable) {
int internalIndex = indexInTable - firstRendered;
if (internalIndex >= 0 && internalIndex < renderedRows.size()) {
return (VScrollTableRow) renderedRows.get(internalIndex);
} else {
return null;
}
}
/**
* @return the height of scrollable body, subpixels ceiled.
*/
public int getRequiredHeight() {
return preSpacer.getOffsetHeight() + postSpacer.getOffsetHeight()
+ Util.getRequiredHeight(table);
}
private void constructDOM() {
DOM.setElementProperty(table, "className", CLASSNAME + "-table");
if (BrowserInfo.get().isIE()) {
table.setPropertyInt("cellSpacing", 0);
}
DOM.setElementProperty(preSpacer, "className", CLASSNAME
+ "-row-spacer");
DOM.setElementProperty(postSpacer, "className", CLASSNAME
+ "-row-spacer");
table.appendChild(tBodyElement);
DOM.appendChild(container, preSpacer);
DOM.appendChild(container, table);
DOM.appendChild(container, postSpacer);
if (BrowserInfo.get().isTouchDevice()) {
NodeList<Node> childNodes = container.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Element item = (Element) childNodes.getItem(i);
item.getStyle().setProperty("webkitTransform",
"translate3d(0,0,0)");
}
}
}
public int getAvailableWidth() {
int availW = scrollBodyPanel.getOffsetWidth() - getBorderWidth();
return availW;
}
public void renderInitialRows(UIDL rowData, int firstIndex, int rows) {
firstRendered = firstIndex;
lastRendered = firstIndex + rows - 1;
final Iterator<?> it = rowData.getChildIterator();
aligns = tHead.getColumnAlignments();
while (it.hasNext()) {
final VScrollTableRow row = createRow((UIDL) it.next(), aligns);
addRow(row);
}
if (isAttached()) {
fixSpacers();
}
}
public void renderRows(UIDL rowData, int firstIndex, int rows) {
// FIXME REVIEW
aligns = tHead.getColumnAlignments();
final Iterator<?> it = rowData.getChildIterator();
if (firstIndex == lastRendered + 1) {
while (it.hasNext()) {
final VScrollTableRow row = prepareRow((UIDL) it.next());
addRow(row);
lastRendered++;
}
fixSpacers();
} else if (firstIndex + rows == firstRendered) {
final VScrollTableRow[] rowArray = new VScrollTableRow[rows];
int i = rows;
while (it.hasNext()) {
i--;
rowArray[i] = prepareRow((UIDL) it.next());
}
for (i = 0; i < rows; i++) {
addRowBeforeFirstRendered(rowArray[i]);
firstRendered--;
}
} else {
// completely new set of rows
while (lastRendered + 1 > firstRendered) {
unlinkRow(false);
}
final VScrollTableRow row = prepareRow((UIDL) it.next());
firstRendered = firstIndex;
lastRendered = firstIndex - 1;
addRow(row);
lastRendered++;
setContainerHeight();
fixSpacers();
while (it.hasNext()) {
addRow(prepareRow((UIDL) it.next()));
lastRendered++;
}
fixSpacers();
}
// this may be a new set of rows due content change,
// ensure we have proper cache rows
ensureCacheFilled();
}
/**
* Ensure we have the correct set of rows on client side, e.g. if the
* content on the server side has changed, or the client scroll position
* has changed since the last request.
*/
protected void ensureCacheFilled() {
int reactFirstRow = (int) (firstRowInViewPort - pageLength
* cache_react_rate);
int reactLastRow = (int) (firstRowInViewPort + pageLength + pageLength
* cache_react_rate);
if (reactFirstRow < 0) {
reactFirstRow = 0;
}
if (reactLastRow >= totalRows) {
reactLastRow = totalRows - 1;
}
if (lastRendered < reactFirstRow || firstRendered > reactLastRow) {
/*
* #8040 - scroll position is completely changed since the
* latest request, so request a new set of rows.
*
* TODO: We should probably check whether the fetched rows match
* the current scroll position right when they arrive, so as to
* not waste time rendering a set of rows that will never be
* visible...
*/
rowRequestHandler.setReqFirstRow(reactFirstRow);
rowRequestHandler.setReqRows(reactLastRow - reactFirstRow + 1);
rowRequestHandler.deferRowFetch(1);
} else if (lastRendered < reactLastRow) {
// get some cache rows below visible area
rowRequestHandler.setReqFirstRow(lastRendered + 1);
rowRequestHandler.setReqRows(reactLastRow - lastRendered);
rowRequestHandler.deferRowFetch(1);
} else if (firstRendered > reactFirstRow) {
/*
* Branch for fetching cache above visible area.
*
* If cache needed for both before and after visible area, this
* will be rendered after-cache is received and rendered. So in
* some rare situations the table may make two cache visits to
* server.
*/
rowRequestHandler.setReqFirstRow(reactFirstRow);
rowRequestHandler.setReqRows(firstRendered - reactFirstRow);
rowRequestHandler.deferRowFetch(1);
}
}
/**
* Inserts rows as provided in the rowData starting at firstIndex.
*
* @param rowData
* @param firstIndex
* @param rows
* the number of rows
* @return a list of the rows added.
*/
protected List<VScrollTableRow> insertRows(UIDL rowData,
int firstIndex, int rows) {
aligns = tHead.getColumnAlignments();
final Iterator<?> it = rowData.getChildIterator();
List<VScrollTableRow> insertedRows = new ArrayList<VScrollTableRow>();
if (firstIndex == lastRendered + 1) {
while (it.hasNext()) {
final VScrollTableRow row = prepareRow((UIDL) it.next());
addRow(row);
insertedRows.add(row);
lastRendered++;
}
fixSpacers();
} else if (firstIndex + rows == firstRendered) {
final VScrollTableRow[] rowArray = new VScrollTableRow[rows];
int i = rows;
while (it.hasNext()) {
i--;
rowArray[i] = prepareRow((UIDL) it.next());
}
for (i = 0; i < rows; i++) {
addRowBeforeFirstRendered(rowArray[i]);
insertedRows.add(rowArray[i]);
firstRendered--;
}
} else {
// insert in the middle
int ix = firstIndex;
while (it.hasNext()) {
VScrollTableRow row = prepareRow((UIDL) it.next());
insertRowAt(row, ix);
insertedRows.add(row);
lastRendered++;
ix++;
}
fixSpacers();
}
return insertedRows;
}
protected List<VScrollTableRow> insertAndReindexRows(UIDL rowData,
int firstIndex, int rows) {
List<VScrollTableRow> inserted = insertRows(rowData, firstIndex,
rows);
int actualIxOfFirstRowAfterInserted = firstIndex + rows
- firstRendered;
for (int ix = actualIxOfFirstRowAfterInserted; ix < renderedRows
.size(); ix++) {
VScrollTableRow r = (VScrollTableRow) renderedRows.get(ix);
r.setIndex(r.getIndex() + rows);
}
setContainerHeight();
return inserted;
}
protected void insertRowsDeleteBelow(UIDL rowData, int firstIndex,
int rows) {
unlinkAllRowsStartingAt(firstIndex);
insertRows(rowData, firstIndex, rows);
setContainerHeight();
}
/**
* This method is used to instantiate new rows for this table. It
* automatically sets correct widths to rows cells and assigns correct
* client reference for child widgets.
*
* This method can be called only after table has been initialized
*
* @param uidl
*/
private VScrollTableRow prepareRow(UIDL uidl) {
final VScrollTableRow row = createRow(uidl, aligns);
row.initCellWidths();
return row;
}
protected VScrollTableRow createRow(UIDL uidl, char[] aligns2) {
if (uidl.hasAttribute("gen_html")) {
// This is a generated row.
return new VScrollTableGeneratedRow(uidl, aligns2);
}
return new VScrollTableRow(uidl, aligns2);
}
private void addRowBeforeFirstRendered(VScrollTableRow row) {
row.setIndex(firstRendered - 1);
if (row.isSelected()) {
row.addStyleName("v-selected");
}
tBodyElement.insertBefore(row.getElement(),
tBodyElement.getFirstChild());
adopt(row);
renderedRows.add(0, row);
}
private void addRow(VScrollTableRow row) {
row.setIndex(firstRendered + renderedRows.size());
if (row.isSelected()) {
row.addStyleName("v-selected");
}
tBodyElement.appendChild(row.getElement());
adopt(row);
renderedRows.add(row);
}
private void insertRowAt(VScrollTableRow row, int index) {
row.setIndex(index);
if (row.isSelected()) {
row.addStyleName("v-selected");
}
if (index > 0) {
VScrollTableRow sibling = getRowByRowIndex(index - 1);
tBodyElement
.insertAfter(row.getElement(), sibling.getElement());
} else {
VScrollTableRow sibling = getRowByRowIndex(index);
tBodyElement.insertBefore(row.getElement(),
sibling.getElement());
}
adopt(row);
int actualIx = index - firstRendered;
renderedRows.add(actualIx, row);
}
public Iterator<Widget> iterator() {
return renderedRows.iterator();
}
/**
* @return false if couldn't remove row
*/
protected boolean unlinkRow(boolean fromBeginning) {
if (lastRendered - firstRendered < 0) {
return false;
}
int actualIx;
if (fromBeginning) {
actualIx = 0;
firstRendered++;
} else {
actualIx = renderedRows.size() - 1;
lastRendered--;
}
if (actualIx >= 0) {
unlinkRowAtActualIndex(actualIx);
fixSpacers();
return true;
}
return false;
}
protected void unlinkRows(int firstIndex, int count) {
if (count < 1) {
return;
}
if (firstRendered > firstIndex
&& firstRendered < firstIndex + count) {
firstIndex = firstRendered;
}
int lastIndex = firstIndex + count - 1;
if (lastRendered < lastIndex) {
lastIndex = lastRendered;
}
for (int ix = lastIndex; ix >= firstIndex; ix--) {
unlinkRowAtActualIndex(actualIndex(ix));
lastRendered--;
}
fixSpacers();
}
protected void unlinkAndReindexRows(int firstIndex, int count) {
unlinkRows(firstIndex, count);
int actualFirstIx = firstIndex - firstRendered;
for (int ix = actualFirstIx; ix < renderedRows.size(); ix++) {
VScrollTableRow r = (VScrollTableRow) renderedRows.get(ix);
r.setIndex(r.getIndex() - count);
}
setContainerHeight();
}
protected void unlinkAllRowsStartingAt(int index) {
if (firstRendered > index) {
index = firstRendered;
}
for (int ix = renderedRows.size() - 1; ix >= index; ix--) {
unlinkRowAtActualIndex(actualIndex(ix));
lastRendered--;
}
fixSpacers();
}
private int actualIndex(int index) {
return index - firstRendered;
}
private void unlinkRowAtActualIndex(int index) {
final VScrollTableRow toBeRemoved = (VScrollTableRow) renderedRows
.get(index);
// Unregister row tooltip
client.registerTooltip(VScrollTable.this, toBeRemoved.getElement(),
null);
for (int i = 0; i < toBeRemoved.getElement().getChildCount(); i++) {
// Unregister cell tooltips
Element td = toBeRemoved.getElement().getChild(i).cast();
client.registerTooltip(VScrollTable.this, td, null);
}
lazyUnregistryBag.add(toBeRemoved);
tBodyElement.removeChild(toBeRemoved.getElement());
orphan(toBeRemoved);
renderedRows.remove(index);
}
@Override
public boolean remove(Widget w) {
throw new UnsupportedOperationException();
}
@Override
protected void onAttach() {
super.onAttach();
setContainerHeight();
}
/**
* Fix container blocks height according to totalRows to avoid
* "bouncing" when scrolling
*/
private void setContainerHeight() {
fixSpacers();
DOM.setStyleAttribute(container, "height",
measureRowHeightOffset(totalRows) + "px");
}
private void fixSpacers() {
int prepx = measureRowHeightOffset(firstRendered);
if (prepx < 0) {
prepx = 0;
}
preSpacer.getStyle().setPropertyPx("height", prepx);
int postpx = measureRowHeightOffset(totalRows - 1)
- measureRowHeightOffset(lastRendered);
if (postpx < 0) {
postpx = 0;
}
postSpacer.getStyle().setPropertyPx("height", postpx);
}
public double getRowHeight() {
return getRowHeight(false);
}
public double getRowHeight(boolean forceUpdate) {
if (tBodyMeasurementsDone && !forceUpdate) {
return rowHeight;
} else {
if (tBodyElement.getRows().getLength() > 0) {
int tableHeight = getTableHeight();
int rowCount = tBodyElement.getRows().getLength();
rowHeight = tableHeight / (double) rowCount;
} else {
if (isAttached()) {
// measure row height by adding a dummy row
VScrollTableRow scrollTableRow = new VScrollTableRow();
tBodyElement.appendChild(scrollTableRow.getElement());
getRowHeight(forceUpdate);
tBodyElement.removeChild(scrollTableRow.getElement());
} else {
// TODO investigate if this can never happen anymore
return DEFAULT_ROW_HEIGHT;
}
}
tBodyMeasurementsDone = true;
return rowHeight;
}
}
public int getTableHeight() {
return table.getOffsetHeight();
}
/**
* Returns the width available for column content.
*
* @param columnIndex
* @return
*/
public int getColWidth(int columnIndex) {
if (tBodyMeasurementsDone) {
if (renderedRows.isEmpty()) {
// no rows yet rendered
return 0;
}
for (Widget row : renderedRows) {
if (!(row instanceof VScrollTableGeneratedRow)) {
TableRowElement tr = row.getElement().cast();
Element wrapperdiv = tr.getCells().getItem(columnIndex)
.getFirstChildElement().cast();
return wrapperdiv.getOffsetWidth();
}
}
return 0;
} else {
return 0;
}
}
/**
* Sets the content width of a column.
*
* Due IE limitation, we must set the width to a wrapper elements inside
* table cells (with overflow hidden, which does not work on td
* elements).
*
* To get this work properly crossplatform, we will also set the width
* of td.
*
* @param colIndex
* @param w
*/
public void setColWidth(int colIndex, int w) {
for (Widget row : renderedRows) {
((VScrollTableRow) row).setCellWidth(colIndex, w);
}
}
private int cellExtraWidth = -1;
/**
* Method to return the space used for cell paddings + border.
*/
private int getCellExtraWidth() {
if (cellExtraWidth < 0) {
detectExtrawidth();
}
return cellExtraWidth;
}
private void detectExtrawidth() {
NodeList<TableRowElement> rows = tBodyElement.getRows();
if (rows.getLength() == 0) {
/* need to temporary add empty row and detect */
VScrollTableRow scrollTableRow = new VScrollTableRow();
tBodyElement.appendChild(scrollTableRow.getElement());
detectExtrawidth();
tBodyElement.removeChild(scrollTableRow.getElement());
} else {
boolean noCells = false;
TableRowElement item = rows.getItem(0);
TableCellElement firstTD = item.getCells().getItem(0);
if (firstTD == null) {
// content is currently empty, we need to add a fake cell
// for measuring
noCells = true;
VScrollTableRow next = (VScrollTableRow) iterator().next();
boolean sorted = tHead.getHeaderCell(0) != null ? tHead
.getHeaderCell(0).isSorted() : false;
next.addCell(null, "", ALIGN_LEFT, "", true, sorted);
firstTD = item.getCells().getItem(0);
}
com.google.gwt.dom.client.Element wrapper = firstTD
.getFirstChildElement();
cellExtraWidth = firstTD.getOffsetWidth()
- wrapper.getOffsetWidth();
if (noCells) {
firstTD.getParentElement().removeChild(firstTD);
}
}
}
private void reLayoutComponents() {
for (Widget w : this) {
VScrollTableRow r = (VScrollTableRow) w;
for (Widget widget : r) {
client.handleComponentRelativeSize(widget);
}
}
}
public int getLastRendered() {
return lastRendered;
}
public int getFirstRendered() {
return firstRendered;
}
public void moveCol(int oldIndex, int newIndex) {
// loop all rows and move given index to its new place
final Iterator<?> rows = iterator();
while (rows.hasNext()) {
final VScrollTableRow row = (VScrollTableRow) rows.next();
final Element td = DOM.getChild(row.getElement(), oldIndex);
if (td != null) {
DOM.removeChild(row.getElement(), td);
DOM.insertChild(row.getElement(), td, newIndex);
}
}
}
/**
* Restore row visibility which is set to "none" when the row is
* rendered (due a performance optimization).
*/
private void restoreRowVisibility() {
for (Widget row : renderedRows) {
row.getElement().getStyle().setProperty("visibility", "");
}
}
public class VScrollTableRow extends Panel implements ActionOwner,
Container {
private static final int TOUCHSCROLL_TIMEOUT = 100;
private static final int DRAGMODE_MULTIROW = 2;
protected ArrayList<Widget> childWidgets = new ArrayList<Widget>();
private boolean selected = false;
protected final int rowKey;
private List<UIDL> pendingComponentPaints;
private String[] actionKeys = null;
private final TableRowElement rowElement;
private boolean mDown;
private int index;
private Event touchStart;
private static final String ROW_CLASSNAME_EVEN = CLASSNAME + "-row";
private static final String ROW_CLASSNAME_ODD = CLASSNAME
+ "-row-odd";
private static final int TOUCH_CONTEXT_MENU_TIMEOUT = 500;
private Timer contextTouchTimeout;
private int touchStartY;
private int touchStartX;
private VScrollTableRow(int rowKey) {
this.rowKey = rowKey;
rowElement = Document.get().createTRElement();
setElement(rowElement);
DOM.sinkEvents(getElement(), Event.MOUSEEVENTS
| Event.TOUCHEVENTS | Event.ONDBLCLICK
| Event.ONCONTEXTMENU | VTooltip.TOOLTIP_EVENTS);
}
public VScrollTableRow(UIDL uidl, char[] aligns) {
this(uidl.getIntAttribute("key"));
/*
* Rendering the rows as hidden improves Firefox and Safari
* performance drastically.
*/
getElement().getStyle().setProperty("visibility", "hidden");
String rowStyle = uidl.getStringAttribute("rowstyle");
if (rowStyle != null) {
addStyleName(CLASSNAME + "-row-" + rowStyle);
}
String rowDescription = uidl.getStringAttribute("rowdescr");
if (rowDescription != null && !rowDescription.equals("")) {
TooltipInfo info = new TooltipInfo(rowDescription);
client.registerTooltip(VScrollTable.this, rowElement, info);
} else {
// Remove possibly previously set tooltip
client.registerTooltip(VScrollTable.this, rowElement, null);
}
tHead.getColumnAlignments();
int col = 0;
int visibleColumnIndex = -1;
// row header
if (showRowHeaders) {
boolean sorted = tHead.getHeaderCell(col).isSorted();
addCell(uidl, buildCaptionHtmlSnippet(uidl), aligns[col++],
"rowheader", true, sorted);
visibleColumnIndex++;
}
if (uidl.hasAttribute("al")) {
actionKeys = uidl.getStringArrayAttribute("al");
}
addCellsFromUIDL(uidl, aligns, col, visibleColumnIndex);
if (uidl.hasAttribute("selected") && !isSelected()) {
toggleSelection();
}
}
/**
* Add a dummy row, used for measurements if Table is empty.
*/
public VScrollTableRow() {
this(0);
addStyleName(CLASSNAME + "-row");
addCell(null, "_", 'b', "", true, false);
}
protected void initCellWidths() {
final int cells = tHead.getVisibleCellCount();
for (int i = 0; i < cells; i++) {
int w = VScrollTable.this.getColWidth(getColKeyByIndex(i));
if (w < 0) {
w = 0;
}
setCellWidth(i, w);
}
}
protected void setCellWidth(int cellIx, int width) {
final Element cell = DOM.getChild(getElement(), cellIx);
cell.getFirstChildElement().getStyle()
.setPropertyPx("width", width);
cell.getStyle().setPropertyPx("width", width);
}
protected void addCellsFromUIDL(UIDL uidl, char[] aligns, int col,
int visibleColumnIndex) {
final Iterator<?> cells = uidl.getChildIterator();
while (cells.hasNext()) {
final Object cell = cells.next();
visibleColumnIndex++;
String columnId = visibleColOrder[visibleColumnIndex];
String style = "";
if (uidl.hasAttribute("style-" + columnId)) {
style = uidl.getStringAttribute("style-" + columnId);
}
String description = null;
if (uidl.hasAttribute("descr-" + columnId)) {
description = uidl.getStringAttribute("descr-"
+ columnId);
}
boolean sorted = tHead.getHeaderCell(col).isSorted();
if (cell instanceof String) {
addCell(uidl, cell.toString(), aligns[col++], style,
isRenderHtmlInCells(), sorted, description);
} else {
final Paintable cellContent = client
.getPaintable((UIDL) cell);
addCell(uidl, (Widget) cellContent, aligns[col++],
style, sorted);
paintComponent(cellContent, (UIDL) cell);
}
}
}
/**
* Overriding this and returning true causes all text cells to be
* rendered as HTML.
*
* @return always returns false in the default implementation
*/
protected boolean isRenderHtmlInCells() {
return false;
}
/**
* Detects whether row is visible in tables viewport.
*
* @return
*/
public boolean isInViewPort() {
int absoluteTop = getAbsoluteTop();
int scrollPosition = scrollBodyPanel.getScrollPosition();
if (absoluteTop < scrollPosition) {
return false;
}
int maxVisible = scrollPosition
+ scrollBodyPanel.getOffsetHeight() - getOffsetHeight();
if (absoluteTop > maxVisible) {
return false;
}
return true;
}
/**
* Makes a check based on indexes whether the row is before the
* compared row.
*
* @param row1
* @return true if this rows index is smaller than in the row1
*/
public boolean isBefore(VScrollTableRow row1) {
return getIndex() < row1.getIndex();
}
/**
* Sets the index of the row in the whole table. Currently used just
* to set even/odd classname
*
* @param indexInWholeTable
*/
private void setIndex(int indexInWholeTable) {
index = indexInWholeTable;
boolean isOdd = indexInWholeTable % 2 == 0;
// Inverted logic to be backwards compatible with earlier 6.4.
// It is very strange because rows 1,3,5 are considered "even"
// and 2,4,6 "odd".
//
// First remove any old styles so that both styles aren't
// applied when indexes are updated.
removeStyleName(ROW_CLASSNAME_ODD);
removeStyleName(ROW_CLASSNAME_EVEN);
if (!isOdd) {
addStyleName(ROW_CLASSNAME_ODD);
} else {
addStyleName(ROW_CLASSNAME_EVEN);
}
}
public int getIndex() {
return index;
}
protected void paintComponent(Paintable p, UIDL uidl) {
if (isAttached()) {
p.updateFromUIDL(uidl, client);
} else {
if (pendingComponentPaints == null) {
pendingComponentPaints = new LinkedList<UIDL>();
}
pendingComponentPaints.add(uidl);
}
}
@Override
protected void onAttach() {
super.onAttach();
if (pendingComponentPaints != null) {
for (UIDL uidl : pendingComponentPaints) {
Paintable paintable = client.getPaintable(uidl);
paintable.updateFromUIDL(uidl, client);
}
pendingComponentPaints.clear();
}
}
@Override
protected void onDetach() {
super.onDetach();
client.getContextMenu().ensureHidden(this);
}
public String getKey() {
return String.valueOf(rowKey);
}
public void addCell(UIDL rowUidl, String text, char align,
String style, boolean textIsHTML, boolean sorted) {
addCell(rowUidl, text, align, style, textIsHTML, sorted, null);
}
public void addCell(UIDL rowUidl, String text, char align,
String style, boolean textIsHTML, boolean sorted,
String description) {
// String only content is optimized by not using Label widget
final TableCellElement td = DOM.createTD().cast();
initCellWithText(text, align, style, textIsHTML, sorted,
description, td);
}
protected void initCellWithText(String text, char align,
String style, boolean textIsHTML, boolean sorted,
String description, final TableCellElement td) {
final Element container = DOM.createDiv();
String className = CLASSNAME + "-cell-content";
if (style != null && !style.equals("")) {
className += " " + CLASSNAME + "-cell-content-" + style;
}
if (sorted) {
className += " " + CLASSNAME + "-cell-content-sorted";
}
td.setClassName(className);
container.setClassName(CLASSNAME + "-cell-wrapper");
if (textIsHTML) {
container.setInnerHTML(text);
} else {
container.setInnerText(text);
}
if (align != ALIGN_LEFT) {
switch (align) {
case ALIGN_CENTER:
container.getStyle().setProperty("textAlign", "center");
break;
case ALIGN_RIGHT:
default:
container.getStyle().setProperty("textAlign", "right");
break;
}
}
if (description != null && !description.equals("")) {
TooltipInfo info = new TooltipInfo(description);
client.registerTooltip(VScrollTable.this, td, info);
} else {
// Remove possibly previously set tooltip
client.registerTooltip(VScrollTable.this, td, null);
}
td.appendChild(container);
getElement().appendChild(td);
}
public void addCell(UIDL rowUidl, Widget w, char align,
String style, boolean sorted) {
final TableCellElement td = DOM.createTD().cast();
initCellWithWidget(w, align, style, sorted, td);
}
protected void initCellWithWidget(Widget w, char align,
String style, boolean sorted, final TableCellElement td) {
final Element container = DOM.createDiv();
String className = CLASSNAME + "-cell-content";
if (style != null && !style.equals("")) {
className += " " + CLASSNAME + "-cell-content-" + style;
}
if (sorted) {
className += " " + CLASSNAME + "-cell-content-sorted";
}
td.setClassName(className);
container.setClassName(CLASSNAME + "-cell-wrapper");
// TODO most components work with this, but not all (e.g.
// Select)
// Old comment: make widget cells respect align.
// text-align:center for IE, margin: auto for others
if (align != ALIGN_LEFT) {
switch (align) {
case ALIGN_CENTER:
container.getStyle().setProperty("textAlign", "center");
break;
case ALIGN_RIGHT:
default:
container.getStyle().setProperty("textAlign", "right");
break;
}
}
td.appendChild(container);
getElement().appendChild(td);
// ensure widget not attached to another element (possible tBody
// change)
w.removeFromParent();
container.appendChild(w.getElement());
adopt(w);
childWidgets.add(w);
}
public Iterator<Widget> iterator() {
return childWidgets.iterator();
}
@Override
public boolean remove(Widget w) {
if (childWidgets.contains(w)) {
orphan(w);
DOM.removeChild(DOM.getParent(w.getElement()),
w.getElement());
childWidgets.remove(w);
return true;
} else {
return false;
}
}
/**
* If there are registered click listeners, sends a click event and
* returns true. Otherwise, does nothing and returns false.
*
* @param event
* @param targetTdOrTr
* @param immediate
* Whether the event is sent immediately
* @return Whether a click event was sent
*/
private boolean handleClickEvent(Event event, Element targetTdOrTr,
boolean immediate) {
if (!client.hasEventListeners(VScrollTable.this,
ITEM_CLICK_EVENT_ID)) {
// Don't send an event if nobody is listening
return false;
}
// This row was clicked
client.updateVariable(paintableId, "clickedKey", "" + rowKey,
false);
if (getElement() == targetTdOrTr.getParentElement()) {
// A specific column was clicked
int childIndex = DOM.getChildIndex(getElement(),
targetTdOrTr);
String colKey = null;
colKey = tHead.getHeaderCell(childIndex).getColKey();
client.updateVariable(paintableId, "clickedColKey", colKey,
false);
}
MouseEventDetails details = new MouseEventDetails(event);
client.updateVariable(paintableId, "clickEvent",
details.toString(), immediate);
return true;
}
private void handleTooltips(final Event event, Element target) {
if (target.hasTagName("TD")) {
// Table cell (td)
Element container = target.getFirstChildElement().cast();
Element widget = container.getFirstChildElement().cast();
boolean containsWidget = false;
for (Widget w : childWidgets) {
if (widget == w.getElement()) {
containsWidget = true;
break;
}
}
if (!containsWidget) {
// Only text nodes has tooltips
if (client.getTooltipTitleInfo(VScrollTable.this,
target) != null) {
// Cell has description, use it
client.handleTooltipEvent(event, VScrollTable.this,
target);
} else {
// Cell might have row description, use row
// description
client.handleTooltipEvent(event, VScrollTable.this,
target.getParentElement());
}
}
} else {
// Table row (tr)
client.handleTooltipEvent(event, VScrollTable.this, target);
}
}
/*
* React on click that occur on content cells only
*/
@Override
public void onBrowserEvent(final Event event) {
if (enabled) {
final int type = event.getTypeInt();
final Element targetTdOrTr = getEventTargetTdOrTr(event);
if (type == Event.ONCONTEXTMENU) {
showContextMenu(event);
if (enabled
&& (actionKeys != null || client
.hasEventListeners(VScrollTable.this,
ITEM_CLICK_EVENT_ID))) {
/*
* Prevent browser context menu only if there are
* action handlers or item click listeners
* registered
*/
event.stopPropagation();
event.preventDefault();
}
return;
}
boolean targetCellOrRowFound = targetTdOrTr != null;
if (targetCellOrRowFound) {
handleTooltips(event, targetTdOrTr);
}
switch (type) {
case Event.ONDBLCLICK:
if (targetCellOrRowFound) {
handleClickEvent(event, targetTdOrTr, true);
}
break;
case Event.ONMOUSEUP:
if (targetCellOrRowFound) {
mDown = false;
/*
* Queue here, send at the same time as the
* corresponding value change event - see #7127
*/
boolean clickEventSent = handleClickEvent(event,
targetTdOrTr, false);
if (event.getButton() == Event.BUTTON_LEFT
&& isSelectable()) {
// Ctrl+Shift click
if ((event.getCtrlKey() || event.getMetaKey())
&& event.getShiftKey()
&& isMultiSelectModeDefault()) {
toggleShiftSelection(false);
setRowFocus(this);
// Ctrl click
} else if ((event.getCtrlKey() || event
.getMetaKey())
&& isMultiSelectModeDefault()) {
boolean wasSelected = isSelected();
toggleSelection();
setRowFocus(this);
/*
* next possible range select must start on
* this row
*/
selectionRangeStart = this;
if (wasSelected) {
removeRowFromUnsentSelectionRanges(this);
}
} else if ((event.getCtrlKey() || event
.getMetaKey()) && isSingleSelectMode()) {
// Ctrl (or meta) click (Single selection)
if (!isSelected()
|| (isSelected() && nullSelectionAllowed)) {
if (!isSelected()) {
deselectAll();
}
toggleSelection();
setRowFocus(this);
}
} else if (event.getShiftKey()
&& isMultiSelectModeDefault()) {
// Shift click
toggleShiftSelection(true);
} else {
// click
boolean currentlyJustThisRowSelected = selectedRowKeys
.size() == 1
&& selectedRowKeys
.contains(getKey());
if (!currentlyJustThisRowSelected) {
if (isSingleSelectMode()
|| isMultiSelectModeDefault()) {
/*
* For default multi select mode
* (ctrl/shift) and for single
* select mode we need to clear the
* previous selection before
* selecting a new one when the user
* clicks on a row. Only in
* multiselect/simple mode the old
* selection should remain after a
* normal click.
*/
deselectAll();
}
toggleSelection();
} else if ((isSingleSelectMode() || isMultiSelectModeSimple())
&& nullSelectionAllowed) {
toggleSelection();
}/*
* else NOP to avoid excessive server
* visits (selection is removed with
* CTRL/META click)
*/
selectionRangeStart = this;
setRowFocus(this);
}
// Remove IE text selection hack
if (BrowserInfo.get().isIE()) {
((Element) event.getEventTarget().cast())
.setPropertyJSO("onselectstart",
null);
}
// Queue value change
sendSelectedRows(false);
}
/*
* Send queued click and value change events if any
* If a click event is sent, send value change with
* it regardless of the immediate flag, see #7127
*/
if (immediate || clickEventSent) {
client.sendPendingVariableChanges();
}
}
break;
case Event.ONTOUCHEND:
case Event.ONTOUCHCANCEL:
if (touchStart != null) {
/*
* Touch has not been handled as neither context or
* drag start, handle it as a click.
*/
Util.simulateClickFromTouchEvent(touchStart, this);
touchStart = null;
}
if (contextTouchTimeout != null) {
contextTouchTimeout.cancel();
}
break;
case Event.ONTOUCHMOVE:
if (isSignificantMove(event)) {
/*
* TODO figure out scroll delegate don't eat events
* if row is selected. Null check for active
* delegate is as a workaround.
*/
if (dragmode != 0
&& touchStart != null
&& (TouchScrollDelegate
.getActiveScrollDelegate() == null)) {
startRowDrag(touchStart, type, targetTdOrTr);
}
if (contextTouchTimeout != null) {
contextTouchTimeout.cancel();
}
/*
* Avoid clicks and drags by clearing touch start
* flag.
*/
touchStart = null;
}
break;
case Event.ONTOUCHSTART:
touchStart = event;
Touch touch = event.getChangedTouches().get(0);
// save position to fields, touches in events are same
// isntance during the operation.
touchStartX = touch.getClientX();
touchStartY = touch.getClientY();
/*
* Prevent simulated mouse events.
*/
touchStart.preventDefault();
if (dragmode != 0 || actionKeys != null) {
new Timer() {
@Override
public void run() {
TouchScrollDelegate activeScrollDelegate = TouchScrollDelegate
.getActiveScrollDelegate();
/*
* If there's a scroll delegate, check if
* we're actually scrolling and handle it.
* If no delegate, do nothing here and let
* the row handle potential drag'n'drop or
* context menu.
*/
if (activeScrollDelegate != null) {
if (activeScrollDelegate.isMoved()) {
/*
* Prevent the row from handling
* touch move/end events (the
* delegate handles those) and from
* doing drag'n'drop or opening a
* context menu.
*/
touchStart = null;
} else {
/*
* Scrolling hasn't started, so
* cancel delegate and let the row
* handle potential drag'n'drop or
* context menu.
*/
activeScrollDelegate
.stopScrolling();
}
}
}
}.schedule(TOUCHSCROLL_TIMEOUT);
if (contextTouchTimeout == null
&& actionKeys != null) {
contextTouchTimeout = new Timer() {
@Override
public void run() {
if (touchStart != null) {
showContextMenu(touchStart);
touchStart = null;
}
}
};
}
if (contextTouchTimeout != null) {
contextTouchTimeout.cancel();
contextTouchTimeout
.schedule(TOUCH_CONTEXT_MENU_TIMEOUT);
}
}
break;
case Event.ONMOUSEDOWN:
if (targetCellOrRowFound) {
setRowFocus(this);
ensureFocus();
if (dragmode != 0
&& (event.getButton() == NativeEvent.BUTTON_LEFT)) {
startRowDrag(event, type, targetTdOrTr);
} else if (event.getCtrlKey()
|| event.getShiftKey()
|| event.getMetaKey()
&& isMultiSelectModeDefault()) {
// Prevent default text selection in Firefox
event.preventDefault();
// Prevent default text selection in IE
if (BrowserInfo.get().isIE()) {
((Element) event.getEventTarget().cast())
.setPropertyJSO(
"onselectstart",
getPreventTextSelectionIEHack());
}
event.stopPropagation();
}
}
break;
case Event.ONMOUSEOUT:
if (targetCellOrRowFound) {
mDown = false;
}
break;
default:
break;
}
}
super.onBrowserEvent(event);
}
private boolean isSignificantMove(Event event) {
if (touchStart == null) {
// no touch start
return false;
}
/*
* TODO calculate based on real distance instead of separate
* axis checks
*/
Touch touch = event.getChangedTouches().get(0);
if (Math.abs(touch.getClientX() - touchStartX) > TouchScrollDelegate.SIGNIFICANT_MOVE_THRESHOLD) {
return true;
}
if (Math.abs(touch.getClientY() - touchStartY) > TouchScrollDelegate.SIGNIFICANT_MOVE_THRESHOLD) {
return true;
}
return false;
}
protected void startRowDrag(Event event, final int type,
Element targetTdOrTr) {
mDown = true;
VTransferable transferable = new VTransferable();
transferable.setDragSource(VScrollTable.this);
transferable.setData("itemId", "" + rowKey);
NodeList<TableCellElement> cells = rowElement.getCells();
for (int i = 0; i < cells.getLength(); i++) {
if (cells.getItem(i).isOrHasChild(targetTdOrTr)) {
HeaderCell headerCell = tHead.getHeaderCell(i);
transferable.setData("propertyId", headerCell.cid);
break;
}
}
VDragEvent ev = VDragAndDropManager.get().startDrag(
transferable, event, true);
if (dragmode == DRAGMODE_MULTIROW && isMultiSelectModeAny()
&& selectedRowKeys.contains("" + rowKey)) {
ev.createDragImage(
(Element) scrollBody.tBodyElement.cast(), true);
Element dragImage = ev.getDragImage();
int i = 0;
for (Iterator<Widget> iterator = scrollBody.iterator(); iterator
.hasNext();) {
VScrollTableRow next = (VScrollTableRow) iterator
.next();
Element child = (Element) dragImage.getChild(i++);
if (!selectedRowKeys.contains("" + next.rowKey)) {
child.getStyle().setVisibility(Visibility.HIDDEN);
}
}
} else {
ev.createDragImage(getElement(), true);
}
if (type == Event.ONMOUSEDOWN) {
event.preventDefault();
}
event.stopPropagation();
}
/**
* Finds the TD that the event interacts with. Returns null if the
* target of the event should not be handled. If the event target is
* the row directly this method returns the TR element instead of
* the TD.
*
* @param event
* @return TD or TR element that the event targets (the actual event
* target is this element or a child of it)
*/
private Element getEventTargetTdOrTr(Event event) {
final Element eventTarget = event.getEventTarget().cast();
Widget widget = Util.findWidget(eventTarget, null);
final Element thisTrElement = getElement();
if (widget != this) {
/*
* This is a workaround to make Labels, read only TextFields
* and Embedded in a Table clickable (see #2688). It is
* really not a fix as it does not work with a custom read
* only components (not extending VLabel/VEmbedded).
*/
while (widget != null && widget.getParent() != this) {
widget = widget.getParent();
}
if (!(widget instanceof VLabel)
&& !(widget instanceof VEmbedded)
&& !(widget instanceof VTextField && ((VTextField) widget)
.isReadOnly())) {
return null;
}
}
if (eventTarget == thisTrElement) {
// This was a click on the TR element
return thisTrElement;
}
// Iterate upwards until we find the TR element
Element element = eventTarget;
while (element != null
&& element.getParentElement().cast() != thisTrElement) {
element = element.getParentElement().cast();
}
return element;
}
public void showContextMenu(Event event) {
if (enabled && actionKeys != null) {
// Show context menu if there are registered action handlers
int left = Util.getTouchOrMouseClientX(event);
int top = Util.getTouchOrMouseClientY(event);
top += Window.getScrollTop();
left += Window.getScrollLeft();
contextMenu = new ContextMenuDetails(getKey(), left, top);
client.getContextMenu().showAt(this, left, top);
}
}
/**
* Has the row been selected?
*
* @return Returns true if selected, else false
*/
public boolean isSelected() {
return selected;
}
/**
* Toggle the selection of the row
*/
public void toggleSelection() {
selected = !selected;
selectionChanged = true;
if (selected) {
selectedRowKeys.add(String.valueOf(rowKey));
addStyleName("v-selected");
} else {
removeStyleName("v-selected");
selectedRowKeys.remove(String.valueOf(rowKey));
}
}
/**
* Is called when a user clicks an item when holding SHIFT key down.
* This will select a new range from the last focused row
*
* @param deselectPrevious
* Should the previous selected range be deselected
*/
private void toggleShiftSelection(boolean deselectPrevious) {
/*
* Ensures that we are in multiselect mode and that we have a
* previous selection which was not a deselection
*/
if (isSingleSelectMode()) {
// No previous selection found
deselectAll();
toggleSelection();
return;
}
// Set the selectable range
VScrollTableRow endRow = this;
VScrollTableRow startRow = selectionRangeStart;
if (startRow == null) {
startRow = focusedRow;
// If start row is null then we have a multipage selection
// from
// above
if (startRow == null) {
startRow = (VScrollTableRow) scrollBody.iterator()
.next();
setRowFocus(endRow);
}
}
// Deselect previous items if so desired
if (deselectPrevious) {
deselectAll();
}
// we'll ensure GUI state from top down even though selection
// was the opposite way
if (!startRow.isBefore(endRow)) {
VScrollTableRow tmp = startRow;
startRow = endRow;
endRow = tmp;
}
SelectionRange range = new SelectionRange(startRow, endRow);
for (Widget w : scrollBody) {
VScrollTableRow row = (VScrollTableRow) w;
if (range.inRange(row)) {
if (!row.isSelected()) {
row.toggleSelection();
}
selectedRowKeys.add(row.getKey());
}
}
// Add range
if (startRow != endRow) {
selectedRowRanges.add(range);
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.terminal.gwt.client.ui.IActionOwner#getActions ()
*/
public Action[] getActions() {
if (actionKeys == null) {
return new Action[] {};
}
final Action[] actions = new Action[actionKeys.length];
for (int i = 0; i < actions.length; i++) {
final String actionKey = actionKeys[i];
final TreeAction a = new TreeAction(this,
String.valueOf(rowKey), actionKey) {
@Override
public void execute() {
super.execute();
lazyRevertFocusToRow(VScrollTableRow.this);
}
};
a.setCaption(getActionCaption(actionKey));
a.setIconUrl(getActionIcon(actionKey));
actions[i] = a;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
public RenderSpace getAllocatedSpace(Widget child) {
int w = 0;
int i = getColIndexOf(child);
HeaderCell headerCell = tHead.getHeaderCell(i);
if (headerCell != null) {
if (initializedAndAttached) {
w = headerCell.getWidth();
} else {
// header offset width is not absolutely correct value,
// but a best guess (expecting similar content in all
// columns ->
// if one component is relative width so are others)
w = headerCell.getOffsetWidth() - getCellExtraWidth();
}
}
return new RenderSpace(w, 0) {
@Override
public int getHeight() {
return (int) getRowHeight();
}
};
}
private int getColIndexOf(Widget child) {
com.google.gwt.dom.client.Element widgetCell = child
.getElement().getParentElement().getParentElement();
NodeList<TableCellElement> cells = rowElement.getCells();
for (int i = 0; i < cells.getLength(); i++) {
if (cells.getItem(i) == widgetCell) {
return i;
}
}
return -1;
}
public boolean hasChildComponent(Widget component) {
return childWidgets.contains(component);
}
public void replaceChildComponent(Widget oldComponent,
Widget newComponent) {
com.google.gwt.dom.client.Element parentElement = oldComponent
.getElement().getParentElement();
int index = childWidgets.indexOf(oldComponent);
oldComponent.removeFromParent();
parentElement.appendChild(newComponent.getElement());
childWidgets.add(index, newComponent);
adopt(newComponent);
}
public boolean requestLayout(Set<Paintable> children) {
// row size should never change and system wouldn't event
// survive as this is a kind of fake paitable
return true;
}
public void updateCaption(Paintable component, UIDL uidl) {
// NOP, not rendered
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// Should never be called,
// Component container interface faked here to get layouts
// render properly
}
}
protected class VScrollTableGeneratedRow extends VScrollTableRow {
private boolean spanColumns;
private boolean htmlContentAllowed;
public VScrollTableGeneratedRow(UIDL uidl, char[] aligns) {
super(uidl, aligns);
addStyleName("v-table-generated-row");
}
public boolean isSpanColumns() {
return spanColumns;
}
@Override
protected void initCellWidths() {
if (spanColumns) {
setSpannedColumnWidthAfterDOMFullyInited();
} else {
super.initCellWidths();
}
}
private void setSpannedColumnWidthAfterDOMFullyInited() {
// Defer setting width on spanned columns to make sure that
// they are added to the DOM before trying to calculate
// widths.
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
public void execute() {
if (showRowHeaders) {
setCellWidth(0, tHead.getHeaderCell(0).getWidth());
calcAndSetSpanWidthOnCell(1);
} else {
calcAndSetSpanWidthOnCell(0);
}
}
});
}
@Override
protected boolean isRenderHtmlInCells() {
return htmlContentAllowed;
}
@Override
protected void addCellsFromUIDL(UIDL uidl, char[] aligns, int col,
int visibleColumnIndex) {
htmlContentAllowed = uidl.getBooleanAttribute("gen_html");
spanColumns = uidl.getBooleanAttribute("gen_span");
final Iterator<?> cells = uidl.getChildIterator();
if (spanColumns) {
int colCount = uidl.getChildCount();
if (cells.hasNext()) {
final Object cell = cells.next();
if (cell instanceof String) {
addSpannedCell(uidl, cell.toString(), aligns[0],
"", htmlContentAllowed, false, null,
colCount);
} else {
addSpannedCell(uidl, (Widget) cell, aligns[0], "",
false, colCount);
}
}
} else {
super.addCellsFromUIDL(uidl, aligns, col,
visibleColumnIndex);
}
}
private void addSpannedCell(UIDL rowUidl, Widget w, char align,
String style, boolean sorted, int colCount) {
TableCellElement td = DOM.createTD().cast();
td.setColSpan(colCount);
initCellWithWidget(w, align, style, sorted, td);
}
private void addSpannedCell(UIDL rowUidl, String text, char align,
String style, boolean textIsHTML, boolean sorted,
String description, int colCount) {
// String only content is optimized by not using Label widget
final TableCellElement td = DOM.createTD().cast();
td.setColSpan(colCount);
initCellWithText(text, align, style, textIsHTML, sorted,
description, td);
}
@Override
protected void setCellWidth(int cellIx, int width) {
if (isSpanColumns()) {
if (showRowHeaders) {
if (cellIx == 0) {
super.setCellWidth(0, width);
} else {
// We need to recalculate the spanning TDs width for
// every cellIx in order to support column resizing.
calcAndSetSpanWidthOnCell(1);
}
} else {
// Same as above.
calcAndSetSpanWidthOnCell(0);
}
} else {
super.setCellWidth(cellIx, width);
}
}
private void calcAndSetSpanWidthOnCell(final int cellIx) {
int spanWidth = 0;
for (int ix = (showRowHeaders ? 1 : 0); ix < tHead
.getVisibleCellCount(); ix++) {
spanWidth += tHead.getHeaderCell(ix).getOffsetWidth();
}
Util.setWidthExcludingPaddingAndBorder((Element) getElement()
.getChild(cellIx), spanWidth, 13, false);
}
}
/**
* Ensure the component has a focus.
*
* TODO the current implementation simply always calls focus for the
* component. In case the Table at some point implements focus/blur
* listeners, this method needs to be evolved to conditionally call
* focus only if not currently focused.
*/
protected void ensureFocus() {
if (!hasFocus) {
scrollBodyPanel.setFocus(true);
}
}
}
/**
* Deselects all items
*/
public void deselectAll() {
for (Widget w : scrollBody) {
VScrollTableRow row = (VScrollTableRow) w;
if (row.isSelected()) {
row.toggleSelection();
}
}
// still ensure all selects are removed from (not necessary rendered)
selectedRowKeys.clear();
selectedRowRanges.clear();
// also notify server that it clears all previous selections (the client
// side does not know about the invisible ones)
instructServerToForgetPreviousSelections();
}
/**
* Used in multiselect mode when the client side knows that all selections
* are in the next request.
*/
private void instructServerToForgetPreviousSelections() {
client.updateVariable(paintableId, "clearSelections", true, false);
}
/**
* Determines the pagelength when the table height is fixed.
*/
public void updatePageLength() {
// Only update if visible and enabled
if (!isVisible() || !enabled) {
return;
}
if (scrollBody == null) {
return;
}
if (height == null || height.equals("")) {
return;
}
int rowHeight = (int) Math.round(scrollBody.getRowHeight());
int bodyH = scrollBodyPanel.getOffsetHeight();
int rowsAtOnce = bodyH / rowHeight;
boolean anotherPartlyVisible = ((bodyH % rowHeight) != 0);
if (anotherPartlyVisible) {
rowsAtOnce++;
}
if (pageLength != rowsAtOnce) {
pageLength = rowsAtOnce;
client.updateVariable(paintableId, "pagelength", pageLength, false);
if (!rendering) {
int currentlyVisible = scrollBody.lastRendered
- scrollBody.firstRendered;
if (currentlyVisible < pageLength
&& currentlyVisible < totalRows) {
// shake scrollpanel to fill empty space
scrollBodyPanel.setScrollPosition(scrollTop + 1);
scrollBodyPanel.setScrollPosition(scrollTop - 1);
}
}
}
}
@Override
public void setWidth(String width) {
if (this.width.equals(width)) {
return;
}
if (!isVisible()) {
/*
* Do not update size when the table is hidden as all column widths
* will be set to zero and they won't be recalculated when the table
* is set visible again (until the size changes again)
*/
return;
}
this.width = width;
if (width != null && !"".equals(width)) {
super.setWidth(width);
int innerPixels = getOffsetWidth() - getBorderWidth();
if (innerPixels < 0) {
innerPixels = 0;
}
setContentWidth(innerPixels);
// readjust undefined width columns
triggerLazyColumnAdjustment(false);
} else {
// Undefined width
super.setWidth("");
// Readjust size of table
sizeInit();
// readjust undefined width columns
triggerLazyColumnAdjustment(false);
}
/*
* setting width may affect wheter the component has scrollbars -> needs
* scrolling or not
*/
setProperTabIndex();
}
private static final int LAZY_COLUMN_ADJUST_TIMEOUT = 300;
private final Timer lazyAdjustColumnWidths = new Timer() {
/**
* Check for column widths, and available width, to see if we can fix
* column widths "optimally". Doing this lazily to avoid expensive
* calculation when resizing is not yet finished.
*/
@Override
public void run() {
if (scrollBody == null) {
// Try again later if we get here before scrollBody has been
// initalized
triggerLazyColumnAdjustment(false);
return;
}
Iterator<Widget> headCells = tHead.iterator();
int usedMinimumWidth = 0;
int totalExplicitColumnsWidths = 0;
float expandRatioDivider = 0;
int colIndex = 0;
while (headCells.hasNext()) {
final HeaderCell hCell = (HeaderCell) headCells.next();
if (hCell.isDefinedWidth()) {
totalExplicitColumnsWidths += hCell.getWidth();
usedMinimumWidth += hCell.getWidth();
} else {
usedMinimumWidth += hCell.getNaturalColumnWidth(colIndex);
expandRatioDivider += hCell.getExpandRatio();
}
colIndex++;
}
int availW = scrollBody.getAvailableWidth();
// Hey IE, are you really sure about this?
availW = scrollBody.getAvailableWidth();
int visibleCellCount = tHead.getVisibleCellCount();
availW -= scrollBody.getCellExtraWidth() * visibleCellCount;
if (willHaveScrollbars()) {
availW -= Util.getNativeScrollbarSize();
}
int extraSpace = availW - usedMinimumWidth;
if (extraSpace < 0) {
extraSpace = 0;
}
int totalUndefinedNaturalWidths = usedMinimumWidth
- totalExplicitColumnsWidths;
// we have some space that can be divided optimally
HeaderCell hCell;
colIndex = 0;
headCells = tHead.iterator();
int checksum = 0;
while (headCells.hasNext()) {
hCell = (HeaderCell) headCells.next();
if (!hCell.isDefinedWidth()) {
int w = hCell.getNaturalColumnWidth(colIndex);
int newSpace;
if (expandRatioDivider > 0) {
// divide excess space by expand ratios
newSpace = Math.round((w + extraSpace
* hCell.getExpandRatio() / expandRatioDivider));
} else {
if (totalUndefinedNaturalWidths != 0) {
// divide relatively to natural column widths
newSpace = Math.round(w + (float) extraSpace
* (float) w / totalUndefinedNaturalWidths);
} else {
newSpace = w;
}
}
checksum += newSpace;
setColWidth(colIndex, newSpace, false);
} else {
checksum += hCell.getWidth();
}
colIndex++;
}
if (extraSpace > 0 && checksum != availW) {
/*
* There might be in some cases a rounding error of 1px when
* extra space is divided so if there is one then we give the
* first undefined column 1 more pixel
*/
headCells = tHead.iterator();
colIndex = 0;
while (headCells.hasNext()) {
HeaderCell hc = (HeaderCell) headCells.next();
if (!hc.isDefinedWidth()) {
setColWidth(colIndex,
hc.getWidth() + availW - checksum, false);
break;
}
colIndex++;
}
}
if ((height == null || "".equals(height))
&& totalRows == pageLength) {
// fix body height (may vary if lazy loading is offhorizontal
// scrollbar appears/disappears)
int bodyHeight = scrollBody.getRequiredHeight();
boolean needsSpaceForHorizontalScrollbar = (availW < usedMinimumWidth);
if (needsSpaceForHorizontalScrollbar) {
bodyHeight += Util.getNativeScrollbarSize();
}
int heightBefore = getOffsetHeight();
scrollBodyPanel.setHeight(bodyHeight + "px");
if (heightBefore != getOffsetHeight()) {
Util.notifyParentOfSizeChange(VScrollTable.this, false);
}
}
scrollBody.reLayoutComponents();
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
});
forceRealignColumnHeaders();
}
};
private void forceRealignColumnHeaders() {
if (BrowserInfo.get().isIE()) {
/*
* IE does not fire onscroll event if scroll position is reverted to
* 0 due to the content element size growth. Ensure headers are in
* sync with content manually. Safe to use null event as we don't
* actually use the event object in listener.
*/
onScroll(null);
}
}
/**
* helper to set pixel size of head and body part
*
* @param pixels
*/
private void setContentWidth(int pixels) {
tHead.setWidth(pixels + "px");
scrollBodyPanel.setWidth(pixels + "px");
tFoot.setWidth(pixels + "px");
}
private int borderWidth = -1;
/**
* @return border left + border right
*/
private int getBorderWidth() {
if (borderWidth < 0) {
borderWidth = Util.measureHorizontalPaddingAndBorder(
scrollBodyPanel.getElement(), 2);
if (borderWidth < 0) {
borderWidth = 0;
}
}
return borderWidth;
}
/**
* Ensures scrollable area is properly sized. This method is used when fixed
* size is used.
*/
private int containerHeight;
private void setContainerHeight() {
if (height != null && !"".equals(height)) {
containerHeight = getOffsetHeight();
containerHeight -= showColHeaders ? tHead.getOffsetHeight() : 0;
containerHeight -= tFoot.getOffsetHeight();
containerHeight -= getContentAreaBorderHeight();
if (containerHeight < 0) {
containerHeight = 0;
}
scrollBodyPanel.setHeight(containerHeight + "px");
}
}
private int contentAreaBorderHeight = -1;
private int scrollLeft;
private int scrollTop;
private VScrollTableDropHandler dropHandler;
private boolean navKeyDown;
private boolean multiselectPending;
/**
* @return border top + border bottom of the scrollable area of table
*/
private int getContentAreaBorderHeight() {
if (contentAreaBorderHeight < 0) {
if (BrowserInfo.get().isIE7() || BrowserInfo.get().isIE6()) {
contentAreaBorderHeight = Util
.measureVerticalBorder(scrollBodyPanel.getElement());
} else {
DOM.setStyleAttribute(scrollBodyPanel.getElement(), "overflow",
"hidden");
int oh = scrollBodyPanel.getOffsetHeight();
int ch = scrollBodyPanel.getElement().getPropertyInt(
"clientHeight");
contentAreaBorderHeight = oh - ch;
DOM.setStyleAttribute(scrollBodyPanel.getElement(), "overflow",
"auto");
}
}
return contentAreaBorderHeight;
}
@Override
public void setHeight(String height) {
this.height = height;
super.setHeight(height);
setContainerHeight();
if (initializedAndAttached) {
updatePageLength();
}
if (!rendering) {
// Webkit may sometimes get an odd rendering bug (white space
// between header and body), see bug #3875. Running
// overflow hack here to shake body element a bit.
Util.runWebkitOverflowAutoFix(scrollBodyPanel.getElement());
}
/*
* setting height may affect wheter the component has scrollbars ->
* needs scrolling or not
*/
setProperTabIndex();
}
/*
* Overridden due Table might not survive of visibility change (scroll pos
* lost). Example ITabPanel just set contained components invisible and back
* when changing tabs.
*/
@Override
public void setVisible(boolean visible) {
if (isVisible() != visible) {
super.setVisible(visible);
if (initializedAndAttached) {
if (visible) {
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
scrollBodyPanel
.setScrollPosition(measureRowHeightOffset(firstRowInViewPort));
}
});
}
}
}
}
/**
* Helper function to build html snippet for column or row headers
*
* @param uidl
* possibly with values caption and icon
* @return html snippet containing possibly an icon + caption text
*/
protected String buildCaptionHtmlSnippet(UIDL uidl) {
String s = uidl.hasAttribute("caption") ? uidl
.getStringAttribute("caption") : "";
if (uidl.hasAttribute("icon")) {
s = "<img src=\""
+ Util.escapeAttribute(client.translateVaadinUri(uidl
.getStringAttribute("icon")))
+ "\" alt=\"icon\" class=\"v-icon\">" + s;
}
return s;
}
/**
* This method has logic which rows needs to be requested from server when
* user scrolls
*/
public void onScroll(ScrollEvent event) {
scrollLeft = scrollBodyPanel.getElement().getScrollLeft();
scrollTop = scrollBodyPanel.getScrollPosition();
/*
* #6970 - IE sometimes fires scroll events for a detached table.
*
* FIXME initializedAndAttached should probably be renamed - its name
* doesn't seem to reflect its semantics. onDetach() doesn't set it to
* false, and changing that might break something else, so we need to
* check isAttached() separately.
*/
if (!initializedAndAttached || !isAttached()) {
return;
}
if (!enabled) {
scrollBodyPanel
.setScrollPosition(measureRowHeightOffset(firstRowInViewPort));
return;
}
rowRequestHandler.cancel();
if (BrowserInfo.get().isSafari() && event != null && scrollTop == 0) {
// due to the webkitoverflowworkaround, top may sometimes report 0
// for webkit, although it really is not. Expecting to have the
// correct
// value available soon.
Scheduler.get().scheduleDeferred(new Command() {
public void execute() {
onScroll(null);
}
});
return;
}
// fix headers horizontal scrolling
tHead.setHorizontalScrollPosition(scrollLeft);
// fix footers horizontal scrolling
tFoot.setHorizontalScrollPosition(scrollLeft);
firstRowInViewPort = calcFirstRowInViewPort();
if (firstRowInViewPort > totalRows - pageLength) {
firstRowInViewPort = totalRows - pageLength;
}
int postLimit = (int) (firstRowInViewPort + (pageLength - 1) + pageLength
* cache_react_rate);
if (postLimit > totalRows - 1) {
postLimit = totalRows - 1;
}
int preLimit = (int) (firstRowInViewPort - pageLength
* cache_react_rate);
if (preLimit < 0) {
preLimit = 0;
}
final int lastRendered = scrollBody.getLastRendered();
final int firstRendered = scrollBody.getFirstRendered();
if (postLimit <= lastRendered && preLimit >= firstRendered) {
// we're within no-react area, no need to request more rows
// remember which firstvisible we requested, in case the server has
// a differing opinion
lastRequestedFirstvisible = firstRowInViewPort;
client.updateVariable(paintableId, "firstvisible",
firstRowInViewPort, false);
return;
}
if (firstRowInViewPort - pageLength * cache_rate > lastRendered
|| firstRowInViewPort + pageLength + pageLength * cache_rate < firstRendered) {
// need a totally new set of rows
rowRequestHandler
.setReqFirstRow((firstRowInViewPort - (int) (pageLength * cache_rate)));
int last = firstRowInViewPort + (int) (cache_rate * pageLength)
+ pageLength - 1;
if (last >= totalRows) {
last = totalRows - 1;
}
rowRequestHandler.setReqRows(last
- rowRequestHandler.getReqFirstRow() + 1);
rowRequestHandler.deferRowFetch();
return;
}
if (preLimit < firstRendered) {
// need some rows to the beginning of the rendered area
rowRequestHandler
.setReqFirstRow((int) (firstRowInViewPort - pageLength
* cache_rate));
rowRequestHandler.setReqRows(firstRendered
- rowRequestHandler.getReqFirstRow());
rowRequestHandler.deferRowFetch();
return;
}
if (postLimit > lastRendered) {
// need some rows to the end of the rendered area
rowRequestHandler.setReqFirstRow(lastRendered + 1);
rowRequestHandler.setReqRows((int) ((firstRowInViewPort
+ pageLength + pageLength * cache_rate) - lastRendered));
rowRequestHandler.deferRowFetch();
}
}
protected int calcFirstRowInViewPort() {
return (int) Math.ceil(scrollTop / scrollBody.getRowHeight());
}
public VScrollTableDropHandler getDropHandler() {
return dropHandler;
}
private static class TableDDDetails {
int overkey = -1;
VerticalDropLocation dropLocation;
String colkey;
@Override
public boolean equals(Object obj) {
if (obj instanceof TableDDDetails) {
TableDDDetails other = (TableDDDetails) obj;
return dropLocation == other.dropLocation
&& overkey == other.overkey
&& ((colkey != null && colkey.equals(other.colkey)) || (colkey == null && other.colkey == null));
}
return false;
}
// @Override
// public int hashCode() {
// return overkey;
// }
}
public class VScrollTableDropHandler extends VAbstractDropHandler {
private static final String ROWSTYLEBASE = "v-table-row-drag-";
private TableDDDetails dropDetails;
private TableDDDetails lastEmphasized;
@Override
public void dragEnter(VDragEvent drag) {
updateDropDetails(drag);
super.dragEnter(drag);
}
private void updateDropDetails(VDragEvent drag) {
dropDetails = new TableDDDetails();
Element elementOver = drag.getElementOver();
VScrollTableRow row = Util.findWidget(elementOver, getRowClass());
if (row != null) {
dropDetails.overkey = row.rowKey;
Element tr = row.getElement();
Element element = elementOver;
while (element != null && element.getParentElement() != tr) {
element = (Element) element.getParentElement();
}
int childIndex = DOM.getChildIndex(tr, element);
dropDetails.colkey = tHead.getHeaderCell(childIndex)
.getColKey();
dropDetails.dropLocation = DDUtil.getVerticalDropLocation(
row.getElement(), drag.getCurrentGwtEvent(), 0.2);
}
drag.getDropDetails().put("itemIdOver", dropDetails.overkey + "");
drag.getDropDetails().put(
"detail",
dropDetails.dropLocation != null ? dropDetails.dropLocation
.toString() : null);
}
private Class<? extends Widget> getRowClass() {
// get the row type this way to make dd work in derived
// implementations
return scrollBody.iterator().next().getClass();
}
@Override
public void dragOver(VDragEvent drag) {
TableDDDetails oldDetails = dropDetails;
updateDropDetails(drag);
if (!oldDetails.equals(dropDetails)) {
deEmphasis();
final TableDDDetails newDetails = dropDetails;
VAcceptCallback cb = new VAcceptCallback() {
public void accepted(VDragEvent event) {
if (newDetails.equals(dropDetails)) {
dragAccepted(event);
}
/*
* Else new target slot already defined, ignore
*/
}
};
validate(cb, drag);
}
}
@Override
public void dragLeave(VDragEvent drag) {
deEmphasis();
super.dragLeave(drag);
}
@Override
public boolean drop(VDragEvent drag) {
deEmphasis();
return super.drop(drag);
}
private void deEmphasis() {
UIObject.setStyleName(getElement(), CLASSNAME + "-drag", false);
if (lastEmphasized == null) {
return;
}
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (lastEmphasized != null
&& row.rowKey == lastEmphasized.overkey) {
String stylename = ROWSTYLEBASE
+ lastEmphasized.dropLocation.toString()
.toLowerCase();
VScrollTableRow.setStyleName(row.getElement(), stylename,
false);
lastEmphasized = null;
return;
}
}
}
/**
* TODO needs different drop modes ?? (on cells, on rows), now only
* supports rows
*/
private void emphasis(TableDDDetails details) {
deEmphasis();
UIObject.setStyleName(getElement(), CLASSNAME + "-drag", true);
// iterate old and new emphasized row
for (Widget w : scrollBody.renderedRows) {
VScrollTableRow row = (VScrollTableRow) w;
if (details != null && details.overkey == row.rowKey) {
String stylename = ROWSTYLEBASE
+ details.dropLocation.toString().toLowerCase();
VScrollTableRow.setStyleName(row.getElement(), stylename,
true);
lastEmphasized = details;
return;
}
}
}
@Override
protected void dragAccepted(VDragEvent drag) {
emphasis(dropDetails);
}
@Override
public Paintable getPaintable() {
return VScrollTable.this;
}
public ApplicationConnection getApplicationConnection() {
return client;
}
}
protected VScrollTableRow getFocusedRow() {
return focusedRow;
}
/**
* Moves the selection head to a specific row
*
* @param row
* The row to where the selection head should move
* @return Returns true if focus was moved successfully, else false
*/
protected boolean setRowFocus(VScrollTableRow row) {
if (!isSelectable()) {
return false;
}
// Remove previous selection
if (focusedRow != null && focusedRow != row) {
focusedRow.removeStyleName(CLASSNAME_SELECTION_FOCUS);
}
if (row != null) {
// Apply focus style to new selection
row.addStyleName(CLASSNAME_SELECTION_FOCUS);
/*
* Trying to set focus on already focused row
*/
if (row == focusedRow) {
return false;
}
// Set new focused row
focusedRow = row;
ensureRowIsVisible(row);
return true;
}
return false;
}
/**
* Ensures that the row is visible
*
* @param row
* The row to ensure is visible
*/
private void ensureRowIsVisible(VScrollTableRow row) {
Util.scrollIntoViewVertically(row.getElement());
}
/**
* Handles the keyboard events handled by the table
*
* @param event
* The keyboard event received
* @return true iff the navigation event was handled
*/
protected boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {
if (keycode == KeyCodes.KEY_TAB || keycode == KeyCodes.KEY_SHIFT) {
// Do not handle tab key
return false;
}
// Down navigation
if (!isSelectable() && keycode == getNavigationDownKey()) {
scrollBodyPanel.setScrollPosition(scrollBodyPanel
.getScrollPosition() + scrollingVelocity);
return true;
} else if (keycode == getNavigationDownKey()) {
if (isMultiSelectModeAny() && moveFocusDown()) {
selectFocusedRow(ctrl, shift);
} else if (isSingleSelectMode() && !shift && moveFocusDown()) {
selectFocusedRow(ctrl, shift);
}
return true;
}
// Up navigation
if (!isSelectable() && keycode == getNavigationUpKey()) {
scrollBodyPanel.setScrollPosition(scrollBodyPanel
.getScrollPosition() - scrollingVelocity);
return true;
} else if (keycode == getNavigationUpKey()) {
if (isMultiSelectModeAny() && moveFocusUp()) {
selectFocusedRow(ctrl, shift);
} else if (isSingleSelectMode() && !shift && moveFocusUp()) {
selectFocusedRow(ctrl, shift);
}
return true;
}
if (keycode == getNavigationLeftKey()) {
// Left navigation
scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
.getHorizontalScrollPosition() - scrollingVelocity);
return true;
} else if (keycode == getNavigationRightKey()) {
// Right navigation
scrollBodyPanel.setHorizontalScrollPosition(scrollBodyPanel
.getHorizontalScrollPosition() + scrollingVelocity);
return true;
}
// Select navigation
if (isSelectable() && keycode == getNavigationSelectKey()) {
if (isSingleSelectMode()) {
boolean wasSelected = focusedRow.isSelected();
deselectAll();
if (!wasSelected || !nullSelectionAllowed) {
focusedRow.toggleSelection();
}
} else {
focusedRow.toggleSelection();
removeRowFromUnsentSelectionRanges(focusedRow);
}
sendSelectedRows();
return true;
}
// Page Down navigation
if (keycode == getNavigationPageDownKey()) {
if (isSelectable()) {
/*
* If selectable we plagiate MSW behaviour: first scroll to the
* end of current view. If at the end, scroll down one page
* length and keep the selected row in the bottom part of
* visible area.
*/
if (!isFocusAtTheEndOfTable()) {
VScrollTableRow lastVisibleRowInViewPort = scrollBody
.getRowByRowIndex(firstRowInViewPort
+ getFullyVisibleRowCount() - 1);
if (lastVisibleRowInViewPort != null
&& lastVisibleRowInViewPort != focusedRow) {
// focused row is not at the end of the table, move
// focus and select the last visible row
setRowFocus(lastVisibleRowInViewPort);
selectFocusedRow(ctrl, shift);
sendSelectedRows();
} else {
int indexOfToBeFocused = focusedRow.getIndex()
+ getFullyVisibleRowCount();
if (indexOfToBeFocused >= totalRows) {
indexOfToBeFocused = totalRows - 1;
}
VScrollTableRow toBeFocusedRow = scrollBody
.getRowByRowIndex(indexOfToBeFocused);
if (toBeFocusedRow != null) {
/*
* if the next focused row is rendered
*/
setRowFocus(toBeFocusedRow);
selectFocusedRow(ctrl, shift);
// TODO needs scrollintoview ?
sendSelectedRows();
} else {
// scroll down by pixels and return, to wait for
// new rows, then select the last item in the
// viewport
selectLastItemInNextRender = true;
multiselectPending = shift;
scrollByPagelenght(1);
}
}
}
} else {
/* No selections, go page down by scrolling */
scrollByPagelenght(1);
}
return true;
}
// Page Up navigation
if (keycode == getNavigationPageUpKey()) {
if (isSelectable()) {
/*
* If selectable we plagiate MSW behaviour: first scroll to the
* end of current view. If at the end, scroll down one page
* length and keep the selected row in the bottom part of
* visible area.
*/
if (!isFocusAtTheBeginningOfTable()) {
VScrollTableRow firstVisibleRowInViewPort = scrollBody
.getRowByRowIndex(firstRowInViewPort);
if (firstVisibleRowInViewPort != null
&& firstVisibleRowInViewPort != focusedRow) {
// focus is not at the beginning of the table, move
// focus and select the first visible row
setRowFocus(firstVisibleRowInViewPort);
selectFocusedRow(ctrl, shift);
sendSelectedRows();
} else {
int indexOfToBeFocused = focusedRow.getIndex()
- getFullyVisibleRowCount();
if (indexOfToBeFocused < 0) {
indexOfToBeFocused = 0;
}
VScrollTableRow toBeFocusedRow = scrollBody
.getRowByRowIndex(indexOfToBeFocused);
if (toBeFocusedRow != null) { // if the next focused row
// is rendered
setRowFocus(toBeFocusedRow);
selectFocusedRow(ctrl, shift);
// TODO needs scrollintoview ?
sendSelectedRows();
} else {
// unless waiting for the next rowset already
// scroll down by pixels and return, to wait for
// new rows, then select the last item in the
// viewport
selectFirstItemInNextRender = true;
multiselectPending = shift;
scrollByPagelenght(-1);
}
}
}
} else {
/* No selections, go page up by scrolling */
scrollByPagelenght(-1);
}
return true;
}
// Goto start navigation
if (keycode == getNavigationStartKey()) {
scrollBodyPanel.setScrollPosition(0);
if (isSelectable()) {
if (focusedRow != null && focusedRow.getIndex() == 0) {
return false;
} else {
VScrollTableRow rowByRowIndex = (VScrollTableRow) scrollBody
.iterator().next();
if (rowByRowIndex.getIndex() == 0) {
setRowFocus(rowByRowIndex);
selectFocusedRow(ctrl, shift);
sendSelectedRows();
} else {
// first row of table will come in next row fetch
if (ctrl) {
focusFirstItemInNextRender = true;
} else {
selectFirstItemInNextRender = true;
multiselectPending = shift;
}
}
}
}
return true;
}
// Goto end navigation
if (keycode == getNavigationEndKey()) {
scrollBodyPanel.setScrollPosition(scrollBody.getOffsetHeight());
if (isSelectable()) {
final int lastRendered = scrollBody.getLastRendered();
if (lastRendered + 1 == totalRows) {
VScrollTableRow rowByRowIndex = scrollBody
.getRowByRowIndex(lastRendered);
if (focusedRow != rowByRowIndex) {
setRowFocus(rowByRowIndex);
selectFocusedRow(ctrl, shift);
sendSelectedRows();
}
} else {
if (ctrl) {
focusLastItemInNextRender = true;
} else {
selectLastItemInNextRender = true;
multiselectPending = shift;
}
}
}
return true;
}
return false;
}
private boolean isFocusAtTheBeginningOfTable() {
return focusedRow.getIndex() == 0;
}
private boolean isFocusAtTheEndOfTable() {
return focusedRow.getIndex() + 1 >= totalRows;
}
private int getFullyVisibleRowCount() {
return (int) (scrollBodyPanel.getOffsetHeight() / scrollBody
.getRowHeight());
}
private void scrollByPagelenght(int i) {
int pixels = i * scrollBodyPanel.getOffsetHeight();
int newPixels = scrollBodyPanel.getScrollPosition() + pixels;
if (newPixels < 0) {
newPixels = 0;
} // else if too high, NOP (all know browsers accept illegally big
// values here)
scrollBodyPanel.setScrollPosition(newPixels);
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.FocusHandler#onFocus(com.google.gwt.event
* .dom.client.FocusEvent)
*/
public void onFocus(FocusEvent event) {
if (isFocusable()) {
hasFocus = true;
// Focus a row if no row is in focus
if (focusedRow == null) {
focusRowFromBody();
} else {
setRowFocus(focusedRow);
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.dom.client.BlurHandler#onBlur(com.google.gwt.event
* .dom.client.BlurEvent)
*/
public void onBlur(BlurEvent event) {
hasFocus = false;
navKeyDown = false;
if (BrowserInfo.get().isIE()) {
// IE sometimes moves focus to a clicked table cell...
Element focusedElement = Util.getIEFocusedElement();
if (Util.getPaintableForElement(client, getParent(), focusedElement) == this) {
// ..in that case, steal the focus back to the focus handler
// but not if focus is in a child component instead (#7965)
focus();
return;
}
}
if (isFocusable()) {
// Unfocus any row
setRowFocus(null);
}
}
/**
* Removes a key from a range if the key is found in a selected range
*
* @param key
* The key to remove
*/
private void removeRowFromUnsentSelectionRanges(VScrollTableRow row) {
Collection<SelectionRange> newRanges = null;
for (Iterator<SelectionRange> iterator = selectedRowRanges.iterator(); iterator
.hasNext();) {
SelectionRange range = iterator.next();
if (range.inRange(row)) {
// Split the range if given row is in range
Collection<SelectionRange> splitranges = range.split(row);
if (newRanges == null) {
newRanges = new ArrayList<SelectionRange>();
}
newRanges.addAll(splitranges);
iterator.remove();
}
}
if (newRanges != null) {
selectedRowRanges.addAll(newRanges);
}
}
/**
* Can the Table be focused?
*
* @return True if the table can be focused, else false
*/
public boolean isFocusable() {
if (scrollBody != null && enabled) {
return !(!hasHorizontalScrollbar() && !hasVerticalScrollbar() && !isSelectable());
}
return false;
}
private boolean hasHorizontalScrollbar() {
return scrollBody.getOffsetWidth() > scrollBodyPanel.getOffsetWidth();
}
private boolean hasVerticalScrollbar() {
return scrollBody.getOffsetHeight() > scrollBodyPanel.getOffsetHeight();
}
/*
* (non-Javadoc)
*
* @see com.vaadin.terminal.gwt.client.Focusable#focus()
*/
public void focus() {
if (isFocusable()) {
scrollBodyPanel.focus();
}
}
/**
* Sets the proper tabIndex for scrollBodyPanel (the focusable elemen in the
* component).
*
* If the component has no explicit tabIndex a zero is given (default
* tabbing order based on dom hierarchy) or -1 if the component does not
* need to gain focus. The component needs no focus if it has no scrollabars
* (not scrollable) and not selectable. Note that in the future shortcut
* actions may need focus.
*
*/
private void setProperTabIndex() {
int storedScrollTop = 0;
int storedScrollLeft = 0;
if (BrowserInfo.get().getOperaVersion() >= 11) {
// Workaround for Opera scroll bug when changing tabIndex (#6222)
storedScrollTop = scrollBodyPanel.getScrollPosition();
storedScrollLeft = scrollBodyPanel.getHorizontalScrollPosition();
}
if (tabIndex == 0 && !isFocusable()) {
scrollBodyPanel.setTabIndex(-1);
} else {
scrollBodyPanel.setTabIndex(tabIndex);
}
if (BrowserInfo.get().getOperaVersion() >= 11) {
// Workaround for Opera scroll bug when changing tabIndex (#6222)
scrollBodyPanel.setScrollPosition(storedScrollTop);
scrollBodyPanel.setHorizontalScrollPosition(storedScrollLeft);
}
}
public void startScrollingVelocityTimer() {
if (scrollingVelocityTimer == null) {
scrollingVelocityTimer = new Timer() {
@Override
public void run() {
scrollingVelocity++;
}
};
scrollingVelocityTimer.scheduleRepeating(100);
}
}
public void cancelScrollingVelocityTimer() {
if (scrollingVelocityTimer != null) {
// Remove velocityTimer if it exists and the Table is disabled
scrollingVelocityTimer.cancel();
scrollingVelocityTimer = null;
scrollingVelocity = 10;
}
}
/**
*
* @param keyCode
* @return true if the given keyCode is used by the table for navigation
*/
private boolean isNavigationKey(int keyCode) {
return keyCode == getNavigationUpKey()
|| keyCode == getNavigationLeftKey()
|| keyCode == getNavigationRightKey()
|| keyCode == getNavigationDownKey()
|| keyCode == getNavigationPageUpKey()
|| keyCode == getNavigationPageDownKey()
|| keyCode == getNavigationEndKey()
|| keyCode == getNavigationStartKey();
}
public void lazyRevertFocusToRow(final VScrollTableRow currentlyFocusedRow) {
Scheduler.get().scheduleFinally(new ScheduledCommand() {
public void execute() {
if (currentlyFocusedRow != null) {
setRowFocus(currentlyFocusedRow);
} else {
VConsole.log("no row?");
focusRowFromBody();
}
scrollBody.ensureFocus();
}
});
}
public Action[] getActions() {
if (bodyActionKeys == null) {
return new Action[] {};
}
final Action[] actions = new Action[bodyActionKeys.length];
for (int i = 0; i < actions.length; i++) {
final String actionKey = bodyActionKeys[i];
Action bodyAction = new TreeAction(this, null, actionKey);
bodyAction.setCaption(getActionCaption(actionKey));
bodyAction.setIconUrl(getActionIcon(actionKey));
actions[i] = bodyAction;
}
return actions;
}
public ApplicationConnection getClient() {
return client;
}
public String getPaintableId() {
return paintableId;
}
/**
* Add this to the element mouse down event by using element.setPropertyJSO
* ("onselectstart",applyDisableTextSelectionIEHack()); Remove it then again
* when the mouse is depressed in the mouse up event.
*
* @return Returns the JSO preventing text selection
*/
private static native JavaScriptObject getPreventTextSelectionIEHack()
/*-{
return function(){ return false; };
}-*/;
protected void triggerLazyColumnAdjustment(boolean now) {
lazyAdjustColumnWidths.cancel();
if (now) {
lazyAdjustColumnWidths.run();
} else {
lazyAdjustColumnWidths.schedule(LAZY_COLUMN_ADJUST_TIMEOUT);
}
}
private void debug(String msg) {
if (enableDebug) {
VConsole.error(msg);
}
}
}
| [merge from 6.7] Skipping "scroll selected/focused row into view" on touch devices as it breaks androids with broken scrolltop and should be obsolete on touch devices anyway
svn changeset:23593/svn branch:6.8
| src/com/vaadin/terminal/gwt/client/ui/VScrollTable.java | [merge from 6.7] Skipping "scroll selected/focused row into view" on touch devices as it breaks androids with broken scrolltop and should be obsolete on touch devices anyway |
|
Java | bsd-2-clause | e75c2bdd53befe5803e537624a9b81543f882b0d | 0 | marckoerner/oci,marckoerner/oci,marckoerner/oci | /**
*
*/
package oci.rom;
import java.net.InetAddress;
/**
* Generic interface for the implementation of a particular resource management environment
* @author Marc Koerner
*/
public interface GenericResourceManagment {
/**
* Validates if sufficient resources are available in order to start a new instance of a given edge service
* @return true if resources are available
*/
public boolean resourcesAvailable();
/**
* Starts and bootstraps the give edge service
* @return true if startup was successful
*/
public boolean startEdgeService();
/**
* Stops the edge service
* @return true if no error occurred
*/
public boolean stopEdgeService();
/**
* Obtains edge service IP address
* @return returns the IP address of the edge service
*/
public InetAddress getEdgeServiceIP();
// public boolean edgeServiceIsRunning();
} // interface
| oci-resource-manager/src/main/java/oci/rom/GenericResourceManagment.java | /**
*
*/
package oci.rom;
import java.net.InetAddress;
/**
* @author Marc Koerner
*
*/
public interface GenericResourceManagment {
public boolean resourcesAvailable();
public boolean startEdgeService();
public boolean stopEdgeService();
public InetAddress getEdgeServiceIP();
// public boolean edgeServiceIsRunning();
} // interface
| added javadoc for resource mgmt interface | oci-resource-manager/src/main/java/oci/rom/GenericResourceManagment.java | added javadoc for resource mgmt interface |
|
Java | mit | 92b6360c16df152258b205c4072469cf4103bf23 | 0 | fr1kin/ForgeHax,fr1kin/ForgeHax | package com.matt.forgehax.asm.utils.remapping;
import bspkrs.mmv.*;
import com.matt.forgehax.asm.utils.ASMStackLogger;
import java.io.File;
import java.io.IOException;
import java.security.DigestException;
import java.security.NoSuchAlgorithmException;
/**
* Credits to bspkrs
*/
public class MCPMappingLoader {
private final File baseDir = new File(new File(System.getProperty("user.home")), ".cache/MCPMappingViewer");
private final String baseSrgDir = "{mc_ver}";
private final String baseMappingDir = "{mc_ver}/{channel}_{map_ver}";
private final String baseMappingUrl = "http://export.mcpbot.bspk.rs/mcp_{channel}/{map_ver}-{mc_ver}/mcp_{channel}-{map_ver}-{mc_ver}.zip";
private final String baseSrgUrl = "http://export.mcpbot.bspk.rs/mcp/{mc_ver}/mcp-{mc_ver}-srg.zip";
private final File srgDir;
private final File mappingDir;
private final File srgFile;
private final File excFile;
private final File staticMethodsFile;
private SrgFile srgFileData;
private ExcFile excFileData;
private StaticMethodsFile staticMethods;
private CsvFile csvFieldData, csvMethodData;
private ParamCsvFile csvParamData;
public MCPMappingLoader(String mapping) throws IOException, CantLoadMCPMappingException, NoSuchAlgorithmException, DigestException {
String[] tokens = mapping.split("_");
if (tokens.length < 3)
throw new CantLoadMCPMappingException("Invalid mapping string specified.");
srgDir = getSubDirForZip(tokens, baseSrgUrl, baseSrgDir);
mappingDir = getSubDirForZip(tokens, baseMappingUrl, baseMappingDir);
srgFile = new File(srgDir, "joined.srg");
excFile = new File(srgDir, "joined.exc");
staticMethodsFile = new File(srgDir, "static_methods.txt");
if (!srgFile.exists())
throw new CantLoadMCPMappingException("Unable to find joined.srg. Your MCP conf folder may be corrupt.");
if (!excFile.exists())
throw new CantLoadMCPMappingException("Unable to find joined.exc. Your MCP conf folder may be corrupt.");
if (!staticMethodsFile.exists())
throw new CantLoadMCPMappingException("Unable to find static_methods.txt. Your MCP conf folder may be corrupt.");
staticMethods = new StaticMethodsFile(staticMethodsFile);
excFileData = new ExcFile(excFile);
srgFileData = new SrgFile(srgFile, excFileData, staticMethods);
csvFieldData = new CsvFile(new File(mappingDir, "fields.csv"));
csvMethodData = new CsvFile(new File(mappingDir, "methods.csv"));
csvParamData = new ParamCsvFile(new File(mappingDir, "params.csv"));
}
public CsvFile getCsvMethodData() {
return csvMethodData;
}
public CsvFile getCsvFieldData() {
return csvFieldData;
}
public SrgFile getSrgFileData() {
return srgFileData;
}
private File getSubDirForZip(String[] tokens, String baseZipUrl, String baseSubDir) throws CantLoadMCPMappingException, NoSuchAlgorithmException, DigestException, IOException
{
if (!baseDir.exists() && !baseDir.mkdirs())
throw new CantLoadMCPMappingException("Application data folder does not exist and cannot be created.");
File subDir = new File(baseDir, replaceTokens(baseSubDir, tokens));
if (!subDir.exists() && !subDir.mkdirs())
throw new CantLoadMCPMappingException("Data folder does not exist and cannot be created.");
try {
RemoteZipHandler rzh = new RemoteZipHandler(replaceTokens(baseZipUrl, tokens), subDir, "SHA1");
rzh.checkRemoteZip();
} catch (Throwable t) {
ASMStackLogger.printStackTrace(t);
}
return subDir;
}
private String replaceTokens(String s, String[] tokens)
{
return s.replace("{mc_ver}", tokens[0]).replace("{channel}", tokens[1]).replace("{map_ver}", tokens[2]);
}
public static class CantLoadMCPMappingException extends Exception {
public CantLoadMCPMappingException(String msg) {
super(msg);
}
}
}
| src/main/java/com/matt/forgehax/asm/utils/remapping/MCPMappingLoader.java | package com.matt.forgehax.asm.utils.remapping;
import bspkrs.mmv.*;
import java.io.File;
import java.io.IOException;
import java.security.DigestException;
import java.security.NoSuchAlgorithmException;
/**
* Credits to bspkrs
*/
public class MCPMappingLoader {
private final File baseDir = new File(new File(System.getProperty("user.home")), ".cache/MCPMappingViewer");
private final String baseSrgDir = "{mc_ver}";
private final String baseMappingDir = "{mc_ver}/{channel}_{map_ver}";
private final String baseMappingUrl = "http://export.mcpbot.bspk.rs/mcp_{channel}/{map_ver}-{mc_ver}/mcp_{channel}-{map_ver}-{mc_ver}.zip";
private final String baseSrgUrl = "http://export.mcpbot.bspk.rs/mcp/{mc_ver}/mcp-{mc_ver}-srg.zip";
private final File srgDir;
private final File mappingDir;
private final File srgFile;
private final File excFile;
private final File staticMethodsFile;
private SrgFile srgFileData;
private ExcFile excFileData;
private StaticMethodsFile staticMethods;
private CsvFile csvFieldData, csvMethodData;
private ParamCsvFile csvParamData;
public MCPMappingLoader(String mapping) throws IOException, CantLoadMCPMappingException, NoSuchAlgorithmException, DigestException {
String[] tokens = mapping.split("_");
if (tokens.length < 3)
throw new CantLoadMCPMappingException("Invalid mapping string specified.");
srgDir = getSubDirForZip(tokens, baseSrgUrl, baseSrgDir);
mappingDir = getSubDirForZip(tokens, baseMappingUrl, baseMappingDir);
srgFile = new File(srgDir, "joined.srg");
excFile = new File(srgDir, "joined.exc");
staticMethodsFile = new File(srgDir, "static_methods.txt");
if (!srgFile.exists())
throw new CantLoadMCPMappingException("Unable to find joined.srg. Your MCP conf folder may be corrupt.");
if (!excFile.exists())
throw new CantLoadMCPMappingException("Unable to find joined.exc. Your MCP conf folder may be corrupt.");
if (!staticMethodsFile.exists())
throw new CantLoadMCPMappingException("Unable to find static_methods.txt. Your MCP conf folder may be corrupt.");
staticMethods = new StaticMethodsFile(staticMethodsFile);
excFileData = new ExcFile(excFile);
srgFileData = new SrgFile(srgFile, excFileData, staticMethods);
csvFieldData = new CsvFile(new File(mappingDir, "fields.csv"));
csvMethodData = new CsvFile(new File(mappingDir, "methods.csv"));
csvParamData = new ParamCsvFile(new File(mappingDir, "params.csv"));
}
public CsvFile getCsvMethodData() {
return csvMethodData;
}
public CsvFile getCsvFieldData() {
return csvFieldData;
}
public SrgFile getSrgFileData() {
return srgFileData;
}
private File getSubDirForZip(String[] tokens, String baseZipUrl, String baseSubDir) throws CantLoadMCPMappingException, NoSuchAlgorithmException, DigestException, IOException
{
if (!baseDir.exists() && !baseDir.mkdirs())
throw new CantLoadMCPMappingException("Application data folder does not exist and cannot be created.");
File subDir = new File(baseDir, replaceTokens(baseSubDir, tokens));
if (!subDir.exists() && !subDir.mkdirs())
throw new CantLoadMCPMappingException("Data folder does not exist and cannot be created.");
RemoteZipHandler rzh = new RemoteZipHandler(replaceTokens(baseZipUrl, tokens), subDir, "SHA1");
rzh.checkRemoteZip();
return subDir;
}
private String replaceTokens(String s, String[] tokens)
{
return s.replace("{mc_ver}", tokens[0]).replace("{channel}", tokens[1]).replace("{map_ver}", tokens[2]);
}
public static class CantLoadMCPMappingException extends Exception {
public CantLoadMCPMappingException(String msg) {
super(msg);
}
}
}
| Added fix that happens when the website hosting the website is down. As long as the client has already downloaded the mappings everything should work fine.
| src/main/java/com/matt/forgehax/asm/utils/remapping/MCPMappingLoader.java | Added fix that happens when the website hosting the website is down. As long as the client has already downloaded the mappings everything should work fine. |
|
Java | mit | 5d9454ed5ee02f8e56f9c164090a0ea5d16984ea | 0 | pshields/futility,pshields/futility | /** @file Brain.java
* Player agent's central logic and memory center.
*
* @author Team F(utility)
*/
package futility;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.LinkedList;
/**
* Threaded class that contains the player agent's sensory data parsing and
* strategy computation algorithms.
*/
public class Brain implements Runnable {
/**
* Enumerator representing the possible strategies that may be used by this
* player agent.
*
* DASH_AROUND_THE_FIELD_CLOCKWISE tells the player to dash around
* the field boundaries clockwise.
*
* DASH_TOWARDS_THE_BALL_AND KICK implements a simple soccer strategy:
* 1. Run towards the ball.
* 2. Rotate around it until you can see the opponent's goal.
* 3. Kick the ball towards said goal.
*
* LOOK_AROUND tells the player to look around in a circle.
*
* GET_BETWEEN_BALL_AND_GOAL is pretty self explanatory
*/
public enum Strategy {
PRE_KICK_OFF_POSITION,
PRE_KICK_OFF_ANGLE,
DASH_AROUND_THE_FIELD_CLOCKWISE,
DASH_TOWARDS_BALL_AND_KICK,
LOOK_AROUND,
GET_BETWEEN_BALL_AND_GOAL,
GOALIE_CATCH_BALL,
PRE_FREE_KICK_POSITION,
PRE_CORNER_KICK_POSITION
}
///////////////////////////////////////////////////////////////////////////
// MEMBER VARIABLES
///////////////////////////////////////////////////////////////////////////
Client client;
Player player;
private int time;
// Self info & Play mode
private String playMode;
private SenseInfo curSenseInfo, lastSenseInfo;
private double playerAcceleration;
private boolean isPositioned = false;
HashMap<String, FieldObject> fieldObjects = new HashMap<String, FieldObject>(100);
ArrayDeque<String> hearMessages = new ArrayDeque<String>();
LinkedList<Settings.RESPONSE>responseHistory = new LinkedList<Settings.RESPONSE>();
private long timeLastSee = 0;
private long timeLastSenseBody = 0;
private int lastRan = -1;
private Strategy currentStrategy = Strategy.LOOK_AROUND;
///////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS
///////////////////////////////////////////////////////////////////////////
/**
* This is the primary constructor for the Brain class.
*
* @param player a back-reference to the invoking player
* @param client the server client by which to send commands, etc.
*/
public Brain(Player player, Client client) {
this.player = player;
this.client = client;
curSenseInfo = new SenseInfo();
lastSenseInfo = new SenseInfo();
playerAcceleration = Double.NaN;
// Load the HashMap
for (int i = 0; i < Settings.STATIONARY_OBJECTS.length; i++) {
StationaryObject object = Settings.STATIONARY_OBJECTS[i];
//client.log(Log.DEBUG, String.format("Adding %s to my HashMap...", object.id));
fieldObjects.put(object.id, object);
}
// Load the response history
this.responseHistory.add(Settings.RESPONSE.NONE);
this.responseHistory.add(Settings.RESPONSE.NONE);
}
///////////////////////////////////////////////////////////////////////////
// GAME LOGIC
///////////////////////////////////////////////////////////////////////////
/**
* Assesses the utility of a strategy for the current time step.
*
* @param strategy the strategy to assess the utility of
* @return an assessment of the strategy's utility in the range [0.0, 1.0]
*/
private final double assessUtility(Strategy strategy) {
double utility = 0;
switch (strategy) {
case PRE_FREE_KICK_POSITION:
case PRE_CORNER_KICK_POSITION:
case PRE_KICK_OFF_POSITION:
// Check play mode, reposition as necessary.
if ( canUseMove() )
utility = 1 - (isPositioned ? 1 : 0);
break;
case PRE_KICK_OFF_ANGLE:
if ( isPositioned )
{
utility = this.player.team.side == 'r' ?
( this.canSee("(b)") ? 0.0 : 1.0 ) :
0.0;
}
break;
case DASH_AROUND_THE_FIELD_CLOCKWISE:
utility = 0.93;
break;
case DASH_TOWARDS_BALL_AND_KICK:
utility = 0.6;
break;
case LOOK_AROUND:
if (this.player.position.getPosition().isUnknown()) {
utility = 1.0;
}
else {
utility = 1 - this.player.position.getConfidence(this.time);
}
break;
case GET_BETWEEN_BALL_AND_GOAL:
// estimate our confidence of where the ball and the player are on the field
double ballConf = this.getOrCreate("(b)").position.getConfidence(this.time);
double playerConf = this.player.position.getConfidence(this.time);
double conf = (ballConf + playerConf) / 2;
double initial = 1;
if (this.player.team.side == Settings.LEFT_SIDE) {
if (this.getOrCreate("(b)").position.getX() < this.player.position.getX()) {
initial = 0.6;
} else {
initial = 0.9;
}
} else {
if (this.getOrCreate("(b)").position.getX() > this.player.position.getX()) {
initial = 0.6;
} else {
initial = 0.9;
}
}
if (!this.player.isGoalie) {
initial *= 0.9;
}
utility = initial * conf;
break;
default:
utility = 0;
break;
}
return utility;
}
/**
* Checks if the play mode allows Move commands
*
* @return true if move commands can be issued.
*/
private final boolean canUseMove() {
return (
playMode.equals( "before_kick_off" ) ||
playMode.startsWith( "goal_r_") ||
playMode.startsWith( "goal_l_" ) ||
playMode.startsWith( "free_kick_" ) ||
playMode.startsWith( "corner_kick_" )
);
}
/**
* A rough estimate of whether the player can catch the ball, dependent
* on their distance to the ball, whether they are a goalie, and whether
* they are within their own penalty area.
*
* @return true if the player can catch the ball
*/
public final boolean canCatchBall() {
if (!player.isGoalie) {
return false;
}
//TODO: check if ball is within catchable distance
if (player.team.side == Settings.LEFT_SIDE) {
if (player.inRectangle(Settings.PENALTY_AREA_LEFT)) {
return true;
}
} else {
if (player.inRectangle(Settings.PENALTY_AREA_RIGHT)) {
return true;
}
}
return false;
}
/**
* A rough estimate of whether the player can kick the ball, dependent
* on its distance to the ball and whether it is inside the playing field.
*
* @return true if the player is on the field and within kicking distance
*/
public final boolean canKickBall() {
if (!player.inRectangle(Settings.FIELD)) {
return false;
}
FieldObject ball = fieldObjects.get("(b)");
if (ball.curInfo.time != time) {
return false;
}
return ball.curInfo.distance < 0.7;
}
/**
* True if and only if the ball was seen in the most recently-parsed 'see' message.
*/
public final boolean canSee(String id) {
if (!this.fieldObjects.containsKey(id)) {
Log.e("Can't see " + id + "!");
return false;
}
FieldObject obj = this.fieldObjects.get(id);
return obj.curInfo.time == this.time;
}
/**
* Accelerates the player in the direction of its body.
*
* @param power the power of the acceleration (0 to 100)
*/
private final void dash(double power) {
this.client.sendCommand(Settings.Commands.DASH, Double.toString(power));
}
/**
* Accelerates the player in the direction of its body, offset by the given
* angle.
*
* @param power the power of the acceleration (0 to 100)
* @param offset an offset to be applied to the player's direction,
* yielding the direction of acceleration
*/
public final void dash(double power, double offset) {
client.sendCommand(Settings.Commands.DASH, Double.toString(power), Double.toString(offset));
}
/**
* Determines the strategy with the current highest utility.
*
* @return the strategy this brain thinks is optimal for the current time step
*/
private final Strategy determineOptimalStrategy() {
Strategy optimalStrategy = this.currentStrategy;
double bestUtility = 0;
for (Strategy strategy : Strategy.values()) {
double utility = this.assessUtility(strategy);
if (utility > bestUtility) {
bestUtility = utility;
optimalStrategy = strategy;
}
}
return optimalStrategy;
}
/**
* Estimates the position of a field object.
*
* @param object a field object to estimate the position of
* @return a position estimate for the field object
*/
private PositionEstimate estimatePositionOf(FieldObject object) {
PositionEstimate estimate = new PositionEstimate();
// TODO
return estimate;
}
/**
* Executes a strategy for the player in the current time step.
*
* @param strategy the strategy to execute
*/
private final void executeStrategy(Strategy strategy) {
switch (strategy) {
case PRE_FREE_KICK_POSITION:
if (playMode.equals("free_kick_l")) {
if (this.player.team.side == Settings.LEFT_SIDE) {
//TODO
} else {
//TODO
}
this.move(Settings.FREE_KICK_L_FORMATION[player.number]);
} else {
if (this.player.team.side == Settings.LEFT_SIDE) {
//TODO
} else {
//TODO
}
this.move(Settings.FREE_KICK_R_FORMATION[player.number]);
}
this.isPositioned = true;
// Since we have now moved back into formation, derivatives
// strategies such as LOOK_AROUND should become dominant.
break;
case PRE_CORNER_KICK_POSITION:
if (playMode.equals("corner_kick_l")) {
if (this.player.team.side == Settings.LEFT_SIDE) {
//TODO
} else {
//TODO
}
this.move(Settings.CORNER_KICK_L_FORMATION[player.number]);
} else {
if (this.player.team.side == Settings.LEFT_SIDE) {
//TODO
} else {
//TODO
}
this.move(Settings.CORNER_KICK_R_FORMATION[player.number]);
}
this.isPositioned = true;
// Since we have now moved back into formation, derivatives
// strategies such as LOOK_AROUND should become dominant.
break;
case PRE_KICK_OFF_POSITION:
this.move(Settings.FORMATION[player.number]);
this.isPositioned = true;
// Since we have now moved back into formation, derivatives
// strategies such as LOOK_AROUND should become dominant.
break;
case PRE_KICK_OFF_ANGLE:
this.turn(30);
break;
case DASH_AROUND_THE_FIELD_CLOCKWISE:
double x = player.position.getPosition().getX();
double y = player.position.getPosition().getY();
double targetDirection = 0;
if (player.inRectangle(Settings.FIELD)) {
targetDirection = -90;
}
// Then run around clockwise between the physical boundary and the field
else if (y <= Settings.FIELD.getTop() && x <= Settings.FIELD.getRight()) {
targetDirection = 0;
}
else if (x >= Settings.FIELD.getRight() && y <= Settings.FIELD.getBottom()) {
targetDirection = 90;
}
else if (y >= Settings.FIELD.getBottom() && x >= Settings.FIELD.getLeft()) {
targetDirection = 180;
}
else if (x <= Settings.FIELD.getLeft() && y >= Settings.FIELD.getTop()) {
targetDirection = -90;
}
else {
Log.e("Strategy " + strategy + " doesn't know how to handle position " + this.player.position.getPosition().render() + ".");
}
double offset = Math.abs(this.player.relativeAngleTo(targetDirection));
if (offset > 10) {
this.turnTo(targetDirection);
}
else {
this.dash(50, this.player.relativeAngleTo(targetDirection));
}
break;
case DASH_TOWARDS_BALL_AND_KICK:
FieldObject ball = this.getOrCreate("(b)");
FieldObject goal = this.getOrCreate(this.player.getOpponentGoalId());
Log.d("Estimated ball position: " + ball.position.render(this.time));
Log.d("Estimated goal position: " + goal.position.render(this.time));
if (this.canKickBall()) {
if (this.canSee(this.player.getOpponentGoalId())) {
kick(100.0, this.player.relativeAngleTo(goal));
}
else {
dash(30.0, 90.0);
}
}
else if (ball.position.getConfidence(this.time) > 0.1) {
double approachAngle;
approachAngle = Futil.simplifyAngle(this.player.relativeAngleTo(ball));
if (Math.abs(approachAngle) > 10) {
this.turn(approachAngle);
}
else {
dash(50.0, approachAngle);
}
}
else {
turn(7.0);
}
break;
case LOOK_AROUND:
turn(7);
break;
case GET_BETWEEN_BALL_AND_GOAL:
//TODO
break;
case GOALIE_CATCH_BALL:
//TODO
break;
default:
break;
}
}
/**
* Gets a field object from fieldObjects, or creates it if it doesn't yet exist.
*
* @param id the object's id
* @return the field object
*/
private final FieldObject getOrCreate(String id) {
if (this.fieldObjects.containsKey(id)) {
return this.fieldObjects.get(id);
}
else {
return FieldObject.create(id);
}
}
/**
* Infers the position and direction of this brain's associated player given two boundary flags
* on the same side seen in the current time step.
*
* @param o1 the first flag
* @param o2 the second flag
*/
private final void inferPositionAndDirection(FieldObject o1, FieldObject o2) {
// x1, x2, y1 and y2 are relative Cartesian coordinates to the flags
double x1 = Math.cos(Math.toRadians(o1.curInfo.direction)) * o1.curInfo.distance;
double y1 = Math.sin(Math.toRadians(o1.curInfo.direction)) * o1.curInfo.distance;
double x2 = Math.cos(Math.toRadians(o2.curInfo.direction)) * o2.curInfo.distance;
double y2 = Math.sin(Math.toRadians(o2.curInfo.direction)) * o2.curInfo.distance;
double direction = -Math.toDegrees(Math.atan((y2 - y1) / (x2 - x1)));
// Need to reverse the direction if looking closer to west and using horizontal boundary flags
if (o1.position.getY() == o2.position.getY()) {
if (Math.signum(o2.position.getX() - o1.position.getX()) != Math.signum(x2 - x1)) {
direction += 180.0;
}
}
// Need to offset the direction by +/- 90 degrees if using vertical boundary flags
else if (o1.position.getX() == o1.position.getX()) {
if (Math.signum(o2.position.getY() - o1.position.getY()) != Math.signum(x2 - x1)) {
direction += 270.0;
}
else {
direction += 90.0;
}
}
this.player.direction.update(Futil.simplifyAngle(direction), 0.95, this.time);
double x = o1.position.getX() - o1.curInfo.distance * Math.cos(Math.toRadians(direction + o1.curInfo.direction));
double y = o1.position.getY() - o1.curInfo.distance * Math.sin(Math.toRadians(direction + o1.curInfo.direction));
double distance = this.player.position.getPosition().distanceTo(new Point(x, y));
this.player.position.update(x, y, 0.95, this.time);
}
/**
* Moves the player to the specified coordinates (server coords).
*
* @param p the Point object to pass coordinates with (must be in server coordinates).
*/
public void move(Point p)
{
move(p.getX(), p.getY());
}
/**
* Moves the player to the specified coordinates (server coords).
*
* @param x x-coordinate
* @param y y-coordinate
*/
public void move(double x, double y) {
client.sendCommand(Settings.Commands.MOVE, Double.toString(x), Double.toString(y));
}
/**
* Kicks the ball in the direction of the player.
*
* @param power the level of power with which to kick (0 to 100)
*/
public void kick(double power) {
client.sendCommand(Settings.Commands.KICK, Double.toString(power));
}
/**
* Kicks the ball in the player's direction, offset by the given angle.
*
* @param power the level of power with which to kick (0 to 100)
* @param offset an angle in degrees to be added to the player's direction, yielding the direction of the kick
*/
public void kick(double power, double offset) {
client.sendCommand(Settings.Commands.KICK, Double.toString(power), Double.toString(offset));
}
/**
* Parses a message from the soccer server. This method is called whenever
* a message from the server is received.
*
* @param message the message (string), exactly as it was received
*/
public void parseMessage(String message) {
long timeReceived = System.currentTimeMillis();
message = Futil.sanitize(message);
// Handle `sense_body` messages
if (message.startsWith("(sense_body")) {
curSenseInfo.copy(lastSenseInfo);
curSenseInfo.reset();
this.timeLastSenseBody = timeReceived;
curSenseInfo.time = Futil.extractTime(message);
this.time = curSenseInfo.time;
// TODO better nested parentheses parsing logic; perhaps
// reconcile with Patrick's parentheses logic?
Log.d("Received a `sense_body` message at time step " + time + ".");
String parts[] = message.split("\\(");
for ( String i : parts ) // for each structured argument:
{
// Clean the string, and break it down into the base arguments.
String nMsg = i.split("\\)")[0].trim();
if ( nMsg.isEmpty() ) continue;
String nArgs[] = nMsg.split("\\s");
// Check for specific argument types; ignore unknown arguments.
if ( nArgs[0].contains("view_mode") )
{ // Player's current view mode
curSenseInfo.viewQuality = nArgs[1];
curSenseInfo.viewWidth = nArgs[2];
}
else if ( nArgs[0].contains("stamina") )
{ // Player's stamina data
curSenseInfo.stamina = Double.parseDouble(nArgs[1]);
curSenseInfo.effort = Double.parseDouble(nArgs[2]);
curSenseInfo.staminaCapacity = Double.parseDouble(nArgs[3]);
}
else if ( nArgs[0].contains("speed") )
{ // Player's speed data
curSenseInfo.amountOfSpeed = Double.parseDouble(nArgs[1]);
curSenseInfo.directionOfSpeed = Double.parseDouble(nArgs[2]);
}
else if ( nArgs[0].contains("head_angle") )
{ // Player's head angle
curSenseInfo.headAngle = Double.parseDouble(nArgs[1]);
}
else if ( nArgs[0].contains("ball") || nArgs[0].contains("player")
|| nArgs[0].contains("post") )
{ // COLLISION flags; limitation of this loop approach is we
// can't handle nested parentheses arguments well.
// Luckily these flags only occur in the collision structure.
curSenseInfo.collision = nArgs[0];
}
}
//update acceleration
if(lastSenseInfo.amountOfSpeed != Double.NaN){
final double dt = curSenseInfo.time - lastSenseInfo.time;
final double dv = curSenseInfo.amountOfSpeed - lastSenseInfo.amountOfSpeed;
playerAcceleration = dv/dt;
}
// If the brain has responded to two see messages in a row, it's time to respond to a sense_body.
if (this.responseHistory.get(0) == Settings.RESPONSE.SEE && this.responseHistory.get(1) == Settings.RESPONSE.SEE) {
this.run();
this.responseHistory.push(Settings.RESPONSE.SENSE_BODY);
this.responseHistory.removeLast();
}
}
// Handle `hear` messages
else if (message.startsWith("(hear"))
{
String parts[] = message.split("\\s");
this.time = Integer.parseInt(parts[1]);
if ( parts[2].startsWith("s") || parts[2].startsWith("o") || parts[2].startsWith("c") )
{
// TODO logic for self, on-line coach, and trainer coach.
// Self could potentially be for feedback,
// On-line coach will require coach language parsing,
// And trainer likely will as well. Outside of Sprint #2 scope.
return;
}
else
{
// Check for a referee message, otherwise continue.
String nMsg = parts[3].split("\\)")[0]; // Retrieve the message.
if ( parts[2].startsWith("r") // Referee;
&& Settings.PLAY_MODES.contains(nMsg) ) // Play Mode?
playMode = nMsg;
else
hearMessages.add( nMsg );
}
}
// Handle `see` messages
else if (message.startsWith("(see")) {
this.timeLastSee = timeReceived;
this.time = Futil.extractTime(message);
Log.d("Received `see` message at time step " + this.time);
LinkedList<String> infos = Futil.extractInfos(message);
for (String info : infos) {
String id = Futil.extractId(info);
if (Futil.isUniqueFieldObject(id)) {
FieldObject obj = this.getOrCreate(id);
obj.update(this.player, info, this.time);
this.fieldObjects.put(id, obj);
}
}
// Immediately run for the current step. Since our computations takes only a few
// milliseconds, it's okay to start running over half-way into the 100ms cycle.
// That means two out of every three time steps will be executed here.
this.run();
// Make sure we stay in sync with the mid-way `see`s
if (this.timeLastSee - this.timeLastSenseBody > 30) {
this.responseHistory.clear();
this.responseHistory.add(Settings.RESPONSE.SEE);
this.responseHistory.add(Settings.RESPONSE.SEE);
}
else {
this.responseHistory.add(Settings.RESPONSE.SEE);
this.responseHistory.removeLast();
}
}
// Handle init messages
else if (message.startsWith("(init")) {
String[] parts = message.split("\\s");
char teamSide = message.charAt(6);
if (teamSide == Settings.LEFT_SIDE) {
player.team.side = Settings.LEFT_SIDE;
player.otherTeam.side = Settings.RIGHT_SIDE;
}
else if (teamSide == Settings.RIGHT_SIDE) {
player.team.side = Settings.RIGHT_SIDE;
player.otherTeam.side = Settings.LEFT_SIDE;
}
else {
// Raise error
Log.e("Could not parse teamSide.");
}
player.number = Integer.parseInt(parts[2]);
playMode = parts[3].split("\\)")[0];
}
else if (message.startsWith("(server_param")) {
parseServerParameters(message);
}
}
public void parseServerParameters(String message)
{
String parts[] = message.split("\\(");
for ( String i : parts ) // for each structured argument:
{
// Clean the string, and break it down into the base arguments.
String nMsg = i.split("\\)")[0].trim();
if ( nMsg.isEmpty() ) continue;
String nArgs[] = nMsg.split("\\s");
// Check for specific argument types; ignore unknown arguments.
if ( nArgs[0].startsWith("goal_width") )
Settings.setGoalHeight(Double.parseDouble(nArgs[1]));
// Ball arguments:
else if ( nArgs[0].startsWith("ball") )
ServerParams_Ball.Builder.dataParser(nArgs);
// Player arguments:
else if ( nArgs[0].startsWith("player") || nArgs[0].startsWith("min")
|| nArgs[0].startsWith("max") )
ServerParams_Player.Builder.dataParser(nArgs);
}
// Rebuild all parameter objects with updated parameters.
Settings.rebuildParams();
}
/**
* Responds for the current time step.
*/
public void run() {
final long startTime = System.currentTimeMillis();
final long endTime;
int expectedNextRun = this.lastRan + 1;
if (this.time > expectedNextRun) {
Log.e("Brain did not run during time step " + expectedNextRun + ".");
}
this.lastRan = this.time;
this.updatePositionAndDirection();
this.currentStrategy = this.determineOptimalStrategy();
Log.i("Current strategy: " + this.currentStrategy);
this.executeStrategy(this.currentStrategy);
Log.d("Estimated player position: " + this.player.position.render(this.time) + ".");
Log.d("Estimated player direction: " + this.player.direction.render(this.time) + ".");
endTime = System.currentTimeMillis();
final long duration = endTime - startTime;
Log.d("Took " + duration + " ms (plus small overhead) to run at time " + this.time + ".");
if (duration > 35) {
Log.e("Took " + duration + " ms (plus small overhead) to run at time " + this.time + ".");
}
}
/**
* Adds the given angle to the player's current direction.
*
* @param offset an angle in degrees to add to the player's current direction
*/
public final void turn(double offset) {
double moment = Futil.toValidMoment(offset);
client.sendCommand(Settings.Commands.TURN, moment);
// TODO Potentially take magnitude of offset into account in the
// determination of the new confidence in the player's position.
player.direction.update(player.direction.getDirection() + moment, 0.95 * player.direction.getConfidence(this.time), this.time);
}
/**
* Updates the player's current direction to be the given direction.
*
* @param direction angle in degrees, assuming soccer server coordinate system
*/
public final void turnTo(double direction) {
this.turn(this.player.relativeAngleTo(direction));
}
/**
* Send commands to move the player to a point at maximum power
* @param point the point to move to
*/
private final void moveTowards(Point point){
moveTowards(point, 100d);
}
/**
* Send commands to move the player to a point with the given power
* @param point to move towards
* @param power to move at
*/
private final void moveTowards(Point point, double power){
final double x = player.position.getX() - point.getX();
final double y = player.position.getY() - point.getY();
final double theta = Math.toDegrees(Math.atan2(y, x));
turnTo(theta);
dash(power);
}
/**
* Updates this this brain's belief about the associated player's position and direction
* at the current time step.
*/
private final void updatePositionAndDirection() {
// Infer from the most-recent `see` if it happened in the current time-step
for (int i = 0; i < 4; i++) {
LinkedList<FieldObject> flagsOnSide = new LinkedList<FieldObject>();
for (String id : Settings.BOUNDARY_FLAG_GROUPS[i]) {
FieldObject flag = this.fieldObjects.get(id);
if (flag.curInfo.time == this.time) {
flagsOnSide.add(flag);
}
else {
//Log.i("Flag " + id + "last updated at time " + flag.info.time + ", not " + this.time);
}
if (flagsOnSide.size() > 1) {
this.inferPositionAndDirection(flagsOnSide.poll(), flagsOnSide.poll());
return;
}
}
}
// TODO Handle other cases
Log.e("Did not update position or direction at time " + this.time);
}
}
| src/futility/Brain.java | /** @file Brain.java
* Player agent's central logic and memory center.
*
* @author Team F(utility)
*/
package futility;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.LinkedList;
/**
* Threaded class that contains the player agent's sensory data parsing and
* strategy computation algorithms.
*/
public class Brain implements Runnable {
/**
* Enumerator representing the possible strategies that may be used by this
* player agent.
*
* DASH_AROUND_THE_FIELD_CLOCKWISE tells the player to dash around
* the field boundaries clockwise.
*
* DASH_TOWARDS_THE_BALL_AND KICK implements a simple soccer strategy:
* 1. Run towards the ball.
* 2. Rotate around it until you can see the opponent's goal.
* 3. Kick the ball towards said goal.
*
* LOOK_AROUND tells the player to look around in a circle.
*
* GET_BETWEEN_BALL_AND_GOAL is pretty self explanatory
*/
public enum Strategy {
PRE_KICK_OFF_POSITION,
PRE_KICK_OFF_ANGLE,
DASH_AROUND_THE_FIELD_CLOCKWISE,
DASH_TOWARDS_BALL_AND_KICK,
LOOK_AROUND,
GET_BETWEEN_BALL_AND_GOAL,
GOALIE_CATCH_BALL,
PRE_FREE_KICK_POSITION,
PRE_CORNER_KICK_POSITION
}
///////////////////////////////////////////////////////////////////////////
// MEMBER VARIABLES
///////////////////////////////////////////////////////////////////////////
Client client;
Player player;
private int time;
// Self info & Play mode
private String playMode;
private SenseInfo curSenseInfo, lastSenseInfo;
private double playerAcceleration;
private boolean isPositioned = false;
HashMap<String, FieldObject> fieldObjects = new HashMap<String, FieldObject>(100);
ArrayDeque<String> hearMessages = new ArrayDeque<String>();
LinkedList<Settings.RESPONSE>responseHistory = new LinkedList<Settings.RESPONSE>();
private long timeLastSee = 0;
private long timeLastSenseBody = 0;
private int lastRan = -1;
private Strategy currentStrategy = Strategy.LOOK_AROUND;
///////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS
///////////////////////////////////////////////////////////////////////////
/**
* This is the primary constructor for the Brain class.
*
* @param player a back-reference to the invoking player
* @param client the server client by which to send commands, etc.
*/
public Brain(Player player, Client client) {
this.player = player;
this.client = client;
curSenseInfo = new SenseInfo();
lastSenseInfo = new SenseInfo();
playerAcceleration = Double.NaN;
// Load the HashMap
for (int i = 0; i < Settings.STATIONARY_OBJECTS.length; i++) {
StationaryObject object = Settings.STATIONARY_OBJECTS[i];
//client.log(Log.DEBUG, String.format("Adding %s to my HashMap...", object.id));
fieldObjects.put(object.id, object);
}
// Load the response history
this.responseHistory.add(Settings.RESPONSE.NONE);
this.responseHistory.add(Settings.RESPONSE.NONE);
}
///////////////////////////////////////////////////////////////////////////
// GAME LOGIC
///////////////////////////////////////////////////////////////////////////
/**
* Assesses the utility of a strategy for the current time step.
*
* @param strategy the strategy to assess the utility of
* @return an assessment of the strategy's utility in the range [0.0, 1.0]
*/
private final double assessUtility(Strategy strategy) {
double utility = 0;
switch (strategy) {
case PRE_FREE_KICK_POSITION:
case PRE_CORNER_KICK_POSITION:
case PRE_KICK_OFF_POSITION:
// Check play mode, reposition as necessary.
if ( canUseMove() )
utility = 1 - (isPositioned ? 1 : 0);
break;
case PRE_KICK_OFF_ANGLE:
if ( isPositioned )
{
utility = this.player.team.side == 'r' ?
( this.canSee("(b)") ? 0.0 : 1.0 ) :
0.0;
}
break;
case DASH_AROUND_THE_FIELD_CLOCKWISE:
utility = 0.93;
break;
case DASH_TOWARDS_BALL_AND_KICK:
utility = 0.6;
break;
case LOOK_AROUND:
if (this.player.position.getPosition().isUnknown()) {
utility = 1.0;
}
else {
utility = 1 - this.player.position.getConfidence(this.time);
}
break;
case GET_BETWEEN_BALL_AND_GOAL:
// estimate our confidence of where the ball and the player are on the field
double ballConf = this.ball.position.getConfidence(this.time);
double playerConf = this.player.position.getConfidence(this.time);
double conf = (ballConf + playerConf) / 2;
double initial = 1;
if (this.player.team.side == Settings.LEFT_SIDE) {
if (this.ball.position.getX() < this.player.position.getX()) {
initial = 0.6;
} else {
initial = 0.9;
}
} else {
if (this.ball.position.getX() > this.player.position.getX()) {
initial = 0.6;
} else {
initial = 0.9;
}
}
if (!this.player.isGoalie) {
initial *= 0.9;
}
utility = initial * conf;
break;
default:
utility = 0;
break;
}
return utility;
}
/**
* Checks if the play mode allows Move commands
*
* @return true if move commands can be issued.
*/
private final boolean canUseMove() {
return (
playMode.equals( "before_kick_off" ) ||
playMode.startsWith( "goal_r_") ||
playMode.startsWith( "goal_l_" ) ||
playMode.startsWith( "free_kick_" ) ||
playMode.startsWith( "corner_kick_" )
);
}
/**
* A rough estimate of whether the player can catch the ball, dependent
* on their distance to the ball, whether they are a goalie, and whether
* they are within their own penalty area.
*
* @return true if the player can catch the ball
*/
public final boolean canCatchBall() {
if (!player.isGoalie) {
return false;
}
//TODO: check if ball is within catchable distance
if (player.team.side == Settings.LEFT_SIDE) {
if (player.inRectangle(Settings.PENALTY_AREA_LEFT)) {
return true;
}
} else {
if (player.inRectangle(Settings.PENALTY_AREA_RIGHT)) {
return true;
}
}
return false;
}
/**
* A rough estimate of whether the player can kick the ball, dependent
* on its distance to the ball and whether it is inside the playing field.
*
* @return true if the player is on the field and within kicking distance
*/
public final boolean canKickBall() {
if (!player.inRectangle(Settings.FIELD)) {
return false;
}
FieldObject ball = fieldObjects.get("(b)");
if (ball.curInfo.time != time) {
return false;
}
return ball.curInfo.distance < 0.7;
}
/**
* True if and only if the ball was seen in the most recently-parsed 'see' message.
*/
public final boolean canSee(String id) {
if (!this.fieldObjects.containsKey(id)) {
Log.e("Can't see " + id + "!");
return false;
}
FieldObject obj = this.fieldObjects.get(id);
return obj.curInfo.time == this.time;
}
/**
* Accelerates the player in the direction of its body.
*
* @param power the power of the acceleration (0 to 100)
*/
private final void dash(double power) {
this.client.sendCommand(Settings.Commands.DASH, Double.toString(power));
}
/**
* Accelerates the player in the direction of its body, offset by the given
* angle.
*
* @param power the power of the acceleration (0 to 100)
* @param offset an offset to be applied to the player's direction,
* yielding the direction of acceleration
*/
public final void dash(double power, double offset) {
client.sendCommand(Settings.Commands.DASH, Double.toString(power), Double.toString(offset));
}
/**
* Determines the strategy with the current highest utility.
*
* @return the strategy this brain thinks is optimal for the current time step
*/
private final Strategy determineOptimalStrategy() {
Strategy optimalStrategy = this.currentStrategy;
double bestUtility = 0;
for (Strategy strategy : Strategy.values()) {
double utility = this.assessUtility(strategy);
if (utility > bestUtility) {
bestUtility = utility;
optimalStrategy = strategy;
}
}
return optimalStrategy;
}
/**
* Estimates the position of a field object.
*
* @param object a field object to estimate the position of
* @return a position estimate for the field object
*/
private PositionEstimate estimatePositionOf(FieldObject object) {
PositionEstimate estimate = new PositionEstimate();
// TODO
return estimate;
}
/**
* Executes a strategy for the player in the current time step.
*
* @param strategy the strategy to execute
*/
private final void executeStrategy(Strategy strategy) {
switch (strategy) {
case PRE_FREE_KICK_POSITION:
if (playMode.equals("free_kick_l")) {
if (this.player.team.side == Settings.LEFT_SIDE) {
//TODO
} else {
//TODO
}
this.move(Settings.FREE_KICK_L_FORMATION[player.number]);
} else {
if (this.player.team.side == Settings.LEFT_SIDE) {
//TODO
} else {
//TODO
}
this.move(Settings.FREE_KICK_R_FORMATION[player.number]);
}
this.isPositioned = true;
// Since we have now moved back into formation, derivatives
// strategies such as LOOK_AROUND should become dominant.
break;
case PRE_CORNER_KICK_POSITION:
if (playMode.equals("corner_kick_l")) {
if (this.player.team.side == Settings.LEFT_SIDE) {
//TODO
} else {
//TODO
}
this.move(Settings.CORNER_KICK_L_FORMATION[player.number]);
} else {
if (this.player.team.side == Settings.LEFT_SIDE) {
//TODO
} else {
//TODO
}
this.move(Settings.CORNER_KICK_R_FORMATION[player.number]);
}
this.isPositioned = true;
// Since we have now moved back into formation, derivatives
// strategies such as LOOK_AROUND should become dominant.
break;
case PRE_KICK_OFF_POSITION:
this.move(Settings.FORMATION[player.number]);
this.isPositioned = true;
// Since we have now moved back into formation, derivatives
// strategies such as LOOK_AROUND should become dominant.
break;
case PRE_KICK_OFF_ANGLE:
this.turn(30);
break;
case DASH_AROUND_THE_FIELD_CLOCKWISE:
double x = player.position.getPosition().getX();
double y = player.position.getPosition().getY();
double targetDirection = 0;
if (player.inRectangle(Settings.FIELD)) {
targetDirection = -90;
}
// Then run around clockwise between the physical boundary and the field
else if (y <= Settings.FIELD.getTop() && x <= Settings.FIELD.getRight()) {
targetDirection = 0;
}
else if (x >= Settings.FIELD.getRight() && y <= Settings.FIELD.getBottom()) {
targetDirection = 90;
}
else if (y >= Settings.FIELD.getBottom() && x >= Settings.FIELD.getLeft()) {
targetDirection = 180;
}
else if (x <= Settings.FIELD.getLeft() && y >= Settings.FIELD.getTop()) {
targetDirection = -90;
}
else {
Log.e("Strategy " + strategy + " doesn't know how to handle position " + this.player.position.getPosition().render() + ".");
}
double offset = Math.abs(this.player.relativeAngleTo(targetDirection));
if (offset > 10) {
this.turnTo(targetDirection);
}
else {
this.dash(50, this.player.relativeAngleTo(targetDirection));
}
break;
case DASH_TOWARDS_BALL_AND_KICK:
FieldObject ball = this.getOrCreate("(b)");
FieldObject goal = this.getOrCreate(this.player.getOpponentGoalId());
Log.d("Estimated ball position: " + ball.position.render(this.time));
Log.d("Estimated goal position: " + goal.position.render(this.time));
if (this.canKickBall()) {
if (this.canSee(this.player.getOpponentGoalId())) {
kick(100.0, this.player.relativeAngleTo(goal));
}
else {
dash(30.0, 90.0);
}
}
else if (ball.position.getConfidence(this.time) > 0.1) {
double approachAngle;
approachAngle = Futil.simplifyAngle(this.player.relativeAngleTo(ball));
if (Math.abs(approachAngle) > 10) {
this.turn(approachAngle);
}
else {
dash(50.0, approachAngle);
}
}
else {
turn(7.0);
}
break;
case LOOK_AROUND:
turn(7);
break;
case GET_BETWEEN_BALL_AND_GOAL:
//TODO
break;
case GOALIE_CATCH_BALL:
//TODO
break;
default:
break;
}
}
/**
* Gets a field object from fieldObjects, or creates it if it doesn't yet exist.
*
* @param id the object's id
* @return the field object
*/
private final FieldObject getOrCreate(String id) {
if (this.fieldObjects.containsKey(id)) {
return this.fieldObjects.get(id);
}
else {
return FieldObject.create(id);
}
}
/**
* Infers the position and direction of this brain's associated player given two boundary flags
* on the same side seen in the current time step.
*
* @param o1 the first flag
* @param o2 the second flag
*/
private final void inferPositionAndDirection(FieldObject o1, FieldObject o2) {
// x1, x2, y1 and y2 are relative Cartesian coordinates to the flags
double x1 = Math.cos(Math.toRadians(o1.curInfo.direction)) * o1.curInfo.distance;
double y1 = Math.sin(Math.toRadians(o1.curInfo.direction)) * o1.curInfo.distance;
double x2 = Math.cos(Math.toRadians(o2.curInfo.direction)) * o2.curInfo.distance;
double y2 = Math.sin(Math.toRadians(o2.curInfo.direction)) * o2.curInfo.distance;
double direction = -Math.toDegrees(Math.atan((y2 - y1) / (x2 - x1)));
// Need to reverse the direction if looking closer to west and using horizontal boundary flags
if (o1.position.getY() == o2.position.getY()) {
if (Math.signum(o2.position.getX() - o1.position.getX()) != Math.signum(x2 - x1)) {
direction += 180.0;
}
}
// Need to offset the direction by +/- 90 degrees if using vertical boundary flags
else if (o1.position.getX() == o1.position.getX()) {
if (Math.signum(o2.position.getY() - o1.position.getY()) != Math.signum(x2 - x1)) {
direction += 270.0;
}
else {
direction += 90.0;
}
}
this.player.direction.update(Futil.simplifyAngle(direction), 0.95, this.time);
double x = o1.position.getX() - o1.curInfo.distance * Math.cos(Math.toRadians(direction + o1.curInfo.direction));
double y = o1.position.getY() - o1.curInfo.distance * Math.sin(Math.toRadians(direction + o1.curInfo.direction));
double distance = this.player.position.getPosition().distanceTo(new Point(x, y));
this.player.position.update(x, y, 0.95, this.time);
}
/**
* Moves the player to the specified coordinates (server coords).
*
* @param p the Point object to pass coordinates with (must be in server coordinates).
*/
public void move(Point p)
{
move(p.getX(), p.getY());
}
/**
* Moves the player to the specified coordinates (server coords).
*
* @param x x-coordinate
* @param y y-coordinate
*/
public void move(double x, double y) {
client.sendCommand(Settings.Commands.MOVE, Double.toString(x), Double.toString(y));
}
/**
* Kicks the ball in the direction of the player.
*
* @param power the level of power with which to kick (0 to 100)
*/
public void kick(double power) {
client.sendCommand(Settings.Commands.KICK, Double.toString(power));
}
/**
* Kicks the ball in the player's direction, offset by the given angle.
*
* @param power the level of power with which to kick (0 to 100)
* @param offset an angle in degrees to be added to the player's direction, yielding the direction of the kick
*/
public void kick(double power, double offset) {
client.sendCommand(Settings.Commands.KICK, Double.toString(power), Double.toString(offset));
}
/**
* Parses a message from the soccer server. This method is called whenever
* a message from the server is received.
*
* @param message the message (string), exactly as it was received
*/
public void parseMessage(String message) {
long timeReceived = System.currentTimeMillis();
message = Futil.sanitize(message);
// Handle `sense_body` messages
if (message.startsWith("(sense_body")) {
curSenseInfo.copy(lastSenseInfo);
curSenseInfo.reset();
this.timeLastSenseBody = timeReceived;
curSenseInfo.time = Futil.extractTime(message);
this.time = curSenseInfo.time;
// TODO better nested parentheses parsing logic; perhaps
// reconcile with Patrick's parentheses logic?
Log.d("Received a `sense_body` message at time step " + time + ".");
String parts[] = message.split("\\(");
for ( String i : parts ) // for each structured argument:
{
// Clean the string, and break it down into the base arguments.
String nMsg = i.split("\\)")[0].trim();
if ( nMsg.isEmpty() ) continue;
String nArgs[] = nMsg.split("\\s");
// Check for specific argument types; ignore unknown arguments.
if ( nArgs[0].contains("view_mode") )
{ // Player's current view mode
curSenseInfo.viewQuality = nArgs[1];
curSenseInfo.viewWidth = nArgs[2];
}
else if ( nArgs[0].contains("stamina") )
{ // Player's stamina data
curSenseInfo.stamina = Double.parseDouble(nArgs[1]);
curSenseInfo.effort = Double.parseDouble(nArgs[2]);
curSenseInfo.staminaCapacity = Double.parseDouble(nArgs[3]);
}
else if ( nArgs[0].contains("speed") )
{ // Player's speed data
curSenseInfo.amountOfSpeed = Double.parseDouble(nArgs[1]);
curSenseInfo.directionOfSpeed = Double.parseDouble(nArgs[2]);
}
else if ( nArgs[0].contains("head_angle") )
{ // Player's head angle
curSenseInfo.headAngle = Double.parseDouble(nArgs[1]);
}
else if ( nArgs[0].contains("ball") || nArgs[0].contains("player")
|| nArgs[0].contains("post") )
{ // COLLISION flags; limitation of this loop approach is we
// can't handle nested parentheses arguments well.
// Luckily these flags only occur in the collision structure.
curSenseInfo.collision = nArgs[0];
}
}
//update acceleration
if(lastSenseInfo.amountOfSpeed != Double.NaN){
final double dt = curSenseInfo.time - lastSenseInfo.time;
final double dv = curSenseInfo.amountOfSpeed - lastSenseInfo.amountOfSpeed;
playerAcceleration = dv/dt;
}
// If the brain has responded to two see messages in a row, it's time to respond to a sense_body.
if (this.responseHistory.get(0) == Settings.RESPONSE.SEE && this.responseHistory.get(1) == Settings.RESPONSE.SEE) {
this.run();
this.responseHistory.push(Settings.RESPONSE.SENSE_BODY);
this.responseHistory.removeLast();
}
}
// Handle `hear` messages
else if (message.startsWith("(hear"))
{
String parts[] = message.split("\\s");
this.time = Integer.parseInt(parts[1]);
if ( parts[2].startsWith("s") || parts[2].startsWith("o") || parts[2].startsWith("c") )
{
// TODO logic for self, on-line coach, and trainer coach.
// Self could potentially be for feedback,
// On-line coach will require coach language parsing,
// And trainer likely will as well. Outside of Sprint #2 scope.
return;
}
else
{
// Check for a referee message, otherwise continue.
String nMsg = parts[3].split("\\)")[0]; // Retrieve the message.
if ( parts[2].startsWith("r") // Referee;
&& Settings.PLAY_MODES.contains(nMsg) ) // Play Mode?
playMode = nMsg;
else
hearMessages.add( nMsg );
}
}
// Handle `see` messages
else if (message.startsWith("(see")) {
this.timeLastSee = timeReceived;
this.time = Futil.extractTime(message);
Log.d("Received `see` message at time step " + this.time);
LinkedList<String> infos = Futil.extractInfos(message);
for (String info : infos) {
String id = Futil.extractId(info);
if (Futil.isUniqueFieldObject(id)) {
FieldObject obj = this.getOrCreate(id);
obj.update(this.player, info, this.time);
this.fieldObjects.put(id, obj);
}
}
// Immediately run for the current step. Since our computations takes only a few
// milliseconds, it's okay to start running over half-way into the 100ms cycle.
// That means two out of every three time steps will be executed here.
this.run();
// Make sure we stay in sync with the mid-way `see`s
if (this.timeLastSee - this.timeLastSenseBody > 30) {
this.responseHistory.clear();
this.responseHistory.add(Settings.RESPONSE.SEE);
this.responseHistory.add(Settings.RESPONSE.SEE);
}
else {
this.responseHistory.add(Settings.RESPONSE.SEE);
this.responseHistory.removeLast();
}
}
// Handle init messages
else if (message.startsWith("(init")) {
String[] parts = message.split("\\s");
char teamSide = message.charAt(6);
if (teamSide == Settings.LEFT_SIDE) {
player.team.side = Settings.LEFT_SIDE;
player.otherTeam.side = Settings.RIGHT_SIDE;
}
else if (teamSide == Settings.RIGHT_SIDE) {
player.team.side = Settings.RIGHT_SIDE;
player.otherTeam.side = Settings.LEFT_SIDE;
}
else {
// Raise error
Log.e("Could not parse teamSide.");
}
player.number = Integer.parseInt(parts[2]);
playMode = parts[3].split("\\)")[0];
}
else if (message.startsWith("(server_param")) {
parseServerParameters(message);
}
}
public void parseServerParameters(String message)
{
String parts[] = message.split("\\(");
for ( String i : parts ) // for each structured argument:
{
// Clean the string, and break it down into the base arguments.
String nMsg = i.split("\\)")[0].trim();
if ( nMsg.isEmpty() ) continue;
String nArgs[] = nMsg.split("\\s");
// Check for specific argument types; ignore unknown arguments.
if ( nArgs[0].startsWith("goal_width") )
Settings.setGoalHeight(Double.parseDouble(nArgs[1]));
// Ball arguments:
else if ( nArgs[0].startsWith("ball") )
ServerParams_Ball.Builder.dataParser(nArgs);
// Player arguments:
else if ( nArgs[0].startsWith("player") || nArgs[0].startsWith("min")
|| nArgs[0].startsWith("max") )
ServerParams_Player.Builder.dataParser(nArgs);
}
// Rebuild all parameter objects with updated parameters.
Settings.rebuildParams();
}
/**
* Responds for the current time step.
*/
public void run() {
final long startTime = System.currentTimeMillis();
final long endTime;
int expectedNextRun = this.lastRan + 1;
if (this.time > expectedNextRun) {
Log.e("Brain did not run during time step " + expectedNextRun + ".");
}
this.lastRan = this.time;
this.updatePositionAndDirection();
this.currentStrategy = this.determineOptimalStrategy();
Log.i("Current strategy: " + this.currentStrategy);
this.executeStrategy(this.currentStrategy);
Log.d("Estimated player position: " + this.player.position.render(this.time) + ".");
Log.d("Estimated player direction: " + this.player.direction.render(this.time) + ".");
endTime = System.currentTimeMillis();
final long duration = endTime - startTime;
Log.d("Took " + duration + " ms (plus small overhead) to run at time " + this.time + ".");
if (duration > 35) {
Log.e("Took " + duration + " ms (plus small overhead) to run at time " + this.time + ".");
}
}
/**
* Adds the given angle to the player's current direction.
*
* @param offset an angle in degrees to add to the player's current direction
*/
public final void turn(double offset) {
double moment = Futil.toValidMoment(offset);
client.sendCommand(Settings.Commands.TURN, moment);
// TODO Potentially take magnitude of offset into account in the
// determination of the new confidence in the player's position.
player.direction.update(player.direction.getDirection() + moment, 0.95 * player.direction.getConfidence(this.time), this.time);
}
/**
* Updates the player's current direction to be the given direction.
*
* @param direction angle in degrees, assuming soccer server coordinate system
*/
public final void turnTo(double direction) {
this.turn(this.player.relativeAngleTo(direction));
}
/**
* Send commands to move the player to a point at maximum power
* @param point the point to move to
*/
private final void moveTowards(Point point){
moveTowards(point, 100d);
}
/**
* Send commands to move the player to a point with the given power
* @param point to move towards
* @param power to move at
*/
private final void moveTowards(Point point, double power){
final double x = player.position.getX() - point.getX();
final double y = player.position.getY() - point.getY();
final double theta = Math.toDegrees(Math.atan2(y, x));
turnTo(theta);
dash(power);
}
/**
* Updates this this brain's belief about the associated player's position and direction
* at the current time step.
*/
private final void updatePositionAndDirection() {
// Infer from the most-recent `see` if it happened in the current time-step
for (int i = 0; i < 4; i++) {
LinkedList<FieldObject> flagsOnSide = new LinkedList<FieldObject>();
for (String id : Settings.BOUNDARY_FLAG_GROUPS[i]) {
FieldObject flag = this.fieldObjects.get(id);
if (flag.curInfo.time == this.time) {
flagsOnSide.add(flag);
}
else {
//Log.i("Flag " + id + "last updated at time " + flag.info.time + ", not " + this.time);
}
if (flagsOnSide.size() > 1) {
this.inferPositionAndDirection(flagsOnSide.poll(), flagsOnSide.poll());
return;
}
}
}
// TODO Handle other cases
Log.e("Did not update position or direction at time " + this.time);
}
}
| refactored ball to getorcreate(b)
| src/futility/Brain.java | refactored ball to getorcreate(b) |
|
Java | mit | ab7c5243d57648cf42cc0557688265fb09ad81be | 0 | sourcepulp/treespy | package com.sourcepulp.treespy.jse7;
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sourcepulp.treespy.Events;
import com.sourcepulp.treespy.TreeSpy;
import com.sourcepulp.treespy.TreeSpyListener;
/**
* Java SE 7 compliant implementation of a directory watching service.
*
* @author Will Faithfull
*
*/
public class TreeSpyJSE7StdLib implements TreeSpy {
private static final Logger log = LoggerFactory.getLogger(TreeSpy.class);
private WatchService watcher;
private ConcurrentMap<WatchKey, Path> watchKeysToDirectories;
private ConcurrentMap<Path, Set<TreeSpyListener>> directoriesToListeners;
private ConcurrentMap<TreeSpyListener, Set<PathMatcher>> callbacksToGlobMatchers;
private AtomicBoolean running = new AtomicBoolean(false);
private Executor daemonExecutor;
private ExecutorService callbackExecutorService;
private boolean runCallbacksOnDaemonThread = true;
/**
* Constructs a directory spy using the provided executor to orchestrate the
* background task.
*
* @param daemonExecutor
* @throws IOException
*/
public TreeSpyJSE7StdLib(Executor daemonExecutor, WatchService watcher) throws IOException {
this.daemonExecutor = daemonExecutor;
this.watcher = watcher;
// Initialise maps
this.watchKeysToDirectories = new ConcurrentHashMap<WatchKey, Path>();
this.directoriesToListeners = new ConcurrentHashMap<Path, Set<TreeSpyListener>>();
this.callbacksToGlobMatchers = new ConcurrentHashMap<TreeSpyListener, Set<PathMatcher>>();
}
/**
* Constructs a directory spy using the provided executor to orchestrate the
* background task, and the provided ExecutorService to execute callbacks.
*
* @param daemonExecutor
* @param callbackExecutorService
* @throws IOException
*/
public TreeSpyJSE7StdLib(Executor daemonExecutor, WatchService watcher, ExecutorService callbackExecutorService)
throws IOException {
this(daemonExecutor, watcher);
this.callbackExecutorService = callbackExecutorService;
// In the default case, we don't use an executorservice, it needs to be
// explicitly told.
runCallbacksOnDaemonThread = false;
}
/**
* {@inheritDoc}
*/
public void reset() throws IOException {
stop();
for (WatchKey key : watchKeysToDirectories.keySet()) {
key.cancel();
}
watchKeysToDirectories = new ConcurrentHashMap<WatchKey, Path>();
directoriesToListeners = new ConcurrentHashMap<Path, Set<TreeSpyListener>>();
callbacksToGlobMatchers = new ConcurrentHashMap<TreeSpyListener, Set<PathMatcher>>();
}
/**
* {@inheritDoc}
*/
public void watchRecursive(File directory, TreeSpyListener callback) throws IOException {
this.watch(directory, callback, true);
}
/**
* {@inheritDoc}
*/
public void watchJust(File directory, TreeSpyListener callback) throws IOException {
this.watch(directory, callback, false);
}
/**
* {@inheritDoc}
*/
public void watchRecursive(File directory, TreeSpyListener callback, String... globs) throws IOException {
registerGlobs(callback, globs);
this.watch(directory, callback, true);
}
/**
* {@inheritDoc}
*/
public void watchJust(File directory, TreeSpyListener callback, String... globs) throws IOException {
registerGlobs(callback, globs);
this.watch(directory, callback, false);
}
private void watch(File directory, TreeSpyListener callback, boolean recursive) throws IOException {
if (!directory.isDirectory())
throw new IllegalArgumentException("Path must be a directory");
Path path = directory.toPath();
if (!isWatched(path))
register(path, callback, recursive);
if (!running.get())
start();
log.info(String.format("Watching %s%s", path.toString(), recursive ? " and subdirectories." : "."));
}
private void registerGlobs(TreeSpyListener callback, String[] globs) {
if (!callbacksToGlobMatchers.containsKey(callback))
callbacksToGlobMatchers.put(callback, new HashSet<PathMatcher>());
Set<PathMatcher> storedMatchers = callbacksToGlobMatchers.get(callback);
for (String glob : globs) {
if (!glob.startsWith("glob:"))
glob = "glob:" + glob;
PathMatcher matcher = FileSystems.getDefault().getPathMatcher(glob);
storedMatchers.add(matcher);
}
}
/**
* Indicates whether the specified directory already has a matching
* WatchKey.
*
* @param directory
* The path to check.
* @return True if there is an existing WatchKey for the path.
*/
private boolean isWatched(Path directory) {
return watchKeysToDirectories.containsValue(directory);
}
/**
* Indicates whether the specified directory already has attached listeners.
*
* @param directory
* The path to check.
* @return True if there are attached listeners to the path.
*/
private boolean isListened(Path directory) {
if (directoriesToListeners.containsKey(directory))
return !directoriesToListeners.get(directory).isEmpty();
return false;
}
/**
* Register the specified listener to the specified path, and recursively
* all subdirectories, if specified by the boolean.
*
* @param path
* The path to register the listener against.
* @param listener
* The listener to be registered.
* @param all
* Whether or not to recurse and register the listener against
* all subdirectories of the specified path.
* @throws IOException
*/
private void register(Path path, TreeSpyListener listener, boolean all) throws IOException {
FileVisitor<Path> visitor = makeVisitor(listener);
if (all)
Files.walkFileTree(path, visitor);
else
visitor.preVisitDirectory(path, Files.readAttributes(path, BasicFileAttributes.class));
}
/**
* Creates a FileVisitor that registers the specified callback at all
* directories it visits.
*
* @param listener
* A callback to be registered at any directories the visitor
* visits.
* @return A FileVisitor implementation that registers the callback where it
* visits.
*/
private FileVisitor<Path> makeVisitor(final TreeSpyListener listener) {
return new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY, OVERFLOW);
watchKeysToDirectories.put(key, dir);
if (!isListened(dir))
directoriesToListeners.put(dir, new LinkedHashSet<TreeSpyListener>());
directoriesToListeners.get(dir).add(listener);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exc.printStackTrace(pw);
log.warn(sw.toString());
return FileVisitResult.SKIP_SUBTREE;
}
};
}
/**
* Attempts to notify all listeners of the specified key.
*
* @param key
*/
private void notifyAll(WatchKey key) {
Path directory = watchKeysToDirectories.get(key);
Set<TreeSpyListener> listeners = directoriesToListeners.get(directory);
for (WatchEvent<?> event : key.pollEvents()) {
// Find the directory or file referenced by this WatchEvent
WatchEvent<Path> ev = cast(event);
Path filename = ev.context();
Path child = directory.resolve(filename);
Kind<?> kind = event.kind();
// Find out ahead of time if a new directory has been created.
boolean newDirectory = kind == ENTRY_CREATE && Files.isDirectory(child, NOFOLLOW_LINKS);
for (TreeSpyListener listener : listeners) {
Events eventType = Events.kindToEvent(kind);
// If users have particularly heavy or frequent tasks in
// callbacks, this provides the option to pass them off to an
// executor service rather than clogging up the daemon thread.
if (this.runCallbacksOnDaemonThread) {
notify(listener, child, eventType);
} else {
notifyAsync(listener, child, eventType);
}
// If a new directory was created, register it and any
// subdirectories.
if (newDirectory) {
try {
register(child, listener, true);
} catch (IOException ex) {
log.warn(String.format("Could not register %s", child.toString()));
}
}
}
// Reset key to allow subsequent monitoring.
boolean valid = key.reset();
if (!valid) {
log.warn(String.format("Invalid key - Directory %s is no longer accessible.", directory.toString()));
watchKeysToDirectories.remove(key);
}
}
}
private void notifyAsync(final TreeSpyListener listener, final Path path, final Events eventType) {
callbackExecutorService.execute(new Runnable() {
@Override
public void run() {
TreeSpyJSE7StdLib.this.notify(listener, path, eventType);
}
});
}
private void notify(final TreeSpyListener listener, final Path path, final Events eventType) {
Set<PathMatcher> globs = callbacksToGlobMatchers.get(listener);
boolean noGlobs = globs == null || globs.isEmpty();
// LHS evaluated first. If there are NO globs, notify. If there ARE globs, then matches also needs to return true in order to notify.
if (noGlobs || matches(globs, path)) {
listener.onChange(path, eventType);
}
}
private boolean matches(Set<PathMatcher> globs, Path path) {
Path file = path.getFileName();
for (PathMatcher glob : globs) {
if (glob.matches(file))
return true;
}
return false;
}
/**
* Unchecked cast method suggested by the Java 7 SE API documentation for
* {@link java.nio.file.WatcherService}
*
* @param event
* @return
*/
@SuppressWarnings("unchecked")
private static <T> WatchEvent<T> cast(WatchEvent<?> event) {
return (WatchEvent<T>) event;
}
/**
* {@inheritDoc}
*/
public void start() {
daemonExecutor.execute(new WatchServiceRunnable(this));
running.set(true);
log.info("TreeSpy started spying.");
}
/**
* {@inheritDoc}
*/
public void stop() {
if (running.get()) {
running.set(false);
log.info("TreeSpy stopped spying.");
}
}
/**
* Runnable implementation for the background daemon thread. Can be lazily
* killed by setting the AtomicBoolean in the outer class.
*
* @author wfaithfull
*
*/
private class WatchServiceRunnable implements Runnable {
TreeSpyJSE7StdLib spy;
public WatchServiceRunnable(TreeSpyJSE7StdLib spy) {
this.spy = spy;
}
public void run() {
while (running.get()) {
WatchKey key;
try {
key = spy.watcher.take();
} catch (InterruptedException ex) {
log.error("Thread was interrupted unexpectedly", ex);
return;
}
spy.notifyAll(key);
}
running.set(false);
}
}
}
| src/main/java/com/sourcepulp/treespy/jse7/TreeSpyJSE7StdLib.java | package com.sourcepulp.treespy.jse7;
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sourcepulp.treespy.Events;
import com.sourcepulp.treespy.TreeSpy;
import com.sourcepulp.treespy.TreeSpyListener;
/**
* Java SE 7 compliant implementation of a directory watching service.
*
* @author Will Faithfull
*
*/
public class TreeSpyJSE7StdLib implements TreeSpy {
private static final Logger log = LoggerFactory.getLogger(TreeSpy.class);
private WatchService watcher;
private ConcurrentMap<WatchKey, Path> watchKeysToDirectories;
private ConcurrentMap<Path, Set<TreeSpyListener>> directoriesToListeners;
private ConcurrentMap<TreeSpyListener, Set<PathMatcher>> callbacksToGlobMatchers;
private AtomicBoolean running = new AtomicBoolean(false);
private Executor daemonExecutor;
private ExecutorService callbackExecutorService;
private boolean runCallbacksOnDaemonThread = true;
/**
* Constructs a directory spy using the provided executor to orchestrate the
* background task.
*
* @param daemonExecutor
* @throws IOException
*/
public TreeSpyJSE7StdLib(Executor daemonExecutor, WatchService watcher) throws IOException {
this.daemonExecutor = daemonExecutor;
this.watcher = watcher;
// Initialise maps
this.watchKeysToDirectories = new ConcurrentHashMap<WatchKey, Path>();
this.directoriesToListeners = new ConcurrentHashMap<Path, Set<TreeSpyListener>>();
this.callbacksToGlobMatchers = new ConcurrentHashMap<TreeSpyListener, Set<PathMatcher>>();
}
/**
* Constructs a directory spy using the provided executor to orchestrate the
* background task, and the provided ExecutorService to execute callbacks.
*
* @param daemonExecutor
* @param callbackExecutorService
* @throws IOException
*/
public TreeSpyJSE7StdLib(Executor daemonExecutor, WatchService watcher, ExecutorService callbackExecutorService)
throws IOException {
this(daemonExecutor, watcher);
this.callbackExecutorService = callbackExecutorService;
// In the default case, we don't use an executorservice, it needs to be
// explicitly told.
runCallbacksOnDaemonThread = false;
}
/**
* {@inheritDoc}
*/
public void reset() throws IOException {
stop();
for (WatchKey key : watchKeysToDirectories.keySet()) {
key.cancel();
}
watchKeysToDirectories = new ConcurrentHashMap<WatchKey, Path>();
directoriesToListeners = new ConcurrentHashMap<Path, Set<TreeSpyListener>>();
callbacksToGlobMatchers = new ConcurrentHashMap<TreeSpyListener, Set<PathMatcher>>();
}
/**
* {@inheritDoc}
*/
public void watchRecursive(File directory, TreeSpyListener callback) throws IOException {
this.watch(directory, callback, true);
}
/**
* {@inheritDoc}
*/
public void watchJust(File directory, TreeSpyListener callback) throws IOException {
this.watch(directory, callback, false);
}
/**
* {@inheritDoc}
*/
public void watchRecursive(File directory, TreeSpyListener callback, String... globs) throws IOException {
registerGlobs(callback, globs);
this.watch(directory, callback, true);
}
/**
* {@inheritDoc}
*/
public void watchJust(File directory, TreeSpyListener callback, String... globs) throws IOException {
registerGlobs(callback, globs);
this.watch(directory, callback, false);
}
private void watch(File directory, TreeSpyListener callback, boolean recursive) throws IOException {
if (!directory.isDirectory())
throw new IllegalArgumentException("Path must be a directory");
Path path = directory.toPath();
if (!isWatched(path))
register(path, callback, recursive);
if (!running.get())
start();
log.info(String.format("Watching %s%s", path.toString(), recursive ? " and subdirectories." : "."));
}
private void registerGlobs(TreeSpyListener callback, String[] globs) {
if (!callbacksToGlobMatchers.containsKey(callback))
callbacksToGlobMatchers.put(callback, new HashSet<PathMatcher>());
Set<PathMatcher> storedMatchers = callbacksToGlobMatchers.get(callback);
for (String glob : globs) {
if (!glob.startsWith("glob:"))
glob = "glob:" + glob;
PathMatcher matcher = FileSystems.getDefault().getPathMatcher(glob);
storedMatchers.add(matcher);
}
}
/**
* Indicates whether the specified directory already has a matching
* WatchKey.
*
* @param directory
* The path to check.
* @return True if there is an existing WatchKey for the path.
*/
private boolean isWatched(Path directory) {
return watchKeysToDirectories.containsValue(directory);
}
/**
* Indicates whether the specified directory already has attached listeners.
*
* @param directory
* The path to check.
* @return True if there are attached listeners to the path.
*/
private boolean isListened(Path directory) {
if (directoriesToListeners.containsKey(directory))
return !directoriesToListeners.get(directory).isEmpty();
return false;
}
/**
* Register the specified listener to the specified path, and recursively
* all subdirectories, if specified by the boolean.
*
* @param path
* The path to register the listener against.
* @param listener
* The listener to be registered.
* @param all
* Whether or not to recurse and register the listener against
* all subdirectories of the specified path.
* @throws IOException
*/
private void register(Path path, TreeSpyListener listener, boolean all) throws IOException {
FileVisitor<Path> visitor = makeVisitor(listener);
if (all)
Files.walkFileTree(path, visitor);
else
visitor.preVisitDirectory(path, Files.readAttributes(path, BasicFileAttributes.class));
}
/**
* Creates a FileVisitor that registers the specified callback at all
* directories it visits.
*
* @param listener
* A callback to be registered at any directories the visitor
* visits.
* @return A FileVisitor implementation that registers the callback where it
* visits.
*/
private FileVisitor<Path> makeVisitor(final TreeSpyListener listener) {
return new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY, OVERFLOW);
watchKeysToDirectories.put(key, dir);
if (!isListened(dir))
directoriesToListeners.put(dir, new LinkedHashSet<TreeSpyListener>());
directoriesToListeners.get(dir).add(listener);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exc.printStackTrace(pw);
log.warn(sw.toString());
return FileVisitResult.SKIP_SUBTREE;
}
};
}
/**
* Attempts to notify all listeners of the specified key.
*
* @param key
*/
private void notifyAll(WatchKey key) {
Path directory = watchKeysToDirectories.get(key);
Set<TreeSpyListener> listeners = directoriesToListeners.get(directory);
for (WatchEvent<?> event : key.pollEvents()) {
// Find the directory or file referenced by this WatchEvent
WatchEvent<Path> ev = cast(event);
Path filename = ev.context();
Path child = directory.resolve(filename);
Kind<?> kind = event.kind();
// Find out ahead of time if a new directory has been created.
boolean newDirectory = kind == ENTRY_CREATE && Files.isDirectory(child, NOFOLLOW_LINKS);
for (TreeSpyListener listener : listeners) {
Events eventType = Events.kindToEvent(kind);
// If users have particularly heavy or frequent tasks in
// callbacks, this provides the option to pass them off to an
// executor service rather than clogging up the daemon thread.
if (this.runCallbacksOnDaemonThread) {
notify(listener, child, eventType);
} else {
notifyAsync(listener, child, eventType);
}
// If a new directory was created, register it and any
// subdirectories.
if (newDirectory) {
try {
register(child, listener, true);
} catch (IOException ex) {
log.warn(String.format("Could not register %s", child.toString()));
}
}
}
// Reset key to allow subsequent monitoring.
boolean valid = key.reset();
if (!valid) {
log.warn(String.format("Invalid key - Directory %s is no longer accessible.", directory.toString()));
watchKeysToDirectories.remove(key);
}
}
}
private void notifyAsync(final TreeSpyListener listener, final Path path, final Events eventType) {
callbackExecutorService.execute(new Runnable() {
@Override
public void run() {
TreeSpyJSE7StdLib.this.notify(listener, path, eventType);
}
});
}
private void notify(final TreeSpyListener listener, final Path path, final Events eventType) {
Set<PathMatcher> globs = callbacksToGlobMatchers.get(listener);
boolean noGlobs = globs == null || globs.isEmpty();
// LHS evaluated first. If there are NO globs, notify. If there ARE globs, then matches also needs to return true in order to notify.
if (noGlobs || matches(globs, path)) {
listener.onChange(path, eventType);
}
}
private boolean matches(Set<PathMatcher> globs, Path path) {
for (PathMatcher glob : globs) {
if (glob.matches(path))
return true;
}
return false;
}
/**
* Unchecked cast method suggested by the Java 7 SE API documentation for
* {@link java.nio.file.WatcherService}
*
* @param event
* @return
*/
@SuppressWarnings("unchecked")
private static <T> WatchEvent<T> cast(WatchEvent<?> event) {
return (WatchEvent<T>) event;
}
/**
* {@inheritDoc}
*/
public void start() {
daemonExecutor.execute(new WatchServiceRunnable(this));
running.set(true);
log.info("TreeSpy started spying.");
}
/**
* {@inheritDoc}
*/
public void stop() {
if (running.get()) {
running.set(false);
log.info("TreeSpy stopped spying.");
}
}
/**
* Runnable implementation for the background daemon thread. Can be lazily
* killed by setting the AtomicBoolean in the outer class.
*
* @author wfaithfull
*
*/
private class WatchServiceRunnable implements Runnable {
TreeSpyJSE7StdLib spy;
public WatchServiceRunnable(TreeSpyJSE7StdLib spy) {
this.spy = spy;
}
public void run() {
while (running.get()) {
WatchKey key;
try {
key = spy.watcher.take();
} catch (InterruptedException ex) {
log.error("Thread was interrupted unexpectedly", ex);
return;
}
spy.notifyAll(key);
}
running.set(false);
}
}
}
| Fixed glob evaluation bug by comparing to fileName path instead of fully qualified path
| src/main/java/com/sourcepulp/treespy/jse7/TreeSpyJSE7StdLib.java | Fixed glob evaluation bug by comparing to fileName path instead of fully qualified path |
|
Java | mit | 7a808ef1ac00e13d4bbff94314ac64b0a2ecc73b | 0 | Aikain/SleepDemocracy | package fi.gosu.mc.plugins.SleepDemocracy;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.*;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* Created by Aikain on 7.5.2016.
*/
public class SleepDemocracy extends JavaPlugin implements Listener {
private boolean SDEnable;
private int SDPercent;
@Override
public void onEnable() {
this.loadConfig();
this.getServer().getPluginManager().registerEvents(this, this);
this.getCommand("sdtoggle").setExecutor(this);
this.getCommand("sdset").setExecutor(this);
super.onEnable();
}
@Override
public void onDisable() {
super.onDisable();
}
public void loadConfig() {
this.getConfig().options().copyDefaults(true);
this.saveConfig();
this.SDEnable = this.getConfig().getBoolean("SDEnable");
this.SDPercent = this.getConfig().getInt("SDPercent");
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
switch (cmd.getName()) {
case "sdtoggle":
if (sender.hasPermission("sleepdemocracy.sdtoggle")) {
if (args.length == 0) {
this.SDEnable = !this.SDEnable;
} else if (args.length == 1) {
if (args[0].equals("ON")) {
this.SDEnable = true;
} else if (args[1].equals("OFF")) {
this.SDEnable = false;
} else {
sender.sendMessage(cmd.getUsage());
return false;
}
} else {
sender.sendMessage(cmd.getUsage());
return false;
}
this.getConfig().set("SDEnable", Boolean.valueOf(this.SDEnable));
this.saveConfig();
sender.sendMessage((this.SDEnable ? "Enabled" : "Disabled") + " SleepDemocracy");
return true;
}
sender.sendMessage(cmd.getPermissionMessage());
break;
case "sdset":
if (sender.hasPermission("sleepdemocracy.sdset")) {
if (args.length == 1) {
try {
int a = Integer.parseInt(args[0]);
if (a < 0 || a > 100) {
throw new Exception();
}
this.SDPercent = a;
this.getConfig().set("SDPercent", Integer.valueOf(a));
this.saveConfig();
sender.sendMessage("Set percent to " + args[0]);
return true;
} catch (Exception e) {
sender.sendMessage("Number invalid. Please enter a number 0 - 100.");
}
} else {
sender.sendMessage(cmd.getUsage());
}
} else {
sender.sendMessage(cmd.getPermissionMessage());
}
break;
}
return false;
}
@EventHandler
public void onBedEnter(PlayerBedEnterEvent event) {
testSleeping();
}
@EventHandler
public void onBedLeave(PlayerBedLeaveEvent event) {
testSleeping();
}
@EventHandler
public void onServerJoin(PlayerJoinEvent event) {
testSleeping();
}
@EventHandler
public void onServerLeave(PlayerQuitEvent event) {
testSleeping();
}
@EventHandler
public void onWorldChange(PlayerChangedWorldEvent event) {
testSleeping();
}
private void testSleeping() {
if (!this.SDEnable) return;
for (World world : Bukkit.getWorlds()) {
int i = 0;
for (Player player : world.getPlayers()) {
if (player.isSleeping()) i++;
}
int currentPercent = 100 * i / world.getPlayers().size();
for (Player player : world.getPlayers()) {
player.sendMessage("Currently " + currentPercent + "% of " + world.getName() + "'s players are sleeping out of " + this.SDPercent + "% needed.");
}
if (currentPercent > SDPercent) {
world.setTime(1000L);
}
}
}
}
| src/main/java/fi/gosu/mc/plugins/SleepDemocracy/SleepDemocracy.java | package fi.gosu.mc.plugins.SleepDemocracy;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.*;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* Created by Aikain on 7.5.2016.
*/
public class SleepDemocracy extends JavaPlugin implements Listener {
private boolean SDEnable;
private int SDPercent;
@Override
public void onEnable() {
this.loadConfig();
this.getServer().getPluginManager().registerEvents(this, this);
this.getCommand("sdtoggle").setExecutor(this);
this.getCommand("sdset").setExecutor(this);
super.onEnable();
}
@Override
public void onDisable() {
super.onDisable();
}
public void loadConfig() {
this.getConfig().options().copyDefaults(true);
this.saveConfig();
this.SDEnable = this.getConfig().getBoolean("SDEnable");
this.SDPercent = this.getConfig().getInt("SDPercent");
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
switch (cmd.getName()) {
case "sdtoggle":
if (sender.hasPermission("sleepdemocracy.sdtoggle")) {
if (args.length == 0) {
this.SDEnable = !this.SDEnable;
} else if (args.length == 1) {
if (args[0].equals("ON")) {
this.SDEnable = true;
} else if (args[1].equals("OFF")) {
this.SDEnable = false;
} else {
sender.sendMessage(cmd.getUsage());
return false;
}
} else {
sender.sendMessage(cmd.getUsage());
return false;
}
this.getConfig().set("SDEnable", Boolean.valueOf(this.SDEnable));
this.saveConfig();
sender.sendMessage((this.SDEnable ? "Enabled" : "Disabled") + " SleepDemocracy");
return true;
}
sender.sendMessage(cmd.getPermissionMessage());
break;
case "sdset":
if (sender.hasPermission("sleepdemocracy.sdset")) {
if (args.length == 1) {
try {
int a = Integer.parseInt(args[0]);
if (a < 0 || a > 100) {
throw new Exception();
}
this.SDPercent = a;
this.getConfig().set("SDPercent", Integer.valueOf(a));
this.saveConfig();
sender.sendMessage("Set percent to " + args[0]);
return true;
} catch (Exception e) {
sender.sendMessage("Number invalid. Please enter a number 0 - 100.");
}
} else {
sender.sendMessage(cmd.getUsage());
}
} else {
sender.sendMessage(cmd.getPermissionMessage());
}
break;
}
return false;
}
@EventHandler
public void onBedEnter(PlayerBedEnterEvent event) {
testSleeping();
}
@EventHandler
public void onBedLeave(PlayerBedLeaveEvent event) {
testSleeping();
}
@EventHandler
public void onServerJoin(PlayerJoinEvent event) {
testSleeping();
}
@EventHandler
public void onServerLeave(PlayerQuitEvent event) {
testSleeping();
}
@EventHandler
public void onWorldChange(PlayerChangedWorldEvent event) {
testSleeping();
}
private void testSleeping() {
if (!this.SDEnable) return;
Map<World, Integer> sleepers = new HashMap<>();
for (Player player : Arrays.asList(Bukkit.getServer().getOnlinePlayers())) {
sleepers.put(player.getWorld(), (sleepers.containsKey(player.getWorld()) ? sleepers.get(player.getWorld()) + 1 : 0));
}
for (Entry<World, Integer> entry : sleepers.entrySet()) {
int currentPercent = 100 * entry.getValue() / entry.getKey().getPlayers().size();
for (Player player : entry.getKey().getPlayers()) {
player.sendMessage("Currently " + entry.getValue() + "% of " + entry.getKey().getName() + "'s players are sleeping out of " + this.SDPercent + "% needed.");
}
if (currentPercent > SDPercent) {
entry.getKey().setTime(1000L);
}
}
}
}
| Fix getting online players v3
| src/main/java/fi/gosu/mc/plugins/SleepDemocracy/SleepDemocracy.java | Fix getting online players v3 |
|
Java | mit | 95e9561a58775917a3f571b841ad3e0f884a14f7 | 0 | antorof/jpa-listacorreos | package antoniotoro.practica2.cliente;
import java.awt.BorderLayout;
import java.awt.Dialog.ModalExclusionType;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.table.TableCellEditor;
import antoniotoro.practica2.listacorreos.Usuario;
public class Cliente extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
private JPanel panelContenido;
private JTable table;
private JScrollPane scroll;
private JToolBar toolBar;
private JButton btnAddUser;
private JPanel panelAniadir;
private JLabel lblNombre;
private JTextField tfNombre;
private JLabel lblApellido;
private JTextField tfApellido;
private JLabel lblEmail;
private JTextField tfEmail;
private JPanel botonera;
private JButton btnAniadir;
private JButton btnCancelar;
private static final String EXPR_REG_EMAIL = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
final Pattern pattern = Pattern.compile(EXPR_REG_EMAIL);
public static String urlString = "http://localhost:8080/antoniotoro.practica2/ListaCorreosServlet";
private ModeloTablaUsuarios modeloTablaUsuarios;
/**
* Se lanza la aplicacion.
*/
public static void main(String[] args) {
try { // Para que no se vea con el look normal de Swing sino con el del sistema
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e)
{ System.err.println("Unable to load System look and feel"); }
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Cliente frame = new Cliente();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Se crea la ventana.
*/
public Cliente() {
setTitle("Pr\u00E1ctica 2 - Antonio Toro");
setModalExclusionType(ModalExclusionType.TOOLKIT_EXCLUDE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 550, 300);
setLocationRelativeTo(null);
panelContenido = new JPanel();
panelContenido.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(panelContenido);
panelContenido.setLayout(new BorderLayout(0, 0));
List<Usuario> listaUsuarios = obtenerListaUsuarios();
modeloTablaUsuarios = new ModeloTablaUsuarios(listaUsuarios);
table = new JTable(modeloTablaUsuarios) {
private static final long serialVersionUID = 1L;
@Override
public void editingStopped(ChangeEvent e) {
TableCellEditor editor = getCellEditor();
if (editor != null) {
Object value = editor.getCellEditorValue();
Usuario usuario = new Usuario(modeloTablaUsuarios.getUsuarioAt(editingRow));
if (editingColumn < 2) {
switch (editingColumn) {
case 0:
usuario.setNombre((String) value);
break;
case 1:
usuario.setApellido((String) value);
break;
default:
break;
}
try {
Map<String,String> parametros = new HashMap<String, String>();
parametros.put("action", "actualizarUsuario");
parametros.put("nombre", usuario.getNombre());
parametros.put("apellido", usuario.getApellido());
parametros.put("email", usuario.getEmail());
ObjectInputStream respuesta = new ObjectInputStream(realizarPeticionPost(urlString, parametros));
int codigo = respuesta.readInt();
String mensaje = (String) respuesta.readObject();
System.out.println(codigo);
System.out.println(mensaje);
switch (codigo) {
case 0:
setValueAt(value, editingRow, editingColumn);
break;
default:
break;
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
removeEditor();
}
}
};
/*
* Accion empleada en los botones de la tabla que permite que ese usuario/fila
* sea eliminado.
*/
Action borrarFila = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
int modelRow = Integer.valueOf( e.getActionCommand() );
Usuario usuario = modeloTablaUsuarios.getUsuarioAt(modelRow);
int resultadoDialogo = JOptionPane.showConfirmDialog(
Cliente.this,
"Ests seguro de que quieres elinimar el usuario <"+usuario.getEmail()+">?",
"Eliminar usuario",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (resultadoDialogo == JOptionPane.YES_OPTION) {
try {
Map<String,String> parametros = new HashMap<String, String>();
parametros.put("action", "eliminarUsuario");
parametros.put("email", usuario.getEmail());
ObjectInputStream respuesta = new ObjectInputStream(realizarPeticionPost(urlString, parametros));
int codigo = respuesta.readInt();
String mensaje = (String) respuesta.readObject();
System.out.println(codigo);
System.out.println(mensaje);
switch (codigo) {
case 0:
modeloTablaUsuarios.removeRow(modelRow);
break;
default:
break;
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
};
// Hacemos que la cuarta columna sea el boton cuya accion la de borrarFila
new ButtonColumn(table, borrarFila, 3);
table.putClientProperty("terminateEditOnFocusLost", true);
scroll = new JScrollPane(table);
panelContenido.add(scroll, BorderLayout.CENTER);
toolBar = new JToolBar();
toolBar.setFloatable(false);
panelContenido.add(toolBar, BorderLayout.NORTH);
btnAddUser = new JButton("A\u00F1adir Usuario");
btnAddUser.setActionCommand("ADDUSER");
btnAddUser.addActionListener(this);
toolBar.add(btnAddUser);
panelAniadir = new JPanel();
panelAniadir.setVisible(false);
panelContenido.add(panelAniadir, BorderLayout.EAST);
GridBagLayout gbl_panelAniadir = new GridBagLayout();
gbl_panelAniadir.columnWidths = new int[]{0, 0, 0, 0};
gbl_panelAniadir.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panelAniadir.columnWeights = new double[]{1.0, 1.0, 1.0, Double.MIN_VALUE};
gbl_panelAniadir.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
panelAniadir.setLayout(gbl_panelAniadir);
lblNombre = new JLabel("Nombre: ");
lblNombre.setHorizontalAlignment(SwingConstants.RIGHT);
GridBagConstraints gbc_lblNombre = new GridBagConstraints();
gbc_lblNombre.insets = new Insets(0, 0, 5, 5);
gbc_lblNombre.anchor = GridBagConstraints.EAST;
gbc_lblNombre.gridx = 0;
gbc_lblNombre.gridy = 0;
panelAniadir.add(lblNombre, gbc_lblNombre);
tfNombre = new JTextField();
GridBagConstraints gbc_tfNombre = new GridBagConstraints();
gbc_tfNombre.insets = new Insets(0, 0, 5, 5);
gbc_tfNombre.fill = GridBagConstraints.HORIZONTAL;
gbc_tfNombre.gridx = 1;
gbc_tfNombre.gridy = 0;
panelAniadir.add(tfNombre, gbc_tfNombre);
tfNombre.setColumns(10);
lblApellido = new JLabel("Apellido: ");
lblApellido.setHorizontalAlignment(SwingConstants.RIGHT);
GridBagConstraints gbc_lblApellido = new GridBagConstraints();
gbc_lblApellido.anchor = GridBagConstraints.EAST;
gbc_lblApellido.insets = new Insets(0, 0, 5, 5);
gbc_lblApellido.gridx = 0;
gbc_lblApellido.gridy = 1;
panelAniadir.add(lblApellido, gbc_lblApellido);
tfApellido = new JTextField();
GridBagConstraints gbc_tfApellido = new GridBagConstraints();
gbc_tfApellido.insets = new Insets(0, 0, 5, 5);
gbc_tfApellido.fill = GridBagConstraints.HORIZONTAL;
gbc_tfApellido.gridx = 1;
gbc_tfApellido.gridy = 1;
panelAniadir.add(tfApellido, gbc_tfApellido);
tfApellido.setColumns(10);
lblEmail = new JLabel("Email: ");
lblEmail.setHorizontalAlignment(SwingConstants.RIGHT);
GridBagConstraints gbc_lblEmail = new GridBagConstraints();
gbc_lblEmail.anchor = GridBagConstraints.EAST;
gbc_lblEmail.insets = new Insets(0, 0, 5, 5);
gbc_lblEmail.gridx = 0;
gbc_lblEmail.gridy = 2;
panelAniadir.add(lblEmail, gbc_lblEmail);
tfEmail = new JTextField();
GridBagConstraints gbc_tfEmail = new GridBagConstraints();
gbc_tfEmail.insets = new Insets(0, 0, 5, 5);
gbc_tfEmail.fill = GridBagConstraints.HORIZONTAL;
gbc_tfEmail.gridx = 1;
gbc_tfEmail.gridy = 2;
panelAniadir.add(tfEmail, gbc_tfEmail);
tfEmail.setColumns(10);
botonera = new JPanel();
GridBagConstraints gbc_botonera = new GridBagConstraints();
gbc_botonera.gridwidth = 2;
gbc_botonera.insets = new Insets(0, 0, 0, 5);
gbc_botonera.fill = GridBagConstraints.BOTH;
gbc_botonera.gridx = 0;
gbc_botonera.gridy = 7;
panelAniadir.add(botonera, gbc_botonera);
botonera.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
btnAniadir = new JButton("A\u00F1adir");
btnAniadir.setActionCommand("EXEC_ANIADIR");
btnAniadir.addActionListener(this);
botonera.add(btnAniadir);
btnCancelar = new JButton("Cancelar");
btnCancelar.setActionCommand("CANCELAR");
btnCancelar.addActionListener(this);
botonera.add(btnCancelar);
}
/**
* Obtiene la lista de usuarios del servlet.
* @return Lista con los usuarios
*/
@SuppressWarnings("unchecked")
private List<Usuario> obtenerListaUsuarios() {
try {
Map<String,String> parametros = new HashMap<String, String>();
parametros.put("action", "listarUsuarios");
ObjectInputStream respuesta = new ObjectInputStream(realizarPeticionPost(urlString, parametros));
List<Usuario> listaUsuarios = (List<Usuario>) respuesta.readObject();
return listaUsuarios;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("ADDUSER")) {
panelAniadir.setVisible(true);
}
else if (e.getActionCommand().equals("EXEC_ANIADIR")) {
Matcher matcher = pattern.matcher(tfEmail.getText());
String nombre = tfNombre.getText(),
apellido = tfApellido.getText(),
email = tfEmail.getText();
String fraseError = "";
boolean error = false;
if (nombre.equals("")) {
error = true;
fraseError += "\n Debe introducir un nombre";
}
if (apellido.equals("")) {
error = true;
fraseError += "\n Debe introducir un apellido";
}
if (!matcher.matches()) {
error = true;
fraseError += "\n Correo electr\u00F3nico no v\u00E1lido.";
}
if (!error) {
try {
Map<String,String> parametros = new HashMap<String, String>();
parametros.put("action", "aniadirUsuario");
parametros.put("nombre", nombre);
parametros.put("apellido", apellido);
parametros.put("email", email);
ObjectInputStream respuesta = new ObjectInputStream(realizarPeticionPost(urlString, parametros));
int codigo = respuesta.readInt();
String mensaje = (String) respuesta.readObject();
System.out.println(codigo);
System.out.println(mensaje);
switch (codigo) {
case 0:
Usuario usuario = new Usuario();
usuario.setNombre(tfNombre.getText());
usuario.setApellido(tfApellido.getText());
usuario.setEmail(tfEmail.getText());
modeloTablaUsuarios.add(usuario);
tfNombre.setText("");
tfApellido.setText("");
tfEmail.setText("");
break;
default:
break;
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
else {
JOptionPane.showMessageDialog(Cliente.this,
fraseError,
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
else if (e.getActionCommand().equals("CANCELAR")) {
tfNombre.setText("");
tfApellido.setText("");
tfEmail.setText("");
panelAniadir.setVisible(false);
}
}
/**
* Realiza una peticin POST a una URL con los parametros provistos.
* @param urlString Direccion a la que se desea realizar a peticion
* @param parametros Parametros de la peticion
* @return Respuesta obtenida o <tt>null</tt> en caso de fallo
*/
@SuppressWarnings("deprecation")
public InputStream realizarPeticionPost(String urlString, Map<String,String> parametros) {
String cadenaParametros = "";
boolean primerPar = true;
for (Map.Entry<String, String> entry : parametros.entrySet()) {
if (!primerPar) {
cadenaParametros += "&";
} else {
primerPar = false;
}
String parDeParametro = String.format("%s=%s",
URLEncoder.encode(entry.getKey()),
URLEncoder.encode(entry.getValue()));
cadenaParametros += parDeParametro;
}
try {
URL url = new URL(urlString);
HttpURLConnection conexion = (HttpURLConnection) url.openConnection();
conexion.setUseCaches(false);
conexion.setRequestMethod("POST");
conexion.setDoOutput(true);
OutputStream output = conexion.getOutputStream();
output.write(cadenaParametros.getBytes());
output.flush();
output.close();
return conexion.getInputStream();
} catch (MalformedURLException | ProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
}
| src/antoniotoro/practica2/cliente/Cliente.java | package antoniotoro.practica2.cliente;
import java.awt.BorderLayout;
import java.awt.Dialog.ModalExclusionType;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.table.TableCellEditor;
import antoniotoro.practica2.listacorreos.Usuario;
public class Cliente extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
private JPanel panelContenido;
private JTable table;
private JScrollPane scroll;
private JToolBar toolBar;
private JButton btnAddUser;
private JPanel panelAniadir;
private JLabel lblNombre;
private JTextField tfNombre;
private JLabel lblApellido;
private JTextField tfApellido;
private JLabel lblEmail;
private JTextField tfEmail;
private JPanel botonera;
private JButton btnAniadir;
private JButton btnCancelar;
public static String urlString = "http://localhost:8080/antoniotoro.practica2/ListaCorreosServlet";
private ModeloTablaUsuarios modeloTablaUsuarios;
/**
* Se lanza la aplicacion.
*/
public static void main(String[] args) {
try { // Para que no se vea con el look normal de Swing sino con el del sistema
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e)
{ System.err.println("Unable to load System look and feel"); }
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Cliente frame = new Cliente();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Se crea la ventana.
*/
public Cliente() {
setTitle("Pr\u00E1ctica 2 - Antonio Toro");
setModalExclusionType(ModalExclusionType.TOOLKIT_EXCLUDE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 550, 300);
setLocationRelativeTo(null);
panelContenido = new JPanel();
panelContenido.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(panelContenido);
panelContenido.setLayout(new BorderLayout(0, 0));
List<Usuario> listaUsuarios = obtenerListaUsuarios();
modeloTablaUsuarios = new ModeloTablaUsuarios(listaUsuarios);
table = new JTable(modeloTablaUsuarios) {
private static final long serialVersionUID = 1L;
@Override
public void editingStopped(ChangeEvent e) {
TableCellEditor editor = getCellEditor();
if (editor != null) {
Object value = editor.getCellEditorValue();
Usuario usuario = new Usuario(modeloTablaUsuarios.getUsuarioAt(editingRow));
if (editingColumn < 2) {
switch (editingColumn) {
case 0:
usuario.setNombre((String) value);
break;
case 1:
usuario.setApellido((String) value);
break;
default:
break;
}
try {
Map<String,String> parametros = new HashMap<String, String>();
parametros.put("action", "actualizarUsuario");
parametros.put("nombre", usuario.getNombre());
parametros.put("apellido", usuario.getApellido());
parametros.put("email", usuario.getEmail());
ObjectInputStream respuesta = new ObjectInputStream(realizarPeticionPost(urlString, parametros));
int codigo = respuesta.readInt();
String mensaje = (String) respuesta.readObject();
System.out.println(codigo);
System.out.println(mensaje);
switch (codigo) {
case 0:
setValueAt(value, editingRow, editingColumn);
break;
default:
break;
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
removeEditor();
}
}
};
/*
* Accion empleada en los botones de la tabla que permite que ese usuario/fila
* sea eliminado.
*/
Action borrarFila = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
int modelRow = Integer.valueOf( e.getActionCommand() );
Usuario usuario = modeloTablaUsuarios.getUsuarioAt(modelRow);
int resultadoDialogo = JOptionPane.showConfirmDialog(
Cliente.this,
"Ests seguro de que quieres elinimar el usuario <"+usuario.getEmail()+">?",
"Eliminar usuario",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (resultadoDialogo == JOptionPane.YES_OPTION) {
try {
Map<String,String> parametros = new HashMap<String, String>();
parametros.put("action", "eliminarUsuario");
parametros.put("email", usuario.getEmail());
ObjectInputStream respuesta = new ObjectInputStream(realizarPeticionPost(urlString, parametros));
int codigo = respuesta.readInt();
String mensaje = (String) respuesta.readObject();
System.out.println(codigo);
System.out.println(mensaje);
switch (codigo) {
case 0:
modeloTablaUsuarios.removeRow(modelRow);
break;
default:
break;
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
};
// Hacemos que la cuarta columna sea el boton cuya accion la de borrarFila
new ButtonColumn(table, borrarFila, 3);
table.putClientProperty("terminateEditOnFocusLost", true);
scroll = new JScrollPane(table);
panelContenido.add(scroll, BorderLayout.CENTER);
toolBar = new JToolBar();
toolBar.setFloatable(false);
panelContenido.add(toolBar, BorderLayout.NORTH);
btnAddUser = new JButton("A\u00F1adir Usuario");
btnAddUser.setActionCommand("ADDUSER");
btnAddUser.addActionListener(this);
toolBar.add(btnAddUser);
panelAniadir = new JPanel();
panelAniadir.setVisible(false);
panelContenido.add(panelAniadir, BorderLayout.EAST);
GridBagLayout gbl_panelAniadir = new GridBagLayout();
gbl_panelAniadir.columnWidths = new int[]{0, 0, 0, 0};
gbl_panelAniadir.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panelAniadir.columnWeights = new double[]{1.0, 1.0, 1.0, Double.MIN_VALUE};
gbl_panelAniadir.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
panelAniadir.setLayout(gbl_panelAniadir);
lblNombre = new JLabel("Nombre: ");
lblNombre.setHorizontalAlignment(SwingConstants.RIGHT);
GridBagConstraints gbc_lblNombre = new GridBagConstraints();
gbc_lblNombre.insets = new Insets(0, 0, 5, 5);
gbc_lblNombre.anchor = GridBagConstraints.EAST;
gbc_lblNombre.gridx = 0;
gbc_lblNombre.gridy = 0;
panelAniadir.add(lblNombre, gbc_lblNombre);
tfNombre = new JTextField();
GridBagConstraints gbc_tfNombre = new GridBagConstraints();
gbc_tfNombre.insets = new Insets(0, 0, 5, 5);
gbc_tfNombre.fill = GridBagConstraints.HORIZONTAL;
gbc_tfNombre.gridx = 1;
gbc_tfNombre.gridy = 0;
panelAniadir.add(tfNombre, gbc_tfNombre);
tfNombre.setColumns(10);
lblApellido = new JLabel("Apellido: ");
lblApellido.setHorizontalAlignment(SwingConstants.RIGHT);
GridBagConstraints gbc_lblApellido = new GridBagConstraints();
gbc_lblApellido.anchor = GridBagConstraints.EAST;
gbc_lblApellido.insets = new Insets(0, 0, 5, 5);
gbc_lblApellido.gridx = 0;
gbc_lblApellido.gridy = 1;
panelAniadir.add(lblApellido, gbc_lblApellido);
tfApellido = new JTextField();
GridBagConstraints gbc_tfApellido = new GridBagConstraints();
gbc_tfApellido.insets = new Insets(0, 0, 5, 5);
gbc_tfApellido.fill = GridBagConstraints.HORIZONTAL;
gbc_tfApellido.gridx = 1;
gbc_tfApellido.gridy = 1;
panelAniadir.add(tfApellido, gbc_tfApellido);
tfApellido.setColumns(10);
lblEmail = new JLabel("Email: ");
lblEmail.setHorizontalAlignment(SwingConstants.RIGHT);
GridBagConstraints gbc_lblEmail = new GridBagConstraints();
gbc_lblEmail.anchor = GridBagConstraints.EAST;
gbc_lblEmail.insets = new Insets(0, 0, 5, 5);
gbc_lblEmail.gridx = 0;
gbc_lblEmail.gridy = 2;
panelAniadir.add(lblEmail, gbc_lblEmail);
tfEmail = new JTextField();
GridBagConstraints gbc_tfEmail = new GridBagConstraints();
gbc_tfEmail.insets = new Insets(0, 0, 5, 5);
gbc_tfEmail.fill = GridBagConstraints.HORIZONTAL;
gbc_tfEmail.gridx = 1;
gbc_tfEmail.gridy = 2;
panelAniadir.add(tfEmail, gbc_tfEmail);
tfEmail.setColumns(10);
botonera = new JPanel();
GridBagConstraints gbc_botonera = new GridBagConstraints();
gbc_botonera.gridwidth = 2;
gbc_botonera.insets = new Insets(0, 0, 0, 5);
gbc_botonera.fill = GridBagConstraints.BOTH;
gbc_botonera.gridx = 0;
gbc_botonera.gridy = 7;
panelAniadir.add(botonera, gbc_botonera);
botonera.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
btnAniadir = new JButton("A\u00F1adir");
btnAniadir.setActionCommand("EXEC_ANIADIR");
btnAniadir.addActionListener(this);
botonera.add(btnAniadir);
btnCancelar = new JButton("Cancelar");
btnCancelar.setActionCommand("CANCELAR");
btnCancelar.addActionListener(this);
botonera.add(btnCancelar);
}
/**
* Obtiene la lista de usuarios del servlet.
* @return Lista con los usuarios
*/
@SuppressWarnings("unchecked")
private List<Usuario> obtenerListaUsuarios() {
try {
Map<String,String> parametros = new HashMap<String, String>();
parametros.put("action", "listarUsuarios");
ObjectInputStream respuesta = new ObjectInputStream(realizarPeticionPost(urlString, parametros));
List<Usuario> listaUsuarios = (List<Usuario>) respuesta.readObject();
return listaUsuarios;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("ADDUSER")) {
panelAniadir.setVisible(true);
}
else if (e.getActionCommand().equals("EXEC_ANIADIR")) {
try {
Map<String,String> parametros = new HashMap<String, String>();
parametros.put("action", "aniadirUsuario");
parametros.put("nombre", tfNombre.getText());
parametros.put("apellido", tfApellido.getText());
parametros.put("email", tfEmail.getText());
ObjectInputStream respuesta = new ObjectInputStream(realizarPeticionPost(urlString, parametros));
int codigo = respuesta.readInt();
String mensaje = (String) respuesta.readObject();
System.out.println(codigo);
System.out.println(mensaje);
switch (codigo) {
case 0:
Usuario usuario = new Usuario();
usuario.setNombre(tfNombre.getText());
usuario.setApellido(tfApellido.getText());
usuario.setEmail(tfEmail.getText());
modeloTablaUsuarios.add(usuario);
tfNombre.setText("");
tfApellido.setText("");
tfEmail.setText("");
break;
default:
break;
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
else if (e.getActionCommand().equals("CANCELAR")) {
tfNombre.setText("");
tfApellido.setText("");
tfEmail.setText("");
panelAniadir.setVisible(false);
}
}
/**
* Realiza una peticin POST a una URL con los parametros provistos.
* @param urlString Direccion a la que se desea realizar a peticion
* @param parametros Parametros de la peticion
* @return Respuesta obtenida o <tt>null</tt> en caso de fallo
*/
@SuppressWarnings("deprecation")
public InputStream realizarPeticionPost(String urlString, Map<String,String> parametros) {
String cadenaParametros = "";
boolean primerPar = true;
for (Map.Entry<String, String> entry : parametros.entrySet()) {
if (!primerPar) {
cadenaParametros += "&";
} else {
primerPar = false;
}
String parDeParametro = String.format("%s=%s",
URLEncoder.encode(entry.getKey()),
URLEncoder.encode(entry.getValue()));
cadenaParametros += parDeParametro;
}
try {
URL url = new URL(urlString);
HttpURLConnection conexion = (HttpURLConnection) url.openConnection();
conexion.setUseCaches(false);
conexion.setRequestMethod("POST");
conexion.setDoOutput(true);
OutputStream output = conexion.getOutputStream();
output.write(cadenaParametros.getBytes());
output.flush();
output.close();
return conexion.getInputStream();
} catch (MalformedURLException | ProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
}
| Comprobación email y campos vacios Cliente.
| src/antoniotoro/practica2/cliente/Cliente.java | Comprobación email y campos vacios Cliente. |
|
Java | mit | 965b46faa0fe34e7765fa3b8f2e53cdcf824a0b8 | 0 | dotdog20/SergBoat | /*
* MIT License
*
* Copyright (c) 2017 Frederik Ar. Mikkelsen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package fredboat.command.util;
import fredboat.Config;
import fredboat.command.fun.RemoteFileCommand;
import fredboat.command.fun.TextCommand;
import fredboat.commandmeta.CommandRegistry;
import fredboat.commandmeta.abs.*;
import fredboat.feature.I18n;
import fredboat.perms.PermissionLevel;
import fredboat.perms.PermsUtil;
import fredboat.util.DiscordUtil;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.TextChannel;
import java.text.MessageFormat;
import java.util.*;
/**
* Created by napster on 22.03.17.
* <p>
* YO DAWG I HEARD YOU LIKE COMMANDS SO I PUT
* THIS COMMAND IN YO BOT SO YOU CAN SHOW MORE
* COMMANDS WHILE YOU EXECUTE THIS COMMAND
* <p>
* Display available commands
*/
public class CommandsCommand extends Command implements IUtilCommand {
//design inspiration by Weiss Schnee's bot
//https://cdn.discordapp.com/attachments/230033957998166016/296356070685671425/unknown.png
@Override
public void onInvoke(Guild guild, TextChannel channel, Member invoker, Message message, String[] args) {
//is this the music boat? shortcut to showing those commands
//taking this shortcut we're missing out on showing a few commands to pure music bot users
// http://i.imgur.com/511Hb8p.png screenshot from 1st April 2017
//bot owner and debug commands (+ ;;music and ;;help) missing + the currently defunct config command
//this is currently fine but might change in the future
if (DiscordUtil.isMusicBot()) {
new MusicHelpCommand().onInvoke(guild, channel, invoker, message, args);
}
if (DiscordUtil.isMainBot()) {
mainBotHelp(guild, channel, invoker);
}
}
private void mainBotHelp(Guild guild, TextChannel channel, Member invoker) {
Set<String> commandsAndAliases = CommandRegistry.getRegisteredCommandsAndAliases();
Set<String> unsortedAliases = new HashSet<>(); //hash set = only unique commands
for (String commandOrAlias : commandsAndAliases) {
String mainAlias = CommandRegistry.getCommand(commandOrAlias).name;
unsortedAliases.add(mainAlias);
}
//alphabetical order
List<String> sortedAliases = new ArrayList<>(unsortedAliases);
Collections.sort(sortedAliases);
String fun = "**" + I18n.get(guild).getString("commandsFun") + ":** ";
String memes = "**" + I18n.get(guild).getString("commandsMemes") + ":**";
String util = "**" + I18n.get(guild).getString("commandsUtility") + ":** ";
String mod = "**" + I18n.get(guild).getString("commandsModeration") + ":** ";
String maint = "**" + I18n.get(guild).getString("commandsMaintenance") + ":** ";
String owner = "**" + I18n.get(guild).getString("commandsBotOwner") + ":** ";
String serg = "**" + I18n.get(guild).getString("commandsSerg") + ":**";
for (String alias : sortedAliases) {
Command c = CommandRegistry.getCommand(alias).command;
String formattedAlias = "`" + alias + "` ";
if (c instanceof ICommandRestricted
&& ((ICommandRestricted) c).getMinimumPerms() == PermissionLevel.BOT_OWNER) {
owner += formattedAlias;
} else if (c instanceof TextCommand || c instanceof RemoteFileCommand) {
memes += formattedAlias;
} else {
//overlap is possible in here, that's ok
if (c instanceof IFunCommand) {
fun += formattedAlias;
}
if (c instanceof IUtilCommand) {
util += formattedAlias;
}
if (c instanceof IModerationCommand) {
mod += formattedAlias;
}
if (c instanceof IMaintenanceCommand) {
maint += formattedAlias;
}
}
}
String out = fun;
out += "\n" + util;
out += "\n" + memes;
if (invoker.hasPermission(Permission.MESSAGE_MANAGE)) {
out += "\n" + mod;
}
if (PermsUtil.isUserBotOwner(invoker.getUser())) {
out += "\n" + maint;
out += "\n" + owner;
}
out += "\n\n" + MessageFormat.format(I18n.get(guild).getString("commandsMoreHelp"), "`" + Config.CONFIG.getPrefix() + "help <command>`");
channel.sendMessage(out).queue();
}
@Override
public String help(Guild guild) {
String usage = "{0}{1}\n#";
return usage + I18n.get(guild).getString("helpCommandsCommand");
}
}
| FredBoat/src/main/java/fredboat/command/util/CommandsCommand.java | /*
* MIT License
*
* Copyright (c) 2017 Frederik Ar. Mikkelsen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package fredboat.command.util;
import fredboat.Config;
import fredboat.command.fun.RemoteFileCommand;
import fredboat.command.fun.TextCommand;
import fredboat.commandmeta.CommandRegistry;
import fredboat.commandmeta.abs.*;
import fredboat.feature.I18n;
import fredboat.perms.PermissionLevel;
import fredboat.perms.PermsUtil;
import fredboat.util.DiscordUtil;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.entities.TextChannel;
import java.text.MessageFormat;
import java.util.*;
/**
* Created by napster on 22.03.17.
* <p>
* YO DAWG I HEARD YOU LIKE COMMANDS SO I PUT
* THIS COMMAND IN YO BOT SO YOU CAN SHOW MORE
* COMMANDS WHILE YOU EXECUTE THIS COMMAND
* <p>
* Display available commands
*/
public class CommandsCommand extends Command implements IUtilCommand {
//design inspiration by Weiss Schnee's bot
//https://cdn.discordapp.com/attachments/230033957998166016/296356070685671425/unknown.png
@Override
public void onInvoke(Guild guild, TextChannel channel, Member invoker, Message message, String[] args) {
//is this the music boat? shortcut to showing those commands
//taking this shortcut we're missing out on showing a few commands to pure music bot users
// http://i.imgur.com/511Hb8p.png screenshot from 1st April 2017
//bot owner and debug commands (+ ;;music and ;;help) missing + the currently defunct config command
//this is currently fine but might change in the future
if (DiscordUtil.isMusicBot()) {
new MusicHelpCommand().onInvoke(guild, channel, invoker, message, args);
}
if (DiscordUtil.isMainBot()) {
mainBotHelp(guild, channel, invoker);
}
}
private void mainBotHelp(Guild guild, TextChannel channel, Member invoker) {
Set<String> commandsAndAliases = CommandRegistry.getRegisteredCommandsAndAliases();
Set<String> unsortedAliases = new HashSet<>(); //hash set = only unique commands
for (String commandOrAlias : commandsAndAliases) {
String mainAlias = CommandRegistry.getCommand(commandOrAlias).name;
unsortedAliases.add(mainAlias);
}
//alphabetical order
List<String> sortedAliases = new ArrayList<>(unsortedAliases);
Collections.sort(sortedAliases);
String fun = "**" + I18n.get(guild).getString("commandsFun") + ":** ";
String memes = "**" + I18n.get(guild).getString("commandsMemes") + ":**";
String util = "**" + I18n.get(guild).getString("commandsUtility") + ":** ";
String mod = "**" + I18n.get(guild).getString("commandsModeration") + ":** ";
String maint = "**" + I18n.get(guild).getString("commandsMaintenance") + ":** ";
String owner = "**" + I18n.get(guild).getString("commandsBotOwner") + ":** ";
for (String alias : sortedAliases) {
Command c = CommandRegistry.getCommand(alias).command;
String formattedAlias = "`" + alias + "` ";
if (c instanceof ICommandRestricted
&& ((ICommandRestricted) c).getMinimumPerms() == PermissionLevel.BOT_OWNER) {
owner += formattedAlias;
} else if (c instanceof TextCommand || c instanceof RemoteFileCommand) {
memes += formattedAlias;
} else {
//overlap is possible in here, that's ok
if (c instanceof IFunCommand) {
fun += formattedAlias;
}
if (c instanceof IUtilCommand) {
util += formattedAlias;
}
if (c instanceof IModerationCommand) {
mod += formattedAlias;
}
if (c instanceof IMaintenanceCommand) {
maint += formattedAlias;
}
}
}
String out = fun;
out += "\n" + util;
out += "\n" + memes;
if (invoker.hasPermission(Permission.MESSAGE_MANAGE)) {
out += "\n" + mod;
}
if (PermsUtil.isUserBotOwner(invoker.getUser())) {
out += "\n" + maint;
out += "\n" + owner;
}
out += "\n\n" + MessageFormat.format(I18n.get(guild).getString("commandsMoreHelp"), "`" + Config.CONFIG.getPrefix() + "help <command>`");
channel.sendMessage(out).queue();
}
@Override
public String help(Guild guild) {
String usage = "{0}{1}\n#";
return usage + I18n.get(guild).getString("helpCommandsCommand");
}
}
| test Adaptive ,commands
| FredBoat/src/main/java/fredboat/command/util/CommandsCommand.java | test Adaptive ,commands |
|
Java | mit | fe8c336bd0bbe6416342a71ae0bab5772fb8e39a | 0 | itenente/igv,igvteam/igv,amwenger/igv,godotgildor/igv,itenente/igv,itenente/igv,amwenger/igv,godotgildor/igv,itenente/igv,amwenger/igv,igvteam/igv,igvteam/igv,godotgildor/igv,igvteam/igv,godotgildor/igv,igvteam/igv,amwenger/igv,amwenger/igv,godotgildor/igv,itenente/igv | /*
* Copyright (c) 2007-2012 The Broad Institute, Inc.
* SOFTWARE COPYRIGHT NOTICE
* This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved.
*
* This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*/
package org.broad.igv.track;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.commons.math.stat.StatUtils;
import org.apache.log4j.Logger;
import org.broad.igv.Globals;
import org.broad.igv.PreferenceManager;
import org.broad.igv.data.CombinedDataSource;
import org.broad.igv.feature.Exon;
import org.broad.igv.feature.FeatureUtils;
import org.broad.igv.feature.IGVFeature;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.feature.tribble.IGVBEDCodec;
import org.broad.igv.renderer.*;
import org.broad.igv.ui.*;
import org.broad.igv.ui.color.ColorUtilities;
import org.broad.igv.ui.panel.FrameManager;
import org.broad.igv.ui.panel.IGVPopupMenu;
import org.broad.igv.ui.panel.ReferenceFrame;
import org.broad.igv.ui.panel.TrackPanel;
import org.broad.igv.ui.util.FileDialogUtils;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.ui.util.UIUtilities;
import org.broad.igv.util.LongRunningTask;
import org.broad.igv.util.StringUtils;
import org.broad.igv.util.blat.BlatClient;
import org.broad.igv.util.collections.CollUtils;
import org.broad.igv.util.stats.KMPlotFrame;
import org.broad.tribble.Feature;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
import java.util.List;
/**
* @author jrobinso
*/
public class TrackMenuUtils {
static Logger log = Logger.getLogger(TrackMenuUtils.class);
final static String LEADING_HEADING_SPACER = " ";
private static final WindowFunction[] ORDERED_WINDOW_FUNCTIONS = new WindowFunction[]{
WindowFunction.min,
WindowFunction.percentile2,
WindowFunction.percentile10,
WindowFunction.median,
WindowFunction.mean,
WindowFunction.percentile90,
WindowFunction.percentile98,
WindowFunction.max,
WindowFunction.none
};
private static List<TrackMenuItemBuilder> trackMenuItems = new ArrayList<TrackMenuItemBuilder>();
/**
* Called by plugins to add a listener, which is then called when TrackMenus are created
* to generate menu entries.
*
* @param builder
* @api
*/
public static void addTrackMenuItemBuilder(TrackMenuItemBuilder builder) {
trackMenuItems.add(builder);
}
/**
* Return a popup menu with items applicable to the collection of tracks.
*
* @param tracks
* @return
*/
public static IGVPopupMenu getPopupMenu(final Collection<Track> tracks, String title, TrackClickEvent te) {
if (log.isDebugEnabled()) {
log.debug("enter getPopupMenu");
}
IGVPopupMenu menu = new IGVPopupMenu();
JLabel popupTitle = new JLabel(LEADING_HEADING_SPACER + title, JLabel.CENTER);
popupTitle.setFont(UIConstants.boldFont);
if (popupTitle != null) {
menu.add(popupTitle);
menu.addSeparator();
}
addStandardItems(menu, tracks, te);
return menu;
}
/**
* Add menu items which have been added through the api, not known until runtime
*
* @param menu
* @param tracks
* @param te
*/
public static void addPluginItems(JPopupMenu menu, Collection<Track> tracks, TrackClickEvent te) {
List<JMenuItem> items = new ArrayList<JMenuItem>(0);
for (TrackMenuItemBuilder builder : trackMenuItems) {
JMenuItem item = builder.build(tracks, te);
if (item != null) {
items.add(item);
}
}
if (items.size() > 0) {
menu.addSeparator();
for (JMenuItem item : items) {
menu.add(item);
}
}
}
public static void addStandardItems(JPopupMenu menu, Collection<Track> tracks, TrackClickEvent te) {
boolean hasDataTracks = false;
boolean hasFeatureTracks = false;
boolean hasOtherTracks = false;
for (Track track : tracks) {
// TODO -- this is ugly, refactor to remove instanceof
if (track instanceof DataTrack) {
hasDataTracks = true;
} else if (track instanceof FeatureTrack) {
hasFeatureTracks = true;
} else {
hasOtherTracks = true;
}
if (hasDataTracks && hasFeatureTracks && hasOtherTracks) {
break;
}
}
boolean featureTracksOnly = hasFeatureTracks && !hasDataTracks && !hasOtherTracks;
boolean dataTracksOnly = !hasFeatureTracks && hasDataTracks && !hasOtherTracks;
addSharedItems(menu, tracks, hasFeatureTracks);
menu.addSeparator();
if (dataTracksOnly) {
addDataItems(menu, tracks);
} else if (featureTracksOnly) {
addFeatureItems(menu, tracks, te);
}
menu.addSeparator();
menu.add(getRemoveMenuItem(tracks));
}
public static void addZoomItems(JPopupMenu menu, final ReferenceFrame frame) {
if (FrameManager.isGeneListMode()) {
JMenuItem item = new JMenuItem("Reset panel to '" + frame.getName() + "'");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.reset();
// TODO -- paint only panels for this frame
}
});
menu.add(item);
}
JMenuItem zoomOutItem = new JMenuItem("Zoom out");
zoomOutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
frame.doZoomIncrement(-1);
}
});
menu.add(zoomOutItem);
JMenuItem zoomInItem = new JMenuItem("Zoom in");
zoomInItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
frame.doZoomIncrement(1);
}
});
menu.add(zoomInItem);
}
/**
* Return popup menu with items applicable to data tracks
*
* @return
*/
public static void addDataItems(JPopupMenu menu, final Collection<Track> tracks) {
if (log.isTraceEnabled()) {
log.trace("enter getDataPopupMenu");
}
final String[] labels = {"Heatmap", "Bar Chart", "Points", "Line Plot"};
final Class[] renderers = {HeatmapRenderer.class, BarChartRenderer.class,
PointsRenderer.class, LineplotRenderer.class
};
//JLabel popupTitle = new JLabel(LEADING_HEADING_SPACER + title, JLabel.CENTER);
JLabel rendererHeading = new JLabel(LEADING_HEADING_SPACER + "Type of Graph", JLabel.LEFT);
rendererHeading.setFont(UIConstants.boldFont);
menu.add(rendererHeading);
// Get existing selections
Set<Class> currentRenderers = new HashSet<Class>();
for (Track track : tracks) {
if (track.getRenderer() != null) {
currentRenderers.add(track.getRenderer().getClass());
}
}
// Create and renderer menu items
for (int i = 0; i < labels.length; i++) {
JCheckBoxMenuItem item = new JCheckBoxMenuItem(labels[i]);
final Class rendererClass = renderers[i];
if (currentRenderers.contains(rendererClass)) {
item.setSelected(true);
}
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeRenderer(tracks, rendererClass);
}
});
menu.add(item);
}
menu.addSeparator();
// Get union of all valid window functions for selected tracks
Set<WindowFunction> avaibleWindowFunctions = new HashSet();
for (Track track : tracks) {
avaibleWindowFunctions.addAll(track.getAvailableWindowFunctions());
}
avaibleWindowFunctions.add(WindowFunction.none);
// dataPopupMenu.addSeparator();
// Collection all window functions for selected tracks
Set<WindowFunction> currentWindowFunctions = new HashSet<WindowFunction>();
for (Track track : tracks) {
if (track.getWindowFunction() != null) {
currentWindowFunctions.add(track.getWindowFunction());
}
}
if (avaibleWindowFunctions.size() > 1 || currentWindowFunctions.size() > 1) {
JLabel statisticsHeading = new JLabel(LEADING_HEADING_SPACER + "Windowing Function", JLabel.LEFT);
statisticsHeading.setFont(UIConstants.boldFont);
menu.add(statisticsHeading);
for (final WindowFunction wf : ORDERED_WINDOW_FUNCTIONS) {
JCheckBoxMenuItem item = new JCheckBoxMenuItem(wf.getValue());
if (avaibleWindowFunctions.contains(wf) || currentWindowFunctions.contains(wf)) {
if (currentWindowFunctions.contains(wf)) {
item.setSelected(true);
}
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeStatType(wf.toString(), tracks);
}
});
menu.add(item);
}
}
menu.addSeparator();
}
menu.add(getDataRangeItem(tracks));
menu.add(getHeatmapScaleItem(tracks));
if (tracks.size() > 0) {
menu.add(getLogScaleItem(tracks));
}
menu.add(getAutoscaleItem(tracks));
menu.add(getShowDataRangeItem(tracks));
menu.addSeparator();
menu.add(getChangeKMPlotItem(tracks));
if (Globals.isDevelopment() && FrameManager.isGeneListMode() && tracks.size() == 1) {
menu.addSeparator();
menu.add(getShowSortFramesItem(tracks.iterator().next()));
}
//Add overlay track option
final List<DataTrack> dataTrackList = Lists.newArrayList(Iterables.filter(tracks, DataTrack.class));
final JMenuItem overlayGroups = new JMenuItem("Create Overlay Track");
overlayGroups.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MergedTracks mergedTracks = new MergedTracks(UUID.randomUUID().toString(), "Overlay", dataTrackList);
Track firstTrack = tracks.iterator().next();
TrackPanel panel = TrackPanel.getParentPanel(firstTrack);
panel.addTrack(mergedTracks);
panel.moveSelectedTracksTo(Arrays.asList(mergedTracks), firstTrack, false);
panel.removeTracks(tracks);
}
});
int numDataTracks = dataTrackList.size();
overlayGroups.setEnabled(numDataTracks >= 2 && numDataTracks == tracks.size());
menu.add(overlayGroups);
/////////////
}
private static List<JMenuItem> getCombinedDataSourceItems(final Collection<Track> tracks) {
Iterable<DataTrack> dataTracksIter = Iterables.filter(tracks, DataTrack.class);
final List<DataTrack> dataTracks = Lists.newArrayList(dataTracksIter);
JMenuItem addItem = new JMenuItem("Sum Tracks");
JMenuItem subItem = new JMenuItem("Subtract Tracks");
boolean enableComb = dataTracks.size() == 2;
addItem.setEnabled(enableComb);
addItem.setEnabled(enableComb);
addItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addCombinedDataTrack(dataTracks, CombinedDataSource.Operation.ADD);
}
});
subItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addCombinedDataTrack(dataTracks, CombinedDataSource.Operation.SUBTRACT);
}
});
return Arrays.asList(addItem, subItem);
}
private static void addCombinedDataTrack(List<DataTrack> dataTracks, CombinedDataSource.Operation op) {
String text = "";
switch (op) {
case ADD:
text = "Sum";
break;
case SUBTRACT:
text = "Difference";
break;
}
DataTrack track0 = dataTracks.get(0);
DataTrack track1 = dataTracks.get(1);
CombinedDataSource source = new CombinedDataSource(track0, track1, op);
DataSourceTrack newTrack = new DataSourceTrack(null, track0.getId() + track1.getId() + text, text, source);
changeRenderer(Arrays.<Track>asList(newTrack), track0.getRenderer().getClass());
newTrack.setDataRange(track0.getDataRange());
newTrack.setColorScale(track0.getColorScale());
IGV.getInstance().addTracks(Arrays.<Track>asList(newTrack), PanelName.DATA_PANEL);
}
/**
* Return popup menu with items applicable to feature tracks
*
* @return
*/
private static void addFeatureItems(JPopupMenu featurePopupMenu, final Collection<Track> tracks, TrackClickEvent te) {
addDisplayModeItems(tracks, featurePopupMenu);
if (tracks.size() == 1) {
Track t = tracks.iterator().next();
Feature f = t.getFeatureAtMousePosition(te);
if (f != null) {
featurePopupMenu.addSeparator();
// If we are over an exon, copy its sequence instead of the entire feature.
if (f instanceof IGVFeature) {
double position = te.getChromosomePosition();
Collection<Exon> exons = ((IGVFeature) f).getExons();
if (exons != null) {
for (Exon exon : exons) {
if (position > exon.getStart() && position < exon.getEnd()) {
f = exon;
break;
}
}
}
}
featurePopupMenu.add(getCopyDetailsItem(f, te));
featurePopupMenu.add(getCopySequenceItem(f));
if (Globals.isDevelopment()) {
featurePopupMenu.add(getBlatItem(f));
}
}
if (Globals.isDevelopment()) {
featurePopupMenu.addSeparator();
featurePopupMenu.add(getFeatureToGeneListItem(t));
}
if (Globals.isDevelopment() && FrameManager.isGeneListMode() && tracks.size() == 1) {
featurePopupMenu.addSeparator();
featurePopupMenu.add(getShowSortFramesItem(tracks.iterator().next()));
}
}
featurePopupMenu.addSeparator();
featurePopupMenu.add(getChangeFeatureWindow(tracks));
}
private static JMenuItem getFeatureToGeneListItem(final Track t) {
JMenuItem mi = new JMenuItem("Use as loci list");
mi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Current chromosome only for now
}
});
return mi;
}
/**
* Return a menu item which will export visible features
* If {@code tracks} is not a single {@code FeatureTrack}, {@code null}
* is returned (there should be no menu entry)
*
* @param tracks
* @return
*/
public static JMenuItem getExportFeatures(final Collection<Track> tracks, final ReferenceFrame.Range range) {
if (tracks.size() != 1 || !(tracks.iterator().next() instanceof FeatureTrack)) {
return null;
}
JMenuItem exportData = new JMenuItem("Export To BED File");
exportData.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File outFile = FileDialogUtils.chooseFile("Save Visible Data",
PreferenceManager.getInstance().getLastTrackDirectory(),
new File("visibleData.bed"),
FileDialogUtils.SAVE);
exportVisibleData(outFile.getAbsolutePath(), tracks, range);
}
});
return exportData;
}
/**
* Write features in {@code track} found in {@code range} to {@code outPath},
* BED format
* TODO Move somewhere else? run on separate thread? Probably shouldn't be here
*
* @param outPath
* @param tracks
* @param range
*/
static void exportVisibleData(String outPath, Collection<Track> tracks, ReferenceFrame.Range range) {
PrintWriter writer;
try {
writer = new PrintWriter(outPath);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
for (Track track : tracks) {
if (track instanceof FeatureTrack) {
FeatureTrack fTrack = (FeatureTrack) track;
//Can't trust FeatureTrack.getFeatures to limit itself, so we filter
List<Feature> features = fTrack.getFeatures(range.getChr(), range.getStart(), range.getEnd());
Predicate<Feature> pred = FeatureUtils.getOverlapPredicate(range.getChr(), range.getStart(), range.getEnd());
features = CollUtils.filter(features, pred);
IGVBEDCodec codec = new IGVBEDCodec();
for (Feature feat : features) {
String featString = codec.encode(feat);
writer.println(featString);
}
}
}
writer.flush();
writer.close();
}
/**
* Popup menu with items applicable to both feature and data tracks
*
* @return
*/
public static void addSharedItems(JPopupMenu menu, final Collection<Track> tracks, boolean hasFeatureTracks) {
//JLabel trackSettingsHeading = new JLabel(LEADING_HEADING_SPACER + "Track Settings", JLabel.LEFT);
//trackSettingsHeading.setFont(boldFont);
//menu.add(trackSettingsHeading);
menu.add(getTrackRenameItem(tracks));
String colorLabel = hasFeatureTracks
? "Change Track Color..." : "Change Track Color (Positive Values)...";
JMenuItem item = new JMenuItem(colorLabel);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeTrackColor(tracks);
}
});
menu.add(item);
if (!hasFeatureTracks) {
// Change track color by attribute
item = new JMenuItem("Change Track Color (Negative Values)...");
item.setToolTipText(
"Change the alternate track color. This color is used when graphing negative values");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeAltTrackColor(tracks);
}
});
menu.add(item);
}
menu.add(getChangeTrackHeightItem(tracks));
menu.add(getChangeFontSizeItem(tracks));
}
private static void changeStatType(String statType, Collection<Track> selectedTracks) {
for (Track track : selectedTracks) {
track.setWindowFunction(WindowFunction.valueOf(statType));
}
refresh();
}
public static JMenuItem getTrackRenameItem(final Collection<Track> selectedTracks) {
// Change track height by attribute
JMenuItem item = new JMenuItem("Rename Track...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
UIUtilities.invokeOnEventThread(new Runnable() {
public void run() {
renameTrack(selectedTracks);
}
});
}
});
if (selectedTracks.size() > 1) {
item.setEnabled(false);
}
return item;
}
private static JMenuItem getHeatmapScaleItem(final Collection<Track> selectedTracks) {
JMenuItem item = new JMenuItem("Set Heatmap Scale...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (selectedTracks.size() > 0) {
ContinuousColorScale colorScale = selectedTracks.iterator().next().getColorScale();
HeatmapScaleDialog dlg = new HeatmapScaleDialog(IGV.getMainFrame(), colorScale);
dlg.setVisible(true);
if (!dlg.isCanceled()) {
colorScale = dlg.getColorScale();
// dlg.isFlipAxis());
for (Track track : selectedTracks) {
track.setColorScale(colorScale);
}
IGV.getInstance().repaint();
}
}
}
});
return item;
}
public static JMenuItem getDataRangeItem(final Collection<Track> selectedTracks) {
JMenuItem item = new JMenuItem("Set Data Range...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (selectedTracks.size() > 0) {
// Create a datarange that spans the extent of prev tracks range
DataRange prevAxisDefinition = DataRange.getFromTracks(selectedTracks);
DataRangeDialog dlg = new DataRangeDialog(IGV.getMainFrame(), prevAxisDefinition);
dlg.setVisible(true);
if (!dlg.isCanceled()) {
float min = Math.min(dlg.getMax(), dlg.getMin());
float max = Math.max(dlg.getMin(), dlg.getMax());
float mid = dlg.getBase();
mid = Math.max(min, Math.min(mid, max));
DataRange axisDefinition = new DataRange(dlg.getMin(), mid, dlg.getMax(),
prevAxisDefinition.isDrawBaseline(), dlg.isLog());
for (Track track : selectedTracks) {
track.setDataRange(axisDefinition);
track.setAutoScale(false);
}
IGV.getInstance().repaint();
}
}
}
});
return item;
}
private static JMenuItem getDrawBorderItem() {
// Change track height by attribute
final JCheckBoxMenuItem drawBorderItem = new JCheckBoxMenuItem("Draw borders");
drawBorderItem.setSelected(FeatureTrack.isDrawBorder());
drawBorderItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
FeatureTrack.setDrawBorder(drawBorderItem.isSelected());
IGV.getInstance().repaintDataPanels();
}
});
return drawBorderItem;
}
public static JMenuItem getLogScaleItem(final Collection<Track> selectedTracks) {
// Change track height by attribute
final JCheckBoxMenuItem logScaleItem = new JCheckBoxMenuItem("Log scale");
final boolean logScale = selectedTracks.iterator().next().getDataRange().isLog();
logScaleItem.setSelected(logScale);
logScaleItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
DataRange.Type scaleType = logScaleItem.isSelected() ?
DataRange.Type.LOG :
DataRange.Type.LINEAR;
for (Track t : selectedTracks) {
t.getDataRange().setType(scaleType);
}
IGV.getInstance().repaintDataPanels();
}
});
return logScaleItem;
}
private static JMenuItem getAutoscaleItem(final Collection<Track> selectedTracks) {
final JCheckBoxMenuItem autoscaleItem = new JCheckBoxMenuItem("Autoscale");
if (selectedTracks.size() == 0) {
autoscaleItem.setEnabled(false);
} else {
boolean autoScale = checkAutoscale(selectedTracks);
autoscaleItem.setSelected(autoScale);
autoscaleItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
boolean autoScale = autoscaleItem.isSelected();
for (Track t : selectedTracks) {
t.setAutoScale(autoScale);
}
IGV.getInstance().repaintDataPanels();
}
});
}
return autoscaleItem;
}
private static boolean checkAutoscale(Collection<Track> selectedTracks) {
boolean autoScale = false;
for (Track t : selectedTracks) {
if (t.getAutoScale()) {
autoScale = true;
break;
}
}
return autoScale;
}
public static JMenuItem getShowDataRangeItem(final Collection<Track> selectedTracks) {
final JCheckBoxMenuItem item = new JCheckBoxMenuItem("Show Data Range");
if (selectedTracks.size() == 0) {
item.setEnabled(false);
} else {
boolean showDataRange = true;
for (Track t : selectedTracks) {
if (!t.isShowDataRange()) {
showDataRange = false;
break;
}
}
item.setSelected(showDataRange);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
boolean showDataRange = item.isSelected();
for (Track t : selectedTracks) {
if (t instanceof DataTrack) {
((DataTrack) t).setShowDataRange(showDataRange);
}
}
IGV.getInstance().repaintDataPanels();
}
});
}
return item;
}
public static void addDisplayModeItems(final Collection<Track> tracks, JPopupMenu menu) {
// Find "most representative" state from track collection
Map<Track.DisplayMode, Integer> counts = new HashMap<Track.DisplayMode, Integer>(Track.DisplayMode.values().length);
Track.DisplayMode currentMode = null;
for (Track t : tracks) {
Track.DisplayMode mode = t.getDisplayMode();
if (counts.containsKey(mode)) {
counts.put(mode, counts.get(mode) + 1);
} else {
counts.put(mode, 1);
}
}
int maxCount = -1;
for (Map.Entry<Track.DisplayMode, Integer> count : counts.entrySet()) {
if (count.getValue() > maxCount) {
currentMode = count.getKey();
maxCount = count.getValue();
}
}
ButtonGroup group = new ButtonGroup();
Map<String, Track.DisplayMode> modes = new LinkedHashMap<String, Track.DisplayMode>(4);
modes.put("Collapsed", Track.DisplayMode.COLLAPSED);
modes.put("Expanded", Track.DisplayMode.EXPANDED);
modes.put("Squished", Track.DisplayMode.SQUISHED);
boolean showAS = Boolean.parseBoolean(System.getProperty("showAS", "false"));
if (showAS) {
modes.put("Alternative Splice", Track.DisplayMode.ALTERNATIVE_SPLICE);
}
for (final Map.Entry<String, Track.DisplayMode> entry : modes.entrySet()) {
JRadioButtonMenuItem mm = new JRadioButtonMenuItem(entry.getKey());
mm.setSelected(currentMode == entry.getValue());
mm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setTrackDisplayMode(tracks, entry.getValue());
refresh();
}
});
group.add(mm);
menu.add(mm);
}
}
private static void setTrackDisplayMode(Collection<Track> tracks, Track.DisplayMode mode) {
for (Track t : tracks) {
t.setDisplayMode(mode);
}
}
public static JMenuItem getRemoveMenuItem(final Collection<Track> selectedTracks) {
boolean multiple = selectedTracks.size() > 1;
JMenuItem item = new JMenuItem("Remove Track" + (multiple ? "s" : ""));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
removeTracksAction(selectedTracks);
}
});
return item;
}
/**
* Display a dialog to the user asking to confirm if they want to remove the
* selected tracks
*
* @param selectedTracks
*/
public static void removeTracksAction(final Collection<Track> selectedTracks) {
if (selectedTracks.isEmpty()) {
return;
}
StringBuffer buffer = new StringBuffer();
for (Track track : selectedTracks) {
buffer.append("\n\t");
buffer.append(track.getName());
}
String deleteItems = buffer.toString();
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
textArea.setText(deleteItems);
JOptionPane optionPane = new JOptionPane(scrollPane,
JOptionPane.PLAIN_MESSAGE,
JOptionPane.YES_NO_OPTION);
optionPane.setPreferredSize(new Dimension(550, 500));
JDialog dialog = optionPane.createDialog(IGV.getMainFrame(), "Remove The Following Tracks");
dialog.setVisible(true);
Object choice = optionPane.getValue();
if ((choice == null) || (JOptionPane.YES_OPTION != ((Integer) choice).intValue())) {
return;
}
IGV.getInstance().removeTracks(selectedTracks);
IGV.getInstance().doRefresh();
}
public static void changeRenderer(final Collection<Track> selectedTracks, Class rendererClass) {
for (Track track : selectedTracks) {
// TODO -- a temporary hack to facilitate RNAi development
if (track.getTrackType() == TrackType.RNAI) {
if (rendererClass == BarChartRenderer.class) {
rendererClass = RNAiBarChartRenderer.class;
}
}
track.setRendererClass(rendererClass);
}
refresh();
}
public static void renameTrack(final Collection<Track> selectedTracks) {
if (selectedTracks.isEmpty()) {
return;
}
Track t = selectedTracks.iterator().next();
String newName = JOptionPane.showInputDialog(IGV.getMainFrame(), "Enter new name: ", t.getName());
if (newName == null || newName.trim() == "") {
return;
}
t.setName(newName);
refresh();
}
public static void changeTrackHeight(final Collection<Track> selectedTracks) {
if (selectedTracks.isEmpty()) {
return;
}
final String parameter = "Track height";
Integer value = getIntegerInput(parameter, getRepresentativeTrackHeight(selectedTracks));
if (value == null) {
return;
}
value = Math.max(0, value);
for (Track track : selectedTracks) {
track.setHeight(value, true);
}
refresh();
}
public static void changeFeatureVisibilityWindow(final Collection<Track> selectedTracks) {
Collection<Track> featureTracks = new ArrayList(selectedTracks.size());
for (Track t : selectedTracks) {
if (t instanceof FeatureTrack) {
featureTracks.add(t);
}
}
if (featureTracks.isEmpty()) {
return;
}
int origValue = featureTracks.iterator().next().getVisibilityWindow();
double origValueKB = (origValue / 1000.0);
Double value = getDoubleInput("Enter visibility window in kilo-bases. To load all data enter zero.", origValueKB);
if (value == null) {
return;
}
for (Track track : featureTracks) {
track.setVisibilityWindow((int) (value * 1000));
}
refresh();
}
public static void changeFontSize(final Collection<Track> selectedTracks) {
if (selectedTracks.isEmpty()) {
return;
}
final String parameter = "Font size";
int defaultValue = selectedTracks.iterator().next().getFontSize();
Integer value = getIntegerInput(parameter, defaultValue);
if (value == null) {
return;
}
for (Track track : selectedTracks) {
track.setFontSize(value);
}
refresh();
}
public static Integer getIntegerInput(String parameter, int value) {
while (true) {
String strValue = JOptionPane.showInputDialog(
IGV.getMainFrame(), parameter + ": ",
String.valueOf(value));
//strValue will be null if dialog cancelled
if ((strValue == null) || strValue.trim().equals("")) {
return null;
}
try {
value = Integer.parseInt(strValue);
return value;
} catch (NumberFormatException numberFormatException) {
JOptionPane.showMessageDialog(IGV.getMainFrame(),
parameter + " must be an integer number.");
}
}
}
public static Double getDoubleInput(String parameter, double value) {
while (true) {
String strValue = JOptionPane.showInputDialog(
IGV.getMainFrame(), parameter + ": ",
String.valueOf(value));
//strValue will be null if dialog cancelled
if ((strValue == null) || strValue.trim().equals("")) {
return null;
}
try {
value = Double.parseDouble(strValue);
return value;
} catch (NumberFormatException numberFormatException) {
MessageUtils.showMessage(parameter + " must be a number.");
}
}
}
public static void changeTrackColor(final Collection<Track> selectedTracks) {
if (selectedTracks.isEmpty()) {
return;
}
Color currentSelection = selectedTracks.iterator().next().getColor();
Color color = UIUtilities.showColorChooserDialog(
"Select Track Color (Positive Values)",
currentSelection);
if (color == null) {
return;
}
for (Track track : selectedTracks) {
//We preserve the alpha value. This is motivated by MergedTracks
track.setColor(ColorUtilities.modifyAlpha(color, currentSelection.getAlpha()));
}
refresh();
}
public static void changeAltTrackColor(final Collection<Track> selectedTracks) {
if (selectedTracks.isEmpty()) {
return;
}
Color currentSelection = selectedTracks.iterator().next().getColor();
Color color = UIUtilities.showColorChooserDialog(
"Select Track Color (Negative Values)",
currentSelection);
if (color == null) {
return;
}
for (Track track : selectedTracks) {
track.setAltColor(ColorUtilities.modifyAlpha(color, currentSelection.getAlpha()));
}
refresh();
}
public static JMenuItem getCopyDetailsItem(final Feature f, final TrackClickEvent evt) {
JMenuItem item = new JMenuItem("Copy Details to Clipboard");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ReferenceFrame frame = evt.getFrame();
int mouseX = evt.getMouseEvent().getX();
double location = frame.getChromosomePosition(mouseX);
if (f instanceof IGVFeature) {
String details = ((IGVFeature) f).getValueString(location, null);
if (details != null) {
details = details.replace("<br>", System.getProperty("line.separator"));
details += System.getProperty("line.separator") +
f.getChr() + ":" + (f.getStart() + 1) + "-" + f.getEnd();
StringUtils.copyTextToClipboard(details);
}
}
}
});
return item;
}
public static JMenuItem getCopySequenceItem(final Feature f) {
JMenuItem item = new JMenuItem("Copy Sequence");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Genome genome = GenomeManager.getInstance().getCurrentGenome();
IGV.copySequenceToClipboard(genome, f.getChr(), f.getStart(), f.getEnd());
}
});
return item;
}
public static JMenuItem getBlatItem(final Feature f) {
JMenuItem item = new JMenuItem("Blat Sequence");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
BlatClient.doBlatQuery(f.getChr(), f.getStart(), f.getEnd());
}
});
return item;
}
/**
* Return a representative track height to use as the default. For now
* using the median track height.
*
* @return
*/
public static int getRepresentativeTrackHeight(Collection<Track> tracks) {
double[] heights = new double[tracks.size()];
int i = 0;
for (Track track : tracks) {
heights[i] = track.getHeight();
i++;
}
int medianTrackHeight = (int) Math.round(StatUtils.percentile(heights, 50));
if (medianTrackHeight > 0) {
return medianTrackHeight;
}
return PreferenceManager.getInstance().getAsInt(PreferenceManager.INITIAL_TRACK_HEIGHT);
}
public static void refresh() {
if (IGV.hasInstance()) {
IGV.getInstance().showLoadedTrackCount();
IGV.getInstance().doRefresh();
}
}
public static JMenuItem getChangeTrackHeightItem(final Collection<Track> selectedTracks) {
// Change track height by attribute
JMenuItem item = new JMenuItem("Change Track Height...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeTrackHeight(selectedTracks);
}
});
return item;
}
public static JMenuItem getChangeKMPlotItem(final Collection<Track> selectedTracks) {
// Change track height by attribute
JMenuItem item = new JMenuItem("Kaplan-Meier Plot...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// If one or fewer tracks are selected assume the intent is to use all tracks. A right-click
// will always result in one selected track.
Collection<Track> tracks = selectedTracks.size() > 1 ? selectedTracks :
IGV.getInstance().getAllTracks();
KMPlotFrame frame = new KMPlotFrame(tracks);
frame.setVisible(true);
}
});
// The Kaplan-Meier plot requires sample information, specifically survival, sample, and censure. We
// can't know if these columns exist, but we can at least know if sample-info has been loaded.
// 3-4 columns always exist by default, more indicate at least some sample attributes are defined.
boolean sampleInfoLoaded = AttributeManager.getInstance().getAttributeNames().size() > 4;
item.setEnabled(sampleInfoLoaded);
return item;
}
public static JMenuItem getChangeFeatureWindow(final Collection<Track> selectedTracks) {
// Change track height by attribute
JMenuItem item = new JMenuItem("Set Feature Visibility Window...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeFeatureVisibilityWindow(selectedTracks);
}
});
return item;
}
public static JMenuItem getChangeFontSizeItem(final Collection<Track> selectedTracks) {
// Change track height by attribute
JMenuItem item = new JMenuItem("Change Font Size...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeFontSize(selectedTracks);
}
});
return item;
}
// Experimental methods follow
public static JMenuItem getShowSortFramesItem(final Track track) {
final JCheckBoxMenuItem item = new JCheckBoxMenuItem("Sort frames");
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Runnable runnable = new Runnable() {
public void run() {
FrameManager.sortFrames(track);
IGV.getInstance().resetFrames();
}
};
LongRunningTask.submit(runnable);
}
});
return item;
}
}
| src/org/broad/igv/track/TrackMenuUtils.java | /*
* Copyright (c) 2007-2012 The Broad Institute, Inc.
* SOFTWARE COPYRIGHT NOTICE
* This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved.
*
* This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*/
package org.broad.igv.track;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.commons.math.stat.StatUtils;
import org.apache.log4j.Logger;
import org.broad.igv.Globals;
import org.broad.igv.PreferenceManager;
import org.broad.igv.data.CombinedDataSource;
import org.broad.igv.feature.Exon;
import org.broad.igv.feature.FeatureUtils;
import org.broad.igv.feature.IGVFeature;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.feature.tribble.IGVBEDCodec;
import org.broad.igv.renderer.*;
import org.broad.igv.ui.*;
import org.broad.igv.ui.color.ColorUtilities;
import org.broad.igv.ui.panel.FrameManager;
import org.broad.igv.ui.panel.IGVPopupMenu;
import org.broad.igv.ui.panel.ReferenceFrame;
import org.broad.igv.ui.panel.TrackPanel;
import org.broad.igv.ui.util.FileDialogUtils;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.ui.util.UIUtilities;
import org.broad.igv.util.LongRunningTask;
import org.broad.igv.util.StringUtils;
import org.broad.igv.util.blat.BlatClient;
import org.broad.igv.util.collections.CollUtils;
import org.broad.igv.util.stats.KMPlotFrame;
import org.broad.tribble.Feature;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
import java.util.List;
/**
* @author jrobinso
*/
public class TrackMenuUtils {
static Logger log = Logger.getLogger(TrackMenuUtils.class);
final static String LEADING_HEADING_SPACER = " ";
private static final WindowFunction[] ORDERED_WINDOW_FUNCTIONS = new WindowFunction[]{
WindowFunction.min,
WindowFunction.percentile2,
WindowFunction.percentile10,
WindowFunction.median,
WindowFunction.mean,
WindowFunction.percentile90,
WindowFunction.percentile98,
WindowFunction.max,
WindowFunction.none
};
private static List<TrackMenuItemBuilder> trackMenuItems = new ArrayList<TrackMenuItemBuilder>();
/**
* Called by plugins to add a listener, which is then called when TrackMenus are created
* to generate menu entries.
*
* @param builder
* @api
*/
public static void addTrackMenuItemBuilder(TrackMenuItemBuilder builder) {
trackMenuItems.add(builder);
}
/**
* Return a popup menu with items applicable to the collection of tracks.
*
* @param tracks
* @return
*/
public static IGVPopupMenu getPopupMenu(final Collection<Track> tracks, String title, TrackClickEvent te) {
if (log.isDebugEnabled()) {
log.debug("enter getPopupMenu");
}
IGVPopupMenu menu = new IGVPopupMenu();
JLabel popupTitle = new JLabel(LEADING_HEADING_SPACER + title, JLabel.CENTER);
popupTitle.setFont(UIConstants.boldFont);
if (popupTitle != null) {
menu.add(popupTitle);
menu.addSeparator();
}
addStandardItems(menu, tracks, te);
return menu;
}
/**
* Add menu items which have been added through the api, not known until runtime
*
* @param menu
* @param tracks
* @param te
*/
public static void addPluginItems(JPopupMenu menu, Collection<Track> tracks, TrackClickEvent te) {
List<JMenuItem> items = new ArrayList<JMenuItem>(0);
for (TrackMenuItemBuilder builder : trackMenuItems) {
JMenuItem item = builder.build(tracks, te);
if (item != null) {
items.add(item);
}
}
if (items.size() > 0) {
menu.addSeparator();
for (JMenuItem item : items) {
menu.add(item);
}
}
}
public static void addStandardItems(JPopupMenu menu, Collection<Track> tracks, TrackClickEvent te) {
boolean hasDataTracks = false;
boolean hasFeatureTracks = false;
boolean hasOtherTracks = false;
for (Track track : tracks) {
// TODO -- this is ugly, refactor to remove instanceof
if (track instanceof DataTrack) {
hasDataTracks = true;
} else if (track instanceof FeatureTrack) {
hasFeatureTracks = true;
} else {
hasOtherTracks = true;
}
if (hasDataTracks && hasFeatureTracks && hasOtherTracks) {
break;
}
}
boolean featureTracksOnly = hasFeatureTracks && !hasDataTracks && !hasOtherTracks;
boolean dataTracksOnly = !hasFeatureTracks && hasDataTracks && !hasOtherTracks;
addSharedItems(menu, tracks, hasFeatureTracks);
menu.addSeparator();
if (dataTracksOnly) {
addDataItems(menu, tracks);
} else if (featureTracksOnly) {
addFeatureItems(menu, tracks, te);
}
menu.addSeparator();
menu.add(getRemoveMenuItem(tracks));
}
public static void addZoomItems(JPopupMenu menu, final ReferenceFrame frame) {
if (FrameManager.isGeneListMode()) {
JMenuItem item = new JMenuItem("Reset panel to '" + frame.getName() + "'");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.reset();
// TODO -- paint only panels for this frame
}
});
menu.add(item);
}
JMenuItem zoomOutItem = new JMenuItem("Zoom out");
zoomOutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
frame.doZoomIncrement(-1);
}
});
menu.add(zoomOutItem);
JMenuItem zoomInItem = new JMenuItem("Zoom in");
zoomInItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
frame.doZoomIncrement(1);
}
});
menu.add(zoomInItem);
}
/**
* Return popup menu with items applicable to data tracks
*
* @return
*/
public static void addDataItems(JPopupMenu menu, final Collection<Track> tracks) {
if (log.isTraceEnabled()) {
log.trace("enter getDataPopupMenu");
}
final String[] labels = {"Heatmap", "Bar Chart", "Points", "Line Plot"};
final Class[] renderers = {HeatmapRenderer.class, BarChartRenderer.class,
PointsRenderer.class, LineplotRenderer.class
};
//JLabel popupTitle = new JLabel(LEADING_HEADING_SPACER + title, JLabel.CENTER);
JLabel rendererHeading = new JLabel(LEADING_HEADING_SPACER + "Type of Graph", JLabel.LEFT);
rendererHeading.setFont(UIConstants.boldFont);
menu.add(rendererHeading);
// Get existing selections
Set<Class> currentRenderers = new HashSet<Class>();
for (Track track : tracks) {
if (track.getRenderer() != null) {
currentRenderers.add(track.getRenderer().getClass());
}
}
// Create and renderer menu items
for (int i = 0; i < labels.length; i++) {
JCheckBoxMenuItem item = new JCheckBoxMenuItem(labels[i]);
final Class rendererClass = renderers[i];
if (currentRenderers.contains(rendererClass)) {
item.setSelected(true);
}
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeRenderer(tracks, rendererClass);
}
});
menu.add(item);
}
menu.addSeparator();
// Get union of all valid window functions for selected tracks
Set<WindowFunction> avaibleWindowFunctions = new HashSet();
for (Track track : tracks) {
avaibleWindowFunctions.addAll(track.getAvailableWindowFunctions());
}
avaibleWindowFunctions.add(WindowFunction.none);
// dataPopupMenu.addSeparator();
// Collection all window functions for selected tracks
Set<WindowFunction> currentWindowFunctions = new HashSet<WindowFunction>();
for (Track track : tracks) {
if (track.getWindowFunction() != null) {
currentWindowFunctions.add(track.getWindowFunction());
}
}
if (avaibleWindowFunctions.size() > 1 || currentWindowFunctions.size() > 1) {
JLabel statisticsHeading = new JLabel(LEADING_HEADING_SPACER + "Windowing Function", JLabel.LEFT);
statisticsHeading.setFont(UIConstants.boldFont);
menu.add(statisticsHeading);
for (final WindowFunction wf : ORDERED_WINDOW_FUNCTIONS) {
JCheckBoxMenuItem item = new JCheckBoxMenuItem(wf.getValue());
if (avaibleWindowFunctions.contains(wf) || currentWindowFunctions.contains(wf)) {
if (currentWindowFunctions.contains(wf)) {
item.setSelected(true);
}
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeStatType(wf.toString(), tracks);
}
});
menu.add(item);
}
}
menu.addSeparator();
}
menu.add(getDataRangeItem(tracks));
menu.add(getHeatmapScaleItem(tracks));
if (tracks.size() > 0) {
menu.add(getLogScaleItem(tracks));
}
menu.add(getAutoscaleItem(tracks));
menu.add(getShowDataRangeItem(tracks));
menu.addSeparator();
menu.add(getChangeKMPlotItem(tracks));
if (Globals.isDevelopment() && FrameManager.isGeneListMode() && tracks.size() == 1) {
menu.addSeparator();
menu.add(getShowSortFramesItem(tracks.iterator().next()));
}
if(Globals.isDevelopment()){
final List<DataTrack> dataTrackList = Lists.newArrayList(Iterables.filter(tracks, DataTrack.class));
final JMenuItem overlayGroups = new JMenuItem("Create Overlay Track");
overlayGroups.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MergedTracks mergedTracks = new MergedTracks(UUID.randomUUID().toString(), "Overlay", dataTrackList);
Track firstTrack = tracks.iterator().next();
TrackPanel panel = TrackPanel.getParentPanel(firstTrack);
panel.addTrack(mergedTracks);
panel.moveSelectedTracksTo(Arrays.asList(mergedTracks), firstTrack, false);
panel.removeTracks(tracks);
}
});
int numDataTracks = dataTrackList.size();
overlayGroups.setEnabled(numDataTracks >= 2 && numDataTracks == tracks.size());
menu.add(overlayGroups);
}
}
private static List<JMenuItem> getCombinedDataSourceItems(final Collection<Track> tracks) {
Iterable<DataTrack> dataTracksIter = Iterables.filter(tracks, DataTrack.class);
final List<DataTrack> dataTracks = Lists.newArrayList(dataTracksIter);
JMenuItem addItem = new JMenuItem("Sum Tracks");
JMenuItem subItem = new JMenuItem("Subtract Tracks");
boolean enableComb = dataTracks.size() == 2;
addItem.setEnabled(enableComb);
addItem.setEnabled(enableComb);
addItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addCombinedDataTrack(dataTracks, CombinedDataSource.Operation.ADD);
}
});
subItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addCombinedDataTrack(dataTracks, CombinedDataSource.Operation.SUBTRACT);
}
});
return Arrays.asList(addItem, subItem);
}
private static void addCombinedDataTrack(List<DataTrack> dataTracks, CombinedDataSource.Operation op) {
String text = "";
switch (op) {
case ADD:
text = "Sum";
break;
case SUBTRACT:
text = "Difference";
break;
}
DataTrack track0 = dataTracks.get(0);
DataTrack track1 = dataTracks.get(1);
CombinedDataSource source = new CombinedDataSource(track0, track1, op);
DataSourceTrack newTrack = new DataSourceTrack(null, track0.getId() + track1.getId() + text, text, source);
changeRenderer(Arrays.<Track>asList(newTrack), track0.getRenderer().getClass());
newTrack.setDataRange(track0.getDataRange());
newTrack.setColorScale(track0.getColorScale());
IGV.getInstance().addTracks(Arrays.<Track>asList(newTrack), PanelName.DATA_PANEL);
}
/**
* Return popup menu with items applicable to feature tracks
*
* @return
*/
private static void addFeatureItems(JPopupMenu featurePopupMenu, final Collection<Track> tracks, TrackClickEvent te) {
addDisplayModeItems(tracks, featurePopupMenu);
if (tracks.size() == 1) {
Track t = tracks.iterator().next();
Feature f = t.getFeatureAtMousePosition(te);
if (f != null) {
featurePopupMenu.addSeparator();
// If we are over an exon, copy its sequence instead of the entire feature.
if (f instanceof IGVFeature) {
double position = te.getChromosomePosition();
Collection<Exon> exons = ((IGVFeature) f).getExons();
if (exons != null) {
for (Exon exon : exons) {
if (position > exon.getStart() && position < exon.getEnd()) {
f = exon;
break;
}
}
}
}
featurePopupMenu.add(getCopyDetailsItem(f, te));
featurePopupMenu.add(getCopySequenceItem(f));
if (Globals.isDevelopment()) {
featurePopupMenu.add(getBlatItem(f));
}
}
if (Globals.isDevelopment()) {
featurePopupMenu.addSeparator();
featurePopupMenu.add(getFeatureToGeneListItem(t));
}
if (Globals.isDevelopment() && FrameManager.isGeneListMode() && tracks.size() == 1) {
featurePopupMenu.addSeparator();
featurePopupMenu.add(getShowSortFramesItem(tracks.iterator().next()));
}
}
featurePopupMenu.addSeparator();
featurePopupMenu.add(getChangeFeatureWindow(tracks));
}
private static JMenuItem getFeatureToGeneListItem(final Track t) {
JMenuItem mi = new JMenuItem("Use as loci list");
mi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Current chromosome only for now
}
});
return mi;
}
/**
* Return a menu item which will export visible features
* If {@code tracks} is not a single {@code FeatureTrack}, {@code null}
* is returned (there should be no menu entry)
*
* @param tracks
* @return
*/
public static JMenuItem getExportFeatures(final Collection<Track> tracks, final ReferenceFrame.Range range) {
if (tracks.size() != 1 || !(tracks.iterator().next() instanceof FeatureTrack)) {
return null;
}
JMenuItem exportData = new JMenuItem("Export To BED File");
exportData.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File outFile = FileDialogUtils.chooseFile("Save Visible Data",
PreferenceManager.getInstance().getLastTrackDirectory(),
new File("visibleData.bed"),
FileDialogUtils.SAVE);
exportVisibleData(outFile.getAbsolutePath(), tracks, range);
}
});
return exportData;
}
/**
* Write features in {@code track} found in {@code range} to {@code outPath},
* BED format
* TODO Move somewhere else? run on separate thread? Probably shouldn't be here
*
* @param outPath
* @param tracks
* @param range
*/
static void exportVisibleData(String outPath, Collection<Track> tracks, ReferenceFrame.Range range) {
PrintWriter writer;
try {
writer = new PrintWriter(outPath);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
for (Track track : tracks) {
if (track instanceof FeatureTrack) {
FeatureTrack fTrack = (FeatureTrack) track;
//Can't trust FeatureTrack.getFeatures to limit itself, so we filter
List<Feature> features = fTrack.getFeatures(range.getChr(), range.getStart(), range.getEnd());
Predicate<Feature> pred = FeatureUtils.getOverlapPredicate(range.getChr(), range.getStart(), range.getEnd());
features = CollUtils.filter(features, pred);
IGVBEDCodec codec = new IGVBEDCodec();
for (Feature feat : features) {
String featString = codec.encode(feat);
writer.println(featString);
}
}
}
writer.flush();
writer.close();
}
/**
* Popup menu with items applicable to both feature and data tracks
*
* @return
*/
public static void addSharedItems(JPopupMenu menu, final Collection<Track> tracks, boolean hasFeatureTracks) {
//JLabel trackSettingsHeading = new JLabel(LEADING_HEADING_SPACER + "Track Settings", JLabel.LEFT);
//trackSettingsHeading.setFont(boldFont);
//menu.add(trackSettingsHeading);
menu.add(getTrackRenameItem(tracks));
String colorLabel = hasFeatureTracks
? "Change Track Color..." : "Change Track Color (Positive Values)...";
JMenuItem item = new JMenuItem(colorLabel);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeTrackColor(tracks);
}
});
menu.add(item);
if (!hasFeatureTracks) {
// Change track color by attribute
item = new JMenuItem("Change Track Color (Negative Values)...");
item.setToolTipText(
"Change the alternate track color. This color is used when graphing negative values");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeAltTrackColor(tracks);
}
});
menu.add(item);
}
menu.add(getChangeTrackHeightItem(tracks));
menu.add(getChangeFontSizeItem(tracks));
}
private static void changeStatType(String statType, Collection<Track> selectedTracks) {
for (Track track : selectedTracks) {
track.setWindowFunction(WindowFunction.valueOf(statType));
}
refresh();
}
public static JMenuItem getTrackRenameItem(final Collection<Track> selectedTracks) {
// Change track height by attribute
JMenuItem item = new JMenuItem("Rename Track...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
UIUtilities.invokeOnEventThread(new Runnable() {
public void run() {
renameTrack(selectedTracks);
}
});
}
});
if (selectedTracks.size() > 1) {
item.setEnabled(false);
}
return item;
}
private static JMenuItem getHeatmapScaleItem(final Collection<Track> selectedTracks) {
JMenuItem item = new JMenuItem("Set Heatmap Scale...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (selectedTracks.size() > 0) {
ContinuousColorScale colorScale = selectedTracks.iterator().next().getColorScale();
HeatmapScaleDialog dlg = new HeatmapScaleDialog(IGV.getMainFrame(), colorScale);
dlg.setVisible(true);
if (!dlg.isCanceled()) {
colorScale = dlg.getColorScale();
// dlg.isFlipAxis());
for (Track track : selectedTracks) {
track.setColorScale(colorScale);
}
IGV.getInstance().repaint();
}
}
}
});
return item;
}
public static JMenuItem getDataRangeItem(final Collection<Track> selectedTracks) {
JMenuItem item = new JMenuItem("Set Data Range...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (selectedTracks.size() > 0) {
// Create a datarange that spans the extent of prev tracks range
DataRange prevAxisDefinition = DataRange.getFromTracks(selectedTracks);
DataRangeDialog dlg = new DataRangeDialog(IGV.getMainFrame(), prevAxisDefinition);
dlg.setVisible(true);
if (!dlg.isCanceled()) {
float min = Math.min(dlg.getMax(), dlg.getMin());
float max = Math.max(dlg.getMin(), dlg.getMax());
float mid = dlg.getBase();
mid = Math.max(min, Math.min(mid, max));
DataRange axisDefinition = new DataRange(dlg.getMin(), mid, dlg.getMax(),
prevAxisDefinition.isDrawBaseline(), dlg.isLog());
for (Track track : selectedTracks) {
track.setDataRange(axisDefinition);
track.setAutoScale(false);
}
IGV.getInstance().repaint();
}
}
}
});
return item;
}
private static JMenuItem getDrawBorderItem() {
// Change track height by attribute
final JCheckBoxMenuItem drawBorderItem = new JCheckBoxMenuItem("Draw borders");
drawBorderItem.setSelected(FeatureTrack.isDrawBorder());
drawBorderItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
FeatureTrack.setDrawBorder(drawBorderItem.isSelected());
IGV.getInstance().repaintDataPanels();
}
});
return drawBorderItem;
}
public static JMenuItem getLogScaleItem(final Collection<Track> selectedTracks) {
// Change track height by attribute
final JCheckBoxMenuItem logScaleItem = new JCheckBoxMenuItem("Log scale");
final boolean logScale = selectedTracks.iterator().next().getDataRange().isLog();
logScaleItem.setSelected(logScale);
logScaleItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
DataRange.Type scaleType = logScaleItem.isSelected() ?
DataRange.Type.LOG :
DataRange.Type.LINEAR;
for (Track t : selectedTracks) {
t.getDataRange().setType(scaleType);
}
IGV.getInstance().repaintDataPanels();
}
});
return logScaleItem;
}
private static JMenuItem getAutoscaleItem(final Collection<Track> selectedTracks) {
final JCheckBoxMenuItem autoscaleItem = new JCheckBoxMenuItem("Autoscale");
if (selectedTracks.size() == 0) {
autoscaleItem.setEnabled(false);
} else {
boolean autoScale = checkAutoscale(selectedTracks);
autoscaleItem.setSelected(autoScale);
autoscaleItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
boolean autoScale = autoscaleItem.isSelected();
for (Track t : selectedTracks) {
t.setAutoScale(autoScale);
}
IGV.getInstance().repaintDataPanels();
}
});
}
return autoscaleItem;
}
private static boolean checkAutoscale(Collection<Track> selectedTracks) {
boolean autoScale = false;
for (Track t : selectedTracks) {
if (t.getAutoScale()) {
autoScale = true;
break;
}
}
return autoScale;
}
public static JMenuItem getShowDataRangeItem(final Collection<Track> selectedTracks) {
final JCheckBoxMenuItem item = new JCheckBoxMenuItem("Show Data Range");
if (selectedTracks.size() == 0) {
item.setEnabled(false);
} else {
boolean showDataRange = true;
for (Track t : selectedTracks) {
if (!t.isShowDataRange()) {
showDataRange = false;
break;
}
}
item.setSelected(showDataRange);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
boolean showDataRange = item.isSelected();
for (Track t : selectedTracks) {
if (t instanceof DataTrack) {
((DataTrack) t).setShowDataRange(showDataRange);
}
}
IGV.getInstance().repaintDataPanels();
}
});
}
return item;
}
public static void addDisplayModeItems(final Collection<Track> tracks, JPopupMenu menu) {
// Find "most representative" state from track collection
Map<Track.DisplayMode, Integer> counts = new HashMap<Track.DisplayMode, Integer>(Track.DisplayMode.values().length);
Track.DisplayMode currentMode = null;
for (Track t : tracks) {
Track.DisplayMode mode = t.getDisplayMode();
if (counts.containsKey(mode)) {
counts.put(mode, counts.get(mode) + 1);
} else {
counts.put(mode, 1);
}
}
int maxCount = -1;
for (Map.Entry<Track.DisplayMode, Integer> count : counts.entrySet()) {
if (count.getValue() > maxCount) {
currentMode = count.getKey();
maxCount = count.getValue();
}
}
ButtonGroup group = new ButtonGroup();
Map<String, Track.DisplayMode> modes = new LinkedHashMap<String, Track.DisplayMode>(4);
modes.put("Collapsed", Track.DisplayMode.COLLAPSED);
modes.put("Expanded", Track.DisplayMode.EXPANDED);
modes.put("Squished", Track.DisplayMode.SQUISHED);
boolean showAS = Boolean.parseBoolean(System.getProperty("showAS", "false"));
if (showAS) {
modes.put("Alternative Splice", Track.DisplayMode.ALTERNATIVE_SPLICE);
}
for (final Map.Entry<String, Track.DisplayMode> entry : modes.entrySet()) {
JRadioButtonMenuItem mm = new JRadioButtonMenuItem(entry.getKey());
mm.setSelected(currentMode == entry.getValue());
mm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setTrackDisplayMode(tracks, entry.getValue());
refresh();
}
});
group.add(mm);
menu.add(mm);
}
}
private static void setTrackDisplayMode(Collection<Track> tracks, Track.DisplayMode mode) {
for (Track t : tracks) {
t.setDisplayMode(mode);
}
}
public static JMenuItem getRemoveMenuItem(final Collection<Track> selectedTracks) {
boolean multiple = selectedTracks.size() > 1;
JMenuItem item = new JMenuItem("Remove Track" + (multiple ? "s" : ""));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
removeTracksAction(selectedTracks);
}
});
return item;
}
/**
* Display a dialog to the user asking to confirm if they want to remove the
* selected tracks
*
* @param selectedTracks
*/
public static void removeTracksAction(final Collection<Track> selectedTracks) {
if (selectedTracks.isEmpty()) {
return;
}
StringBuffer buffer = new StringBuffer();
for (Track track : selectedTracks) {
buffer.append("\n\t");
buffer.append(track.getName());
}
String deleteItems = buffer.toString();
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
textArea.setText(deleteItems);
JOptionPane optionPane = new JOptionPane(scrollPane,
JOptionPane.PLAIN_MESSAGE,
JOptionPane.YES_NO_OPTION);
optionPane.setPreferredSize(new Dimension(550, 500));
JDialog dialog = optionPane.createDialog(IGV.getMainFrame(), "Remove The Following Tracks");
dialog.setVisible(true);
Object choice = optionPane.getValue();
if ((choice == null) || (JOptionPane.YES_OPTION != ((Integer) choice).intValue())) {
return;
}
IGV.getInstance().removeTracks(selectedTracks);
IGV.getInstance().doRefresh();
}
public static void changeRenderer(final Collection<Track> selectedTracks, Class rendererClass) {
for (Track track : selectedTracks) {
// TODO -- a temporary hack to facilitate RNAi development
if (track.getTrackType() == TrackType.RNAI) {
if (rendererClass == BarChartRenderer.class) {
rendererClass = RNAiBarChartRenderer.class;
}
}
track.setRendererClass(rendererClass);
}
refresh();
}
public static void renameTrack(final Collection<Track> selectedTracks) {
if (selectedTracks.isEmpty()) {
return;
}
Track t = selectedTracks.iterator().next();
String newName = JOptionPane.showInputDialog(IGV.getMainFrame(), "Enter new name: ", t.getName());
if (newName == null || newName.trim() == "") {
return;
}
t.setName(newName);
refresh();
}
public static void changeTrackHeight(final Collection<Track> selectedTracks) {
if (selectedTracks.isEmpty()) {
return;
}
final String parameter = "Track height";
Integer value = getIntegerInput(parameter, getRepresentativeTrackHeight(selectedTracks));
if (value == null) {
return;
}
value = Math.max(0, value);
for (Track track : selectedTracks) {
track.setHeight(value, true);
}
refresh();
}
public static void changeFeatureVisibilityWindow(final Collection<Track> selectedTracks) {
Collection<Track> featureTracks = new ArrayList(selectedTracks.size());
for (Track t : selectedTracks) {
if (t instanceof FeatureTrack) {
featureTracks.add(t);
}
}
if (featureTracks.isEmpty()) {
return;
}
int origValue = featureTracks.iterator().next().getVisibilityWindow();
double origValueKB = (origValue / 1000.0);
Double value = getDoubleInput("Enter visibility window in kilo-bases. To load all data enter zero.", origValueKB);
if (value == null) {
return;
}
for (Track track : featureTracks) {
track.setVisibilityWindow((int) (value * 1000));
}
refresh();
}
public static void changeFontSize(final Collection<Track> selectedTracks) {
if (selectedTracks.isEmpty()) {
return;
}
final String parameter = "Font size";
int defaultValue = selectedTracks.iterator().next().getFontSize();
Integer value = getIntegerInput(parameter, defaultValue);
if (value == null) {
return;
}
for (Track track : selectedTracks) {
track.setFontSize(value);
}
refresh();
}
public static Integer getIntegerInput(String parameter, int value) {
while (true) {
String strValue = JOptionPane.showInputDialog(
IGV.getMainFrame(), parameter + ": ",
String.valueOf(value));
//strValue will be null if dialog cancelled
if ((strValue == null) || strValue.trim().equals("")) {
return null;
}
try {
value = Integer.parseInt(strValue);
return value;
} catch (NumberFormatException numberFormatException) {
JOptionPane.showMessageDialog(IGV.getMainFrame(),
parameter + " must be an integer number.");
}
}
}
public static Double getDoubleInput(String parameter, double value) {
while (true) {
String strValue = JOptionPane.showInputDialog(
IGV.getMainFrame(), parameter + ": ",
String.valueOf(value));
//strValue will be null if dialog cancelled
if ((strValue == null) || strValue.trim().equals("")) {
return null;
}
try {
value = Double.parseDouble(strValue);
return value;
} catch (NumberFormatException numberFormatException) {
MessageUtils.showMessage(parameter + " must be a number.");
}
}
}
public static void changeTrackColor(final Collection<Track> selectedTracks) {
if (selectedTracks.isEmpty()) {
return;
}
Color currentSelection = selectedTracks.iterator().next().getColor();
Color color = UIUtilities.showColorChooserDialog(
"Select Track Color (Positive Values)",
currentSelection);
if (color == null) {
return;
}
for (Track track : selectedTracks) {
//We preserve the alpha value. This is motivated by MergedTracks
track.setColor(ColorUtilities.modifyAlpha(color, currentSelection.getAlpha()));
}
refresh();
}
public static void changeAltTrackColor(final Collection<Track> selectedTracks) {
if (selectedTracks.isEmpty()) {
return;
}
Color currentSelection = selectedTracks.iterator().next().getColor();
Color color = UIUtilities.showColorChooserDialog(
"Select Track Color (Negative Values)",
currentSelection);
if (color == null) {
return;
}
for (Track track : selectedTracks) {
track.setAltColor(ColorUtilities.modifyAlpha(color, currentSelection.getAlpha()));
}
refresh();
}
public static JMenuItem getCopyDetailsItem(final Feature f, final TrackClickEvent evt) {
JMenuItem item = new JMenuItem("Copy Details to Clipboard");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ReferenceFrame frame = evt.getFrame();
int mouseX = evt.getMouseEvent().getX();
double location = frame.getChromosomePosition(mouseX);
if (f instanceof IGVFeature) {
String details = ((IGVFeature) f).getValueString(location, null);
if (details != null) {
details = details.replace("<br>", System.getProperty("line.separator"));
details += System.getProperty("line.separator") +
f.getChr() + ":" + (f.getStart() + 1) + "-" + f.getEnd();
StringUtils.copyTextToClipboard(details);
}
}
}
});
return item;
}
public static JMenuItem getCopySequenceItem(final Feature f) {
JMenuItem item = new JMenuItem("Copy Sequence");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Genome genome = GenomeManager.getInstance().getCurrentGenome();
IGV.copySequenceToClipboard(genome, f.getChr(), f.getStart(), f.getEnd());
}
});
return item;
}
public static JMenuItem getBlatItem(final Feature f) {
JMenuItem item = new JMenuItem("Blat Sequence");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
BlatClient.doBlatQuery(f.getChr(), f.getStart(), f.getEnd());
}
});
return item;
}
/**
* Return a representative track height to use as the default. For now
* using the median track height.
*
* @return
*/
public static int getRepresentativeTrackHeight(Collection<Track> tracks) {
double[] heights = new double[tracks.size()];
int i = 0;
for (Track track : tracks) {
heights[i] = track.getHeight();
i++;
}
int medianTrackHeight = (int) Math.round(StatUtils.percentile(heights, 50));
if (medianTrackHeight > 0) {
return medianTrackHeight;
}
return PreferenceManager.getInstance().getAsInt(PreferenceManager.INITIAL_TRACK_HEIGHT);
}
public static void refresh() {
if (IGV.hasInstance()) {
IGV.getInstance().showLoadedTrackCount();
IGV.getInstance().doRefresh();
}
}
public static JMenuItem getChangeTrackHeightItem(final Collection<Track> selectedTracks) {
// Change track height by attribute
JMenuItem item = new JMenuItem("Change Track Height...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeTrackHeight(selectedTracks);
}
});
return item;
}
public static JMenuItem getChangeKMPlotItem(final Collection<Track> selectedTracks) {
// Change track height by attribute
JMenuItem item = new JMenuItem("Kaplan-Meier Plot...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// If one or fewer tracks are selected assume the intent is to use all tracks. A right-click
// will always result in one selected track.
Collection<Track> tracks = selectedTracks.size() > 1 ? selectedTracks :
IGV.getInstance().getAllTracks();
KMPlotFrame frame = new KMPlotFrame(tracks);
frame.setVisible(true);
}
});
// The Kaplan-Meier plot requires sample information, specifically survival, sample, and censure. We
// can't know if these columns exist, but we can at least know if sample-info has been loaded.
// 3-4 columns always exist by default, more indicate at least some sample attributes are defined.
boolean sampleInfoLoaded = AttributeManager.getInstance().getAttributeNames().size() > 4;
item.setEnabled(sampleInfoLoaded);
return item;
}
public static JMenuItem getChangeFeatureWindow(final Collection<Track> selectedTracks) {
// Change track height by attribute
JMenuItem item = new JMenuItem("Set Feature Visibility Window...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeFeatureVisibilityWindow(selectedTracks);
}
});
return item;
}
public static JMenuItem getChangeFontSizeItem(final Collection<Track> selectedTracks) {
// Change track height by attribute
JMenuItem item = new JMenuItem("Change Font Size...");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeFontSize(selectedTracks);
}
});
return item;
}
// Experimental methods follow
public static JMenuItem getShowSortFramesItem(final Track track) {
final JCheckBoxMenuItem item = new JCheckBoxMenuItem("Sort frames");
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Runnable runnable = new Runnable() {
public void run() {
FrameManager.sortFrames(track);
IGV.getInstance().resetFrames();
}
};
LongRunningTask.submit(runnable);
}
});
return item;
}
}
| Put overlay tracks option into production
IGV-1979
| src/org/broad/igv/track/TrackMenuUtils.java | Put overlay tracks option into production |
|
Java | mit | f4700fc337cb85fd2f28f9510337388815718746 | 0 | jourdanrodrigues/controk-android | package com.example.jourdanrodrigues.controk;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
private String[] mMenuEntries;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMenuEntries = getResources().getStringArray(R.array.menu_entries);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, mMenuEntries));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
if (getSupportActionBar() != null) {
// Solution source: https://stackoverflow.com/a/35719588/4694834
getSupportActionBar().setTitle(mTitle);
}
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(mDrawerTitle);
}
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.addDrawerListener(mDrawerToggle);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mMenuEntries[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(mTitle);
}
}
}
| app/src/main/java/com/example/jourdanrodrigues/controk/MainActivity.java | package com.example.jourdanrodrigues.controk;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
private String[] mMenuEntries;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMenuEntries = getResources().getStringArray(R.array.menu_entries);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, mMenuEntries));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
if (getSupportActionBar() != null) {
// Solution source: https://stackoverflow.com/a/35719588/4694834
getSupportActionBar().setTitle(mTitle);
}
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(mDrawerTitle);
}
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.addDrawerListener(mDrawerToggle);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mMenuEntries[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(mTitle);
}
}
}
| :fire: Remove useless statements.
| app/src/main/java/com/example/jourdanrodrigues/controk/MainActivity.java | :fire: Remove useless statements. |
|
Java | mit | d07ee6be2cb8601239e32842dbe179725ee8682e | 0 | weihang7/WikipediaScorer | import WikipediaTemplateParser.info.bliki.wiki.filter.PlainTextConverter;
import WikipediaTemplateParser.info.bliki.wiki.model.WikiModel;
import java.util.*;
public class Tokenizer {
//Make a WikiModel at compile-time for rendering Wikipedia's templates.
static WikiModel wikiModel = new WikiModel("http://www.mywiki.com/wiki/${image}",
"http://www.mywiki.com/wiki/${title}");
public static String[] tokenize(String templatedText) {
/*
* Given some Wikipedia text (templatedText),
* return the plaintext render of it, stripped
* of punctuation except periods, lowercased,
* and split by spaces.
*/
//Use the bliki api to render the Wikipedia templating text:
String plaintext = wikiModel.render(new PlainTextConverter(),templatedText);
//Do our regex modifications to the resultant plaintext:
String[] tokens = plaintext.toLowerCase()
.replaceAll("\\{\\{[^\\{\\}]*\\}\\}","") //Take out all braced information, which doesn't show to the reader
.replaceAll("\\n+",".") //Replace line breaks with periods
.replaceAll("[^\\w\\. ]","") //Take out punctuation and special characters
.replaceAll(" +"," ") //Remove duplicatespaces
.replaceAll("(?: ?\\. ?)+"," . ") //Remove duplicate periods
.split(" "); //Split by spaces.
return tokens;
}
public static String[] getAlphabet(String[] text, int size) {
/*
* Given an array of tokens (text), output
* the (size) most common tokens, for use as
* an alphabet in later Markov counting.
*/
//Initiate the table where we'll store our counts:
Hashtable counts = new Hashtable();
//Initiate the alphabet array:
String[] alphabet = new String[size];
for (int i = 0; i < text.length; i += 1) {
if (counts.containsKey(text[i])) {
//If we've seen this word before, add one to our count of it:
counts.put(text[i],(Integer)counts.get(text[i]) + 1);
}
else {
//Otherwise, intiate the count of this word as 1.
counts.put(text[i], 1);
}
for (int x = 0; x < size; x += 1) {
if (alphabet[x] == null) {
//If the alphabet array is not full yet, add this token to it:
alphabet[x] = text[i];
}
else if ((Integer)counts.get(text[i]) > (Integer)counts.get(alphabet[x])) {
//If it is full, but the current word is now more common than a word already in it, replace
//the less common word with the current one.
alphabet[x] = text[i];
}
}
}
return alphabet;
}
public static String[] stripTokens(String[] text, String[] alphabet) {
/*
* Given a string of tokens (text), and an
* alphabet (alphabet), return (text) with every word
* not in (alphabet) replaced with "*."
*/
//Clone text so that we don't effect it:
String[] textToReturn = text.clone();
for (int i = 0; i < text.length; i += 1) {
//Initiate the delete flag for this token to be on:
boolean delete = true;
for (int x = 0; x < alphabet.length; x += 1) {
if (alphabet[x] == textToReturn[i]) {
//If the token is in the alphabet, turn off the delete flag:
delete = false;
break;
}
}
if (delete) {
//If the token is still flagged for deletion, replace with "*".
textToReturn[i] = "*";
}
}
return textToReturn;
}
public static String[][] fullTokenization(String text, int alphabetSize) {
/*
* Given a Wikipedia template string (text) and an alphabet size
* (alphabetSize), tokenizes (text), gets the alphabet of size
* (alphabetSize) from it, and strips (text) using that alphabet.
*/
//Initiate a an array of string arrays that will utimately contain
//the stripped tokens and the alphabet:
String[][] returnValue = new String[0][2];
returnValue[0] = tokenize(text); //First, tokenize the text and store it
returnValue[1] = getAlphabet(returnValue[0],alphabetSize); //Then get the alphabet for that token string
returnValue[0] = stripTokens(returnValue[0],returnValue[1]); //Then strip the token string using that alphabet.
return returnValue;
}
} | Tokenizer.java | import WikipediaTemplateParser.info.bliki.wiki.filter.PlainTextConverter;
import WikipediaTemplateParser.info.bliki.wiki.model.WikiModel;
import java.util.*;
public class Tokenizer {
static WikiModel wikiModel = new WikiModel("http://www.mywiki.com/wiki/${image}",
"http://www.mywiki.com/wiki/${title}");
public static String[] tokenize(String templatedText) {
String plaintext = wikiModel.render(new PlainTextConverter(),templatedText);
String[] tokens = plaintext.toLowerCase()
.replaceAll("\\{\\{[^\\{\\}]*\\}\\}","")
.replaceAll("\\n+",".")
.replaceAll("[^\\w\\. ]","")
.replaceAll(" +"," ")
.replaceAll("(?: ?\\. ?)+"," . ")
.split(" ");
return tokens;
}
public static String[] getAlphabet(String[] text, int size) {
Hashtable counts = new Hashtable();
String[] alphabet = new String[size];
for (int i = 0; i < text.length; i += 1) {
if (counts.containsKey(text[i])) {
counts.put(text[i],(Integer)counts.get(text[i]) + 1);
}
else {
counts.put(text[i], 1);
}
for (int x = 0; x < size; x += 1) {
if (alphabet[x] == null) {
alphabet[x] = text[i];
}
else if ((Integer)counts.get(text[i]) > (Integer)counts.get(alphabet[x])) {
alphabet[x] = text[i];
}
}
}
return alphabet;
}
public static String[] stripTokens(String[] text, String[] alphabet) {
String[] textToReturn = text.clone();
for (int i = 0; i < text.length; i += 1) {
boolean delete = true;
for (int x = 0; x < alphabet.length; x += 1) {
if (alphabet[x] == textToReturn[i]) {
delete = false;
break;
}
}
if (delete) {
textToReturn[i] = "*";
}
}
return textToReturn;
}
public static String[][] fullTokenization(String text, int alphabetSize) {
String[][] returnValue = new String[2][2];
returnValue[0] = tokenize(text);
returnValue[1] = getAlphabet(returnValue[0],alphabetSize);
returnValue[0] = stripTokens(returnValue[0],returnValue[1]);
return returnValue;
}
public static void main(String[] args) {
String[] tokens = Fetcher.getRandomPageTexts(Integer.decode(args[0]));
tokens = tokenize(tokens[0]);
for (int i = 0; i < tokens.length; i += 1) {
System.out.print(tokens[i] + " ");
}
}
} | Commented the Tokenizer.
| Tokenizer.java | Commented the Tokenizer. |
|
Java | mit | 80aee65f3258dfa3f84f4f52a6695e61793e66ba | 0 | scoot-software/sms-server | /*
* Author: Scott Ware <[email protected]>
* Copyright (c) 2015 Scott Ware
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.scooter1556.sms.server.service;
import com.scooter1556.sms.server.SMS;
import com.scooter1556.sms.server.dao.MediaDao;
import com.scooter1556.sms.server.dao.SettingsDao;
import com.scooter1556.sms.server.domain.MediaElement;
import com.scooter1556.sms.server.domain.MediaElement.AudioStream;
import com.scooter1556.sms.server.domain.MediaElement.DirectoryMediaType;
import com.scooter1556.sms.server.domain.MediaElement.MediaElementType;
import com.scooter1556.sms.server.domain.MediaElement.SubtitleStream;
import com.scooter1556.sms.server.domain.MediaElement.VideoStream;
import com.scooter1556.sms.server.domain.MediaFolder;
import com.scooter1556.sms.server.domain.Playlist;
import com.scooter1556.sms.server.service.LogService.Level;
import com.scooter1556.sms.server.service.parser.FrameParser;
import com.scooter1556.sms.server.service.parser.MetadataParser;
import com.scooter1556.sms.server.service.parser.NFOParser;
import com.scooter1556.sms.server.service.parser.NFOParser.NFOData;
import com.scooter1556.sms.server.utilities.LogUtils;
import com.scooter1556.sms.server.utilities.MediaUtils;
import com.scooter1556.sms.server.utilities.PlaylistUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import static java.nio.file.FileVisitResult.CONTINUE;
import static java.nio.file.FileVisitResult.SKIP_SIBLINGS;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.sql.Timestamp;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Date;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
@EnableScheduling
public class ScannerService implements DisposableBean {
private static final String CLASS_NAME = "MediaScannerService";
@Autowired
private SettingsDao settingsDao;
@Autowired
private MediaDao mediaDao;
@Autowired
private MetadataParser metadataParser;
@Autowired
private NFOParser nfoParser;
@Autowired
private FrameParser frameParser;
@Autowired
private PlaylistService playlistService;
@Autowired
private SessionService sessionService;
private static final String[] INFO_FILE_TYPES = {"nfo"};
private static final String[] EXCLUDED_FILE_NAMES = {"extras", "trailers"};
private static final Pattern FILE_NAME = Pattern.compile("(.+)(\\s+[(\\[](\\d{4})[)\\]])$?");
private long mTotal = 0, dTotal = 0;
// Media scanning thread pool
ExecutorService scanningThreads = null;
// Deep scan executor
ExecutorService deepScanExecutor = null;
// Logs
String deepScanLog;
// End scanning jobs on application exit
@Override
public void destroy() {
if(isScanning()) {
scanningThreads.shutdownNow();
}
stopDeepScan();
}
// Check for inactive jobs at midnight
@Scheduled(cron="#{config.deepScanSchedule}")
public int startDeepScan() {
// Check a scanning process is not already active
if (isScanning() || isDeepScanning()) {
return SMS.Status.NOT_ALLOWED;
}
// Check there are no active sessions which may be affected
if(sessionService.getNumSessions() > 0) {
return SMS.Status.NOT_ALLOWED;
}
// List of streams to scan
List<VideoStream> streams = mediaDao.getIncompleteVideoStreams();
// Start scanning
if(streams.isEmpty()) {
return SMS.Status.NOT_REQUIRED;
}
// Start scanning
deepScan(streams);
LogService.getInstance().addLogEntry(LogService.Level.INFO, CLASS_NAME, "Started deep scan of media.", null);
return SMS.Status.OK;
}
//
// Returns whether media folders are currently being scanned.
//
public synchronized boolean isScanning() {
// Check if we have any scanning threads
if(scanningThreads == null) {
return false;
}
// Check if scanning threads have terminated
return !scanningThreads.isTerminated();
}
//
// Returns whether deep scan is in progress.
//
public synchronized boolean isDeepScanning() {
if(deepScanExecutor == null) {
return false;
}
return !deepScanExecutor.isTerminated();
}
//
// Returns the number of files scanned so far.
//
public long getScanCount() {
return mTotal;
}
//
// Returns the number of streams scanned so far.
//
public long getDeepScanCount() {
return dTotal;
}
//
// Scans media in a separate thread.
//
public synchronized void startMediaScanning(List<MediaFolder> folders) {
// Check if media is already being scanned
if (isScanning()) {
return;
}
// Stop deep scanning if in progress
stopDeepScan();
// Reset scan count
mTotal = 0;
// Log
final String log = SettingsService.getInstance().getLogDirectory() + "/mediascanner-" + new Timestamp(new Date().getTime()) + ".log";
// Create media scanning threads
scanningThreads = Executors.newFixedThreadPool(folders.size());
// Submit scanning jobs for each media folder
for (final MediaFolder folder : folders) {
scanningThreads.submit(new Runnable() {
@Override
public void run() {
scanMediaFolder(folder, log);
}
});
}
// Shutdown thread pool so no further threads can be added
scanningThreads.shutdown();
}
//
// Scans playlist in a separate thread.
//
public synchronized void startPlaylistScanning(List<Playlist> playlists) {
// Check if media is already being scanned
if (isScanning()) {
return;
}
// Create media scanning threads
scanningThreads = Executors.newFixedThreadPool(playlists.size());
// Submit processing jobs for each playlist
for (final Playlist playlist : playlists) {
scanningThreads.submit(new Runnable() {
@Override
public void run() {
scanPlaylist(playlist);
}
});
}
// Shutdown thread pool so no further threads can be added
scanningThreads.shutdown();
}
//
// Performs a deep scan of media streams
//
private synchronized void deepScan(final List<VideoStream> streams) {
// Create log file
Timestamp scanTime = new Timestamp(new Date().getTime());
deepScanLog = SettingsService.getInstance().getLogDirectory() + "/deepscan-" + scanTime + ".log";
// Reset counter
dTotal = 0;
// Create media scanning threads
deepScanExecutor = Executors.newSingleThreadExecutor();
deepScanExecutor.submit(new Runnable() {
@Override
public void run() {
LogUtils.writeToLog(deepScanLog, "Found " + streams.size() + " streams to parse.", Level.DEBUG);
for(VideoStream stream : streams) {
dTotal ++;
LogUtils.writeToLog(deepScanLog, "Scanning stream " + stream.getStreamId() + " for media element with id " + stream.getMediaElementId(), Level.DEBUG);
VideoStream update = frameParser.parse(stream);
if(update != null) {
mediaDao.updateVideoStream(update);
LogUtils.writeToLog(deepScanLog, stream.toString(), Level.DEBUG);
}
LogUtils.writeToLog(deepScanLog, "Finished Scanning stream " + stream.getStreamId() + " for media element with id " + stream.getMediaElementId(), Level.DEBUG);
}
}
});
deepScanExecutor.shutdownNow();
}
public void stopDeepScan() {
if(deepScanExecutor != null && !deepScanExecutor.isTerminated()) {
deepScanExecutor.shutdownNow();
frameParser.stop();
LogUtils.writeToLog(deepScanLog, "Deep scan terminated early!", Level.DEBUG);
}
}
private void scanPlaylist(Playlist playlist) {
// Check this is a file based playlist
if(playlist.getPath() == null || playlist.getPath().isEmpty()) {
return;
}
LogService.getInstance().addLogEntry(LogService.Level.INFO, CLASS_NAME, "Scanning playlist " + playlist.getPath(), null);
// Remove existing playlist content
mediaDao.removePlaylistContent(playlist.getID());
// Parse playlist
List<MediaElement> mediaElements = playlistService.parsePlaylist(playlist.getPath());
if(mediaElements == null || mediaElements.isEmpty()) {
LogService.getInstance().addLogEntry(LogService.Level.INFO, CLASS_NAME, "No content found for playlist " + playlist.getPath(), null);
return;
}
// Update playlist content
mediaDao.setPlaylistContent(playlist.getID(), mediaElements);
LogService.getInstance().addLogEntry(LogService.Level.INFO, CLASS_NAME, "Finished scanning playlist " + playlist.getPath() + " (Found " + mediaElements.size() + " items)", null);
}
private void scanMediaFolder(MediaFolder folder, String log) {
Path path = FileSystems.getDefault().getPath(folder.getPath());
ParseFiles fileParser = new ParseFiles(folder, log);
try {
// Start Scan directory
LogService.getInstance().addLogEntry(LogService.Level.INFO, CLASS_NAME, "Scanning media folder " + folder.getPath(), null);
Files.walkFileTree(path, fileParser);
// Add new media elements in database
if(!fileParser.getNewMediaElements().isEmpty()) {
mediaDao.createMediaElements(fileParser.getNewMediaElements());
}
// Update existing media elements in database
if(!fileParser.getUpdatedMediaElements().isEmpty()) {
mediaDao.updateMediaElementsByID(fileParser.getUpdatedMediaElements());
}
// Extract media streams from parsed media elements
List<VideoStream> vStreams = new ArrayList<>();
List<AudioStream> aStreams = new ArrayList<>();
List<SubtitleStream> sStreams = new ArrayList<>();
for(MediaElement element : fileParser.getAllMediaElements()) {
if(element.getVideoStreams() != null) {
vStreams.addAll(element.getVideoStreams());
}
if(element.getAudioStreams() != null) {
aStreams.addAll(element.getAudioStreams());
}
if(element.getSubtitleStreams() != null) {
sStreams.addAll(element.getSubtitleStreams());
}
}
// Add media streams to database
mediaDao.createVideoStreams(vStreams);
mediaDao.createAudioStreams(aStreams);
mediaDao.createSubtitleStreams(sStreams);
// Add new playlists
if(!fileParser.getNewPlaylists().isEmpty()) {
for(Playlist playlist : fileParser.getNewPlaylists()) {
mediaDao.createPlaylist(playlist);
}
}
// Update existing playlists
if(!fileParser.getUpdatedPlaylists().isEmpty()) {
for(Playlist playlist : fileParser.getUpdatedPlaylists()) {
mediaDao.updatePlaylistLastScanned(playlist.getID(), fileParser.getScanTime());
}
}
// Remove files which no longer exist
mediaDao.removeDeletedMediaElements(folder.getPath(), fileParser.getScanTime());
mediaDao.removeDeletedPlaylists(folder.getPath(), fileParser.getScanTime());
// Update folder statistics
folder.setFolders(fileParser.getFolders());
folder.setFiles(fileParser.getFiles());
folder.setLastScanned(fileParser.getScanTime());
// Determine primary media type in folder
if(folder.getType() == null || folder.getType() == MediaFolder.ContentType.UNKNOWN) {
int audio = 0, video = 0, playlist;
// Get number of playlists
playlist = fileParser.getAllPlaylists().size();
// Iterate over media elements to determine number of each type
for(MediaElement element : fileParser.getAllMediaElements()) {
switch(element.getType()) {
case MediaElementType.AUDIO:
audio++;
break;
case MediaElementType.VIDEO:
video++;
break;
}
}
if(audio == 0 && video == 0 && playlist > 0) {
folder.setType(MediaFolder.ContentType.PLAYLIST);
} else if(audio > video) {
folder.setType(MediaFolder.ContentType.AUDIO);
} else if(video > audio) {
folder.setType(MediaFolder.ContentType.VIDEO);
}
}
settingsDao.updateMediaFolder(folder);
LogService.getInstance().addLogEntry(LogService.Level.INFO, CLASS_NAME, "Finished scanning media folder " + folder.getPath() + " (Items Scanned: " + fileParser.getTotal() + ", Folders: " + fileParser.getFolders() + ", Files: " + fileParser.getFiles() + ", Playlists: " + fileParser.getPlaylists() + ")", null);
} catch (Exception ex) {
LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Error scanning media folder " + folder.getPath(), ex);
}
}
private class ParseFiles extends SimpleFileVisitor<Path> {
Timestamp scanTime = new Timestamp(new Date().getTime());
private final MediaFolder folder;
private final Deque<MediaElement> directories = new ArrayDeque<>();
private final Deque<Deque<MediaElement>> directoryElements = new ArrayDeque<>();
private final Deque<NFOData> nfoData = new ArrayDeque<>();
private final HashSet<Path> directoriesToUpdate = new HashSet<>();
String log;
boolean directoryChanged = false;
private final List<MediaElement> newElements = new ArrayList<>();
private final List<MediaElement> updatedElements = new ArrayList<>();
private final List<Playlist> newPlaylists = new ArrayList<>();
private final List<Playlist> updatedPlaylists = new ArrayList<>();
private long files = 0, folders = 0, playlists = 0;
public ParseFiles(MediaFolder folder, String log) {
this.folder = folder;
this.log = log;
folders = 0;
files = 0;
playlists = 0;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attr) {
// Check if we need to scan this directory
if(!MediaUtils.containsMedia(dir.toFile(), true) && !PlaylistUtils.containsPlaylists(dir.toFile())) {
return SKIP_SIBLINGS;
}
LogUtils.writeToLog(log, "Parsing directory " + dir.toString(), Level.DEBUG);
// Initialise variables
directoryChanged = false;
directoryElements.add(new ArrayDeque<MediaElement>());
// Determine if this directory has changed
directoryChanged = folder.getLastScanned() == null || new Timestamp(attr.lastModifiedTime().toMillis()).after(folder.getLastScanned());
// If this is the root directory procede without processing
if(dir.toString().equals(folder.getPath())) {
return CONTINUE;
}
// Check if directory already has an associated media element
MediaElement directory = mediaDao.getMediaElementByPath(dir.toString());
if (directory == null) {
directory = getMediaElementFromPath(dir, attr);
directory.setType(MediaElementType.DIRECTORY);
}
if(directoryChanged || directory.getLastScanned().equals(scanTime)) {
// Add directory to update list
directoriesToUpdate.add(dir);
// Parse file name for media element attributes
directory = parseFileName(dir, directory);
// Determine if the directory should be excluded from categorised lists
if (isExcluded(dir.getFileName())) {
directory.setExcluded(true);
}
}
// Add directory to list
directories.add(directory);
return CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
// Determine type of file and how to process it
if(MediaUtils.isMediaFile(file)) {
LogUtils.writeToLog(log, "Parsing file " + file.toString(), Level.DEBUG);
// Update statistics
mTotal++;
files++;
// Check if media file already has an associated media element
MediaElement mediaElement = mediaDao.getMediaElementByPath(file.toString());
if (mediaElement == null) {
mediaElement = getMediaElementFromPath(file, attr);
mediaElement.setFormat(MediaUtils.getSMSContainer(FilenameUtils.getExtension(file.toString())));
}
// Determine if we need to process the file
if(folder.getLastScanned() == null || new Timestamp(attr.lastModifiedTime().toMillis()).after(folder.getLastScanned()) || mediaElement.getLastScanned().equals(scanTime)) {
LogUtils.writeToLog(log, "Processing file " + file.toString(), Level.DEBUG);
// Add parent directory to update list
directoriesToUpdate.add(file.getParent());
// Parse file name for media element attributes
mediaElement = parseFileName(file.getFileName(), mediaElement);
mediaElement.setSize(attr.size());
// Remove existing media streams and parse Metadata
if(!mediaDao.removeStreamsByMediaElementId(mediaElement.getID())) {
LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to remove streams from database for media element with ID " + mediaElement.getID(), null);
}
metadataParser.parse(mediaElement, log);
// If we don't support this media file move on...
if(mediaElement.getType() == MediaElementType.NONE) {
LogUtils.writeToLog(log, "No media streams found for file " + file.toString(), Level.DEBUG);
mediaDao.removeMediaElement(mediaElement.getID());
return CONTINUE;
}
}
// Add media element to list
directoryElements.peekLast().add(mediaElement);
} else if(PlaylistUtils.isPlaylist(file)) {
LogUtils.writeToLog(log, "Parsing playlist " + file.toString(), Level.DEBUG);
// Update statistics
mTotal++;
files++;
playlists++;
// Check if playlist already has an associated database entry
Playlist playlist = mediaDao.getPlaylistByPath(file.toString());
// Generate new playlist object or update existing one if necessary
if (playlist == null) {
playlist = getPlaylistFromPath(file);
newPlaylists.add(playlist);
} else {
if(folder.getLastScanned() == null || new Timestamp(attr.lastModifiedTime().toMillis()).after(folder.getLastScanned())) {
LogUtils.writeToLog(log, "Processing playlist " + file.toString(), Level.DEBUG);
playlist.setLastScanned(null);
}
// Add to list of playlists to update
updatedPlaylists.add(playlist);
}
} else if(isInfoFile(file)) {
// Determine if we need to parse this file
if(directoryChanged || folder.getLastScanned() == null || new Timestamp(attr.lastModifiedTime().toMillis()).after(folder.getLastScanned())) {
LogUtils.writeToLog(log, "Processing file " + file.toString(), Level.DEBUG);
nfoData.add(nfoParser.parse(file));
}
}
return CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
// Update statistics
mTotal++;
folders++;
MediaElement directory = null;
Deque<MediaElement> dirElements;
Deque<NFOData> dirData = new ArrayDeque<>();
// Retrieve directory from list
if(!directories.isEmpty()) {
directory = directories.removeLast();
}
// Get child elements for directory
dirElements = directoryElements.removeLast();
// Get NFO data for directory
if(!nfoData.isEmpty()) {
while(nfoData.peekLast() != null && nfoData.peekLast().getPath().getParent().equals(dir)) {
dirData.add(nfoData.removeLast());
}
}
// Process child media elements
for(MediaElement element : dirElements) {
if(!dirData.isEmpty()) {
boolean dataFound = false;
// Test for file specific data
for(NFOData test : dirData) {
if(test.getPath().getFileName().toString().contains(element.getTitle())) {
LogUtils.writeToLog(log, "Parsing NFO file " + test.getPath(), Level.DEBUG);
nfoParser.updateMediaElement(element, test);
dirData.remove(test);
dataFound = true;
break;
}
}
// Use generic data for directory
if(!dataFound) {
NFOData data = dirData.getFirst();
LogUtils.writeToLog(log, "Parsing NFO file " + data.getPath(), Level.DEBUG);
nfoParser.updateMediaElement(element, data);
}
}
// Set media elements to add or update
if(element.getLastScanned().equals(scanTime)) {
newElements.add(element);
} else {
element.setLastScanned(scanTime);
updatedElements.add(element);
}
LogUtils.writeToLog(log, element.toString(), Level.INSANE);
}
// Update directory element if necessary
if(directory != null && directoriesToUpdate.contains(dir)) {
LogUtils.writeToLog(log, "Processing directory " + dir.toString(), Level.DEBUG);
if(!dirData.isEmpty()) {
nfoParser.updateMediaElement(directory, dirData.removeFirst());
}
// Determine directory media type
directory.setDirectoryType(getDirectoryMediaType(dirElements));
// Check for common attributes if the directory contains media
if (!directory.getDirectoryType().equals(DirectoryMediaType.NONE)) {
// Get year if not set
if (directory.getYear() == 0) {
directory.setYear(getDirectoryYear(dirElements));
}
// Get common media attributes for the directory if available (artist, collection, TV series etc...)
if (directory.getDirectoryType().equals(DirectoryMediaType.AUDIO) || directory.getDirectoryType().equals(DirectoryMediaType.MIXED)) {
// Get directory description if possible.
String description = getDirectoryDescription(dirElements);
if (description != null) {
directory.setDescription(description);
}
// Get directory artist if possible.
String artist = getDirectoryArtist(dirElements);
// Try album artist
if (artist == null) {
artist = getDirectoryAlbumArtist(dirElements);
}
// Try root directory name
if (artist == null) {
artist = getDirectoryRoot(dir, folder.getPath());
}
// Set directory artist if found
if (artist != null) {
directory.setArtist(artist);
}
}
if (directory.getDirectoryType().equals(DirectoryMediaType.VIDEO)) {
// Get directory collection/series if possible.
String collection = getDirectoryCollection(dirElements);
// Try root directory name
if (collection == null) {
collection = getDirectoryRoot(dir, folder.getPath());
}
// Set directory collection if found
if (collection != null) {
directory.setCollection(collection);
}
}
} else {
// Exclude directories from categorised lists which do not directly contain media
directory.setExcluded(true);
}
LogUtils.writeToLog(log, directory.toString(), Level.INSANE);
}
// Set media elements to add or update
if(directory != null) {
if(directory.getLastScanned().equals(scanTime)) {
newElements.add(directory);
} else {
directory.setLastScanned(scanTime);
updatedElements.add(directory);
}
}
LogUtils.writeToLog(log, "Finished parsing directory " + dir.toString(), Level.DEBUG);
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Error parsing file " + file.toString(), exc);
return CONTINUE;
}
//
// Helper Functions
//
private boolean isInfoFile(Path path) {
return FilenameUtils.isExtension(path.getFileName().toString().toLowerCase(), INFO_FILE_TYPES);
}
private boolean isExcluded(Path path) {
for (String name : EXCLUDED_FILE_NAMES) {
if (path.getFileName().toString().equalsIgnoreCase(name)) {
return true;
}
}
return false;
}
// Return a new media element object for a given file
private MediaElement getMediaElementFromPath(Path path, BasicFileAttributes attr) {
MediaElement mediaElement = new MediaElement();
// Set ID
mediaElement.setID(UUID.randomUUID());
// Set common attributes
mediaElement.setCreated(new Timestamp(attr.creationTime().toMillis()));
mediaElement.setPath(path.toString());
mediaElement.setParentPath(path.getParent().toString());
mediaElement.setLastScanned(scanTime);
return mediaElement;
}
// Return a new playlist object for a given file
private Playlist getPlaylistFromPath(Path path) {
Playlist playlist = new Playlist();
// Set ID
playlist.setID(UUID.randomUUID());
// Set common attributes
playlist.setName(FilenameUtils.getBaseName(path.toString()));
playlist.setPath(path.toString());
playlist.setParentPath(path.getParent().toString());
playlist.setLastScanned(scanTime);
return playlist;
}
// Get title and other information from file name
private MediaElement parseFileName(Path path, MediaElement mediaElement) {
// Parse file name for title and year
Matcher matcher = FILE_NAME.matcher(path.getFileName().toString());
if (matcher.find()) {
mediaElement.setTitle(String.valueOf(matcher.group(1)));
if (matcher.group(2) != null) {
mediaElement.setYear(Short.parseShort(matcher.group(3)));
}
} else if(path.toFile().isDirectory()){
mediaElement.setTitle(path.getFileName().toString());
} else {
int extensionIndex = path.getFileName().toString().lastIndexOf(".");
mediaElement.setTitle(extensionIndex == -1 ? path.getFileName().toString() : path.getFileName().toString().substring(0, extensionIndex));
}
return mediaElement;
}
private Byte getDirectoryMediaType(Deque<MediaElement> mediaElements) {
Byte type = DirectoryMediaType.NONE;
for (MediaElement child : mediaElements) {
if (child.getType() == MediaElementType.AUDIO || child.getType() == MediaElementType.VIDEO) {
// Set an initial media type
if (type == DirectoryMediaType.NONE) {
type = child.getType();
} else if (child.getType().compareTo(type) != 0) {
return DirectoryMediaType.MIXED;
}
}
}
return type;
}
// Get directory year from child media elements
private Short getDirectoryYear(Deque<MediaElement> mediaElements) {
Short year = 0;
for (MediaElement child : mediaElements) {
if (child.getType() != MediaElementType.DIRECTORY) {
if (child.getYear() > 0) {
// Set an initial year
if (year == 0) {
year = child.getYear();
} else if (child.getYear().intValue() != year.intValue()) {
return 0;
}
}
}
}
return year;
}
// Get directory artist from child media elements
private String getDirectoryArtist(Deque<MediaElement> mediaElements) {
String artist = null;
for (MediaElement child : mediaElements) {
if (child.getType() == MediaElementType.AUDIO) {
if (child.getArtist() != null) {
// Set an initial artist
if (artist == null) {
artist = child.getArtist();
} else if (!child.getArtist().equals(artist)) {
return null;
}
}
}
}
return artist;
}
// Get directory album artist from child media elements
private String getDirectoryAlbumArtist(Deque<MediaElement> mediaElements) {
String albumArtist = null;
for (MediaElement child : mediaElements) {
if (child.getType() == MediaElementType.AUDIO) {
if (child.getAlbumArtist() != null) {
// Set an initial album artist
if (albumArtist == null) {
albumArtist = child.getAlbumArtist();
} else if (!child.getAlbumArtist().equals(albumArtist)) {
return null;
}
}
}
}
return albumArtist;
}
// Get directory collection from child media elements
private String getDirectoryCollection(Deque<MediaElement> mediaElements) {
String collection = null;
for (MediaElement child : mediaElements) {
if (child.getType() == MediaElementType.VIDEO) {
if (child.getCollection() != null) {
// Set an initial collection
if (collection == null) {
collection = child.getCollection();
} else if (!child.getCollection().equals(collection)) {
return null;
}
}
}
}
return collection;
}
// Get directory description from child media elements (audio only)
private String getDirectoryDescription(Deque<MediaElement> mediaElements) {
String description = null;
for (MediaElement child : mediaElements) {
if (child.getType() == MediaElementType.AUDIO) {
if (child.getDescription() != null) {
// Set an initial description
if (description == null) {
description = child.getDescription();
} else if (!child.getDescription().equals(description)) {
return null;
}
}
}
}
return description;
}
// Depending on directory structure this could return artist, series or collection based on the parent directory name.
private String getDirectoryRoot(Path path, String mediaFolderPath) {
File dir = path.toFile();
// Check variables
if (!dir.isDirectory()) {
return null;
}
// If the parent directory is the current media folder forget it
if (dir.getParent().equals(mediaFolderPath)) {
return null;
}
// Check if the root directory contains media, if so forget it
if (MediaUtils.containsMedia(dir.getParentFile(), false)) {
return null;
}
return dir.getParentFile().getName();
}
public long getTotal() {
return files + folders + playlists;
}
public long getPlaylists() {
return playlists;
}
public long getFiles() {
return files;
}
public long getFolders() {
return folders;
}
public Timestamp getScanTime() {
return scanTime;
}
public List<MediaElement> getNewMediaElements() {
return newElements;
}
public List<MediaElement> getUpdatedMediaElements() {
return updatedElements;
}
public List<MediaElement> getAllMediaElements() {
List<MediaElement> all = new ArrayList<>();
all.addAll(newElements);
all.addAll(updatedElements);
return all;
}
public List<Playlist> getNewPlaylists() {
return newPlaylists;
}
public List<Playlist> getUpdatedPlaylists() {
return updatedPlaylists;
}
public List<Playlist> getAllPlaylists() {
List<Playlist> all = new ArrayList<>();
all.addAll(newPlaylists);
all.addAll(updatedPlaylists);
return all;
}
}
}
| src/main/java/com/scooter1556/sms/server/service/ScannerService.java | /*
* Author: Scott Ware <[email protected]>
* Copyright (c) 2015 Scott Ware
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.scooter1556.sms.server.service;
import com.scooter1556.sms.server.SMS;
import com.scooter1556.sms.server.dao.MediaDao;
import com.scooter1556.sms.server.dao.SettingsDao;
import com.scooter1556.sms.server.domain.Job;
import com.scooter1556.sms.server.domain.MediaElement;
import com.scooter1556.sms.server.domain.MediaElement.AudioStream;
import com.scooter1556.sms.server.domain.MediaElement.DirectoryMediaType;
import com.scooter1556.sms.server.domain.MediaElement.MediaElementType;
import com.scooter1556.sms.server.domain.MediaElement.SubtitleStream;
import com.scooter1556.sms.server.domain.MediaElement.VideoStream;
import com.scooter1556.sms.server.domain.MediaFolder;
import com.scooter1556.sms.server.domain.Playlist;
import com.scooter1556.sms.server.service.LogService.Level;
import com.scooter1556.sms.server.service.parser.FrameParser;
import com.scooter1556.sms.server.service.parser.MetadataParser;
import com.scooter1556.sms.server.service.parser.NFOParser;
import com.scooter1556.sms.server.service.parser.NFOParser.NFOData;
import com.scooter1556.sms.server.utilities.LogUtils;
import com.scooter1556.sms.server.utilities.MediaUtils;
import com.scooter1556.sms.server.utilities.PlaylistUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import static java.nio.file.FileVisitResult.CONTINUE;
import static java.nio.file.FileVisitResult.SKIP_SIBLINGS;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.sql.Timestamp;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Date;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
@EnableScheduling
public class ScannerService implements DisposableBean {
private static final String CLASS_NAME = "MediaScannerService";
@Autowired
private SettingsDao settingsDao;
@Autowired
private MediaDao mediaDao;
@Autowired
private MetadataParser metadataParser;
@Autowired
private NFOParser nfoParser;
@Autowired
private FrameParser frameParser;
@Autowired
private PlaylistService playlistService;
@Autowired
private SessionService sessionService;
private static final String[] INFO_FILE_TYPES = {"nfo"};
private static final String[] EXCLUDED_FILE_NAMES = {"Extras","extras"};
private static final Pattern FILE_NAME = Pattern.compile("(.+)(\\s+[(\\[](\\d{4})[)\\]])$?");
private long mTotal = 0, dTotal = 0;
// Media scanning thread pool
ExecutorService scanningThreads = null;
// Deep scan executor
ExecutorService deepScanExecutor = null;
// Logs
String deepScanLog;
// End scanning jobs on application exit
@Override
public void destroy() {
if(isScanning()) {
scanningThreads.shutdownNow();
}
stopDeepScan();
}
// Check for inactive jobs at midnight
@Scheduled(cron="#{config.deepScanSchedule}")
public int startDeepScan() {
// Check a scanning process is not already active
if (isScanning() || isDeepScanning()) {
return SMS.Status.NOT_ALLOWED;
}
// Check there are no active sessions which may be affected
if(sessionService.getNumSessions() > 0) {
return SMS.Status.NOT_ALLOWED;
}
// List of streams to scan
List<VideoStream> streams = mediaDao.getIncompleteVideoStreams();
// Start scanning
if(streams.isEmpty()) {
return SMS.Status.NOT_REQUIRED;
}
// Start scanning
deepScan(streams);
LogService.getInstance().addLogEntry(LogService.Level.INFO, CLASS_NAME, "Started deep scan of media.", null);
return SMS.Status.OK;
}
//
// Returns whether media folders are currently being scanned.
//
public synchronized boolean isScanning() {
// Check if we have any scanning threads
if(scanningThreads == null) {
return false;
}
// Check if scanning threads have terminated
return !scanningThreads.isTerminated();
}
//
// Returns whether deep scan is in progress.
//
public synchronized boolean isDeepScanning() {
if(deepScanExecutor == null) {
return false;
}
return !deepScanExecutor.isTerminated();
}
//
// Returns the number of files scanned so far.
//
public long getScanCount() {
return mTotal;
}
//
// Returns the number of streams scanned so far.
//
public long getDeepScanCount() {
return dTotal;
}
//
// Scans media in a separate thread.
//
public synchronized void startMediaScanning(List<MediaFolder> folders) {
// Check if media is already being scanned
if (isScanning()) {
return;
}
// Stop deep scanning if in progress
stopDeepScan();
// Reset scan count
mTotal = 0;
// Log
final String log = SettingsService.getInstance().getLogDirectory() + "/mediascanner-" + new Timestamp(new Date().getTime()) + ".log";
// Create media scanning threads
scanningThreads = Executors.newFixedThreadPool(folders.size());
// Submit scanning jobs for each media folder
for (final MediaFolder folder : folders) {
scanningThreads.submit(new Runnable() {
@Override
public void run() {
scanMediaFolder(folder, log);
}
});
}
// Shutdown thread pool so no further threads can be added
scanningThreads.shutdown();
}
//
// Scans playlist in a separate thread.
//
public synchronized void startPlaylistScanning(List<Playlist> playlists) {
// Check if media is already being scanned
if (isScanning()) {
return;
}
// Create media scanning threads
scanningThreads = Executors.newFixedThreadPool(playlists.size());
// Submit processing jobs for each playlist
for (final Playlist playlist : playlists) {
scanningThreads.submit(new Runnable() {
@Override
public void run() {
scanPlaylist(playlist);
}
});
}
// Shutdown thread pool so no further threads can be added
scanningThreads.shutdown();
}
//
// Performs a deep scan of media streams
//
private synchronized void deepScan(final List<VideoStream> streams) {
// Create log file
Timestamp scanTime = new Timestamp(new Date().getTime());
deepScanLog = SettingsService.getInstance().getLogDirectory() + "/deepscan-" + scanTime + ".log";
// Reset counter
dTotal = 0;
// Create media scanning threads
deepScanExecutor = Executors.newSingleThreadExecutor();
deepScanExecutor.submit(new Runnable() {
@Override
public void run() {
LogUtils.writeToLog(deepScanLog, "Found " + streams.size() + " streams to parse.", Level.DEBUG);
for(VideoStream stream : streams) {
dTotal ++;
LogUtils.writeToLog(deepScanLog, "Scanning stream " + stream.getStreamId() + " for media element with id " + stream.getMediaElementId(), Level.DEBUG);
VideoStream update = frameParser.parse(stream);
if(update != null) {
mediaDao.updateVideoStream(update);
LogUtils.writeToLog(deepScanLog, stream.toString(), Level.DEBUG);
}
LogUtils.writeToLog(deepScanLog, "Finished Scanning stream " + stream.getStreamId() + " for media element with id " + stream.getMediaElementId(), Level.DEBUG);
}
}
});
deepScanExecutor.shutdownNow();
}
public void stopDeepScan() {
if(deepScanExecutor != null && !deepScanExecutor.isTerminated()) {
deepScanExecutor.shutdownNow();
frameParser.stop();
LogUtils.writeToLog(deepScanLog, "Deep scan terminated early!", Level.DEBUG);
}
}
private void scanPlaylist(Playlist playlist) {
// Check this is a file based playlist
if(playlist.getPath() == null || playlist.getPath().isEmpty()) {
return;
}
LogService.getInstance().addLogEntry(LogService.Level.INFO, CLASS_NAME, "Scanning playlist " + playlist.getPath(), null);
// Remove existing playlist content
mediaDao.removePlaylistContent(playlist.getID());
// Parse playlist
List<MediaElement> mediaElements = playlistService.parsePlaylist(playlist.getPath());
if(mediaElements == null || mediaElements.isEmpty()) {
LogService.getInstance().addLogEntry(LogService.Level.INFO, CLASS_NAME, "No content found for playlist " + playlist.getPath(), null);
return;
}
// Update playlist content
mediaDao.setPlaylistContent(playlist.getID(), mediaElements);
LogService.getInstance().addLogEntry(LogService.Level.INFO, CLASS_NAME, "Finished scanning playlist " + playlist.getPath() + " (Found " + mediaElements.size() + " items)", null);
}
private void scanMediaFolder(MediaFolder folder, String log) {
Path path = FileSystems.getDefault().getPath(folder.getPath());
ParseFiles fileParser = new ParseFiles(folder, log);
try {
// Start Scan directory
LogService.getInstance().addLogEntry(LogService.Level.INFO, CLASS_NAME, "Scanning media folder " + folder.getPath(), null);
Files.walkFileTree(path, fileParser);
// Add new media elements in database
if(!fileParser.getNewMediaElements().isEmpty()) {
mediaDao.createMediaElements(fileParser.getNewMediaElements());
}
// Update existing media elements in database
if(!fileParser.getUpdatedMediaElements().isEmpty()) {
mediaDao.updateMediaElementsByID(fileParser.getUpdatedMediaElements());
}
// Extract media streams from parsed media elements
List<VideoStream> vStreams = new ArrayList<>();
List<AudioStream> aStreams = new ArrayList<>();
List<SubtitleStream> sStreams = new ArrayList<>();
for(MediaElement element : fileParser.getAllMediaElements()) {
if(element.getVideoStreams() != null) {
vStreams.addAll(element.getVideoStreams());
}
if(element.getAudioStreams() != null) {
aStreams.addAll(element.getAudioStreams());
}
if(element.getSubtitleStreams() != null) {
sStreams.addAll(element.getSubtitleStreams());
}
}
// Add media streams to database
mediaDao.createVideoStreams(vStreams);
mediaDao.createAudioStreams(aStreams);
mediaDao.createSubtitleStreams(sStreams);
// Add new playlists
if(!fileParser.getNewPlaylists().isEmpty()) {
for(Playlist playlist : fileParser.getNewPlaylists()) {
mediaDao.createPlaylist(playlist);
}
}
// Update existing playlists
if(!fileParser.getUpdatedPlaylists().isEmpty()) {
for(Playlist playlist : fileParser.getUpdatedPlaylists()) {
mediaDao.updatePlaylistLastScanned(playlist.getID(), fileParser.getScanTime());
}
}
// Remove files which no longer exist
mediaDao.removeDeletedMediaElements(folder.getPath(), fileParser.getScanTime());
mediaDao.removeDeletedPlaylists(folder.getPath(), fileParser.getScanTime());
// Update folder statistics
folder.setFolders(fileParser.getFolders());
folder.setFiles(fileParser.getFiles());
folder.setLastScanned(fileParser.getScanTime());
// Determine primary media type in folder
if(folder.getType() == null || folder.getType() == MediaFolder.ContentType.UNKNOWN) {
int audio = 0, video = 0, playlist;
// Get number of playlists
playlist = fileParser.getAllPlaylists().size();
// Iterate over media elements to determine number of each type
for(MediaElement element : fileParser.getAllMediaElements()) {
switch(element.getType()) {
case MediaElementType.AUDIO:
audio++;
break;
case MediaElementType.VIDEO:
video++;
break;
}
}
if(audio == 0 && video == 0 && playlist > 0) {
folder.setType(MediaFolder.ContentType.PLAYLIST);
} else if(audio > video) {
folder.setType(MediaFolder.ContentType.AUDIO);
} else if(video > audio) {
folder.setType(MediaFolder.ContentType.VIDEO);
}
}
settingsDao.updateMediaFolder(folder);
LogService.getInstance().addLogEntry(LogService.Level.INFO, CLASS_NAME, "Finished scanning media folder " + folder.getPath() + " (Items Scanned: " + fileParser.getTotal() + ", Folders: " + fileParser.getFolders() + ", Files: " + fileParser.getFiles() + ", Playlists: " + fileParser.getPlaylists() + ")", null);
} catch (Exception ex) {
LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Error scanning media folder " + folder.getPath(), ex);
}
}
private class ParseFiles extends SimpleFileVisitor<Path> {
Timestamp scanTime = new Timestamp(new Date().getTime());
private final MediaFolder folder;
private final Deque<MediaElement> directories = new ArrayDeque<>();
private final Deque<Deque<MediaElement>> directoryElements = new ArrayDeque<>();
private final Deque<NFOData> nfoData = new ArrayDeque<>();
private final HashSet<Path> directoriesToUpdate = new HashSet<>();
String log;
boolean directoryChanged = false;
private final List<MediaElement> newElements = new ArrayList<>();
private final List<MediaElement> updatedElements = new ArrayList<>();
private final List<Playlist> newPlaylists = new ArrayList<>();
private final List<Playlist> updatedPlaylists = new ArrayList<>();
private long files = 0, folders = 0, playlists = 0;
public ParseFiles(MediaFolder folder, String log) {
this.folder = folder;
this.log = log;
folders = 0;
files = 0;
playlists = 0;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attr) {
// Check if we need to scan this directory
if(!MediaUtils.containsMedia(dir.toFile(), true) && !PlaylistUtils.containsPlaylists(dir.toFile())) {
return SKIP_SIBLINGS;
}
LogUtils.writeToLog(log, "Parsing directory " + dir.toString(), Level.DEBUG);
// Initialise variables
directoryChanged = false;
directoryElements.add(new ArrayDeque<MediaElement>());
// Determine if this directory has changed
directoryChanged = folder.getLastScanned() == null || new Timestamp(attr.lastModifiedTime().toMillis()).after(folder.getLastScanned());
// If this is the root directory procede without processing
if(dir.toString().equals(folder.getPath())) {
return CONTINUE;
}
// Check if directory already has an associated media element
MediaElement directory = mediaDao.getMediaElementByPath(dir.toString());
if (directory == null) {
directory = getMediaElementFromPath(dir, attr);
directory.setType(MediaElementType.DIRECTORY);
}
if(directoryChanged || directory.getLastScanned().equals(scanTime)) {
// Add directory to update list
directoriesToUpdate.add(dir);
// Parse file name for media element attributes
directory = parseFileName(dir, directory);
// Determine if the directory should be excluded from categorised lists
if (isExcluded(dir.getFileName())) {
directory.setExcluded(true);
}
}
// Add directory to list
directories.add(directory);
return CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
// Determine type of file and how to process it
if(MediaUtils.isMediaFile(file)) {
LogUtils.writeToLog(log, "Parsing file " + file.toString(), Level.DEBUG);
// Update statistics
mTotal++;
files++;
// Check if media file already has an associated media element
MediaElement mediaElement = mediaDao.getMediaElementByPath(file.toString());
if (mediaElement == null) {
mediaElement = getMediaElementFromPath(file, attr);
mediaElement.setFormat(MediaUtils.getSMSContainer(FilenameUtils.getExtension(file.toString())));
}
// Determine if we need to process the file
if(folder.getLastScanned() == null || new Timestamp(attr.lastModifiedTime().toMillis()).after(folder.getLastScanned()) || mediaElement.getLastScanned().equals(scanTime)) {
LogUtils.writeToLog(log, "Processing file " + file.toString(), Level.DEBUG);
// Add parent directory to update list
directoriesToUpdate.add(file.getParent());
// Parse file name for media element attributes
mediaElement = parseFileName(file.getFileName(), mediaElement);
mediaElement.setSize(attr.size());
// Remove existing media streams and parse Metadata
if(!mediaDao.removeStreamsByMediaElementId(mediaElement.getID())) {
LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Failed to remove streams from database for media element with ID " + mediaElement.getID(), null);
}
metadataParser.parse(mediaElement, log);
// If we don't support this media file move on...
if(mediaElement.getType() == MediaElementType.NONE) {
LogUtils.writeToLog(log, "No media streams found for file " + file.toString(), Level.DEBUG);
mediaDao.removeMediaElement(mediaElement.getID());
return CONTINUE;
}
}
// Add media element to list
directoryElements.peekLast().add(mediaElement);
} else if(PlaylistUtils.isPlaylist(file)) {
LogUtils.writeToLog(log, "Parsing playlist " + file.toString(), Level.DEBUG);
// Update statistics
mTotal++;
files++;
playlists++;
// Check if playlist already has an associated database entry
Playlist playlist = mediaDao.getPlaylistByPath(file.toString());
// Generate new playlist object or update existing one if necessary
if (playlist == null) {
playlist = getPlaylistFromPath(file);
newPlaylists.add(playlist);
} else {
if(folder.getLastScanned() == null || new Timestamp(attr.lastModifiedTime().toMillis()).after(folder.getLastScanned())) {
LogUtils.writeToLog(log, "Processing playlist " + file.toString(), Level.DEBUG);
playlist.setLastScanned(null);
}
// Add to list of playlists to update
updatedPlaylists.add(playlist);
}
} else if(isInfoFile(file)) {
// Determine if we need to parse this file
if(directoryChanged || folder.getLastScanned() == null || new Timestamp(attr.lastModifiedTime().toMillis()).after(folder.getLastScanned())) {
LogUtils.writeToLog(log, "Processing file " + file.toString(), Level.DEBUG);
nfoData.add(nfoParser.parse(file));
}
}
return CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
// Update statistics
mTotal++;
folders++;
MediaElement directory = null;
Deque<MediaElement> dirElements;
Deque<NFOData> dirData = new ArrayDeque<>();
// Retrieve directory from list
if(!directories.isEmpty()) {
directory = directories.removeLast();
}
// Get child elements for directory
dirElements = directoryElements.removeLast();
// Get NFO data for directory
if(!nfoData.isEmpty()) {
while(nfoData.peekLast() != null && nfoData.peekLast().getPath().getParent().equals(dir)) {
dirData.add(nfoData.removeLast());
}
}
// Process child media elements
for(MediaElement element : dirElements) {
if(!dirData.isEmpty()) {
boolean dataFound = false;
// Test for file specific data
for(NFOData test : dirData) {
if(test.getPath().getFileName().toString().contains(element.getTitle())) {
LogUtils.writeToLog(log, "Parsing NFO file " + test.getPath(), Level.DEBUG);
nfoParser.updateMediaElement(element, test);
dirData.remove(test);
dataFound = true;
break;
}
}
// Use generic data for directory
if(!dataFound) {
NFOData data = dirData.getFirst();
LogUtils.writeToLog(log, "Parsing NFO file " + data.getPath(), Level.DEBUG);
nfoParser.updateMediaElement(element, data);
}
}
// Set media elements to add or update
if(element.getLastScanned().equals(scanTime)) {
newElements.add(element);
} else {
element.setLastScanned(scanTime);
updatedElements.add(element);
}
LogUtils.writeToLog(log, element.toString(), Level.INSANE);
}
// Update directory element if necessary
if(directory != null && directoriesToUpdate.contains(dir)) {
LogUtils.writeToLog(log, "Processing directory " + dir.toString(), Level.DEBUG);
if(!dirData.isEmpty()) {
nfoParser.updateMediaElement(directory, dirData.removeFirst());
}
// Determine directory media type
directory.setDirectoryType(getDirectoryMediaType(dirElements));
// Check for common attributes if the directory contains media
if (!directory.getDirectoryType().equals(DirectoryMediaType.NONE)) {
// Get year if not set
if (directory.getYear() == 0) {
directory.setYear(getDirectoryYear(dirElements));
}
// Get common media attributes for the directory if available (artist, collection, TV series etc...)
if (directory.getDirectoryType().equals(DirectoryMediaType.AUDIO) || directory.getDirectoryType().equals(DirectoryMediaType.MIXED)) {
// Get directory description if possible.
String description = getDirectoryDescription(dirElements);
if (description != null) {
directory.setDescription(description);
}
// Get directory artist if possible.
String artist = getDirectoryArtist(dirElements);
// Try album artist
if (artist == null) {
artist = getDirectoryAlbumArtist(dirElements);
}
// Try root directory name
if (artist == null) {
artist = getDirectoryRoot(dir, folder.getPath());
}
// Set directory artist if found
if (artist != null) {
directory.setArtist(artist);
}
}
if (directory.getDirectoryType().equals(DirectoryMediaType.VIDEO)) {
// Get directory collection/series if possible.
String collection = getDirectoryCollection(dirElements);
// Try root directory name
if (collection == null) {
collection = getDirectoryRoot(dir, folder.getPath());
}
// Set directory collection if found
if (collection != null) {
directory.setCollection(collection);
}
}
} else {
// Exclude directories from categorised lists which do not directly contain media
directory.setExcluded(true);
}
LogUtils.writeToLog(log, directory.toString(), Level.INSANE);
}
// Set media elements to add or update
if(directory != null) {
if(directory.getLastScanned().equals(scanTime)) {
newElements.add(directory);
} else {
directory.setLastScanned(scanTime);
updatedElements.add(directory);
}
}
LogUtils.writeToLog(log, "Finished parsing directory " + dir.toString(), Level.DEBUG);
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Error parsing file " + file.toString(), exc);
return CONTINUE;
}
//
// Helper Functions
//
private boolean isInfoFile(Path path) {
return FilenameUtils.isExtension(path.getFileName().toString().toLowerCase(), INFO_FILE_TYPES);
}
private boolean isExcluded(Path path) {
for (String name : EXCLUDED_FILE_NAMES) {
if (path.getFileName().toString().equals(name)) {
return true;
}
}
return false;
}
// Return a new media element object for a given file
private MediaElement getMediaElementFromPath(Path path, BasicFileAttributes attr) {
MediaElement mediaElement = new MediaElement();
// Set ID
mediaElement.setID(UUID.randomUUID());
// Set common attributes
mediaElement.setCreated(new Timestamp(attr.creationTime().toMillis()));
mediaElement.setPath(path.toString());
mediaElement.setParentPath(path.getParent().toString());
mediaElement.setLastScanned(scanTime);
return mediaElement;
}
// Return a new playlist object for a given file
private Playlist getPlaylistFromPath(Path path) {
Playlist playlist = new Playlist();
// Set ID
playlist.setID(UUID.randomUUID());
// Set common attributes
playlist.setName(FilenameUtils.getBaseName(path.toString()));
playlist.setPath(path.toString());
playlist.setParentPath(path.getParent().toString());
playlist.setLastScanned(scanTime);
return playlist;
}
// Get title and other information from file name
private MediaElement parseFileName(Path path, MediaElement mediaElement) {
// Parse file name for title and year
Matcher matcher = FILE_NAME.matcher(path.getFileName().toString());
if (matcher.find()) {
mediaElement.setTitle(String.valueOf(matcher.group(1)));
if (matcher.group(2) != null) {
mediaElement.setYear(Short.parseShort(matcher.group(3)));
}
} else if(path.toFile().isDirectory()){
mediaElement.setTitle(path.getFileName().toString());
} else {
int extensionIndex = path.getFileName().toString().lastIndexOf(".");
mediaElement.setTitle(extensionIndex == -1 ? path.getFileName().toString() : path.getFileName().toString().substring(0, extensionIndex));
}
return mediaElement;
}
private Byte getDirectoryMediaType(Deque<MediaElement> mediaElements) {
Byte type = DirectoryMediaType.NONE;
for (MediaElement child : mediaElements) {
if (child.getType() == MediaElementType.AUDIO || child.getType() == MediaElementType.VIDEO) {
// Set an initial media type
if (type == DirectoryMediaType.NONE) {
type = child.getType();
} else if (child.getType().compareTo(type) != 0) {
return DirectoryMediaType.MIXED;
}
}
}
return type;
}
// Get directory year from child media elements
private Short getDirectoryYear(Deque<MediaElement> mediaElements) {
Short year = 0;
for (MediaElement child : mediaElements) {
if (child.getType() != MediaElementType.DIRECTORY) {
if (child.getYear() > 0) {
// Set an initial year
if (year == 0) {
year = child.getYear();
} else if (child.getYear().intValue() != year.intValue()) {
return 0;
}
}
}
}
return year;
}
// Get directory artist from child media elements
private String getDirectoryArtist(Deque<MediaElement> mediaElements) {
String artist = null;
for (MediaElement child : mediaElements) {
if (child.getType() == MediaElementType.AUDIO) {
if (child.getArtist() != null) {
// Set an initial artist
if (artist == null) {
artist = child.getArtist();
} else if (!child.getArtist().equals(artist)) {
return null;
}
}
}
}
return artist;
}
// Get directory album artist from child media elements
private String getDirectoryAlbumArtist(Deque<MediaElement> mediaElements) {
String albumArtist = null;
for (MediaElement child : mediaElements) {
if (child.getType() == MediaElementType.AUDIO) {
if (child.getAlbumArtist() != null) {
// Set an initial album artist
if (albumArtist == null) {
albumArtist = child.getAlbumArtist();
} else if (!child.getAlbumArtist().equals(albumArtist)) {
return null;
}
}
}
}
return albumArtist;
}
// Get directory collection from child media elements
private String getDirectoryCollection(Deque<MediaElement> mediaElements) {
String collection = null;
for (MediaElement child : mediaElements) {
if (child.getType() == MediaElementType.VIDEO) {
if (child.getCollection() != null) {
// Set an initial collection
if (collection == null) {
collection = child.getCollection();
} else if (!child.getCollection().equals(collection)) {
return null;
}
}
}
}
return collection;
}
// Get directory description from child media elements (audio only)
private String getDirectoryDescription(Deque<MediaElement> mediaElements) {
String description = null;
for (MediaElement child : mediaElements) {
if (child.getType() == MediaElementType.AUDIO) {
if (child.getDescription() != null) {
// Set an initial description
if (description == null) {
description = child.getDescription();
} else if (!child.getDescription().equals(description)) {
return null;
}
}
}
}
return description;
}
// Depending on directory structure this could return artist, series or collection based on the parent directory name.
private String getDirectoryRoot(Path path, String mediaFolderPath) {
File dir = path.toFile();
// Check variables
if (!dir.isDirectory()) {
return null;
}
// If the parent directory is the current media folder forget it
if (dir.getParent().equals(mediaFolderPath)) {
return null;
}
// Check if the root directory contains media, if so forget it
if (MediaUtils.containsMedia(dir.getParentFile(), false)) {
return null;
}
return dir.getParentFile().getName();
}
public long getTotal() {
return files + folders + playlists;
}
public long getPlaylists() {
return playlists;
}
public long getFiles() {
return files;
}
public long getFolders() {
return folders;
}
public Timestamp getScanTime() {
return scanTime;
}
public List<MediaElement> getNewMediaElements() {
return newElements;
}
public List<MediaElement> getUpdatedMediaElements() {
return updatedElements;
}
public List<MediaElement> getAllMediaElements() {
List<MediaElement> all = new ArrayList<>();
all.addAll(newElements);
all.addAll(updatedElements);
return all;
}
public List<Playlist> getNewPlaylists() {
return newPlaylists;
}
public List<Playlist> getUpdatedPlaylists() {
return updatedPlaylists;
}
public List<Playlist> getAllPlaylists() {
List<Playlist> all = new ArrayList<>();
all.addAll(newPlaylists);
all.addAll(updatedPlaylists);
return all;
}
}
}
| Scanning: Add 'Trailers' directory to excluded list
Signed-off-by: Scott Ware <[email protected]>
| src/main/java/com/scooter1556/sms/server/service/ScannerService.java | Scanning: Add 'Trailers' directory to excluded list |
|
Java | lgpl-2.1 | 22d7cc5cfb310ae8d04c0f47d62fe99eb19229b3 | 0 | cfallin/soot,cfallin/soot,anddann/soot,plast-lab/soot,xph906/SootNew,xph906/SootNew,xph906/SootNew,anddann/soot,plast-lab/soot,mbenz89/soot,anddann/soot,mbenz89/soot,cfallin/soot,plast-lab/soot,xph906/SootNew,anddann/soot,mbenz89/soot,cfallin/soot,mbenz89/soot | package soot.toolkits.astmetrics;
import java.util.*;
import polyglot.ast.*;
import polyglot.visit.NodeVisitor;
public class StmtSumWeightedByDepth extends ASTMetric {
int currentDepth;
int sum;
int maxDepth;
int numNodes;
//int returnSum;
Stack labelNodesSoFar = new Stack();
ArrayList blocksWithAbruptFlow = new ArrayList();
public static boolean tmpAbruptChecker = false;
public StmtSumWeightedByDepth(Node node){
super(node);
}
public void reset() {
currentDepth = 1; //inside a class
maxDepth = 1;
sum = 0;
numNodes = 0;
//returnSum =0;
}
public void addMetrics(ClassData data) {
data.addMetric(new MetricData("MaxDepth",new Integer(maxDepth)));
data.addMetric(new MetricData("D-W-Complexity",new Integer(sum)));
data.addMetric(new MetricData("AST-Node-Count",new Integer(numNodes)));
//data.addMetric(new MetricData("Return-Depth-Sum",new Integer(returnSum)));
}
private void increaseDepth(){
currentDepth++;
if(currentDepth > maxDepth)
maxDepth = currentDepth;
}
private void decreaseDepth(){
currentDepth--;
}
/*
* List of Node types which increase depth of traversal!!!
* Any construct where one can have a { } increases the depth
* hence even though if(cond) stmt doesnt expicitly use a block
* its depth is still +1 when executing the stmt
*
* If the "if" stmt has code if(cond) { stmt } OR if(cond) stmt this will only increase the depth by 1 (ignores compound stmt blocks)
*
* If, Loop, Try, Synch, ProcDecl, Init, Switch, LocalClassDecl .... add currentDepth to sum and then increase depth by one
* irrespective of how many stmts there are in the body
*
* Block ... if it is a block within a block, add currentDepth plus increment depth ONLY if it has abrupt flow out of it.
*/
public NodeVisitor enter(Node parent, Node n){
numNodes++;
if (n instanceof CodeDecl) {
// maintain stack of label arrays (can't have label from inside method to outside)
labelNodesSoFar.push(new ArrayList());
}
else if (n instanceof Labeled) {
// add any labels we find to the array
((ArrayList)labelNodesSoFar.peek()).add(((Labeled)n).label());
}
if(n instanceof If || n instanceof Loop || n instanceof Try || n instanceof Switch
|| n instanceof LocalClassDecl || n instanceof Synchronized
|| n instanceof ProcedureDecl || n instanceof Initializer ){
sum += currentDepth*2;
increaseDepth();
} else if (parent instanceof Block && n instanceof Block) {
StmtSumWeightedByDepth.tmpAbruptChecker = false;
n.visit(new NodeVisitor() {
// extended NodeVisitor that checks for branching out of a block
public NodeVisitor enter(Node parent, Node node){
if(node instanceof Branch) {
Branch b = (Branch)node;
// null branching out of a plain block is NOT ALLOWED!
if (b.label() != null && ((ArrayList)labelNodesSoFar.peek()).contains(b.label()))
{
StmtSumWeightedByDepth.tmpAbruptChecker = true;
}
}
return enter(node);
}
// this method simply stops further node visiting if we found our info
public Node override(Node parent, Node node) {
if (StmtSumWeightedByDepth.tmpAbruptChecker)
return node;
return null;
}
});
if (StmtSumWeightedByDepth.tmpAbruptChecker)
{
blocksWithAbruptFlow.add(n);
sum += currentDepth*2;
increaseDepth();
}
} else {
//if(n instanceof Return){
// returnSum += currentDepth;
// System.out.println("RETURN111111111111111111111111111111111"+currentDepth);
//}
sum+= currentDepth;
}
return enter(n);
}
public Node leave(Node old, Node n, NodeVisitor v){
// stack maintenance, if leaving a method
if (n instanceof CodeDecl)
labelNodesSoFar.pop();
if(n instanceof If || n instanceof Loop || n instanceof Try || n instanceof Switch
|| n instanceof LocalClassDecl || n instanceof Synchronized
|| n instanceof ProcedureDecl || n instanceof Initializer ) {
decreaseDepth();
} else if (n instanceof Block && blocksWithAbruptFlow.contains(n)) {
decreaseDepth();
}
return n;
}
}
| src/soot/toolkits/astmetrics/StmtSumWeightedByDepth.java | package soot.toolkits.astmetrics;
import polyglot.ast.*;
import polyglot.visit.NodeVisitor;
public class StmtSumWeightedByDepth extends ASTMetric {
int currentDepth;
int sum;
int maxDepth;
int returnSum;
public StmtSumWeightedByDepth(Node node){
super(node);
}
public void reset() {
// TODO Auto-generated method stub
currentDepth = 1; //inside a class
maxDepth = 1;
sum = 0;
returnSum =0;
}
public void addMetrics(ClassData data) {
// TODO Auto-generated method stub
data.addMetric(new MetricData("MaxDepth",new Integer(maxDepth)));
data.addMetric(new MetricData("D-W-Complexity",new Integer(sum)));
data.addMetric(new MetricData("Return-Depth-Sum",new Integer(returnSum)));
}
private void increaseDepth(){
currentDepth++;
if(currentDepth > maxDepth)
maxDepth = currentDepth;
}
private void decreaseDepth(){
currentDepth--;
}
/*
* List of Node types which increase depth of traversal!!!
* Any construct where one can have a { } increases the depth
* hence even though if(cond) stmt doesnt expicitly use a block
* its depth is still +1 when executing the stmt
*
* If the "if" stmt has code if(cond) { stmt } this will actually increase the depth by 2 first by the if and then by the block
*
* If .... add currentDepth to sum and then increase depth by one for both then and else branch irrespective of how many stmts there are in the body
* Loop (Takes care of do while and for): Add currentDepth then increment by 1
* Block ... add currentDepth plus increment depth
* LocalClassDecl.... add currentDepth plus increment since everything inside is more complex
*
* Try ... add currentDepth (Dont incremenet as this will be done by the respective BLOCK as all try catch and finally are blocks!!
* Synchronized ... add currentDepth....dont increment depth as this will be done by the block as synchs are always blocks)
* ProcedureDecl (methods and constructors. thats where currentDepth is ONE as these belong to the class) ...
* Initializer (Handles static and non static class level chunks of code)
* Switch .... add current Depth however since each case is necessarily a block dont increment depth that WILL get incremented
*
*/
public NodeVisitor enter(Node parent, Node n){
if(n instanceof If || n instanceof Loop || n instanceof Block || n instanceof LocalClassDecl){
sum += currentDepth*3;
increaseDepth();
}
else if(n instanceof Try || n instanceof Synchronized || n instanceof ProcedureDecl || n instanceof Initializer || n instanceof Switch){
sum+= currentDepth*3;
}
else{
if(n instanceof Return){
returnSum += currentDepth;
System.out.println("RETURN111111111111111111111111111111111"+currentDepth);
}
sum+= currentDepth;
}
return enter(n);
}
public Node leave(Node old, Node n, NodeVisitor v){
if(n instanceof If || n instanceof Loop || n instanceof Block || n instanceof LocalClassDecl){
decreaseDepth();
}
return n;
}
}
| Added Node counting
Added blocks in blocks depth complexity check
Removed return stmt depth sum
| src/soot/toolkits/astmetrics/StmtSumWeightedByDepth.java | Added Node counting Added blocks in blocks depth complexity check Removed return stmt depth sum |
|
Java | lgpl-2.1 | 924d0bba7065445ca70c079a8ea2f153236a96b3 | 0 | MenoData/Time4J | package net.time4j.scale;
import net.time4j.Moment;
import net.time4j.PlainDate;
import net.time4j.PlainTime;
import net.time4j.PlainTimestamp;
import net.time4j.Platform;
import net.time4j.ZonalDateTime;
import net.time4j.format.TemporalFormatter;
import net.time4j.tz.Timezone;
import net.time4j.tz.ZonalOffset;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.text.ParseException;
import java.util.Locale;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@RunWith(JUnit4.class)
public class ZonalDateTimeTest {
@Test
public void toMoment() {
Moment moment = Moment.of(1278028824, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
assertThat(
moment.inZonalView(tz.getID()).toMoment(),
is(moment));
}
@Test
public void toTimestamp() {
Moment moment = Moment.of(1278028824, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
assertThat(
moment.inZonalView(tz.getID()).toTimestamp(),
is(PlainTimestamp.of(2012, 7, 1, 8, 59, 59)));
}
@Test
public void hasTimezone() {
Moment moment = Moment.of(1278028824, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
assertThat(
moment.inZonalView(tz.getID()).hasTimezone(),
is(true));
}
@Test
public void getTimezone() {
Moment moment = Moment.of(1278028824, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
assertThat(
moment.inZonalView(tz.getID()).getTimezone(),
is(tz.getID()));
}
@Test
public void isLeapsecond() {
Moment moment = Moment.of(1278028824, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
assertThat(
moment.inZonalView(tz.getID()).isLeapSecond(),
is(true));
}
@Test
public void getSecondOfMinute() {
Moment moment = Moment.of(1278028824, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
assertThat(
moment.inZonalView(tz.getID()).get(PlainTime.SECOND_OF_MINUTE),
is(60));
}
@Test
public void getDayOfMonth() {
Moment moment = Moment.of(1278028824, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
assertThat(
moment.inZonalView(tz.getID()).get(PlainDate.DAY_OF_MONTH),
is(1));
}
@Test
public void getPosixTime() {
long utc = 1278028824L;
Moment moment = Moment.of(utc, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
assertThat(
moment.inZonalView(tz.getID()).getPosixTime(),
is(utc + 2 * 365 * 86400 - 25));
}
@Test
public void getMaxSecondOfMinute() {
Moment moment =
PlainTimestamp.of(2012, 6, 30, 23, 59, 0).atUTC();
assertThat(
moment.inZonalView(ZonalOffset.UTC)
.getMaximum(PlainTime.SECOND_OF_MINUTE),
is(60));
}
@Test
public void printZDT() {
Moment moment = Moment.of(1278028825, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
TemporalFormatter<Moment> formatter =
Moment.formatter("yyyy-MM-dd'T'HH:mmZ", Platform.PATTERN, Locale.ROOT, tz.getID());
System.out.println("ZonalDateTime-Formatter-INFO: " + formatter.getClass().getName());
assertThat(
moment.inZonalView(tz.getID()).print(formatter),
is("2012-07-01T09:00+0900"));
}
@Test
public void parseZDT() throws ParseException {
Moment moment = Moment.of(1278028825, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
TemporalFormatter<Moment> formatter =
Moment.formatter("yyyy-MM-dd'T'HH:mmZ", Platform.PATTERN, Locale.ROOT, tz.getID());
assertThat(
ZonalDateTime.parse("2012-07-01T09:00+0900", formatter),
is(moment.inZonalView(tz.getID())));
}
} | core/src/test/java/net/time4j/scale/ZonalDateTimeTest.java | package net.time4j.scale;
import net.time4j.Moment;
import net.time4j.PlainDate;
import net.time4j.PlainTime;
import net.time4j.PlainTimestamp;
import net.time4j.Platform;
import net.time4j.ZonalDateTime;
import net.time4j.format.TemporalFormatter;
import net.time4j.tz.Timezone;
import net.time4j.tz.ZonalOffset;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.text.ParseException;
import java.util.Locale;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@RunWith(JUnit4.class)
public class ZonalDateTimeTest {
@Test
public void toMoment() {
Moment moment = Moment.of(1278028824, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
assertThat(
moment.inZonalView(tz.getID()).toMoment(),
is(moment));
}
@Test
public void toTimestamp() {
Moment moment = Moment.of(1278028824, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
assertThat(
moment.inZonalView(tz.getID()).toTimestamp(),
is(PlainTimestamp.of(2012, 7, 1, 8, 59, 59)));
}
@Test
public void hasTimezone() {
Moment moment = Moment.of(1278028824, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
assertThat(
moment.inZonalView(tz.getID()).hasTimezone(),
is(true));
}
@Test
public void getTimezone() {
Moment moment = Moment.of(1278028824, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
assertThat(
moment.inZonalView(tz.getID()).getTimezone(),
is(tz.getID()));
}
@Test
public void isLeapsecond() {
Moment moment = Moment.of(1278028824, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
assertThat(
moment.inZonalView(tz.getID()).isLeapSecond(),
is(true));
}
@Test
public void getSecondOfMinute() {
Moment moment = Moment.of(1278028824, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
assertThat(
moment.inZonalView(tz.getID()).get(PlainTime.SECOND_OF_MINUTE),
is(60));
}
@Test
public void getDayOfMonth() {
Moment moment = Moment.of(1278028824, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
assertThat(
moment.inZonalView(tz.getID()).get(PlainDate.DAY_OF_MONTH),
is(1));
}
@Test
public void getPosixTime() {
long utc = 1278028824L;
Moment moment = Moment.of(utc, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
assertThat(
moment.inZonalView(tz.getID()).getPosixTime(),
is(utc + 2 * 365 * 86400 - 25));
}
@Test
public void getMaxSecondOfMinute() {
Moment moment =
PlainTimestamp.of(2012, 6, 30, 23, 59, 0).atUTC();
assertThat(
moment.inZonalView(ZonalOffset.UTC)
.getMaximum(PlainTime.SECOND_OF_MINUTE),
is(60));
}
@Test
public void printZDT() {
Moment moment = Moment.of(1278028825, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
TemporalFormatter<Moment> formatter =
Moment.formatter("yyyy-MM-dd'T'HH:mmXX", Platform.PATTERN, Locale.ROOT, tz.getID());
System.out.println("ZonalDateTime-Formatter-INFO: " + formatter.getClass().getName());
assertThat(
moment.inZonalView(tz.getID()).print(formatter),
is("2012-07-01T09:00+0900"));
}
@Test
public void parseZDT() throws ParseException {
Moment moment = Moment.of(1278028825, TimeScale.UTC);
Timezone tz = Timezone.of("Asia/Tokyo");
TemporalFormatter<Moment> formatter =
Moment.formatter("yyyy-MM-dd'T'HH:mmXX", Platform.PATTERN, Locale.ROOT, tz.getID());
assertThat(
ZonalDateTime.parse("2012-07-01T09:00+0900", formatter),
is(moment.inZonalView(tz.getID())));
}
} | make test class suitable for Java 6
| core/src/test/java/net/time4j/scale/ZonalDateTimeTest.java | make test class suitable for Java 6 |
|
Java | lgpl-2.1 | 85d49715791b71edeabc38edb85561477afaec5e | 0 | ebollens/ccnmp,ebollens/ccnmp,ebollens/ccnmp,cawka/ndnx,cawka/ndnx,svartika/ccnx,svartika/ccnx,svartika/ccnx,cawka/ndnx,cawka/ndnx,svartika/ccnx,svartika/ccnx,svartika/ccnx,ebollens/ccnmp,cawka/ndnx,svartika/ccnx | /**
* Part of the CCNx Java Library.
*
* Copyright (C) 2008, 2009 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. You should have received
* a copy of the GNU Lesser General Public License along with this library;
* if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.ccnx.ccn.profiles.access;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.stream.XMLStreamException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.KeyManager;
import org.ccnx.ccn.config.ConfigurationException;
import org.ccnx.ccn.impl.support.DataUtils;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.io.content.Link;
import org.ccnx.ccn.io.content.PublicKeyObject;
import org.ccnx.ccn.io.content.WrappedKey;
import org.ccnx.ccn.io.content.WrappedKey.WrappedKeyObject;
import org.ccnx.ccn.profiles.VersionMissingException;
import org.ccnx.ccn.profiles.VersioningProfile;
import org.ccnx.ccn.profiles.access.ACL.ACLObject;
import org.ccnx.ccn.profiles.access.ACL.ACLOperation;
import org.ccnx.ccn.profiles.access.AccessControlProfile.PrincipalInfo;
import org.ccnx.ccn.profiles.nameenum.EnumeratedNameList;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.MalformedContentNameStringException;
/**
* This class is used in updating node keys and by #getEffectiveNodeKey(ContentName).
* To achieve this, we walk up the tree for this node. At each point, we check to
* see if a node key exists. If one exists, we decrypt it if we know an appropriate
* key. Otherwise we return null.
*
* We are going for a low-enumeration approach. We could enumerate node keys and
* see if we have rights on the latest version; but then we need to enumerate keys
* and figure out whether we have a copy of a key or one of its previous keys.
* If we don't know our group memberships, even if we enumerate the node key
* access, we don't know what groups we're a member of.
*
* Node keys and ACLs evolve in the following fashion:
* - if ACL adds rights, by adding a group, we merely add encrypted node key blocks for
* the same node key version (ACL version increases, node key version does not)
* - if an ACL removes rights, by removing a group, we version the ACL and the node key
* (both versions increase)
* - if a group adds rights by adding a member, we merely add key blocks to the group key
* (no change to node key or ACL)
* - if a group removes rights by removing a member, we need to evolve all the node keys
* that point to that node key, at the time of next write using that node key (so we don't
* have to enumerate them). (node key version increases, but ACL version does not).
*
* One could have the node key (NK) point to its ACL version, or vice versa, but they really
* do most efficiently evolve in parallel. One could have the ACL point to group versions,
* and update the ACL and NK together in the last case as well.
* In this last case, we want to update the NK only on next write; if we never write again,
* we never need to generate a new NK (unless we can delete). And we want to wait as long
* as possible, to skip NK updates with no corresponding writes.
* But, a writer needs to determine first what the most recent node key is for a given
* node, and then must determine whether or not that node key must be updated -- whether or
* not the most recent versions of groups are what that node key is encrypted under.
* Ideally we don't want to have it update the ACL, as that allows management access separation --
* we can let writers write the node key without allowing them to write the ACL.
*
* So, we can't store the group version information in the ACL. We don't necessarily
* want a writer to have to pull all the node key blocks to see what version of each
* group the node key is encrypted under.
*
* We could name the node key blocks <prefix>/_access_/NK/\#version/<group name>:<group key id>,
* if we could match on partial components, but we can't.
*
* We can name the node key blocks <prefix>/_access_/NK/\#version/<group key id> with
* a link pointing to that from NK/\#version/<group name>.
*
* For both read and write, we don't actually care what the ACL says. We only care what
* the node key is. Most efficient option, if we have a full key cache, is to list the
* node key blocks by key id used to encrypt them, and then pull one for a key in our cache.
* On the read side, we're looking at a specific version NK, and we might have rights by going
* through its later siblings. On the write side, we're looking at the latest version NK, and
* we should have rights to one of the key blocks, or we don't have rights.
* If we don't have a full key cache, we have to walk the access hierarchy. In that case,
* the most efficient thing to do is to pull the latest version of the ACL for that node
* (if we have a NK, we have an ACL, and vice versa, so we can enumerate NK and then pull
* ACLs). We then walk that ACL. If we know we are in one of the groups in that ACL, walk
* back to find the group key encrypting that node key. If we don't, walk the groups in that
* ACL to find out if we're in any of them. If we are, pull the current group key, see if
* it works, and start working backwards through group keys, populating the cache in the process,
* to find the relevant group key.
*
* Right answer might be intentional containment. Besides the overall group key structures,
* we make a master list that points to the current versions of all the groups. That would
* have to be writable by anyone who is on the manage list for any group. That would let you
* get, easily, a single list indicating what groups are available and what their versions are.
* Unless NE lets you do that in a single pass, which would be better. (Enumerate name/latestversion,
* not just given name, enumerate versions.)
*
*
* Operational Process:
*
* read:
* - look at content, find data key
* - data key refers to specific node key and version used to encrypt it
* - attempt to retrieve that node key from cache, if get it, done
* - go to specific node key key directory, attempt to find a block we can decrypt using keys in cache;
* if so, done
* - (maybe) for groups that node key is encrypted under which we believe we are a member of,
* attempt to retrieve the group key version we need to decrypt the node key
* - if that node key has been superseded, find the latest version of the node key (if we're not
* allowed access to that, we're not allowed access to the data) and walk first the cache,
* then the groups we believe we're a member of, then the groups we don't know about,
* trying to find a key to read it (== retrieve latest version of node key process)
* - if still can't read node key, attempt to find a new ACL interposed between the data node
* and the old node key node, and see if we have access to its latest node key (== retrieve
* latest version of node key process), and then crawl through previous key blocks till we
* get the one we want
*
* write:
* - find closest node key (non-gone)
* - decrypt its latest version, if can't, have no read access, which means have no write access
* - determine whether it's "dirty" -- needs to be superseded. ACL-changes update node key versions,
* what we need to do is determine whether any groups have updated their keys
* - if so, replace it
* - use it to protect data key
// We don't have a key cached. Either we don't have access, we aren't in one of the
// relevant groups, or we are, but we haven't pulled the appropriate version of the group
// key (because it's old, or because we don't know we're in that group).
// We can get this node key because either we're in one of the groups it was made
// available to, or because it's old, and we have access to one of the groups that
// has current access.
// Want to get the latest version of this node key, then do the walk to figure
// out how to read it. Need to split this code up:
// Given specific version (potentially old):
// - enumerate key blocks and group names
// - if we have one cached, use key
// - for groups we believe we're a member of, pull the link and see what key it points to
// - if it's older than the group key we know, walk back from the group key we know, caching
// all the way (this will err on the side of reading; starting from the current group will
// err on the side of making access control coverage look more extensive)
// - if we know nothing else, pull the latest version and walk that if it's newer than this one
// - if that results in a key, chain backwards to this key
// Given latest version:
// - enumerate key blocks, and group names
// - if we have one cached, just use it
// - walk the groups, starting with the groups we believe we're a member of
// - for groups we believe we're in, check if we're still in, then check for a given key
// - walk the groups we don't know if we're in, see if we're in, and can pull the necessary key
// - given that, unwrap the key and return it
// basic flow -- flag that says whether we believe we have the latest or not, if set, walk
// groups we don't know about, if not set, pull latest and if we get something later, make
// recursive call saying we believe it's the latest (2-depth recursion max)
// As we look at more stuff, we cache more keys, and fall more and more into the cache-only
// path.
*
*/
public class AccessControlManager {
/**
* Default data key length in bytes. No real reason this can't be bumped up to 32. It
* acts as the seed for a KDF, not an encryption key.
*/
public static final int DEFAULT_DATA_KEY_LENGTH = 16;
/**
* The keys we're wrapping are really seeds for a KDF, not keys in their own right.
* Eventually we'll use CMAC, so call them AES...
*/
public static final String DEFAULT_DATA_KEY_ALGORITHM = "AES";
/**
* This algorithm must be capable of key wrap (RSA, ElGamal, etc).
*/
public static final String DEFAULT_GROUP_KEY_ALGORITHM = "RSA";
public static final int DEFAULT_GROUP_KEY_LENGTH = 1024;
public static final String DATA_KEY_LABEL = "Data Key";
public static final String NODE_KEY_LABEL = "Node Key";
public static final long DEFAULT_TIMEOUT = 1000;
public static final long DEFAULT_FRESHNESS_INTERVAL = 100;
public static final long DEFAULT_NODE_KEY_FRESHNESS_INTERVAL = DEFAULT_FRESHNESS_INTERVAL;
public static final long DEFAULT_DATA_KEY_FRESHNESS_INTERVAL = DEFAULT_FRESHNESS_INTERVAL;
public static final long DEFAULT_ACL_FRESHNESS_INTERVAL = DEFAULT_FRESHNESS_INTERVAL;
public static final long DEFAULT_GROUP_PUBLIC_KEY_FRESHNESS_INTERVAL = 3600;
public static final long DEFAULT_GROUP_PRIVATE_KEY_FRESHNESS_INTERVAL = 3600;
public static final long DEFAULT_GROUP_ENCRYPTED_KEY_BLOCK_FRESHNESS_INTERVAL = DEFAULT_FRESHNESS_INTERVAL;
private ContentName _namespace;
private ContentName _userStorage;
private EnumeratedNameList _userList;
private GroupManager _groupManager = null;
private HashSet<ContentName> _myIdentities = new HashSet<ContentName>();
private KeyCache _keyCache;
private CCNHandle _handle;
private SecureRandom _random = new SecureRandom();
public AccessControlManager(ContentName namespace) throws ConfigurationException, IOException {
this(namespace, null);
}
public AccessControlManager(ContentName namespace, CCNHandle handle) throws ConfigurationException, IOException {
this(namespace, AccessControlProfile.groupNamespaceName(namespace), AccessControlProfile.userNamespaceName(namespace), handle);
}
public AccessControlManager(ContentName namespace, ContentName groupStorage, ContentName userStorage) throws ConfigurationException, IOException {
this(namespace, groupStorage, userStorage, null);
}
public AccessControlManager(ContentName namespace, ContentName groupStorage, ContentName userStorage, CCNHandle handle) throws ConfigurationException, IOException {
_namespace = namespace;
_userStorage = userStorage;
if (null == handle) {
_handle = CCNHandle.open();
} else {
_handle = handle;
}
_keyCache = new KeyCache(_handle.keyManager());
// start enumerating users in the background
userList();
_groupManager = new GroupManager(this, groupStorage, _handle);
// TODO here, check for a namespace marker, and if one not there, write it (async)
}
public GroupManager groupManager() { return _groupManager; }
/**
* Publish my identity (i.e. my public key) under a specified CCN name
* @param identity the name
* @param myPublicKey my public key
* @throws InvalidKeyException
* @throws IOException
* @throws ConfigurationException
* @throws XMLStreamException
*/
public void publishMyIdentity(ContentName identity, PublicKey myPublicKey) throws InvalidKeyException, IOException, ConfigurationException, XMLStreamException {
KeyManager km = _handle.keyManager();
if (null == myPublicKey) {
myPublicKey = km.getDefaultPublicKey();
}
PublicKeyObject pko = new PublicKeyObject(identity, myPublicKey, handle());
pko.saveToRepository();
_myIdentities.add(identity);
}
/**
* Publish my identity (i.e. my public key) under a specified user name
* @param userName the user name
* @param myPublicKey my public key
* @throws InvalidKeyException
* @throws IOException
* @throws ConfigurationException
* @throws XMLStreamException
*/
public void publishMyIdentity(String userName, PublicKey myPublicKey) throws InvalidKeyException, IOException, ConfigurationException, XMLStreamException {
Log.finest("publishing my identity" + AccessControlProfile.userNamespaceName(_userStorage, userName));
publishMyIdentity(AccessControlProfile.userNamespaceName(_userStorage, userName), myPublicKey);
}
/**
* Publish the specified identity (i.e. the public key) of a specified user
* @param userName the name of the user
* @param userPublicKey the public key of the user
* @throws ConfigurationException
* @throws IOException
* @throws MalformedContentNameStringException
*/
public void publishUserIdentity(String userName, PublicKey userPublicKey) throws ConfigurationException, IOException, MalformedContentNameStringException {
PublicKeyObject pko = new PublicKeyObject(ContentName.fromNative(userName), userPublicKey, handle());
System.out.println("saving user pubkey to repo:" + userName);
pko.saveToRepository();
}
public boolean haveIdentity(String userName) {
return _myIdentities.contains(AccessControlProfile.userNamespaceName(_userStorage, userName));
}
public boolean haveIdentity(ContentName userName) {
return _myIdentities.contains(userName);
}
/**
* Labels for deriving various types of keys.
* @return
*/
public String dataKeyLabel() {
return DATA_KEY_LABEL;
}
public String nodeKeyLabel() {
return NODE_KEY_LABEL;
}
CCNHandle handle() { return _handle; }
KeyCache keyCache() { return _keyCache; }
/**
* Enumerate users
* @return user enumeration
* @throws IOException
*/
public EnumeratedNameList userList() throws IOException {
if (null == _userList) {
_userList = new EnumeratedNameList(_userStorage, handle());
}
return _userList;
}
public boolean inProtectedNamespace(ContentName content) {
return _namespace.isPrefixOf(content);
}
/**
* Get the latest key for a specified principal
* TODO shortcut slightly -- the principal we have cached might not meet the
* constraints of the link.
* @param principal the principal
* @return the public key object
* @throws XMLStreamException
* @throws IOException
* @throws ConfigurationException
*/
public PublicKeyObject getLatestKeyForPrincipal(Link principal) throws IOException, XMLStreamException, ConfigurationException {
if (null == principal) {
Log.info("Cannot retrieve key for empty principal.");
return null;
}
PublicKeyObject pko = null;
if (_groupManager.isGroup(principal)) {
pko = _groupManager.getLatestPublicKeyForGroup(principal);
} else {
Log.info("Retrieving latest key for user: " + principal.targetName());
pko = new PublicKeyObject(principal.targetName(), principal.targetAuthenticator().publisher(), handle());
}
return pko;
}
/**
* Creates the root ACL for _namespace.
* This initialization must be done before any other ACL or node key can be read or written.
* @param rootACL the root ACL
*/
public void initializeNamespace(ACL rootACL) throws XMLStreamException, IOException, ConfigurationException, InvalidKeyException {
// generates the new node key
generateNewNodeKey(_namespace, null, rootACL);
// write the root ACL
ACLObject aclo = new ACLObject(AccessControlProfile.aclName(_namespace), rootACL, handle());
aclo.saveToRepository();
}
/**
* Retrieves the latest version of an ACL effective at this node, either stored
* here or at one of its ancestors.
* @param nodeName the name of the node
* @return the ACL object
* @throws ConfigurationException
* @throws IOException
* @throws XMLStreamException
* @throws ConfigurationException
*/
public ACLObject getEffectiveACLObject(ContentName nodeName) throws XMLStreamException, IOException, ConfigurationException {
// Find the closest node that has a non-gone ACL
ACLObject aclo = findAncestorWithACL(nodeName);
if (null == aclo) {
Log.warning("Unexpected: cannot find an ancestor of node " + nodeName + " that has an ACL.");
throw new IOException("Unexpected: cannot find an ancestor of node " + nodeName + " that has an ACL.");
}
return aclo;
}
private ACLObject findAncestorWithACL(ContentName dataNodeName) throws XMLStreamException, IOException, ConfigurationException {
ACLObject ancestorACLObject = null;
ContentName parentName = dataNodeName;
ContentName nextParentName = null;
while (null == ancestorACLObject) {
ancestorACLObject = getACLObjectForNodeIfExists(parentName);
if ((null != ancestorACLObject) && (ancestorACLObject.isGone())) {
Log.info("Found an ACL object at " + ancestorACLObject.getVersionedName() + " but its GONE.");
ancestorACLObject = null;
}
nextParentName = parentName.parent();
// stop looking once we're above our namespace, or if we've already checked the top level
if (nextParentName.count() < _namespace.count() || parentName.count() == 0) {
break;
}
parentName = nextParentName;
}
if (null == ancestorACLObject) {
throw new IllegalStateException("No ACL available in ancestor tree for node : " + dataNodeName);
}
Log.info("Found ACL for " + dataNodeName + " at ancestor :" + ancestorACLObject.getVersionedName());
return ancestorACLObject;
}
/**
* Try to pull an ACL for a particular node. If it doesn't exist, will time
* out. Use enumeration to decide whether to call this to avoid the timeout.
* @param aclNodeName the node name
* @return the ACL object
* @throws IOException
* @throws XMLStreamException
* @throws ConfigurationException
*/
public ACLObject getACLObjectForNode(ContentName aclNodeName) throws XMLStreamException, IOException, ConfigurationException {
// Get the latest version of the acl. We don't care so much about knowing what version it was.
ACLObject aclo = new ACLObject(AccessControlProfile.aclName(aclNodeName), handle());
aclo.update();
// if there is no update, this will probably throw an exception -- IO or XMLStream
if (aclo.isGone()) {
// treat as if no acl on node
return null;
}
return aclo;
}
/**
* Try to pull an ACL for a specified node if it exists.
* @param aclNodeName the name of the node
* @return the ACL object
* @throws XMLStreamException
* @throws IOException
* @throws ConfigurationException
*/
public ACLObject getACLObjectForNodeIfExists(ContentName aclNodeName) throws XMLStreamException, IOException, ConfigurationException {
EnumeratedNameList aclNameList = EnumeratedNameList.exists(AccessControlProfile.aclName(aclNodeName), aclNodeName, handle());
if (null != aclNameList) {
ContentName aclName = new ContentName(AccessControlProfile.aclName(aclNodeName));
Log.info("Found latest version of acl for " + aclNodeName + " at " + aclName);
ACLObject aclo = new ACLObject(aclName, handle());
aclo.update();
if (aclo.isGone())
return null;
return aclo;
}
Log.info("No ACL found on node: " + aclNodeName);
return null;
}
/**
* Get the effective ACL for a node specified by its name
* @param nodeName the name of the node
* @return the effective ACL
* @throws XMLStreamException
* @throws IOException
* @throws ConfigurationException
*/
public ACL getEffectiveACL(ContentName nodeName) throws XMLStreamException, IOException, ConfigurationException {
ACLObject aclo = getEffectiveACLObject(nodeName);
if (null != aclo) {
return aclo.acl();
}
return null;
}
/**
* Adds an ACL to a node that doesn't have one, or replaces one that exists.
* Just writes, doesn't bother to look at any current ACL. Does need to pull
* the effective node key at this node, though, to wrap the old ENK in a new
* node key.
*
* @param nodeName the name of the node
* @param newACL the new ACL
* @return
* @throws XMLStreamException
* @throws IOException
* @throws InvalidKeyException
* @throws ConfigurationException
* @throws AccessDeniedException
* @throws InvalidCipherTextException
*/
public ACL setACL(ContentName nodeName, ACL newACL) throws XMLStreamException, IOException, InvalidKeyException, ConfigurationException, AccessDeniedException, InvalidCipherTextException {
// Throws access denied exception if we can't read the old node key.
NodeKey effectiveNodeKey = getEffectiveNodeKey(nodeName);
// generates the new node key, wraps it under the new acl, and wraps the old node key
generateNewNodeKey(nodeName, effectiveNodeKey, newACL);
// write the acl
ACLObject aclo = new ACLObject(AccessControlProfile.aclName(nodeName), newACL, handle());
// DKS FIX REPO WRITE
aclo.save();
return aclo.acl();
}
/**
* Delete the ACL at this node if one exists, returning control to the
* next ACL upstream.
* We simply add a supserseded by block at this node, wrapping this key in the key of the upstream
* node. If we don't have read access at that node, throw AccessDeniedException.
* Then we write a GONE block here for the ACL, and a new node key version with a superseded by block.
* The superseded by block should probably be encrypted not with the ACL in force, but with the effective
* node key of the parent -- that will be derivable from the appropriate ACL, and will have the right semantics
* if a new ACL is interposed later. In the meantime, all the people with the newly in-force ancestor
* ACL should be able to read this content.
* @param nodeName
* @throws XMLStreamException
* @throws IOException
* @throws ConfigurationException
* @throws InvalidKeyException
* @throws InvalidCipherTextException
* @throws AccessDeniedException
*/
public void deleteACL(ContentName nodeName) throws XMLStreamException, IOException, ConfigurationException, InvalidKeyException, InvalidCipherTextException, AccessDeniedException {
// First, find ACL at this node if one exists.
ACLObject thisNodeACL = getACLObjectForNodeIfExists(nodeName);
if (null == thisNodeACL) {
Log.info("Asked to delete ACL for node " + nodeName + " that doesn't have one. Doing nothing.");
return;
}
Log.info("Deleting ACL for node " + nodeName + " latest version: " + thisNodeACL.getVersionedName());
// Then, find the latest node key. This should not be a derived node key.
NodeKey nk = getEffectiveNodeKey(nodeName);
// Next, find the ACL that is in force after the deletion.
ContentName parentName = nodeName.parent();
NodeKey effectiveParentNodeKey = getLatestNodeKeyForNode(parentName);
// Generate a superseded block for this node, wrapping its key in the parent.
// TODO want to wrap key in parent's effective key, but can't point to that -- no way to name an
// effective node key... need one.
KeyDirectory.addSupersededByBlock(nk.storedNodeKeyName(), nk.nodeKey(),
effectiveParentNodeKey.nodeName(), effectiveParentNodeKey.nodeKey(), handle());
// Then mark the ACL as gone.
thisNodeACL.saveAsGone();
}
/**
* Pulls the ACL for this node, if one exists, and modifies it to include
* the following changes, then stores the result using setACL, updating
* the node key if necessary in the process.
*
* @param nodeName the name of the node
* @param ACLUpdates the updates to the ACL
* @return the updated ACL
* @throws XMLStreamException
* @throws IOException
* @throws InvalidKeyException
* @throws ConfigurationException
* @throws AccessDeniedException
* @throws InvalidCipherTextException
*/
public ACL updateACL(ContentName nodeName, ArrayList<ACL.ACLOperation> ACLUpdates) throws XMLStreamException, IOException, InvalidKeyException, ConfigurationException, AccessDeniedException, InvalidCipherTextException {
ACLObject currentACL = getACLObjectForNodeIfExists(nodeName);
ACL newACL = null;
if (null != currentACL) {
newACL = currentACL.acl();
}else{
Log.info("Adding brand new ACL to node: " + nodeName);
//TODO: if no operations is specified, then a new empty ACL is created...
newACL = new ACL();
}
LinkedList<Link> newReaders = newACL.update(ACLUpdates);
if ((null == newReaders) || (null == currentACL)) {
// null newReaders means we revoked someone.
// null currentACL means we're starting from scratch
// Set the ACL and update the node key.
return setACL(nodeName, newACL);
}
// If we get back a list of new readers, it means all we have to do
// is add key blocks for them, not update the node key. (And it means
// we have a node key for this node.)
// Wait to save the new ACL till we are sure we're allowed to do this.
KeyDirectory keyDirectory = null;
try {
// If we can't read the node key, we can't update. Get the effective node key.
// Better be a node key here... and we'd better be allowed to read it.
NodeKey latestNodeKey = getLatestNodeKeyForNode(nodeName);
if (null == latestNodeKey) {
Log.info("Cannot read the latest node key for " + nodeName);
throw new AccessDeniedException("Cannot read the latest node key for " + nodeName);
}
keyDirectory = new KeyDirectory(this, latestNodeKey.storedNodeKeyName(), handle());
for (Link principal : newReaders) {
PublicKeyObject latestKey = getLatestKeyForPrincipal(principal);
try {
if (!latestKey.available()) {
latestKey.wait(DEFAULT_TIMEOUT);
}
} catch (InterruptedException ex) {
// do nothing
}
if (latestKey.available()) {
Log.info("Adding wrapped key block for reader: " + latestKey.getVersionedName());
try {
keyDirectory.addWrappedKeyBlock(latestNodeKey.nodeKey(), latestKey.getVersionedName(), latestKey.publicKey());
} catch (VersionMissingException e) {
Log.warning("UNEXPECTED: latest key for prinicpal: " + latestKey.getVersionedName() + " has no version? Skipping.");
}
} else {
// Do we use an old key or give up?
Log.info("No key for " + principal + " found. Skipping.");
}
}
} finally {
if (null != keyDirectory) {
keyDirectory.stopEnumerating();
}
}
// If we got here, we got the node key we were updating, so we are allowed
// to at least read this stuff (though maybe not write it). Save the acl.
currentACL.save(newACL);
return newACL;
}
/**
* Add readers to a specified node
* @param nodeName the name of the node
* @param newReaders the list of new readers
* @return the updated ACL
* @throws InvalidKeyException
* @throws XMLStreamException
* @throws IOException
* @throws ConfigurationException
* @throws AccessDeniedException
* @throws InvalidCipherTextException
*/
public ACL addReaders(ContentName nodeName, ArrayList<Link> newReaders) throws InvalidKeyException, XMLStreamException, IOException, ConfigurationException, AccessDeniedException, InvalidCipherTextException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link reader : newReaders){
ops.add(ACLOperation.addReaderOperation(reader));
}
return updateACL(nodeName, ops);
}
/**
* Add writers to a specified node.
* @param nodeName the name of the node
* @param newWriters the list of new writers
* @return the updated ACL
* @throws InvalidKeyException
* @throws XMLStreamException
* @throws IOException
* @throws ConfigurationException
* @throws AccessDeniedException
* @throws InvalidCipherTextException
*/
public ACL addWriters(ContentName nodeName, ArrayList<Link> newWriters) throws InvalidKeyException, XMLStreamException, IOException, ConfigurationException, AccessDeniedException, InvalidCipherTextException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link writer : newWriters){
ops.add(ACLOperation.addWriterOperation(writer));
}
return updateACL(nodeName, ops);
}
/**
* Add managers to a specified node
* @param nodeName the name of the node
* @param newManagers the list of new managers
* @return the updated ACL
* @throws InvalidKeyException
* @throws XMLStreamException
* @throws IOException
* @throws ConfigurationException
* @throws AccessDeniedException
* @throws InvalidCipherTextException
*/
public ACL addManagers(ContentName nodeName, ArrayList<Link> newManagers) throws InvalidKeyException, XMLStreamException, IOException, ConfigurationException, AccessDeniedException, InvalidCipherTextException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link manager: newManagers){
ops.add(ACLOperation.addManagerOperation(manager));
}
return updateACL(nodeName, ops);
}
/**
* Get the ancestor node key in force at this node (if we can decrypt it),
* including a key at this node itself. We use the fact that ACLs and
* node keys are co-located; if you have one, you have the other.
* @param nodeName the name of the node
* @return null means while node keys exist, we can't decrypt any of them --
* we have no read access to this node (which implies no write access)
* @throws IOException if something is wrong (e.g. no node keys at all)
* @throws XMLStreamException
* @throws ConfigurationException
* @throws InvalidKeyException
* @throws InvalidCipherTextException
* @throws AccessDeniedException
*/
protected NodeKey findAncestorWithNodeKey(ContentName nodeName) throws IOException, XMLStreamException, ConfigurationException, InvalidKeyException, InvalidCipherTextException, AccessDeniedException {
// climb up looking for node keys, then make sure that one isn't GONE
// if it isn't, call read-side routine to figure out how to decrypt it
ACLObject effectiveACL = findAncestorWithACL(nodeName);
if (null == effectiveACL) {
Log.warning("Unexpected: could not find effective ACL for node: " + nodeName);
throw new IOException("Unexpected: could not find effective ACL for node: " + nodeName);
}
Log.info("Got ACL named: " + effectiveACL.getVersionedName() + " attempting to retrieve node key from " + AccessControlProfile.accessRoot(effectiveACL.getVersionedName()));
return getLatestNodeKeyForNode(AccessControlProfile.accessRoot(effectiveACL.getVersionedName()));
}
/**
* Write path: get the latest node key for a node.
* @param nodeName the name of the node
* @return the corresponding node key
* @throws IOException
* @throws InvalidKeyException
* @throws InvalidCipherTextException
* @throws XMLStreamException
* @throws ConfigurationException
* @throws AccessDeniedException
*/
public NodeKey getLatestNodeKeyForNode(ContentName nodeName) throws IOException, InvalidKeyException, InvalidCipherTextException, XMLStreamException, ConfigurationException, AccessDeniedException {
// Could do this using getLatestVersion...
// First we need to figure out what the latest version is of the node key.
ContentName nodeKeyVersionedName =
EnumeratedNameList.getLatestVersionName(AccessControlProfile.nodeKeyName(nodeName), handle());
// DKS TODO this may not handle ACL deletion correctly -- we need to make sure that this
// key wasn't superseded by something that isn't a later version of itself.
// then, pull the node key we can decrypt
return getNodeKeyByVersionedName(nodeKeyVersionedName, null);
}
/**
* Read path:
* Retrieve a specific node key from a given location, as specified by a
* key it was used to wrap, and, if possible, find a key we can use to
* unwrap the node key.
*
* Throw an exception if there is no node key block at the appropriate name.
* @param nodeKeyName
* @param nodeKeyIdentifier
* @return the node key
* @throws IOException
* @throws XMLStreamException
* @throws InvalidCipherTextException
* @throws InvalidKeyException
* @throws ConfigurationException
* @throws AccessDeniedException
*/
public NodeKey getSpecificNodeKey(ContentName nodeKeyName, byte [] nodeKeyIdentifier) throws InvalidKeyException, InvalidCipherTextException, XMLStreamException, IOException, ConfigurationException, AccessDeniedException {
if ((null == nodeKeyName) && (null == nodeKeyIdentifier)) {
throw new IllegalArgumentException("Node key name and identifier cannot both be null!");
}
// We should know what node key to use (down to the version), but we have to find the specific
// wrapped key copy we can decrypt.
NodeKey nk = getNodeKeyByVersionedName(nodeKeyName, nodeKeyIdentifier);
if (null == nk) {
Log.warning("No decryptable node key available at " + nodeKeyName + ", access denied.");
return null;
}
return nk;
}
/**
* We have the name of a specific version of a node key. Now we just need to figure
* out which of our keys can be used to decrypt it.
* @param nodeKeyName
* @param nodeKeyIdentifier
* @return
* @throws XMLStreamException
* @throws IOException
* @throws InvalidKeyException
* @throws InvalidCipherTextException
* @throws ConfigurationException
* @throws AccessDeniedException
*/
NodeKey getNodeKeyByVersionedName(ContentName nodeKeyName, byte [] nodeKeyIdentifier) throws XMLStreamException, IOException, InvalidKeyException, InvalidCipherTextException, ConfigurationException, AccessDeniedException {
NodeKey nk = null;
KeyDirectory keyDirectory = null;
try {
keyDirectory = new KeyDirectory(this, nodeKeyName, handle());
// this will handle the caching.
Key unwrappedKey = keyDirectory.getUnwrappedKey(nodeKeyIdentifier);
if (null != unwrappedKey) {
nk = new NodeKey(nodeKeyName, unwrappedKey);
} else {
throw new AccessDeniedException("Access denied: cannot retrieve key " + DataUtils.printBytes(nodeKeyIdentifier) + " at name " + nodeKeyName);
}
} finally {
if (null != keyDirectory) {
keyDirectory.stopEnumerating();
}
}
return nk;
}
/**
* Write path:
* Get the effective node key in force at this node, used to derive keys to
* encrypt content. Vertical chaining. Works if you ask for node which has
* a node key.
* TODO -- when called by writers, check to see if node key is dirty & update.
* @param nodeName
* @return
* @throws InvalidKeyException
* @throws XMLStreamException
* @throws IOException
* @throws AccessDeniedException
* @throws InvalidCipherTextException
* @throws ConfigurationException
*/
public NodeKey getEffectiveNodeKey(ContentName nodeName) throws InvalidKeyException, XMLStreamException, IOException, AccessDeniedException, InvalidCipherTextException, ConfigurationException {
// Get the ancestor node key in force at this node.
NodeKey nodeKey = findAncestorWithNodeKey(nodeName);
if (null == nodeKey) {
throw new AccessDeniedException("Cannot retrieve node key for node: " + nodeName + ".");
}
Log.info("Found node key at " + nodeKey.storedNodeKeyName());
NodeKey effectiveNodeKey = nodeKey.computeDescendantNodeKey(nodeName, nodeKeyLabel());
Log.info("Computing effective node key for " + nodeName + " using stored node key " + effectiveNodeKey.storedNodeKeyName());
return effectiveNodeKey;
}
/**
* Like #getEffectiveNodeKey(ContentName), except checks to see if node
* key is dirty and updates it if necessary.
* @param nodeName
* @return
* @throws InvalidKeyException
* @throws InvalidCipherTextException
* @throws AccessDeniedException
* @throws IOException
* @throws XMLStreamException
* @throws ConfigurationException
*/
public NodeKey getFreshEffectiveNodeKey(ContentName nodeName) throws InvalidKeyException, InvalidCipherTextException, AccessDeniedException, IOException, XMLStreamException, ConfigurationException {
NodeKey nodeKey = findAncestorWithNodeKey(nodeName);
if (null == nodeKey) {
throw new AccessDeniedException("Cannot retrieve node key for node: " + nodeName + ".");
}
// This should be the latest node key; i.e. not superseded.
if (nodeKeyIsDirty(nodeKey.storedNodeKeyName())) {
Log.info("Found node key at " + nodeKey.storedNodeKeyName() + ", updating.");
ContentName nodeKeyNodeName = AccessControlProfile.accessRoot(nodeKey.storedNodeKeyName());
ACLObject acl = getACLObjectForNode(nodeKeyNodeName);
nodeKey = generateNewNodeKey(nodeKeyNodeName, nodeKey, acl.acl());
} else {
Log.info("Found node key at " + nodeKey.storedNodeKeyName());
}
NodeKey effectiveNodeKey = nodeKey.computeDescendantNodeKey(nodeName, nodeKeyLabel());
Log.info("Computing effective node key for " + nodeName + " using stored node key " + effectiveNodeKey.storedNodeKeyName());
return effectiveNodeKey;
}
/**
* Do we need to update this node key?
* First, we look to see whether or not we know the key is dirty -- i.e.
* does it have a superseded block (if it's gone, it will also have a
* superseded block). If not, we have to really check...
* Basically, we look at all the entities this node key is encrypted for,
* and determine whether any of them have a new version of their public
* key. If so, the node key is dirty.
*
* The initial implementation of this will be simple and slow -- iterating through
* groups and assuming the active object system will keep updating itself whenever
* a new key appears. Eventually, we might want an index directory of all the
* versions of keys, so that one name enumeration request might give us information
* about whether keys have been updated. (Or some kind of aggregate versioning,
* that tell us a) whether any groups have changed their versions, or b) just the
* ones we care about have.)
*
* This can be called by anyone -- the data about whether a node key is dirty
* is visible to anyone. Fixing a dirty node key requires access, though.
* @param theNodeKeyName this might be the name of the node where the NK is stored,
* or the NK name itself.
* We assume this exists -- that there at some point has been a node key here.
* TODO ephemeral node key naming
* @return
* @throws IOException
* @throws ConfigurationException
* @throws XMLStreamException
*/
public boolean nodeKeyIsDirty(ContentName theNodeKeyName) throws IOException, ConfigurationException, XMLStreamException {
// first, is this a node key name?
if (!AccessControlProfile.isNodeKeyName(theNodeKeyName)) {
// assume it's a data node name.
theNodeKeyName = AccessControlProfile.nodeKeyName(theNodeKeyName);
}
// get the requested version of this node key; or if unversioned, get the latest.
KeyDirectory nodeKeyDirectory = null;
try {
nodeKeyDirectory = new KeyDirectory(this, theNodeKeyName, handle());
if (null == nodeKeyDirectory) {
throw new IOException("Cannot get node key directory for : " + theNodeKeyName);
}
if (nodeKeyDirectory.hasSupersededBlock()) {
return true;
}
for (PrincipalInfo principal : nodeKeyDirectory.getCopyOfPrincipals().values()) {
if (principal.isGroup()) {
Group theGroup = groupManager().getGroup(principal.friendlyName());
if (theGroup.publicKeyVersion().after(principal.versionTimestamp())) {
return true;
}
} else {
// DKS TODO -- for now, don't handle versioning of non-group keys
Log.info("User key for " + principal.friendlyName() + ", not checking version.");
// Technically, we're not handling versioning for user keys, but be nice. Start
// by seeing if we have a link to the key in our user space.
// If the principal isn't available in our enumerated list, have to go get its key
// from the wrapped key object.
}
}
return false;
} finally {
if (null != nodeKeyDirectory)
nodeKeyDirectory.stopEnumerating();
}
}
/**
* Would we update this data key if we were doing reencryption?
* This one is simpler -- what node key is the data key encrypted under, and is
* that node key dirty?
*
* This can be called by anyone -- the data about whether a data key is dirty
* is visible to anyone. Fixing a dirty key requires access, though.
*
* @param dataName
* @return
* @throws IOException
* @throws XMLStreamException
* @throws ConfigurationException
*/
public boolean dataKeyIsDirty(ContentName dataName) throws IOException, XMLStreamException, ConfigurationException {
// TODO -- do we need to check whether there *is* a key?
// The trick: we need the header information in the wrapped key; we don't need to unwrap it.
// ephemeral key naming
WrappedKeyObject wrappedDataKey = new WrappedKeyObject(AccessControlProfile.dataKeyName(dataName), handle());
return nodeKeyIsDirty(wrappedDataKey.wrappedKey().wrappingKeyName());
}
/**
* We've looked for a node key we can decrypt at the expected node key location,
* but no dice. See if a new ACL has been interposed granting us rights at a lower
* portion of the tree.
* @param dataNodeName
* @param wrappingKeyName
* @param wrappingKeyIdentifier
* @return
* @throws XMLStreamException
* @throws IOException
* @throws InvalidKeyException
* @throws InvalidCipherTextException
* @throws ConfigurationException
* @throws AccessDeniedException
*/
protected NodeKey getNodeKeyUsingInterposedACL(ContentName dataNodeName,
ContentName wrappingKeyName, byte[] wrappingKeyIdentifier) throws XMLStreamException, IOException, InvalidKeyException, InvalidCipherTextException, ConfigurationException, AccessDeniedException {
ACLObject nearestACL = findAncestorWithACL(dataNodeName);
if (null == nearestACL) {
Log.warning("Unexpected -- node with no ancestor ACL: " + dataNodeName);
// no dice
return null;
}
if (nearestACL.equals(AccessControlProfile.accessRoot(wrappingKeyName))) {
Log.info("Node key: " + wrappingKeyName + " is the nearest ACL to " + dataNodeName);
return null;
}
NodeKey nk = getLatestNodeKeyForNode(AccessControlProfile.accessRoot(nearestACL.getVersionedName()));
return nk;
}
/**
* Make a new node key and encrypt it under the given ACL.
* If there is a previous node key (oldEffectiveNodeKey not null), it is wrapped in the new node key.
* Put all the blocks into the aggregating writer, but don't flush.
*
* @param nodeName
* @param oldEffectiveNodeKey
* @param effectiveACL
* @return
* @throws IOException
* @throws ConfigurationException
* @throws XMLStreamException
* @throws InvalidKeyException if one of the public keys for someone specified on the ACL is invalid.
*/
protected NodeKey generateNewNodeKey(ContentName nodeName, NodeKey oldEffectiveNodeKey, ACL effectiveACL)
throws IOException, ConfigurationException, XMLStreamException, InvalidKeyException {
// Get the name of the key directory; this is unversioned. Make a new version of it.
ContentName nodeKeyDirectoryName = VersioningProfile.addVersion(AccessControlProfile.nodeKeyName(nodeName));
Log.info("Generating new node key " + nodeKeyDirectoryName);
// Now, generate the node key.
if (effectiveACL.publiclyReadable()) {
// TODO Put something here that will represent public; need to then make it so that key-reading code will do
// the right thing when it encounters it.
throw new UnsupportedOperationException("Need to implement public node key representation!");
}
byte [] nodeKeyBytes = new byte[NodeKey.DEFAULT_NODE_KEY_LENGTH];
_random.nextBytes(nodeKeyBytes);
Key nodeKey = new SecretKeySpec(nodeKeyBytes, NodeKey.DEFAULT_NODE_KEY_ALGORITHM);
// Now, wrap it under the keys listed in its ACL.
// Make a key directory. If we give it a versioned name, it will start enumerating it, but won't block.
KeyDirectory nodeKeyDirectory = null;
NodeKey theNodeKey = null;
try {
nodeKeyDirectory = new KeyDirectory(this, nodeKeyDirectoryName, handle());
theNodeKey = new NodeKey(nodeKeyDirectoryName, nodeKey);
// Add a key block for every reader on the ACL. As managers and writers can read, they are all readers.
// TODO -- pulling public keys here; could be slow; might want to manage concurrency over acl.
for (Link aclEntry : effectiveACL.contents()) {
PublicKeyObject entryPublicKey = null;
if (groupManager().isGroup(aclEntry)) {
entryPublicKey = groupManager().getLatestPublicKeyForGroup(aclEntry);
} else {
// Calls update. Will get latest version if name unversioned.
if (aclEntry.targetAuthenticator() != null)
entryPublicKey = new PublicKeyObject(aclEntry.targetName(), aclEntry.targetAuthenticator().publisher(), handle());
else entryPublicKey = new PublicKeyObject(aclEntry.targetName(), handle());
}
try {
nodeKeyDirectory.addWrappedKeyBlock(nodeKey, entryPublicKey.getVersionedName(), entryPublicKey.publicKey());
} catch (VersionMissingException ve) {
Log.logException("Unexpected version missing exception for public key " + entryPublicKey.getVersionedName(), ve);
throw new IOException("Unexpected version missing exception for public key " + entryPublicKey.getVersionedName() + ": " + ve);
}
}
// Add a superseded by block to the previous key. Two cases: old effective node key is at the same level
// as us (we are superseding it entirely), or we are interposing a key (old key is above or below us).
// OK, here are the options:
// Replaced node key is a derived node key -- we are interposing an ACL
// Replaced node key is a stored node key
// -- we are updating that node key to a new version
// NK/vn replaced by NK/vn+k -- new node key will be later version of previous node key
// -- we don't get called if we are deleting an ACL here -- no new node key is added.
if (oldEffectiveNodeKey != null) {
if (oldEffectiveNodeKey.isDerivedNodeKey()) {
// Interposing an ACL.
// Add a previous key block wrapping the previous key. There is nothing to link to.
nodeKeyDirectory.addPreviousKeyBlock(oldEffectiveNodeKey.nodeKey(), nodeKeyDirectoryName, nodeKey);
} else {
try {
if (!VersioningProfile.isLaterVersionOf(nodeKeyDirectoryName, oldEffectiveNodeKey.storedNodeKeyName())) {
Log.warning("Unexpected: replacing node key stored at " + oldEffectiveNodeKey.storedNodeKeyName() + " with new node key " +
nodeKeyDirectoryName + " but latter is not later version of the former.");
}
} catch (VersionMissingException vex) {
Log.warning("Very unexpected version missing exception when replacing node key : " + vex);
}
// Add a previous key link to the old version of the key.
// TODO do we need to add publisher?
nodeKeyDirectory.addPreviousKeyLink(oldEffectiveNodeKey.storedNodeKeyName(), null);
// OK, just add superseded-by block to the old directory.
KeyDirectory.addSupersededByBlock(oldEffectiveNodeKey.storedNodeKeyName(), oldEffectiveNodeKey.nodeKey(),
nodeKeyDirectoryName, nodeKey, handle());
}
}
} finally {
if (null != nodeKeyDirectory) {
nodeKeyDirectory.stopEnumerating();
}
}
// Return the key for use, along with its name.
return theNodeKey;
}
public NodeKey getNodeKeyForObject(ContentName nodeName, WrappedKeyObject wko) throws InvalidKeyException, XMLStreamException, InvalidCipherTextException, IOException, ConfigurationException, AccessDeniedException {
// First, we go and look for the node key where the data key suggests
// it should be, and attempt to decrypt it from there.
NodeKey nk = null;
try {
nk = getSpecificNodeKey(wko.wrappedKey().wrappingKeyName(),
wko.wrappedKey().wrappingKeyIdentifier());
} catch (AccessDeniedException ex) {
// ignore
}
if (null == nk) {
// OK, we will have gotten an exception if the node key simply didn't exist
// there, so this means that we don't have rights to read it there.
// The only way we might have rights not visible from this link is if an
// ACL has been interposed between where we are and the node key, and that
// ACL does give us rights.
nk = getNodeKeyUsingInterposedACL(nodeName, wko.wrappedKey().wrappingKeyName(),
wko.wrappedKey().wrappingKeyIdentifier());
if (null == nk) {
// Still can't find one we can read. Give up. Return null, and allow caller to throw the
// access exception.
return null;
}
}
NodeKey enk = nk.computeDescendantNodeKey(nodeName, dataKeyLabel());
return enk;
}
/**
* Used by content reader to retrieve the keys necessary to decrypt this content
* under this access control model.
* Given a data location, pull the data key block and decrypt it using
* whatever node keys are necessary.
* To turn the result of this into a key for decrypting content,
* follow the steps in the comments to #generateAndStoreDataKey(ContentName).
* @param dataNodeName
* @return
* @throws IOException
* @throws XMLStreamException
* @throws InvalidKeyException
* @throws InvalidCipherTextException
* @throws ConfigurationException
* @throws AccessDeniedException
*/
public byte [] getDataKey(ContentName dataNodeName) throws XMLStreamException, IOException, InvalidKeyException, InvalidCipherTextException, ConfigurationException, AccessDeniedException {
WrappedKeyObject wdko = new WrappedKeyObject(AccessControlProfile.dataKeyName(dataNodeName), handle());
wdko.update();
if (null == wdko.wrappedKey()) {
Log.warning("Could not retrieve data key for node: " + dataNodeName);
return null;
}
NodeKey enk = getNodeKeyForObject(dataNodeName, wdko);
if (null != enk) {
Key dataKey = wdko.wrappedKey().unwrapKey(enk.nodeKey());
return dataKey.getEncoded();
}
return null;
}
/**
* Take a randomly generated data key and store it. This requires finding
* the current effective node key, and wrapping this data key in it. If the
* current node key is dirty, this causes a new one to be generated.
* @param dataNodeName
* @param newRandomDataKey
* @throws XMLStreamException
* @throws InvalidKeyException
* @throws IllegalBlockSizeException
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws IOException
* @throws ConfigurationException
* @throws AccessDeniedException
* @throws InvalidCipherTextException
*/
public void storeDataKey(ContentName dataNodeName, Key newRandomDataKey) throws InvalidKeyException, XMLStreamException, IOException, ConfigurationException, AccessDeniedException, InvalidCipherTextException {
NodeKey effectiveNodeKey = getFreshEffectiveNodeKey(dataNodeName);
if (null == effectiveNodeKey) {
throw new AccessDeniedException("Cannot retrieve effective node key for node: " + dataNodeName + ".");
}
Log.info("Wrapping data key for node: " + dataNodeName + " with effective node key for node: " +
effectiveNodeKey.nodeName() + " derived from stored node key for node: " +
effectiveNodeKey.storedNodeKeyName());
// TODO another case where we're wrapping in an effective node key but labeling it with
// the stored node key information. This will work except if we interpose an ACL in the meantime --
// we may not have the information necessary to figure out how to decrypt.
WrappedKey wrappedDataKey = WrappedKey.wrapKey(newRandomDataKey,
null, dataKeyLabel(),
effectiveNodeKey.nodeKey());
wrappedDataKey.setWrappingKeyIdentifier(effectiveNodeKey.storedNodeKeyID());
wrappedDataKey.setWrappingKeyName(effectiveNodeKey.storedNodeKeyName());
storeKeyContent(AccessControlProfile.dataKeyName(dataNodeName), wrappedDataKey);
}
/**
* Generate a random data key, store it, and return it to use to derive keys to encrypt
* content. All that's left is to call
* byte [] randomDataKey = generateAndStoreDataKey(dataNodeName);
* byte [][] keyandiv =
* KeyDerivationFunction.DeriveKeyForObject(randomDataKey, keyLabel,
* dataNodeName, dataPublisherPublicKeyDigest)
* and then give keyandiv to the segmenter to encrypt the data.
* @throws InvalidKeyException
* @throws XMLStreamException
* @throws IOException
* @throws ConfigurationException
* @throws AccessDeniedException
* @throws InvalidCipherTextException
**/
public Key generateAndStoreDataKey(ContentName dataNodeName) throws InvalidKeyException, XMLStreamException, IOException, ConfigurationException, AccessDeniedException, InvalidCipherTextException {
// Generate new random data key of appropriate length
byte [] dataKeyBytes = new byte[DEFAULT_DATA_KEY_LENGTH];
_random.nextBytes(dataKeyBytes);
Key dataKey = new SecretKeySpec(dataKeyBytes, DEFAULT_DATA_KEY_ALGORITHM);
storeDataKey(AccessControlProfile.dataKeyName(dataNodeName), dataKey);
return dataKey;
}
/**
* Actual output functions. Needs to get this into the repo.
* @param dataNodeName -- the content node for whom this is the data key.
* @param wrappedDataKey
* @throws IOException
* @throws XMLStreamException
* @throws ConfigurationException
*/
private void storeKeyContent(ContentName dataNodeName,
WrappedKey wrappedKey) throws XMLStreamException, IOException, ConfigurationException {
// TODO DKS FIX FOR REPO
WrappedKeyObject wko = new WrappedKeyObject(AccessControlProfile.dataKeyName(dataNodeName), wrappedKey, handle());
wko.save();
}
/**
* add a private key to _keyCache
* @param keyName
* @param publicKeyIdentifier
* @param pk
*/
void addPrivateKey(ContentName keyName, byte [] publicKeyIdentifier, PrivateKey pk) {
_keyCache.addPrivateKey(keyName, publicKeyIdentifier, pk);
}
/**
* add my private key to _keyCache
* @param publicKeyIdentifier
* @param pk
*/
void addMyPrivateKey(byte [] publicKeyIdentifier, PrivateKey pk) {
_keyCache.addMyPrivateKey(publicKeyIdentifier, pk);
}
/**
* add a key to _keyCache
* @param name
* @param key
*/
public void addKey(ContentName name, Key key) {
_keyCache.addKey(name, key);
}
}
| javasrc/src/org/ccnx/ccn/profiles/access/AccessControlManager.java | /**
* Part of the CCNx Java Library.
*
* Copyright (C) 2008, 2009 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. You should have received
* a copy of the GNU Lesser General Public License along with this library;
* if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.ccnx.ccn.profiles.access;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.stream.XMLStreamException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.KeyManager;
import org.ccnx.ccn.config.ConfigurationException;
import org.ccnx.ccn.impl.support.DataUtils;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.io.content.Link;
import org.ccnx.ccn.io.content.PublicKeyObject;
import org.ccnx.ccn.io.content.WrappedKey;
import org.ccnx.ccn.io.content.WrappedKey.WrappedKeyObject;
import org.ccnx.ccn.profiles.VersionMissingException;
import org.ccnx.ccn.profiles.VersioningProfile;
import org.ccnx.ccn.profiles.access.ACL.ACLObject;
import org.ccnx.ccn.profiles.access.ACL.ACLOperation;
import org.ccnx.ccn.profiles.access.AccessControlProfile.PrincipalInfo;
import org.ccnx.ccn.profiles.nameenum.EnumeratedNameList;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.MalformedContentNameStringException;
/**
* This class is used in updating node keys and by #getEffectiveNodeKey(ContentName).
* To achieve this, we walk up the tree for this node. At each point, we check to
* see if a node key exists. If one exists, we decrypt it if we know an appropriate
* key. Otherwise we return null.
*
* We are going for a low-enumeration approach. We could enumerate node keys and
* see if we have rights on the latest version; but then we need to enumerate keys
* and figure out whether we have a copy of a key or one of its previous keys.
* If we don't know our group memberships, even if we enumerate the node key
* access, we don't know what groups we're a member of.
*
* Node keys and ACLs evolve in the following fashion:
* - if ACL adds rights, by adding a group, we merely add encrypted node key blocks for
* the same node key version (ACL version increases, node key version does not)
* - if an ACL removes rights, by removing a group, we version the ACL and the node key
* (both versions increase)
* - if a group adds rights by adding a member, we merely add key blocks to the group key
* (no change to node key or ACL)
* - if a group removes rights by removing a member, we need to evolve all the node keys
* that point to that node key, at the time of next write using that node key (so we don't
* have to enumerate them). (node key version increases, but ACL version does not).
*
* One could have the node key (NK) point to its ACL version, or vice versa, but they really
* do most efficiently evolve in parallel. One could have the ACL point to group versions,
* and update the ACL and NK together in the last case as well.
* In this last case, we want to update the NK only on next write; if we never write again,
* we never need to generate a new NK (unless we can delete). And we want to wait as long
* as possible, to skip NK updates with no corresponding writes.
* But, a writer needs to determine first what the most recent node key is for a given
* node, and then must determine whether or not that node key must be updated -- whether or
* not the most recent versions of groups are what that node key is encrypted under.
* Ideally we don't want to have it update the ACL, as that allows management access separation --
* we can let writers write the node key without allowing them to write the ACL.
*
* So, we can't store the group version information in the ACL. We don't necessarily
* want a writer to have to pull all the node key blocks to see what version of each
* group the node key is encrypted under.
*
* We could name the node key blocks <prefix>/_access_/NK/\#version/<group name>:<group key id>,
* if we could match on partial components, but we can't.
*
* We can name the node key blocks <prefix>/_access_/NK/\#version/<group key id> with
* a link pointing to that from NK/\#version/<group name>.
*
* For both read and write, we don't actually care what the ACL says. We only care what
* the node key is. Most efficient option, if we have a full key cache, is to list the
* node key blocks by key id used to encrypt them, and then pull one for a key in our cache.
* On the read side, we're looking at a specific version NK, and we might have rights by going
* through its later siblings. On the write side, we're looking at the latest version NK, and
* we should have rights to one of the key blocks, or we don't have rights.
* If we don't have a full key cache, we have to walk the access hierarchy. In that case,
* the most efficient thing to do is to pull the latest version of the ACL for that node
* (if we have a NK, we have an ACL, and vice versa, so we can enumerate NK and then pull
* ACLs). We then walk that ACL. If we know we are in one of the groups in that ACL, walk
* back to find the group key encrypting that node key. If we don't, walk the groups in that
* ACL to find out if we're in any of them. If we are, pull the current group key, see if
* it works, and start working backwards through group keys, populating the cache in the process,
* to find the relevant group key.
*
* Right answer might be intentional containment. Besides the overall group key structures,
* we make a master list that points to the current versions of all the groups. That would
* have to be writable by anyone who is on the manage list for any group. That would let you
* get, easily, a single list indicating what groups are available and what their versions are.
* Unless NE lets you do that in a single pass, which would be better. (Enumerate name/latestversion,
* not just given name, enumerate versions.)
*
*
* Operational Process:
*
* read:
* - look at content, find data key
* - data key refers to specific node key and version used to encrypt it
* - attempt to retrieve that node key from cache, if get it, done
* - go to specific node key key directory, attempt to find a block we can decrypt using keys in cache;
* if so, done
* - (maybe) for groups that node key is encrypted under which we believe we are a member of,
* attempt to retrieve the group key version we need to decrypt the node key
* - if that node key has been superseded, find the latest version of the node key (if we're not
* allowed access to that, we're not allowed access to the data) and walk first the cache,
* then the groups we believe we're a member of, then the groups we don't know about,
* trying to find a key to read it (== retrieve latest version of node key process)
* - if still can't read node key, attempt to find a new ACL interposed between the data node
* and the old node key node, and see if we have access to its latest node key (== retrieve
* latest version of node key process), and then crawl through previous key blocks till we
* get the one we want
*
* write:
* - find closest node key (non-gone)
* - decrypt its latest version, if can't, have no read access, which means have no write access
* - determine whether it's "dirty" -- needs to be superseded. ACL-changes update node key versions,
* what we need to do is determine whether any groups have updated their keys
* - if so, replace it
* - use it to protect data key
// We don't have a key cached. Either we don't have access, we aren't in one of the
// relevant groups, or we are, but we haven't pulled the appropriate version of the group
// key (because it's old, or because we don't know we're in that group).
// We can get this node key because either we're in one of the groups it was made
// available to, or because it's old, and we have access to one of the groups that
// has current access.
// Want to get the latest version of this node key, then do the walk to figure
// out how to read it. Need to split this code up:
// Given specific version (potentially old):
// - enumerate key blocks and group names
// - if we have one cached, use key
// - for groups we believe we're a member of, pull the link and see what key it points to
// - if it's older than the group key we know, walk back from the group key we know, caching
// all the way (this will err on the side of reading; starting from the current group will
// err on the side of making access control coverage look more extensive)
// - if we know nothing else, pull the latest version and walk that if it's newer than this one
// - if that results in a key, chain backwards to this key
// Given latest version:
// - enumerate key blocks, and group names
// - if we have one cached, just use it
// - walk the groups, starting with the groups we believe we're a member of
// - for groups we believe we're in, check if we're still in, then check for a given key
// - walk the groups we don't know if we're in, see if we're in, and can pull the necessary key
// - given that, unwrap the key and return it
// basic flow -- flag that says whether we believe we have the latest or not, if set, walk
// groups we don't know about, if not set, pull latest and if we get something later, make
// recursive call saying we believe it's the latest (2-depth recursion max)
// As we look at more stuff, we cache more keys, and fall more and more into the cache-only
// path.
*
*/
public class AccessControlManager {
/**
* Default data key length in bytes. No real reason this can't be bumped up to 32. It
* acts as the seed for a KDF, not an encryption key.
*/
public static final int DEFAULT_DATA_KEY_LENGTH = 16;
/**
* The keys we're wrapping are really seeds for a KDF, not keys in their own right.
* Eventually we'll use CMAC, so call them AES...
*/
public static final String DEFAULT_DATA_KEY_ALGORITHM = "AES";
/**
* This algorithm must be capable of key wrap (RSA, ElGamal, etc).
*/
public static final String DEFAULT_GROUP_KEY_ALGORITHM = "RSA";
public static final int DEFAULT_GROUP_KEY_LENGTH = 1024;
public static final String DATA_KEY_LABEL = "Data Key";
public static final String NODE_KEY_LABEL = "Node Key";
public static final long DEFAULT_TIMEOUT = 1000;
public static final long DEFAULT_FRESHNESS_INTERVAL = 100;
public static final long DEFAULT_NODE_KEY_FRESHNESS_INTERVAL = DEFAULT_FRESHNESS_INTERVAL;
public static final long DEFAULT_DATA_KEY_FRESHNESS_INTERVAL = DEFAULT_FRESHNESS_INTERVAL;
public static final long DEFAULT_ACL_FRESHNESS_INTERVAL = DEFAULT_FRESHNESS_INTERVAL;
public static final long DEFAULT_GROUP_PUBLIC_KEY_FRESHNESS_INTERVAL = 3600;
public static final long DEFAULT_GROUP_PRIVATE_KEY_FRESHNESS_INTERVAL = 3600;
public static final long DEFAULT_GROUP_ENCRYPTED_KEY_BLOCK_FRESHNESS_INTERVAL = DEFAULT_FRESHNESS_INTERVAL;
private ContentName _namespace;
private ContentName _userStorage;
private EnumeratedNameList _userList;
private GroupManager _groupManager = null;
private HashSet<ContentName> _myIdentities = new HashSet<ContentName>();
private KeyCache _keyCache;
private CCNHandle _handle;
private SecureRandom _random = new SecureRandom();
public AccessControlManager(ContentName namespace) throws ConfigurationException, IOException {
this(namespace, null);
}
public AccessControlManager(ContentName namespace, CCNHandle handle) throws ConfigurationException, IOException {
this(namespace, AccessControlProfile.groupNamespaceName(namespace), AccessControlProfile.userNamespaceName(namespace), handle);
}
public AccessControlManager(ContentName namespace, ContentName groupStorage, ContentName userStorage) throws ConfigurationException, IOException {
this(namespace, groupStorage, userStorage, null);
}
public AccessControlManager(ContentName namespace, ContentName groupStorage, ContentName userStorage, CCNHandle handle) throws ConfigurationException, IOException {
_namespace = namespace;
_userStorage = userStorage;
if (null == handle) {
_handle = CCNHandle.open();
} else {
_handle = handle;
}
_keyCache = new KeyCache(_handle.keyManager());
// start enumerating users in the background
userList();
_groupManager = new GroupManager(this, groupStorage, _handle);
// TODO here, check for a namespace marker, and if one not there, write it (async)
}
public GroupManager groupManager() { return _groupManager; }
/**
* Publish my identity (i.e. my public key) under a specified CCN name
* @param identity the name
* @param myPublicKey my public key
* @throws InvalidKeyException
* @throws IOException
* @throws ConfigurationException
* @throws XMLStreamException
*/
public void publishMyIdentity(ContentName identity, PublicKey myPublicKey) throws InvalidKeyException, IOException, ConfigurationException, XMLStreamException {
KeyManager km = _handle.keyManager();
if (null == myPublicKey) {
myPublicKey = km.getDefaultPublicKey();
}
PublicKeyObject pko = new PublicKeyObject(identity, myPublicKey, handle());
pko.saveToRepository();
_myIdentities.add(identity);
}
/**
* Publish my identity (i.e. my public key) under a specified user name
* @param userName the user name
* @param myPublicKey my public key
* @throws InvalidKeyException
* @throws IOException
* @throws ConfigurationException
* @throws XMLStreamException
*/
public void publishMyIdentity(String userName, PublicKey myPublicKey) throws InvalidKeyException, IOException, ConfigurationException, XMLStreamException {
Log.finest("publishing my identity" + AccessControlProfile.userNamespaceName(_userStorage, userName));
publishMyIdentity(AccessControlProfile.userNamespaceName(_userStorage, userName), myPublicKey);
}
/**
* Publish the specified identity (i.e. the public key) of a specified user
* @param userName the name of the user
* @param userPublicKey the public key of the user
* @throws ConfigurationException
* @throws IOException
* @throws MalformedContentNameStringException
*/
public void publishUserIdentity(String userName, PublicKey userPublicKey) throws ConfigurationException, IOException, MalformedContentNameStringException {
PublicKeyObject pko = new PublicKeyObject(ContentName.fromNative(userName), userPublicKey, handle());
System.out.println("saving user pubkey to repo:" + userName);
pko.saveToRepository();
}
public boolean haveIdentity(String userName) {
return _myIdentities.contains(AccessControlProfile.userNamespaceName(_userStorage, userName));
}
public boolean haveIdentity(ContentName userName) {
return _myIdentities.contains(userName);
}
/**
* Labels for deriving various types of keys.
* @return
*/
public String dataKeyLabel() {
return DATA_KEY_LABEL;
}
public String nodeKeyLabel() {
return NODE_KEY_LABEL;
}
CCNHandle handle() { return _handle; }
KeyCache keyCache() { return _keyCache; }
/**
* Enumerate users
* @return user enumeration
* @throws IOException
*/
public EnumeratedNameList userList() throws IOException {
if (null == _userList) {
_userList = new EnumeratedNameList(_userStorage, handle());
}
return _userList;
}
public boolean inProtectedNamespace(ContentName content) {
return _namespace.isPrefixOf(content);
}
/**
* Get the latest key for a specified principal
* TODO shortcut slightly -- the principal we have cached might not meet the
* constraints of the link.
* @param principal the principal
* @return the public key object
* @throws XMLStreamException
* @throws IOException
* @throws ConfigurationException
*/
public PublicKeyObject getLatestKeyForPrincipal(Link principal) throws IOException, XMLStreamException, ConfigurationException {
if (null == principal) {
Log.info("Cannot retrieve key for empty principal.");
return null;
}
PublicKeyObject pko = null;
if (_groupManager.isGroup(principal)) {
pko = _groupManager.getLatestPublicKeyForGroup(principal);
} else {
Log.info("Retrieving latest key for user: " + principal.targetName());
pko = new PublicKeyObject(principal.targetName(), principal.targetAuthenticator().publisher(), handle());
}
return pko;
}
/**
* Creates the root ACL for _namespace.
* This initialization must be done before any other ACL or node key can be read or written.
* @param rootACL the root ACL
*/
public void initializeNamespace(ACL rootACL) throws XMLStreamException, IOException, ConfigurationException, InvalidKeyException {
// generates the new node key
generateNewNodeKey(_namespace, null, rootACL);
// write the root ACL
ACLObject aclo = new ACLObject(AccessControlProfile.aclName(_namespace), rootACL, handle());
aclo.saveToRepository();
}
/**
* Retrieves the latest version of an ACL effective at this node, either stored
* here or at one of its ancestors.
* @param nodeName the name of the node
* @return the ACL object
* @throws ConfigurationException
* @throws IOException
* @throws XMLStreamException
* @throws ConfigurationException
*/
public ACLObject getEffectiveACLObject(ContentName nodeName) throws XMLStreamException, IOException, ConfigurationException {
// Find the closest node that has a non-gone ACL
ACLObject aclo = findAncestorWithACL(nodeName);
if (null == aclo) {
Log.warning("Unexpected: cannot find an ancestor of node " + nodeName + " that has an ACL.");
throw new IOException("Unexpected: cannot find an ancestor of node " + nodeName + " that has an ACL.");
}
return aclo;
}
private ACLObject findAncestorWithACL(ContentName dataNodeName) throws XMLStreamException, IOException, ConfigurationException {
ACLObject ancestorACLObject = null;
ContentName parentName = dataNodeName;
ContentName nextParentName = null;
while (null == ancestorACLObject) {
ancestorACLObject = getACLObjectForNodeIfExists(parentName);
if ((null != ancestorACLObject) && (ancestorACLObject.isGone())) {
Log.info("Found an ACL object at " + ancestorACLObject.getVersionedName() + " but its GONE.");
ancestorACLObject = null;
}
nextParentName = parentName.parent();
// stop looking once we're above our namespace, or if we've already checked the top level
if (nextParentName.count() < _namespace.count() || parentName.count() == 0) {
break;
}
parentName = nextParentName;
}
if (null == ancestorACLObject) {
throw new IllegalStateException("No ACL available in ancestor tree for node : " + dataNodeName);
}
Log.info("Found ACL for " + dataNodeName + " at ancestor :" + ancestorACLObject.getVersionedName());
return ancestorACLObject;
}
/**
* Try to pull an ACL for a particular node. If it doesn't exist, will time
* out. Use enumeration to decide whether to call this to avoid the timeout.
* @param aclNodeName the node name
* @return the ACL object
* @throws IOException
* @throws XMLStreamException
* @throws ConfigurationException
*/
public ACLObject getACLObjectForNode(ContentName aclNodeName) throws XMLStreamException, IOException, ConfigurationException {
// Get the latest version of the acl. We don't care so much about knowing what version it was.
ACLObject aclo = new ACLObject(AccessControlProfile.aclName(aclNodeName), handle());
aclo.update();
// if there is no update, this will probably throw an exception -- IO or XMLStream
if (aclo.isGone()) {
// treat as if no acl on node
return null;
}
return aclo;
}
/**
* Try to pull an ACL for a specified node if it exists.
* @param aclNodeName the name of the node
* @return the ACL object
* @throws XMLStreamException
* @throws IOException
* @throws ConfigurationException
*/
public ACLObject getACLObjectForNodeIfExists(ContentName aclNodeName) throws XMLStreamException, IOException, ConfigurationException {
EnumeratedNameList aclNameList = EnumeratedNameList.exists(AccessControlProfile.aclName(aclNodeName), aclNodeName, handle());
if (null != aclNameList) {
ContentName aclName = new ContentName(AccessControlProfile.aclName(aclNodeName));
Log.info("Found latest version of acl for " + aclNodeName + " at " + aclName);
ACLObject aclo = new ACLObject(aclName, handle());
aclo.update();
if (aclo.isGone())
return null;
return aclo;
}
Log.info("No ACL found on node: " + aclNodeName);
return null;
}
/**
* Get the effective ACL for a node specified by its name
* @param nodeName the name of the node
* @return the effective ACL
* @throws XMLStreamException
* @throws IOException
* @throws ConfigurationException
*/
public ACL getEffectiveACL(ContentName nodeName) throws XMLStreamException, IOException, ConfigurationException {
ACLObject aclo = getEffectiveACLObject(nodeName);
if (null != aclo) {
return aclo.acl();
}
return null;
}
/**
* Adds an ACL to a node that doesn't have one, or replaces one that exists.
* Just writes, doesn't bother to look at any current ACL. Does need to pull
* the effective node key at this node, though, to wrap the old ENK in a new
* node key.
*
* @param nodeName the name of the node
* @param newACL the new ACL
* @return
* @throws XMLStreamException
* @throws IOException
* @throws InvalidKeyException
* @throws ConfigurationException
* @throws AccessDeniedException
* @throws InvalidCipherTextException
*/
public ACL setACL(ContentName nodeName, ACL newACL) throws XMLStreamException, IOException, InvalidKeyException, ConfigurationException, AccessDeniedException, InvalidCipherTextException {
// Throws access denied exception if we can't read the old node key.
NodeKey effectiveNodeKey = getEffectiveNodeKey(nodeName);
// generates the new node key, wraps it under the new acl, and wraps the old node key
generateNewNodeKey(nodeName, effectiveNodeKey, newACL);
// write the acl
ACLObject aclo = new ACLObject(AccessControlProfile.aclName(nodeName), newACL, handle());
// DKS FIX REPO WRITE
aclo.save();
return aclo.acl();
}
/**
* Delete the ACL at this node if one exists, returning control to the
* next ACL upstream.
* We simply add a supserseded by block at this node, wrapping this key in the key of the upstream
* node. If we don't have read access at that node, throw AccessDeniedException.
* Then we write a GONE block here for the ACL, and a new node key version with a superseded by block.
* The superseded by block should probably be encrypted not with the ACL in force, but with the effective
* node key of the parent -- that will be derivable from the appropriate ACL, and will have the right semantics
* if a new ACL is interposed later. In the meantime, all the people with the newly in-force ancestor
* ACL should be able to read this content.
* @param nodeName
* @throws XMLStreamException
* @throws IOException
* @throws ConfigurationException
* @throws InvalidKeyException
* @throws InvalidCipherTextException
* @throws AccessDeniedException
*/
public void deleteACL(ContentName nodeName) throws XMLStreamException, IOException, ConfigurationException, InvalidKeyException, InvalidCipherTextException, AccessDeniedException {
// First, find ACL at this node if one exists.
ACLObject thisNodeACL = getACLObjectForNodeIfExists(nodeName);
if (null == thisNodeACL) {
Log.info("Asked to delete ACL for node " + nodeName + " that doesn't have one. Doing nothing.");
return;
}
Log.info("Deleting ACL for node " + nodeName + " latest version: " + thisNodeACL.getVersionedName());
// Then, find the latest node key. This should not be a derived node key.
NodeKey nk = getEffectiveNodeKey(nodeName);
// Next, find the ACL that is in force after the deletion.
ContentName parentName = nodeName.parent();
NodeKey effectiveParentNodeKey = getLatestNodeKeyForNode(parentName);
// Generate a superseded block for this node, wrapping its key in the parent.
// TODO want to wrap key in parent's effective key, but can't point to that -- no way to name an
// effective node key... need one.
KeyDirectory.addSupersededByBlock(nk.storedNodeKeyName(), nk.nodeKey(),
effectiveParentNodeKey.nodeName(), effectiveParentNodeKey.nodeKey(), handle());
// Then mark the ACL as gone.
thisNodeACL.saveAsGone();
}
/**
* Pulls the ACL for this node, if one exists, and modifies it to include
* the following changes, then stores the result using setACL, updating
* the node key if necessary in the process.
*
* @param nodeName the name of the node
* @param ACLUpdates the updates to the ACL
* @return the updated ACL
* @throws XMLStreamException
* @throws IOException
* @throws InvalidKeyException
* @throws ConfigurationException
* @throws AccessDeniedException
* @throws InvalidCipherTextException
*/
public ACL updateACL(ContentName nodeName, ArrayList<ACL.ACLOperation> ACLUpdates) throws XMLStreamException, IOException, InvalidKeyException, ConfigurationException, AccessDeniedException, InvalidCipherTextException {
ACLObject currentACL = getACLObjectForNodeIfExists(nodeName);
ACL newACL = null;
if (null != currentACL) {
newACL = currentACL.acl();
}else{
Log.info("Adding brand new ACL to node: " + nodeName);
//TODO: if no operations is specified, then a new empty ACL is created...
newACL = new ACL();
}
LinkedList<Link> newReaders = newACL.update(ACLUpdates);
if ((null == newReaders) || (null == currentACL)) {
// null newReaders means we revoked someone.
// null currentACL means we're starting from scratch
// Set the ACL and update the node key.
return setACL(nodeName, newACL);
}
// If we get back a list of new readers, it means all we have to do
// is add key blocks for them, not update the node key. (And it means
// we have a node key for this node.)
// Wait to save the new ACL till we are sure we're allowed to do this.
KeyDirectory keyDirectory = null;
try {
// If we can't read the node key, we can't update. Get the effective node key.
// Better be a node key here... and we'd better be allowed to read it.
NodeKey latestNodeKey = getLatestNodeKeyForNode(nodeName);
if (null == latestNodeKey) {
Log.info("Cannot read the latest node key for " + nodeName);
throw new AccessDeniedException("Cannot read the latest node key for " + nodeName);
}
keyDirectory = new KeyDirectory(this, latestNodeKey.storedNodeKeyName(), handle());
for (Link principal : newReaders) {
PublicKeyObject latestKey = getLatestKeyForPrincipal(principal);
try {
if (!latestKey.available()) {
latestKey.wait(DEFAULT_TIMEOUT);
}
} catch (InterruptedException ex) {
// do nothing
}
if (latestKey.available()) {
Log.info("Adding wrapped key block for reader: " + latestKey.getVersionedName());
try {
keyDirectory.addWrappedKeyBlock(latestNodeKey.nodeKey(), latestKey.getVersionedName(), latestKey.publicKey());
} catch (VersionMissingException e) {
Log.warning("UNEXPECTED: latest key for prinicpal: " + latestKey.getVersionedName() + " has no version? Skipping.");
}
} else {
// Do we use an old key or give up?
Log.info("No key for " + principal + " found. Skipping.");
}
}
} finally {
if (null != keyDirectory) {
keyDirectory.stopEnumerating();
}
}
// If we got here, we got the node key we were updating, so we are allowed
// to at least read this stuff (though maybe not write it). Save the acl.
currentACL.save(newACL);
return newACL;
}
/**
* Add readers to a specified node
* @param nodeName the name of the node
* @param newReaders the list of new readers
* @return the updated ACL
* @throws InvalidKeyException
* @throws XMLStreamException
* @throws IOException
* @throws ConfigurationException
* @throws AccessDeniedException
* @throws InvalidCipherTextException
*/
public ACL addReaders(ContentName nodeName, ArrayList<Link> newReaders) throws InvalidKeyException, XMLStreamException, IOException, ConfigurationException, AccessDeniedException, InvalidCipherTextException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link reader : newReaders){
ops.add(ACLOperation.addReaderOperation(reader));
}
return updateACL(nodeName, ops);
}
/**
* Add writers to a specified node.
* @param nodeName the name of the node
* @param newWriters the list of new writers
* @return the updated ACL
* @throws InvalidKeyException
* @throws XMLStreamException
* @throws IOException
* @throws ConfigurationException
* @throws AccessDeniedException
* @throws InvalidCipherTextException
*/
public ACL addWriters(ContentName nodeName, ArrayList<Link> newWriters) throws InvalidKeyException, XMLStreamException, IOException, ConfigurationException, AccessDeniedException, InvalidCipherTextException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link writer : newWriters){
ops.add(ACLOperation.addWriterOperation(writer));
}
return updateACL(nodeName, ops);
}
/**
* Add managers to a specified node
* @param nodeName the name of the node
* @param newManagers the list of new managers
* @return the updated ACL
* @throws InvalidKeyException
* @throws XMLStreamException
* @throws IOException
* @throws ConfigurationException
* @throws AccessDeniedException
* @throws InvalidCipherTextException
*/
public ACL addManagers(ContentName nodeName, ArrayList<Link> newManagers) throws InvalidKeyException, XMLStreamException, IOException, ConfigurationException, AccessDeniedException, InvalidCipherTextException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link manager: newManagers){
ops.add(ACLOperation.addManagerOperation(manager));
}
return updateACL(nodeName, ops);
}
/**
* Get the ancestor node key in force at this node (if we can decrypt it),
* including a key at this node itself. We use the fact that ACLs and
* node keys are co-located; if you have one, you have the other.
* @param nodeName the name of the node
* @return null means while node keys exist, we can't decrypt any of them --
* we have no read access to this node (which implies no write access)
* @throws IOException if something is wrong (e.g. no node keys at all)
* @throws XMLStreamException
* @throws ConfigurationException
* @throws InvalidKeyException
* @throws InvalidCipherTextException
* @throws AccessDeniedException
*/
protected NodeKey findAncestorWithNodeKey(ContentName nodeName) throws IOException, XMLStreamException, ConfigurationException, InvalidKeyException, InvalidCipherTextException, AccessDeniedException {
// climb up looking for node keys, then make sure that one isn't GONE
// if it isn't, call read-side routine to figure out how to decrypt it
ACLObject effectiveACL = findAncestorWithACL(nodeName);
if (null == effectiveACL) {
Log.warning("Unexpected: could not find effective ACL for node: " + nodeName);
throw new IOException("Unexpected: could not find effective ACL for node: " + nodeName);
}
Log.info("Got ACL named: " + effectiveACL.getVersionedName() + " attempting to retrieve node key from " + AccessControlProfile.accessRoot(effectiveACL.getVersionedName()));
return getLatestNodeKeyForNode(AccessControlProfile.accessRoot(effectiveACL.getVersionedName()));
}
/**
* Write path: get the latest node key for a node.
* @param nodeName the name of the node
* @return the corresponding node key
* @throws IOException
* @throws InvalidKeyException
* @throws InvalidCipherTextException
* @throws XMLStreamException
* @throws ConfigurationException
* @throws AccessDeniedException
*/
public NodeKey getLatestNodeKeyForNode(ContentName nodeName) throws IOException, InvalidKeyException, InvalidCipherTextException, XMLStreamException, ConfigurationException, AccessDeniedException {
// Could do this using getLatestVersion...
// First we need to figure out what the latest version is of the node key.
ContentName nodeKeyVersionedName =
EnumeratedNameList.getLatestVersionName(AccessControlProfile.nodeKeyName(nodeName), handle());
// DKS TODO this may not handle ACL deletion correctly -- we need to make sure that this
// key wasn't superseded by something that isn't a later version of itself.
// then, pull the node key we can decrypt
return getNodeKeyByVersionedName(nodeKeyVersionedName, null);
}
/**
* Read path:
* Retrieve a specific node key from a given location, as specified by a
* key it was used to wrap, and, if possible, find a key we can use to
* unwrap the node key.
*
* Throw an exception if there is no node key block at the appropriate name.
* @param nodeKeyName
* @param nodeKeyIdentifier
* @return the node key
* @throws IOException
* @throws XMLStreamException
* @throws InvalidCipherTextException
* @throws InvalidKeyException
* @throws ConfigurationException
* @throws AccessDeniedException
*/
public NodeKey getSpecificNodeKey(ContentName nodeKeyName, byte [] nodeKeyIdentifier) throws InvalidKeyException, InvalidCipherTextException, XMLStreamException, IOException, ConfigurationException, AccessDeniedException {
if ((null == nodeKeyName) && (null == nodeKeyIdentifier)) {
throw new IllegalArgumentException("Node key name and identifier cannot both be null!");
}
// We should know what node key to use (down to the version), but we have to find the specific
// wrapped key copy we can decrypt.
NodeKey nk = getNodeKeyByVersionedName(nodeKeyName, nodeKeyIdentifier);
if (null == nk) {
Log.warning("No decryptable node key available at " + nodeKeyName + ", access denied.");
return null;
}
return nk;
}
/**
* We have the name of a specific version of a node key. Now we just need to figure
* out which of our keys can be used to decrypt it.
* @param nodeKeyName
* @param nodeKeyIdentifier
* @return
* @throws XMLStreamException
* @throws IOException
* @throws InvalidKeyException
* @throws InvalidCipherTextException
* @throws ConfigurationException
* @throws AccessDeniedException
*/
NodeKey getNodeKeyByVersionedName(ContentName nodeKeyName, byte [] nodeKeyIdentifier) throws XMLStreamException, IOException, InvalidKeyException, InvalidCipherTextException, ConfigurationException, AccessDeniedException {
NodeKey nk = null;
KeyDirectory keyDirectory = null;
try {
keyDirectory = new KeyDirectory(this, nodeKeyName, handle());
// this will handle the caching.
Key unwrappedKey = keyDirectory.getUnwrappedKey(nodeKeyIdentifier);
if (null != unwrappedKey) {
nk = new NodeKey(nodeKeyName, unwrappedKey);
} else {
throw new AccessDeniedException("Access denied: cannot retrieve key " + DataUtils.printBytes(nodeKeyIdentifier) + " at name " + nodeKeyName);
}
} finally {
if (null != keyDirectory) {
keyDirectory.stopEnumerating();
}
}
return nk;
}
/**
* Write path:
* Get the effective node key in force at this node, used to derive keys to
* encrypt content. Vertical chaining. Works if you ask for node which has
* a node key.
* TODO -- when called by writers, check to see if node key is dirty & update.
* @param nodeName
* @return
* @throws InvalidKeyException
* @throws XMLStreamException
* @throws IOException
* @throws AccessDeniedException
* @throws InvalidCipherTextException
* @throws ConfigurationException
*/
public NodeKey getEffectiveNodeKey(ContentName nodeName) throws InvalidKeyException, XMLStreamException, IOException, AccessDeniedException, InvalidCipherTextException, ConfigurationException {
// Get the ancestor node key in force at this node.
NodeKey nodeKey = findAncestorWithNodeKey(nodeName);
if (null == nodeKey) {
throw new AccessDeniedException("Cannot retrieve node key for node: " + nodeName + ".");
}
Log.info("Found node key at " + nodeKey.storedNodeKeyName());
NodeKey effectiveNodeKey = nodeKey.computeDescendantNodeKey(nodeName, nodeKeyLabel());
Log.info("Computing effective node key for " + nodeName + " using stored node key " + effectiveNodeKey.storedNodeKeyName());
return effectiveNodeKey;
}
/**
* Like #getEffectiveNodeKey(ContentName), except checks to see if node
* key is dirty and updates it if necessary.
* @param nodeName
* @return
* @throws InvalidKeyException
* @throws InvalidCipherTextException
* @throws AccessDeniedException
* @throws IOException
* @throws XMLStreamException
* @throws ConfigurationException
*/
public NodeKey getFreshEffectiveNodeKey(ContentName nodeName) throws InvalidKeyException, InvalidCipherTextException, AccessDeniedException, IOException, XMLStreamException, ConfigurationException {
NodeKey nodeKey = findAncestorWithNodeKey(nodeName);
if (null == nodeKey) {
throw new AccessDeniedException("Cannot retrieve node key for node: " + nodeName + ".");
}
// This should be the latest node key; i.e. not superseded.
if (nodeKeyIsDirty(nodeKey.storedNodeKeyName())) {
Log.info("Found node key at " + nodeKey.storedNodeKeyName() + ", updating.");
ContentName nodeKeyNodeName = AccessControlProfile.accessRoot(nodeKey.storedNodeKeyName());
ACLObject acl = getACLObjectForNode(nodeKeyNodeName);
nodeKey = generateNewNodeKey(nodeKeyNodeName, nodeKey, acl.acl());
} else {
Log.info("Found node key at " + nodeKey.storedNodeKeyName());
}
NodeKey effectiveNodeKey = nodeKey.computeDescendantNodeKey(nodeName, nodeKeyLabel());
Log.info("Computing effective node key for " + nodeName + " using stored node key " + effectiveNodeKey.storedNodeKeyName());
return effectiveNodeKey;
}
/**
* Do we need to update this node key?
* First, we look to see whether or not we know the key is dirty -- i.e.
* does it have a superseded block (if it's gone, it will also have a
* superseded block). If not, we have to really check...
* Basically, we look at all the entities this node key is encrypted for,
* and determine whether any of them have a new version of their public
* key. If so, the node key is dirty.
*
* The initial implementation of this will be simple and slow -- iterating through
* groups and assuming the active object system will keep updating itself whenever
* a new key appears. Eventually, we might want an index directory of all the
* versions of keys, so that one name enumeration request might give us information
* about whether keys have been updated. (Or some kind of aggregate versioning,
* that tell us a) whether any groups have changed their versions, or b) just the
* ones we care about have.)
*
* This can be called by anyone -- the data about whether a node key is dirty
* is visible to anyone. Fixing a dirty node key requires access, though.
* @param theNodeKeyName this might be the name of the node where the NK is stored,
* or the NK name itself.
* We assume this exists -- that there at some point has been a node key here.
* TODO ephemeral node key naming
* @return
* @throws IOException
* @throws ConfigurationException
* @throws XMLStreamException
*/
public boolean nodeKeyIsDirty(ContentName theNodeKeyName) throws IOException, ConfigurationException, XMLStreamException {
// first, is this a node key name?
if (!AccessControlProfile.isNodeKeyName(theNodeKeyName)) {
// assume it's a data node name.
theNodeKeyName = AccessControlProfile.nodeKeyName(theNodeKeyName);
}
// get the requested version of this node key; or if unversioned, get the latest.
KeyDirectory nodeKeyDirectory = null;
try {
nodeKeyDirectory = new KeyDirectory(this, theNodeKeyName, handle());
if (null == nodeKeyDirectory) {
throw new IOException("Cannot get node key directory for : " + theNodeKeyName);
}
if (nodeKeyDirectory.hasSupersededBlock()) {
return true;
}
for (PrincipalInfo principal : nodeKeyDirectory.getCopyOfPrincipals().values()) {
if (principal.isGroup()) {
Group theGroup = groupManager().getGroup(principal.friendlyName());
if (theGroup.publicKeyVersion().after(principal.versionTimestamp())) {
return true;
}
} else {
// DKS TODO -- for now, don't handle versioning of non-group keys
Log.info("User key for " + principal.friendlyName() + ", not checking version.");
// Technically, we're not handling versioning for user keys, but be nice. Start
// by seeing if we have a link to the key in our user space.
// If the principal isn't available in our enumerated list, have to go get its key
// from the wrapped key object.
}
}
return false;
} finally {
if (null != nodeKeyDirectory)
nodeKeyDirectory.stopEnumerating();
}
}
/**
* Would we update this data key if we were doing reencryption?
* This one is simpler -- what node key is the data key encrypted under, and is
* that node key dirty?
*
* This can be called by anyone -- the data about whether a data key is dirty
* is visible to anyone. Fixing a dirty key requires access, though.
*
* @param dataName
* @return
* @throws IOException
* @throws XMLStreamException
* @throws ConfigurationException
*/
public boolean dataKeyIsDirty(ContentName dataName) throws IOException, XMLStreamException, ConfigurationException {
// TODO -- do we need to check whether there *is* a key?
// The trick: we need the header information in the wrapped key; we don't need to unwrap it.
// ephemeral key naming
WrappedKeyObject wrappedDataKey = new WrappedKeyObject(AccessControlProfile.dataKeyName(dataName), handle());
return nodeKeyIsDirty(wrappedDataKey.wrappedKey().wrappingKeyName());
}
/**
* We've looked for a node key we can decrypt at the expected node key location,
* but no dice. See if a new ACL has been interposed granting us rights at a lower
* portion of the tree.
* @param dataNodeName
* @param wrappingKeyName
* @param wrappingKeyIdentifier
* @return
* @throws XMLStreamException
* @throws IOException
* @throws InvalidKeyException
* @throws InvalidCipherTextException
* @throws ConfigurationException
* @throws AccessDeniedException
*/
protected NodeKey getNodeKeyUsingInterposedACL(ContentName dataNodeName,
ContentName wrappingKeyName, byte[] wrappingKeyIdentifier) throws XMLStreamException, IOException, InvalidKeyException, InvalidCipherTextException, ConfigurationException, AccessDeniedException {
ACLObject nearestACL = findAncestorWithACL(dataNodeName);
if (null == nearestACL) {
Log.warning("Unexpected -- node with no ancestor ACL: " + dataNodeName);
// no dice
return null;
}
if (nearestACL.equals(AccessControlProfile.accessRoot(wrappingKeyName))) {
Log.info("Node key: " + wrappingKeyName + " is the nearest ACL to " + dataNodeName);
return null;
}
NodeKey nk = getLatestNodeKeyForNode(AccessControlProfile.accessRoot(nearestACL.getVersionedName()));
return nk;
}
/**
* Make a new node key and encrypt it under the given ACL.
* If there is a previous node key (oldEffectiveNodeKey not null), it is wrapped in the new node key.
* Put all the blocks into the aggregating writer, but don't flush.
*
* @param nodeName
* @param oldEffectiveNodeKey
* @param effectiveACL
* @return
* @throws IOException
* @throws ConfigurationException
* @throws XMLStreamException
* @throws InvalidKeyException if one of the public keys for someone specified on the ACL is invalid.
*/
protected NodeKey generateNewNodeKey(ContentName nodeName, NodeKey oldEffectiveNodeKey, ACL effectiveACL)
throws IOException, ConfigurationException, XMLStreamException, InvalidKeyException {
// Get the name of the key directory; this is unversioned. Make a new version of it.
ContentName nodeKeyDirectoryName = VersioningProfile.addVersion(AccessControlProfile.nodeKeyName(nodeName));
Log.info("Generating new node key " + nodeKeyDirectoryName);
// Now, generate the node key.
if (effectiveACL.publiclyReadable()) {
// TODO Put something here that will represent public; need to then make it so that key-reading code will do
// the right thing when it encounters it.
throw new UnsupportedOperationException("Need to implement public node key representation!");
}
byte [] nodeKeyBytes = new byte[NodeKey.DEFAULT_NODE_KEY_LENGTH];
_random.nextBytes(nodeKeyBytes);
Key nodeKey = new SecretKeySpec(nodeKeyBytes, NodeKey.DEFAULT_NODE_KEY_ALGORITHM);
// Now, wrap it under the keys listed in its ACL.
// Make a key directory. If we give it a versioned name, it will start enumerating it, but won't block.
KeyDirectory nodeKeyDirectory = null;
NodeKey theNodeKey = null;
try {
nodeKeyDirectory = new KeyDirectory(this, nodeKeyDirectoryName, handle());
theNodeKey = new NodeKey(nodeKeyDirectoryName, nodeKey);
// Add a key block for every reader on the ACL. As managers and writers can read, they are all readers.
// TODO -- pulling public keys here; could be slow; might want to manage concurrency over acl.
for (Link aclEntry : effectiveACL.contents()) {
PublicKeyObject entryPublicKey = null;
if (groupManager().isGroup(aclEntry)) {
entryPublicKey = groupManager().getLatestPublicKeyForGroup(aclEntry);
} else {
// Calls update. Will get latest version if name unversioned.
entryPublicKey = new PublicKeyObject(aclEntry.targetName(), aclEntry.targetAuthenticator().publisher(), handle());
}
try {
nodeKeyDirectory.addWrappedKeyBlock(nodeKey, entryPublicKey.getVersionedName(), entryPublicKey.publicKey());
} catch (VersionMissingException ve) {
Log.logException("Unexpected version missing exception for public key " + entryPublicKey.getVersionedName(), ve);
throw new IOException("Unexpected version missing exception for public key " + entryPublicKey.getVersionedName() + ": " + ve);
}
}
// Add a superseded by block to the previous key. Two cases: old effective node key is at the same level
// as us (we are superseding it entirely), or we are interposing a key (old key is above or below us).
// OK, here are the options:
// Replaced node key is a derived node key -- we are interposing an ACL
// Replaced node key is a stored node key
// -- we are updating that node key to a new version
// NK/vn replaced by NK/vn+k -- new node key will be later version of previous node key
// -- we don't get called if we are deleting an ACL here -- no new node key is added.
if (oldEffectiveNodeKey != null) {
if (oldEffectiveNodeKey.isDerivedNodeKey()) {
// Interposing an ACL.
// Add a previous key block wrapping the previous key. There is nothing to link to.
nodeKeyDirectory.addPreviousKeyBlock(oldEffectiveNodeKey.nodeKey(), nodeKeyDirectoryName, nodeKey);
} else {
try {
if (!VersioningProfile.isLaterVersionOf(nodeKeyDirectoryName, oldEffectiveNodeKey.storedNodeKeyName())) {
Log.warning("Unexpected: replacing node key stored at " + oldEffectiveNodeKey.storedNodeKeyName() + " with new node key " +
nodeKeyDirectoryName + " but latter is not later version of the former.");
}
} catch (VersionMissingException vex) {
Log.warning("Very unexpected version missing exception when replacing node key : " + vex);
}
// Add a previous key link to the old version of the key.
// TODO do we need to add publisher?
nodeKeyDirectory.addPreviousKeyLink(oldEffectiveNodeKey.storedNodeKeyName(), null);
// OK, just add superseded-by block to the old directory.
KeyDirectory.addSupersededByBlock(oldEffectiveNodeKey.storedNodeKeyName(), oldEffectiveNodeKey.nodeKey(),
nodeKeyDirectoryName, nodeKey, handle());
}
}
} finally {
if (null != nodeKeyDirectory) {
nodeKeyDirectory.stopEnumerating();
}
}
// Return the key for use, along with its name.
return theNodeKey;
}
public NodeKey getNodeKeyForObject(ContentName nodeName, WrappedKeyObject wko) throws InvalidKeyException, XMLStreamException, InvalidCipherTextException, IOException, ConfigurationException, AccessDeniedException {
// First, we go and look for the node key where the data key suggests
// it should be, and attempt to decrypt it from there.
NodeKey nk = null;
try {
nk = getSpecificNodeKey(wko.wrappedKey().wrappingKeyName(),
wko.wrappedKey().wrappingKeyIdentifier());
} catch (AccessDeniedException ex) {
// ignore
}
if (null == nk) {
// OK, we will have gotten an exception if the node key simply didn't exist
// there, so this means that we don't have rights to read it there.
// The only way we might have rights not visible from this link is if an
// ACL has been interposed between where we are and the node key, and that
// ACL does give us rights.
nk = getNodeKeyUsingInterposedACL(nodeName, wko.wrappedKey().wrappingKeyName(),
wko.wrappedKey().wrappingKeyIdentifier());
if (null == nk) {
// Still can't find one we can read. Give up. Return null, and allow caller to throw the
// access exception.
return null;
}
}
NodeKey enk = nk.computeDescendantNodeKey(nodeName, dataKeyLabel());
return enk;
}
/**
* Used by content reader to retrieve the keys necessary to decrypt this content
* under this access control model.
* Given a data location, pull the data key block and decrypt it using
* whatever node keys are necessary.
* To turn the result of this into a key for decrypting content,
* follow the steps in the comments to #generateAndStoreDataKey(ContentName).
* @param dataNodeName
* @return
* @throws IOException
* @throws XMLStreamException
* @throws InvalidKeyException
* @throws InvalidCipherTextException
* @throws ConfigurationException
* @throws AccessDeniedException
*/
public byte [] getDataKey(ContentName dataNodeName) throws XMLStreamException, IOException, InvalidKeyException, InvalidCipherTextException, ConfigurationException, AccessDeniedException {
WrappedKeyObject wdko = new WrappedKeyObject(AccessControlProfile.dataKeyName(dataNodeName), handle());
wdko.update();
if (null == wdko.wrappedKey()) {
Log.warning("Could not retrieve data key for node: " + dataNodeName);
return null;
}
NodeKey enk = getNodeKeyForObject(dataNodeName, wdko);
if (null != enk) {
Key dataKey = wdko.wrappedKey().unwrapKey(enk.nodeKey());
return dataKey.getEncoded();
}
return null;
}
/**
* Take a randomly generated data key and store it. This requires finding
* the current effective node key, and wrapping this data key in it. If the
* current node key is dirty, this causes a new one to be generated.
* @param dataNodeName
* @param newRandomDataKey
* @throws XMLStreamException
* @throws InvalidKeyException
* @throws IllegalBlockSizeException
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws IOException
* @throws ConfigurationException
* @throws AccessDeniedException
* @throws InvalidCipherTextException
*/
public void storeDataKey(ContentName dataNodeName, Key newRandomDataKey) throws InvalidKeyException, XMLStreamException, IOException, ConfigurationException, AccessDeniedException, InvalidCipherTextException {
NodeKey effectiveNodeKey = getFreshEffectiveNodeKey(dataNodeName);
if (null == effectiveNodeKey) {
throw new AccessDeniedException("Cannot retrieve effective node key for node: " + dataNodeName + ".");
}
Log.info("Wrapping data key for node: " + dataNodeName + " with effective node key for node: " +
effectiveNodeKey.nodeName() + " derived from stored node key for node: " +
effectiveNodeKey.storedNodeKeyName());
// TODO another case where we're wrapping in an effective node key but labeling it with
// the stored node key information. This will work except if we interpose an ACL in the meantime --
// we may not have the information necessary to figure out how to decrypt.
WrappedKey wrappedDataKey = WrappedKey.wrapKey(newRandomDataKey,
null, dataKeyLabel(),
effectiveNodeKey.nodeKey());
wrappedDataKey.setWrappingKeyIdentifier(effectiveNodeKey.storedNodeKeyID());
wrappedDataKey.setWrappingKeyName(effectiveNodeKey.storedNodeKeyName());
storeKeyContent(AccessControlProfile.dataKeyName(dataNodeName), wrappedDataKey);
}
/**
* Generate a random data key, store it, and return it to use to derive keys to encrypt
* content. All that's left is to call
* byte [] randomDataKey = generateAndStoreDataKey(dataNodeName);
* byte [][] keyandiv =
* KeyDerivationFunction.DeriveKeyForObject(randomDataKey, keyLabel,
* dataNodeName, dataPublisherPublicKeyDigest)
* and then give keyandiv to the segmenter to encrypt the data.
* @throws InvalidKeyException
* @throws XMLStreamException
* @throws IOException
* @throws ConfigurationException
* @throws AccessDeniedException
* @throws InvalidCipherTextException
**/
public Key generateAndStoreDataKey(ContentName dataNodeName) throws InvalidKeyException, XMLStreamException, IOException, ConfigurationException, AccessDeniedException, InvalidCipherTextException {
// Generate new random data key of appropriate length
byte [] dataKeyBytes = new byte[DEFAULT_DATA_KEY_LENGTH];
_random.nextBytes(dataKeyBytes);
Key dataKey = new SecretKeySpec(dataKeyBytes, DEFAULT_DATA_KEY_ALGORITHM);
storeDataKey(AccessControlProfile.dataKeyName(dataNodeName), dataKey);
return dataKey;
}
/**
* Actual output functions. Needs to get this into the repo.
* @param dataNodeName -- the content node for whom this is the data key.
* @param wrappedDataKey
* @throws IOException
* @throws XMLStreamException
* @throws ConfigurationException
*/
private void storeKeyContent(ContentName dataNodeName,
WrappedKey wrappedKey) throws XMLStreamException, IOException, ConfigurationException {
// TODO DKS FIX FOR REPO
WrappedKeyObject wko = new WrappedKeyObject(AccessControlProfile.dataKeyName(dataNodeName), wrappedKey, handle());
wko.save();
}
/**
* add a private key to _keyCache
* @param keyName
* @param publicKeyIdentifier
* @param pk
*/
void addPrivateKey(ContentName keyName, byte [] publicKeyIdentifier, PrivateKey pk) {
_keyCache.addPrivateKey(keyName, publicKeyIdentifier, pk);
}
/**
* add my private key to _keyCache
* @param publicKeyIdentifier
* @param pk
*/
void addMyPrivateKey(byte [] publicKeyIdentifier, PrivateKey pk) {
_keyCache.addMyPrivateKey(publicKeyIdentifier, pk);
}
/**
* add a key to _keyCache
* @param name
* @param key
*/
public void addKey(ContentName name, Key key) {
_keyCache.addKey(name, key);
}
}
| Bug fix in AccessControlManager
| javasrc/src/org/ccnx/ccn/profiles/access/AccessControlManager.java | Bug fix in AccessControlManager |
|
Java | unlicense | dfe2d47fa4874b01b7bd6b3761bb9e3d6536f07c | 0 | charlesmadere/smash-ranks-android | package com.garpr.android.data2;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.android.volley.toolbox.JsonObjectRequest;
import com.garpr.android.data.Settings;
import com.garpr.android.misc.Constants;
import com.garpr.android.models2.Match;
import com.garpr.android.models2.Player;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public final class Matches {
static final String TAG = "Matches";
static void createTable(final SQLiteDatabase db) {
final String sql = "CREATE TABLE IF NOT EXISTS " + TAG + " (" +
Constants.OPPONENT_ID + " TEXT NOT NULL , " +
Constants.PLAYER_ID + " TEXT NOT NULL, " +
Constants.REGION_ID + " TEXT NOT NULL, " +
Constants.RESULT + " TEXT NOT NULL, " +
Constants.TOURNAMENT_ID + " TEXT NOT NULL, " +
"FOREIGN KEY (" + Constants.OPPONENT_ID + ") REFERENCES " + Players.TAG + '(' + Constants.PLAYER_ID + "), " +
"FOREIGN KEY (" + Constants.PLAYER_ID + ") REFERENCES " + Players.TAG + '(' + Constants.PLAYER_ID + "), " +
"FOREIGN KEY (" + Constants.REGION_ID + ") REFERENCES " + Regions.TAG + '(' + Constants.REGION_ID + "), " +
"FOREIGN KEY (" + Constants.TOURNAMENT_ID + ") REFERENCES " + Tournaments.TAG + '(' + Constants.TOURNAMENT_ID + "));";
db.execSQL(sql);
}
public static void get(final Response<ArrayList<Match>> response, final Player player,
final boolean clear) {
new MatchesCall(response, player, clear).start();
}
public static void get(final Response<ArrayList<Match>> response, final String regionId,
final Player player, final boolean clear) {
new MatchesCall(response, regionId, player, clear).start();
}
private static final class MatchesCall extends RegionBasedCall<ArrayList<Match>> {
private static final String TAG = "MatchesCall";
private final boolean mClear;
private final Player mPlayer;
private MatchesCall(final Response<ArrayList<Match>> response, final Player player,
final boolean clear) throws IllegalArgumentException {
this(response, Settings.getRegion().getId(), player, clear);
}
private MatchesCall(final Response<ArrayList<Match>> response, final String regionId,
final Player player, final boolean clear) {
super(response, regionId);
if (player == null) {
throw new IllegalArgumentException("player is null");
}
mPlayer = player;
mClear = clear;
}
private void clearThenMake() {
final SQLiteDatabase database = Database.start();
final String whereClause = Constants.PLAYER_ID + " = ? AND " + Constants.REGION_ID + " = ?";
final String[] whereArgs = { mPlayer.getId(), mRegionId };
database.delete(Matches.TAG, whereClause, whereArgs);
Database.stop();
super.make();
}
@Override
String getCallName() {
return TAG;
}
@Override
JsonObjectRequest getRequest() {
final String url = getBaseUrl() + '/' + Constants.MATCHES + '/' + mPlayer.getId();
return new JsonObjectRequest(url, null, this, this);
}
@Override
void make() {
if (mClear) {
clearThenMake();
} else {
readThenMake();
}
}
@Override
void onJSONResponse(final JSONObject json) throws JSONException {
final JSONArray matchesJSON = json.getJSONArray(Constants.MATCHES);
final int matchesLength = matchesJSON.length();
final ArrayList<Match> matches = new ArrayList<>(matchesLength);
for (int i = 0; i < matchesLength; ++i) {
final JSONObject matchJSON = matchesJSON.getJSONObject(i);
final Match match = new Match(matchJSON, mPlayer);
matches.add(match);
}
final SQLiteDatabase database = Database.start();
database.beginTransaction();
for (final Match match : matches) {
final ContentValues cv = match.toContentValues(mRegionId);
database.insert(Matches.TAG, null, cv);
}
database.setTransactionSuccessful();
database.endTransaction();
Database.stop();
mResponse.success(matches);
}
private void readThenMake() {
// TODO
final SQLiteDatabase database = Database.start();
final String sql = "";
final Cursor cursor = database.rawQuery(sql, null);
final ArrayList<Match> matches;
if (cursor.moveToFirst()) {
matches = new ArrayList<>();
final int opponentIdIndex = cursor.getColumnIndexOrThrow(Constants.OPPONENT_ID);
final int playerIdIndex = cursor.getColumnIndexOrThrow(Constants.PLAYER_ID);
final int playerNameIndex = cursor.getColumnIndexOrThrow(Constants.PLAYER_NAME);
do {
matches.add(null);
} while (cursor.moveToNext());
matches.trimToSize();
} else {
matches = null;
}
cursor.close();
Database.stop();
if (matches == null || matches.isEmpty()) {
super.make();
} else {
mResponse.success(matches);
}
}
}
}
| smash-ranks-android/app/src/main/java/com/garpr/android/data2/Matches.java | package com.garpr.android.data2;
import android.database.sqlite.SQLiteDatabase;
import com.garpr.android.misc.Constants;
public final class Matches {
static final String TAG = "Matches";
static void createTable(final SQLiteDatabase db) {
final String sql = "CREATE TABLE IF NOT EXISTS " + TAG + " (" +
Constants.PLAYER_1_ID + " TEXT NOT NULL , " +
Constants.PLAYER_2_ID + " TEXT NOT NULL, " +
Constants.REGION_ID + " TEXT NOT NULL, " +
Constants.RESULT + " TEXT NOT NULL, " +
Constants.TOURNAMENT_ID + " TEXT NOT NULL, " +
"FOREIGN KEY (" + Constants.PLAYER_1_ID + ") REFERENCES " + Players.TAG + '(' + Constants.ID + "), " +
"FOREIGN KEY (" + Constants.PLAYER_2_ID + ") REFERENCES " + Players.TAG + '(' + Constants.ID + "), " +
"FOREIGN KEY (" + Constants.REGION_ID + ") REFERENCES " + Regions.TAG + '(' + Constants.ID + "), " +
"FOREIGN KEY (" + Constants.TOURNAMENT_ID + ") REFERENCES " + Tournaments.TAG + '(' + Constants.ID + "));";
db.execSQL(sql);
}
}
| progress on implementing Match retrieval
| smash-ranks-android/app/src/main/java/com/garpr/android/data2/Matches.java | progress on implementing Match retrieval |
|
Java | apache-2.0 | 8a6b2109e306de6c877f1b078ee836d9ba5c1406 | 0 | bazelbuild/intellij,bazelbuild/intellij,bazelbuild/intellij,bazelbuild/intellij,bazelbuild/intellij,bazelbuild/intellij,bazelbuild/intellij | /*
* Copyright 2017 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.blaze.base.plugin;
import com.google.idea.blaze.base.bazel.BazelVersion;
import com.google.idea.blaze.base.model.BlazeVersionData;
import com.google.idea.blaze.base.scope.BlazeContext;
import com.google.idea.blaze.base.scope.output.IssueOutput;
import com.google.idea.blaze.base.settings.BuildSystem;
/** Verifies that the available Bazel version is supported by this plugin. */
public class BazelVersionChecker implements BuildSystemVersionChecker {
// version 0.23 introduced a backwards-incompatible change to the Py struct providers.
// See: https://github.com/bazelbuild/bazel/issues/7298
private static final BazelVersion OLDEST_SUPPORTED_VERSION = new BazelVersion(0, 23, 0);
@Override
public boolean versionSupported(BlazeContext context, BlazeVersionData version) {
if (version.buildSystem() != BuildSystem.Bazel) {
return true;
}
if (version.bazelIsAtLeastVersion(OLDEST_SUPPORTED_VERSION)) {
return true;
}
IssueOutput.error(
String.format(
"Bazel version %s is not supported by this version of the Bazel plugin. "
+ "Please upgrade to Bazel version %s+.\n"
+ "Upgrade instructions are available at https://bazel.build",
version, OLDEST_SUPPORTED_VERSION))
.submit(context);
return false;
}
}
| base/src/com/google/idea/blaze/base/plugin/BazelVersionChecker.java | /*
* Copyright 2017 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.blaze.base.plugin;
import com.google.idea.blaze.base.bazel.BazelVersion;
import com.google.idea.blaze.base.model.BlazeVersionData;
import com.google.idea.blaze.base.scope.BlazeContext;
import com.google.idea.blaze.base.scope.output.IssueOutput;
import com.google.idea.blaze.base.settings.BuildSystem;
/** Verifies that the available Bazel version is supported by this plugin. */
public class BazelVersionChecker implements BuildSystemVersionChecker {
// version 0.18 introduced a backwards-incompatible change to the depset API
private static final BazelVersion OLDEST_SUPPORTED_VERSION = new BazelVersion(0, 18, 0);
@Override
public boolean versionSupported(BlazeContext context, BlazeVersionData version) {
if (version.buildSystem() != BuildSystem.Bazel) {
return true;
}
if (version.bazelIsAtLeastVersion(OLDEST_SUPPORTED_VERSION)) {
return true;
}
IssueOutput.error(
String.format(
"Bazel version %s is not supported by this version of the Bazel plugin. "
+ "Please upgrade to Bazel version %s+.\n"
+ "Upgrade instructions are available at https://bazel.build",
version, OLDEST_SUPPORTED_VERSION))
.submit(context);
return false;
}
}
| Automatic GitHub Sync with Copybara
PiperOrigin-RevId: 242464990
| base/src/com/google/idea/blaze/base/plugin/BazelVersionChecker.java | Automatic GitHub Sync with Copybara |
|
Java | apache-2.0 | f85c56af54cd61b85fb9b577f91e1c5648122e4c | 0 | amaembo/streamex,manikitos/streamex | /*
* Copyright 2015 Tagir Valeev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package one.util.streamex;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.OptionalInt;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
import java.util.stream.Collector;
import java.util.stream.Collector.Characteristics;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import one.util.streamex.StreamExInternals.ObjIntBox;
import static one.util.streamex.StreamExInternals.*;
/**
* Implementations of several collectors in addition to ones available in JDK.
*
* @author Tagir Valeev
* @see Collectors
* @see Joining
* @since 0.3.2
*/
public final class MoreCollectors {
private MoreCollectors() {
throw new UnsupportedOperationException();
}
/**
* Returns a {@code Collector} which just ignores the input and calls the
* provided supplier once to return the output.
*
* @param <T>
* the type of input elements
* @param <U>
* the type of output
* @param supplier
* the supplier of the output
* @return a {@code Collector} which just ignores the input and calls the
* provided supplier once to return the output.
*/
private static <T, U> Collector<T, ?, U> empty(Supplier<U> supplier) {
return new CancellableCollectorImpl<>(() -> NONE, (acc, t) -> {
// empty
}, selectFirst(), acc -> supplier.get(), acc -> true, EnumSet.allOf(Characteristics.class));
}
private static <T> Collector<T, ?, List<T>> empty() {
return empty(ArrayList<T>::new);
}
/**
* Returns a {@code Collector} that accumulates the input elements into a
* new array.
*
* The operation performed by the returned collector is equivalent to
* {@code stream.toArray(generator)}. This collector is mostly useful as a
* downstream collector.
*
* @param <T>
* the type of the input elements
* @param generator
* a function which produces a new array of the desired type and
* the provided length
* @return a {@code Collector} which collects all the input elements into an
* array, in encounter order
*/
public static <T> Collector<T, ?, T[]> toArray(IntFunction<T[]> generator) {
return Collectors.collectingAndThen(Collectors.toList(), list -> list.toArray(generator.apply(list.size())));
}
/**
* Returns a {@code Collector} which produces a boolean array containing the
* results of applying the given predicate to the input elements, in
* encounter order.
*
* @param <T>
* the type of the input elements
* @param predicate
* a non-interfering, stateless predicate to apply to each input
* element. The result values of this predicate are collected to
* the resulting boolean array.
* @return a {@code Collector} which collects the results of the predicate
* function to the boolean array, in encounter order.
* @since 0.3.8
*/
public static <T> Collector<T, ?, boolean[]> toBooleanArray(Predicate<T> predicate) {
return PartialCollector.booleanArray().asRef((box, t) -> {
if (predicate.test(t))
box.a.set(box.b);
box.b = StrictMath.addExact(box.b, 1);
});
}
/**
* Returns a {@code Collector} that accumulates the input enum values into a
* new {@code EnumSet}.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a>: it may not process all the elements if the resulting set
* contains all possible enum values.
*
* @param <T>
* the type of the input elements
* @param enumClass
* the class of input enum values
* @return a {@code Collector} which collects all the input elements into a
* {@code EnumSet}
*/
public static <T extends Enum<T>> Collector<T, ?, EnumSet<T>> toEnumSet(Class<T> enumClass) {
int size = EnumSet.allOf(enumClass).size();
return new CancellableCollectorImpl<>(() -> EnumSet.noneOf(enumClass), EnumSet::add, (s1, s2) -> {
s1.addAll(s2);
return s1;
}, Function.identity(), set -> set.size() == size, UNORDERED_ID_CHARACTERISTICS);
}
/**
* Returns a {@code Collector} which counts a number of distinct values the
* mapper function returns for the stream elements.
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.map(mapper).distinct().count()}. This collector is mostly
* useful as a downstream collector.
*
* @param <T>
* the type of the input elements
* @param mapper
* a function which classifies input elements.
* @return a collector which counts a number of distinct classes the mapper
* function returns for the stream elements.
*/
public static <T> Collector<T, ?, Integer> distinctCount(Function<? super T, ?> mapper) {
return Collectors.collectingAndThen(Collectors.mapping(mapper, Collectors.toSet()), Set::size);
}
/**
* Returns a {@code Collector} which collects into the {@link List} the
* input elements for which given mapper function returns distinct results.
*
* <p>
* For ordered source the order of collected elements is preserved. If the
* same result is returned by mapper function for several elements, only the
* first element is included into the resulting list.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code List} returned.
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.distinct(mapper).toList()}, but may work faster.
*
* @param <T>
* the type of the input elements
* @param mapper
* a function which classifies input elements.
* @return a collector which collects distinct elements to the {@code List}.
* @since 0.3.8
*/
public static <T> Collector<T, ?, List<T>> distinctBy(Function<? super T, ?> mapper) {
return Collector.<T, Map<Object, T>, List<T>> of(LinkedHashMap::new,
(map, t) -> map.putIfAbsent(mapper.apply(t), t), (m1, m2) -> {
for (Entry<Object, T> e : m2.entrySet()) {
m1.putIfAbsent(e.getKey(), e.getValue());
}
return m1;
}, map -> new ArrayList<>(map.values()));
}
/**
* Returns a {@code Collector} accepting elements of type {@code T} that
* counts the number of input elements and returns result as {@code Integer}
* . If no elements are present, the result is 0.
*
* @param <T>
* the type of the input elements
* @return a {@code Collector} that counts the input elements
* @since 0.3.3
* @see Collectors#counting()
*/
public static <T> Collector<T, ?, Integer> countingInt() {
return PartialCollector.intSum().asRef((acc, t) -> acc[0]++);
}
/**
* Returns a {@code Collector} which aggregates the results of two supplied
* collectors using the supplied finisher function.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> if both downstream collectors are short-circuiting. The
* collection might stop when both downstream collectors report that the
* collection is complete.
*
* @param <T>
* the type of the input elements
* @param <A1>
* the intermediate accumulation type of the first collector
* @param <A2>
* the intermediate accumulation type of the second collector
* @param <R1>
* the result type of the first collector
* @param <R2>
* the result type of the second collector
* @param <R>
* the final result type
* @param c1
* the first collector
* @param c2
* the second collector
* @param finisher
* the function which merges two results into the single one.
* @return a {@code Collector} which aggregates the results of two supplied
* collectors.
*/
public static <T, A1, A2, R1, R2, R> Collector<T, ?, R> pairing(Collector<? super T, A1, R1> c1,
Collector<? super T, A2, R2> c2, BiFunction<? super R1, ? super R2, ? extends R> finisher) {
EnumSet<Characteristics> c = EnumSet.noneOf(Characteristics.class);
c.addAll(c1.characteristics());
c.retainAll(c2.characteristics());
c.remove(Characteristics.IDENTITY_FINISH);
Supplier<A1> c1Supplier = c1.supplier();
Supplier<A2> c2Supplier = c2.supplier();
BiConsumer<A1, ? super T> c1Accumulator = c1.accumulator();
BiConsumer<A2, ? super T> c2Accumulator = c2.accumulator();
BinaryOperator<A1> c1Combiner = c1.combiner();
BinaryOperator<A2> c2combiner = c2.combiner();
Supplier<PairBox<A1, A2>> supplier = () -> new PairBox<>(c1Supplier.get(), c2Supplier.get());
BiConsumer<PairBox<A1, A2>, T> accumulator = (acc, v) -> {
c1Accumulator.accept(acc.a, v);
c2Accumulator.accept(acc.b, v);
};
BinaryOperator<PairBox<A1, A2>> combiner = (acc1, acc2) -> {
acc1.a = c1Combiner.apply(acc1.a, acc2.a);
acc1.b = c2combiner.apply(acc1.b, acc2.b);
return acc1;
};
Function<PairBox<A1, A2>, R> resFinisher = acc -> {
R1 r1 = c1.finisher().apply(acc.a);
R2 r2 = c2.finisher().apply(acc.b);
return finisher.apply(r1, r2);
};
Predicate<A1> c1Finished = finished(c1);
Predicate<A2> c2Finished = finished(c2);
if (c1Finished != null && c2Finished != null) {
Predicate<PairBox<A1, A2>> finished = acc -> c1Finished.test(acc.a) && c2Finished.test(acc.b);
return new CancellableCollectorImpl<>(supplier, accumulator, combiner, resFinisher, finished, c);
}
return Collector.of(supplier, accumulator, combiner, resFinisher, c.toArray(new Characteristics[c.size()]));
}
/**
* Returns a {@code Collector} which finds all the elements which are equal
* to each other and bigger than any other element according to the
* specified {@link Comparator}. The found elements are reduced using the
* specified downstream {@code Collector}.
*
* @param <T>
* the type of the input elements
* @param <A>
* the intermediate accumulation type of the downstream collector
* @param <D>
* the result type of the downstream reduction
* @param comparator
* a {@code Comparator} to compare the elements
* @param downstream
* a {@code Collector} implementing the downstream reduction
* @return a {@code Collector} which finds all the maximal elements.
* @see #maxAll(Comparator)
* @see #maxAll(Collector)
* @see #maxAll()
*/
public static <T, A, D> Collector<T, ?, D> maxAll(Comparator<? super T> comparator,
Collector<? super T, A, D> downstream) {
Supplier<A> downstreamSupplier = downstream.supplier();
BiConsumer<A, ? super T> downstreamAccumulator = downstream.accumulator();
BinaryOperator<A> downstreamCombiner = downstream.combiner();
Supplier<PairBox<A, T>> supplier = () -> new PairBox<>(downstreamSupplier.get(), none());
BiConsumer<PairBox<A, T>, T> accumulator = (acc, t) -> {
if (acc.b == NONE) {
downstreamAccumulator.accept(acc.a, t);
acc.b = t;
} else {
int cmp = comparator.compare(t, acc.b);
if (cmp > 0) {
acc.a = downstreamSupplier.get();
acc.b = t;
}
if (cmp >= 0)
downstreamAccumulator.accept(acc.a, t);
}
};
BinaryOperator<PairBox<A, T>> combiner = (acc1, acc2) -> {
if (acc2.b == NONE) {
return acc1;
}
if (acc1.b == NONE) {
return acc2;
}
int cmp = comparator.compare(acc1.b, acc2.b);
if (cmp > 0) {
return acc1;
}
if (cmp < 0) {
return acc2;
}
acc1.a = downstreamCombiner.apply(acc1.a, acc2.a);
return acc1;
};
Function<PairBox<A, T>, D> finisher = acc -> downstream.finisher().apply(acc.a);
return Collector.of(supplier, accumulator, combiner, finisher);
}
/**
* Returns a {@code Collector} which finds all the elements which are equal
* to each other and bigger than any other element according to the
* specified {@link Comparator}. The found elements are collected to
* {@link List}.
*
* @param <T>
* the type of the input elements
* @param comparator
* a {@code Comparator} to compare the elements
* @return a {@code Collector} which finds all the maximal elements and
* collects them to the {@code List}.
* @see #maxAll(Comparator, Collector)
* @see #maxAll()
*/
public static <T> Collector<T, ?, List<T>> maxAll(Comparator<? super T> comparator) {
return maxAll(comparator, Collectors.toList());
}
/**
* Returns a {@code Collector} which finds all the elements which are equal
* to each other and bigger than any other element according to the natural
* order. The found elements are reduced using the specified downstream
* {@code Collector}.
*
* @param <T>
* the type of the input elements
* @param <A>
* the intermediate accumulation type of the downstream collector
* @param <D>
* the result type of the downstream reduction
* @param downstream
* a {@code Collector} implementing the downstream reduction
* @return a {@code Collector} which finds all the maximal elements.
* @see #maxAll(Comparator, Collector)
* @see #maxAll(Comparator)
* @see #maxAll()
*/
public static <T extends Comparable<? super T>, A, D> Collector<T, ?, D> maxAll(Collector<T, A, D> downstream) {
return maxAll(Comparator.<T> naturalOrder(), downstream);
}
/**
* Returns a {@code Collector} which finds all the elements which are equal
* to each other and bigger than any other element according to the natural
* order. The found elements are collected to {@link List}.
*
* @param <T>
* the type of the input elements
* @return a {@code Collector} which finds all the maximal elements and
* collects them to the {@code List}.
* @see #maxAll(Comparator)
* @see #maxAll(Collector)
*/
public static <T extends Comparable<? super T>> Collector<T, ?, List<T>> maxAll() {
return maxAll(Comparator.<T> naturalOrder(), Collectors.toList());
}
/**
* Returns a {@code Collector} which finds all the elements which are equal
* to each other and smaller than any other element according to the
* specified {@link Comparator}. The found elements are reduced using the
* specified downstream {@code Collector}.
*
* @param <T>
* the type of the input elements
* @param <A>
* the intermediate accumulation type of the downstream collector
* @param <D>
* the result type of the downstream reduction
* @param comparator
* a {@code Comparator} to compare the elements
* @param downstream
* a {@code Collector} implementing the downstream reduction
* @return a {@code Collector} which finds all the minimal elements.
* @see #minAll(Comparator)
* @see #minAll(Collector)
* @see #minAll()
*/
public static <T, A, D> Collector<T, ?, D> minAll(Comparator<? super T> comparator, Collector<T, A, D> downstream) {
return maxAll(comparator.reversed(), downstream);
}
/**
* Returns a {@code Collector} which finds all the elements which are equal
* to each other and smaller than any other element according to the
* specified {@link Comparator}. The found elements are collected to
* {@link List}.
*
* @param <T>
* the type of the input elements
* @param comparator
* a {@code Comparator} to compare the elements
* @return a {@code Collector} which finds all the minimal elements and
* collects them to the {@code List}.
* @see #minAll(Comparator, Collector)
* @see #minAll()
*/
public static <T> Collector<T, ?, List<T>> minAll(Comparator<? super T> comparator) {
return maxAll(comparator.reversed(), Collectors.toList());
}
/**
* Returns a {@code Collector} which finds all the elements which are equal
* to each other and smaller than any other element according to the natural
* order. The found elements are reduced using the specified downstream
* {@code Collector}.
*
* @param <T>
* the type of the input elements
* @param <A>
* the intermediate accumulation type of the downstream collector
* @param <D>
* the result type of the downstream reduction
* @param downstream
* a {@code Collector} implementing the downstream reduction
* @return a {@code Collector} which finds all the minimal elements.
* @see #minAll(Comparator, Collector)
* @see #minAll(Comparator)
* @see #minAll()
*/
public static <T extends Comparable<? super T>, A, D> Collector<T, ?, D> minAll(Collector<T, A, D> downstream) {
return maxAll(Comparator.<T> reverseOrder(), downstream);
}
/**
* Returns a {@code Collector} which finds all the elements which are equal
* to each other and smaller than any other element according to the natural
* order. The found elements are collected to {@link List}.
*
* @param <T>
* the type of the input elements
* @return a {@code Collector} which finds all the minimal elements and
* collects them to the {@code List}.
* @see #minAll(Comparator)
* @see #minAll(Collector)
*/
public static <T extends Comparable<? super T>> Collector<T, ?, List<T>> minAll() {
return maxAll(Comparator.<T> reverseOrder(), Collectors.toList());
}
/**
* Returns a {@code Collector} which collects the stream element if stream
* contains exactly one element.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a>.
*
* @param <T>
* the type of the input elements
* @return a collector which returns an {@link Optional} describing the only
* element of the stream. For empty stream or stream containing more
* than one element an empty {@code Optional} is returned.
* @since 0.4.0
*/
public static <T> Collector<T, ?, Optional<T>> onlyOne() {
return new CancellableCollectorImpl<T, Box<Optional<T>>, Optional<T>>(() -> new Box<Optional<T>>(null),
(box, t) -> box.a = box.a == null ? Optional.of(t) : Optional.empty(),
(box1, box2) -> box1.a == null ? box2 : box2.a == null ? box1 : new Box<>(Optional.empty()),
box -> box.a == null ? Optional.empty() : box.a, box -> box.a != null && !box.a.isPresent(),
UNORDERED_CHARACTERISTICS);
}
/**
* Returns a {@code Collector} which collects only the first stream element
* if any.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a>.
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.findFirst()}. This collector is mostly useful as a
* downstream collector.
*
* @param <T>
* the type of the input elements
* @return a collector which returns an {@link Optional} which describes the
* first element of the stream. For empty stream an empty
* {@code Optional} is returned.
*/
public static <T> Collector<T, ?, Optional<T>> first() {
return new CancellableCollectorImpl<>(() -> new Box<T>(none()), (box, t) -> {
if (box.a == NONE)
box.a = t;
}, (box1, box2) -> box1.a == NONE ? box2 : box1, box -> box.a == NONE ? Optional.empty() : Optional.of(box.a),
box -> box.a != NONE, NO_CHARACTERISTICS);
}
/**
* Returns a {@code Collector} which collects only the last stream element
* if any.
*
* @param <T>
* the type of the input elements
* @return a collector which returns an {@link Optional} which describes the
* last element of the stream. For empty stream an empty
* {@code Optional} is returned.
*/
public static <T> Collector<T, ?, Optional<T>> last() {
return Collectors.reducing((u, v) -> v);
}
/**
* Returns a {@code Collector} which collects at most specified number of
* the first stream elements into the {@link List}.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a>.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code List} returned.
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.limit(n).collect(Collectors.toList())}. This collector is
* mostly useful as a downstream collector.
*
* @param <T>
* the type of the input elements
* @param n
* maximum number of stream elements to preserve
* @return a collector which returns a {@code List} containing the first n
* stream elements or less if the stream was shorter.
*/
public static <T> Collector<T, ?, List<T>> head(int n) {
if (n <= 0)
return empty();
return new CancellableCollectorImpl<>(ArrayList::new, (acc, t) -> {
if (acc.size() < n)
acc.add(t);
}, (acc1, acc2) -> {
acc1.addAll(acc2.subList(0, Math.min(acc2.size(), n - acc1.size())));
return acc1;
}, Function.identity(), acc -> acc.size() >= n, ID_CHARACTERISTICS);
}
/**
* Returns a {@code Collector} which collects at most specified number of
* the last stream elements into the {@link List}.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code List} returned.
*
* <p>
* When supplied {@code n} is less or equal to zero, this method returns a
* <a href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> which ignores the input and produces an empty list.
*
* @param <T>
* the type of the input elements
* @param n
* maximum number of stream elements to preserve
* @return a collector which returns a {@code List} containing the last n
* stream elements or less if the stream was shorter.
*/
public static <T> Collector<T, ?, List<T>> tail(int n) {
if (n <= 0)
return empty();
return Collector.<T, Deque<T>, List<T>> of(ArrayDeque::new, (acc, t) -> {
if (acc.size() == n)
acc.pollFirst();
acc.addLast(t);
}, (acc1, acc2) -> {
while (acc2.size() < n && !acc1.isEmpty()) {
acc2.addFirst(acc1.pollLast());
}
return acc2;
}, ArrayList<T>::new);
}
/**
* Returns a {@code Collector} which collects at most specified number of
* the greatest stream elements according to the specified
* {@link Comparator} into the {@link List}. The resulting {@code List} is
* sorted in comparator reverse order (greatest element is the first).
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.sorted(comparator.reversed()).limit(n).collect(Collectors.toList())}
* , but can be performed much faster if the input is not sorted and
* {@code n} is much less than the stream size.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code List} returned.
*
* <p>
* When supplied {@code n} is less or equal to zero, this method returns a
* <a href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> which ignores the input and produces an empty list.
*
* @param <T>
* the type of the input elements
* @param comparator
* the comparator to compare the elements by
* @param n
* maximum number of stream elements to preserve
* @return a collector which returns a {@code List} containing the greatest
* n stream elements or less if the stream was shorter.
*/
public static <T> Collector<T, ?, List<T>> greatest(Comparator<? super T> comparator, int n) {
if (n <= 0)
return empty();
BiConsumer<PriorityQueue<T>, T> accumulator = (queue, t) -> {
if (queue.size() < n)
queue.add(t);
else if (comparator.compare(queue.peek(), t) < 0) {
queue.poll();
queue.add(t);
}
};
return Collector.of(() -> new PriorityQueue<>(comparator), accumulator, (q1, q2) -> {
for (T t : q2) {
accumulator.accept(q1, t);
}
return q1;
}, queue -> {
List<T> result = new ArrayList<>(queue);
result.sort(comparator.reversed());
return result;
});
}
/**
* Returns a {@code Collector} which collects at most specified number of
* the greatest stream elements according to the natural order into the
* {@link List}. The resulting {@code List} is sorted in reverse order
* (greatest element is the first).
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.sorted(Comparator.reverseOrder()).limit(n).collect(Collectors.toList())}
* , but can be performed much faster if the input is not sorted and
* {@code n} is much less than the stream size.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code List} returned.
*
* <p>
* When supplied {@code n} is less or equal to zero, this method returns a
* <a href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> which ignores the input and produces an empty list.
*
* @param <T>
* the type of the input elements
* @param n
* maximum number of stream elements to preserve
* @return a collector which returns a {@code List} containing the greatest
* n stream elements or less if the stream was shorter.
*/
public static <T extends Comparable<? super T>> Collector<T, ?, List<T>> greatest(int n) {
return greatest(Comparator.<T> naturalOrder(), n);
}
/**
* Returns a {@code Collector} which collects at most specified number of
* the least stream elements according to the specified {@link Comparator}
* into the {@link List}. The resulting {@code List} is sorted in comparator
* order (least element is the first).
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.sorted(comparator).limit(n).collect(Collectors.toList())},
* but can be performed much faster if the input is not sorted and {@code n}
* is much less than the stream size.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code List} returned.
*
* <p>
* When supplied {@code n} is less or equal to zero, this method returns a
* <a href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> which ignores the input and produces an empty list.
*
* @param <T>
* the type of the input elements
* @param comparator
* the comparator to compare the elements by
* @param n
* maximum number of stream elements to preserve
* @return a collector which returns a {@code List} containing the least n
* stream elements or less if the stream was shorter.
*/
public static <T> Collector<T, ?, List<T>> least(Comparator<? super T> comparator, int n) {
return greatest(comparator.reversed(), n);
}
/**
* Returns a {@code Collector} which collects at most specified number of
* the least stream elements according to the natural order into the
* {@link List}. The resulting {@code List} is sorted in natural order
* (least element is the first).
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.sorted().limit(n).collect(Collectors.toList())}, but can be
* performed much faster if the input is not sorted and {@code n} is much
* less than the stream size.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code List} returned.
*
* <p>
* When supplied {@code n} is less or equal to zero, this method returns a
* <a href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> which ignores the input and produces an empty list.
*
* @param <T>
* the type of the input elements
* @param n
* maximum number of stream elements to preserve
* @return a collector which returns a {@code List} containing the least n
* stream elements or less if the stream was shorter.
*/
public static <T extends Comparable<? super T>> Collector<T, ?, List<T>> least(int n) {
return greatest(Comparator.<T> reverseOrder(), n);
}
/**
* Returns a {@code Collector} which finds the index of the minimal stream
* element according to the specified {@link Comparator}. If there are
* several minimal elements, the index of the first one is returned.
*
* @param <T>
* the type of the input elements
* @param comparator
* a {@code Comparator} to compare the elements
* @return a {@code Collector} which finds the index of the minimal element.
* @see #minIndex()
* @since 0.3.5
*/
public static <T> Collector<T, ?, OptionalLong> minIndex(Comparator<? super T> comparator) {
class Container {
T value;
long count = 0;
long index = -1;
}
BiConsumer<Container, T> accumulator = (c, t) -> {
if (c.index == -1 || comparator.compare(c.value, t) > 0) {
c.value = t;
c.index = c.count;
}
c.count++;
};
BinaryOperator<Container> combiner = (c1, c2) -> {
if (c1.index == -1 || (c2.index != -1 && comparator.compare(c1.value, c2.value) > 0)) {
c2.index += c1.count;
c2.count += c1.count;
return c2;
}
c1.count += c2.count;
return c1;
};
Function<Container, OptionalLong> finisher = c -> c.index == -1 ? OptionalLong.empty() : OptionalLong
.of(c.index);
return Collector.of(Container::new, accumulator, combiner, finisher);
}
/**
* Returns a {@code Collector} which finds the index of the minimal stream
* element according to the elements natural order. If there are several
* minimal elements, the index of the first one is returned.
*
* @param <T>
* the type of the input elements
* @return a {@code Collector} which finds the index of the minimal element.
* @see #minIndex(Comparator)
* @since 0.3.5
*/
public static <T extends Comparable<? super T>> Collector<T, ?, OptionalLong> minIndex() {
return minIndex(Comparator.naturalOrder());
}
/**
* Returns a {@code Collector} which finds the index of the maximal stream
* element according to the specified {@link Comparator}. If there are
* several maximal elements, the index of the first one is returned.
*
* @param <T>
* the type of the input elements
* @param comparator
* a {@code Comparator} to compare the elements
* @return a {@code Collector} which finds the index of the maximal element.
* @see #maxIndex()
* @since 0.3.5
*/
public static <T> Collector<T, ?, OptionalLong> maxIndex(Comparator<? super T> comparator) {
return minIndex(comparator.reversed());
}
/**
* Returns a {@code Collector} which finds the index of the maximal stream
* element according to the elements natural order. If there are several
* maximal elements, the index of the first one is returned.
*
* @param <T>
* the type of the input elements
* @return a {@code Collector} which finds the index of the maximal element.
* @see #maxIndex(Comparator)
* @since 0.3.5
*/
public static <T extends Comparable<? super T>> Collector<T, ?, OptionalLong> maxIndex() {
return minIndex(Comparator.reverseOrder());
}
/**
* Returns a {@code Collector} implementing a cascaded "group by" operation
* on input elements of type {@code T}, for classification function which
* maps input elements to the enum values. The downstream reduction for
* repeating keys is performed using the specified downstream
* {@code Collector}.
*
* <p>
* Unlike the {@link Collectors#groupingBy(Function, Collector)} collector
* this collector produces an {@link EnumMap} which contains all possible
* keys including keys which were never returned by the classification
* function. These keys are mapped to the default collector value which is
* equivalent to collecting an empty stream with the same collector.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> if the downstream collector is short-circuiting. The
* collection might stop when for every possible enum key the downstream
* collection is known to be finished.
*
* @param <T>
* the type of the input elements
* @param <K>
* the type of the enum values returned by the classifier
* @param <A>
* the intermediate accumulation type of the downstream collector
* @param <D>
* the result type of the downstream reduction
* @param enumClass
* the class of enum values returned by the classifier
* @param classifier
* a classifier function mapping input elements to enum values
* @param downstream
* a {@code Collector} implementing the downstream reduction
* @return a {@code Collector} implementing the cascaded group-by operation
* @see Collectors#groupingBy(Function, Collector)
* @see #groupingBy(Function, Set, Supplier, Collector)
* @since 0.3.7
*/
public static <T, K extends Enum<K>, A, D> Collector<T, ?, EnumMap<K, D>> groupingByEnum(Class<K> enumClass,
Function<? super T, K> classifier, Collector<? super T, A, D> downstream) {
return groupingBy(classifier, EnumSet.allOf(enumClass), () -> new EnumMap<>(enumClass), downstream);
}
/**
* Returns a {@code Collector} implementing a cascaded "group by" operation
* on input elements of type {@code T}, grouping elements according to a
* classification function, and then performing a reduction operation on the
* values associated with a given key using the specified downstream
* {@code Collector}.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code Map} returned.
*
* <p>
* The main difference of this collector from
* {@link Collectors#groupingBy(Function, Collector)} is that it accepts
* additional domain parameter which is the {@code Set} of all possible map
* keys. If the mapper function produces the key out of domain, an
* {@code IllegalStateException} will occur. If the mapper function does not
* produce some of domain keys at all, they are also added to the result.
* These keys are mapped to the default collector value which is equivalent
* to collecting an empty stream with the same collector.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> if the downstream collector is short-circuiting. The
* collection might stop when for every possible key from the domain the
* downstream collection is known to be finished.
*
* @param <T>
* the type of the input elements
* @param <K>
* the type of the keys
* @param <A>
* the intermediate accumulation type of the downstream collector
* @param <D>
* the result type of the downstream reduction
* @param classifier
* a classifier function mapping input elements to keys
* @param domain
* a domain of all possible key values
* @param downstream
* a {@code Collector} implementing the downstream reduction
* @return a {@code Collector} implementing the cascaded group-by operation
* with given domain
*
* @see #groupingBy(Function, Set, Supplier, Collector)
* @see #groupingByEnum(Class, Function, Collector)
* @since 0.4.0
*/
public static <T, K, D, A> Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,
Set<K> domain, Collector<? super T, A, D> downstream) {
return groupingBy(classifier, domain, HashMap::new, downstream);
}
/**
* Returns a {@code Collector} implementing a cascaded "group by" operation
* on input elements of type {@code T}, grouping elements according to a
* classification function, and then performing a reduction operation on the
* values associated with a given key using the specified downstream
* {@code Collector}. The {@code Map} produced by the Collector is created
* with the supplied factory function.
*
* <p>
* The main difference of this collector from
* {@link Collectors#groupingBy(Function, Supplier, Collector)} is that it
* accepts additional domain parameter which is the {@code Set} of all
* possible map keys. If the mapper function produces the key out of domain,
* an {@code IllegalStateException} will occur. If the mapper function does
* not produce some of domain keys at all, they are also added to the
* result. These keys are mapped to the default collector value which is
* equivalent to collecting an empty stream with the same collector.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> if the downstream collector is short-circuiting. The
* collection might stop when for every possible key from the domain the
* downstream collection is known to be finished.
*
* @param <T>
* the type of the input elements
* @param <K>
* the type of the keys
* @param <A>
* the intermediate accumulation type of the downstream collector
* @param <D>
* the result type of the downstream reduction
* @param <M>
* the type of the resulting {@code Map}
* @param classifier
* a classifier function mapping input elements to keys
* @param domain
* a domain of all possible key values
* @param downstream
* a {@code Collector} implementing the downstream reduction
* @param mapFactory
* a function which, when called, produces a new empty
* {@code Map} of the desired type
* @return a {@code Collector} implementing the cascaded group-by operation
* with given domain
*
* @see #groupingBy(Function, Set, Collector)
* @see #groupingByEnum(Class, Function, Collector)
* @since 0.4.0
*/
public static <T, K, D, A, M extends Map<K, D>> Collector<T, ?, M> groupingBy(
Function<? super T, ? extends K> classifier, Set<K> domain, Supplier<M> mapFactory,
Collector<? super T, A, D> downstream) {
Supplier<A> downstreamSupplier = downstream.supplier();
Collector<T, ?, M> groupingBy;
Function<K, A> supplier = k -> {
if (!domain.contains(k))
throw new IllegalStateException("Classifier returned value '" + k + "' which is out of domain");
return downstreamSupplier.get();
};
BiConsumer<A, ? super T> downstreamAccumulator = downstream.accumulator();
BiConsumer<Map<K, A>, T> accumulator = (m, t) -> {
K key = Objects.requireNonNull(classifier.apply(t));
A container = m.computeIfAbsent(key, supplier);
downstreamAccumulator.accept(container, t);
};
PartialCollector<Map<K, A>, M> partial = PartialCollector.grouping(mapFactory, downstream);
Predicate<A> downstreamFinished = finished(downstream);
if (downstreamFinished != null) {
int size = domain.size();
groupingBy = partial.asCancellable(accumulator, map -> {
if (map.size() < size)
return false;
for (A container : map.values()) {
if (!downstreamFinished.test(container))
return false;
}
return true;
});
} else {
groupingBy = partial.asRef(accumulator);
}
return collectingAndThen(groupingBy, map -> {
Function<A, D> finisher = downstream.finisher();
domain.forEach(key -> map.computeIfAbsent(key, k -> finisher.apply(downstreamSupplier.get())));
return map;
});
}
/**
* Returns a {@code Collector} which collects the intersection of the input
* collections into the newly-created {@link Set}.
*
* <p>
* The returned collector produces an empty set if the input is empty or
* intersection of the input collections is empty.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code Set} returned.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a>: it may not process all the elements if the resulting
* intersection is empty.
*
* @param <T>
* the type of the elements in the input collections
* @param <S>
* the type of the input collections
* @return a {@code Collector} which finds all the minimal elements and
* collects them to the {@code List}.
* @since 0.4.0
*/
public static <T, S extends Collection<T>> Collector<S, ?, Set<T>> intersecting() {
return new CancellableCollectorImpl<>(() -> new Box<Set<T>>(null), (b, t) -> {
if (b.a == null) {
b.a = new HashSet<>(t);
} else {
b.a.retainAll(t);
}
}, (b1, b2) -> {
if (b1.a == null)
return b2;
if (b2.a != null)
b1.a.retainAll(b2.a);
return b1;
}, b -> b.a == null ? Collections.emptySet() : b.a, b -> b.a != null && b.a.isEmpty(),
UNORDERED_CHARACTERISTICS);
}
/**
* Adapts a {@code Collector} to perform an additional finishing
* transformation.
*
* <p>
* Unlike {@link Collectors#collectingAndThen(Collector, Function)} this
* method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> if the downstream collector is short-circuiting.
*
* @param <T>
* the type of the input elements
* @param <A>
* intermediate accumulation type of the downstream collector
* @param <R>
* result type of the downstream collector
* @param <RR>
* result type of the resulting collector
* @param downstream
* a collector
* @param finisher
* a function to be applied to the final result of the downstream
* collector
* @return a collector which performs the action of the downstream
* collector, followed by an additional finishing step
* @see Collectors#collectingAndThen(Collector, Function)
* @since 0.4.0
*/
public static <T, A, R, RR> Collector<T, A, RR> collectingAndThen(Collector<T, A, R> downstream,
Function<R, RR> finisher) {
Predicate<A> finished = finished(downstream);
if (finished != null) {
return new CancellableCollectorImpl<>(downstream.supplier(), downstream.accumulator(),
downstream.combiner(), downstream.finisher().andThen(finisher), finished, downstream
.characteristics().contains(Characteristics.UNORDERED) ? UNORDERED_CHARACTERISTICS
: NO_CHARACTERISTICS);
}
return Collectors.collectingAndThen(downstream, finisher);
}
/**
* Returns a {@code Collector} which partitions the input elements according
* to a {@code Predicate}, reduces the values in each partition according to
* another {@code Collector}, and organizes them into a
* {@code Map<Boolean, D>} whose values are the result of the downstream
* reduction.
*
* <p>
* Unlike {@link Collectors#partitioningBy(Predicate, Collector)} this
* method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> if the downstream collector is short-circuiting.
*
* @param <T>
* the type of the input elements
* @param <A>
* the intermediate accumulation type of the downstream collector
* @param <D>
* the result type of the downstream reduction
* @param predicate
* a predicate used for classifying input elements
* @param downstream
* a {@code Collector} implementing the downstream reduction
* @return a {@code Collector} implementing the cascaded partitioning
* operation
* @since 0.4.0
* @see Collectors#partitioningBy(Predicate, Collector)
*/
public static <T, D, A> Collector<T, ?, Map<Boolean, D>> partitioningBy(Predicate<? super T> predicate,
Collector<? super T, A, D> downstream) {
Predicate<A> finished = finished(downstream);
if (finished != null) {
BiConsumer<A, ? super T> accumulator = downstream.accumulator();
return BooleanMap.partialCollector(downstream).asCancellable(
(map, t) -> accumulator.accept(predicate.test(t) ? map.trueValue : map.falseValue, t),
map -> finished.test(map.trueValue) && finished.test(map.falseValue));
}
return Collectors.partitioningBy(predicate, downstream);
}
/**
* Adapts a {@code Collector} accepting elements of type {@code U} to one
* accepting elements of type {@code T} by applying a mapping function to
* each input element before accumulation.
*
* <p>
* Unlike {@link Collectors#mapping(Function, Collector)} this method
* returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> if the downstream collector is short-circuiting.
*
* @param <T>
* the type of the input elements
* @param <U>
* type of elements accepted by downstream collector
* @param <A>
* intermediate accumulation type of the downstream collector
* @param <R>
* result type of collector
* @param mapper
* a function to be applied to the input elements
* @param downstream
* a collector which will accept mapped values
* @return a collector which applies the mapping function to the input
* elements and provides the mapped results to the downstream
* collector
* @see Collectors#mapping(Function, Collector)
* @since 0.4.0
*/
public static <T, U, A, R> Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper,
Collector<? super U, A, R> downstream) {
Predicate<A> finished = finished(downstream);
if (finished != null) {
BiConsumer<A, ? super U> downstreamAccumulator = downstream.accumulator();
return new CancellableCollectorImpl<>(downstream.supplier(), (acc, t) -> {
if (!finished.test(acc))
downstreamAccumulator.accept(acc, mapper.apply(t));
}, downstream.combiner(), downstream.finisher(), finished, downstream.characteristics());
}
return Collectors.mapping(mapper, downstream);
}
/**
* Adapts a {@code Collector} accepting elements of type {@code U} to one
* accepting elements of type {@code T} by applying a flat mapping function
* to each input element before accumulation. The flat mapping function maps
* an input element to a {@link Stream stream} covering zero or more output
* elements that are then accumulated downstream. Each mapped stream is
* {@link java.util.stream.BaseStream#close() closed} after its contents
* have been placed downstream. (If a mapped stream is {@code null} an empty
* stream is used, instead.)
*
* This method is similar to {@code Collectors.flatMapping} method which
* appears in JDK 9. However when downstream collector is <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting</a>,
* this method will also return a short-circuiting collector.
*
* @param <T>
* the type of the input elements
* @param <U>
* type of elements accepted by downstream collector
* @param <A>
* intermediate accumulation type of the downstream collector
* @param <R>
* result type of collector
* @param mapper
* a function to be applied to the input elements, which returns
* a stream of results
* @param downstream
* a collector which will receive the elements of the stream
* returned by mapper
* @return a collector which applies the mapping function to the input
* elements and provides the flat mapped results to the downstream
* collector
* @since 0.4.1
*/
public static <T, U, A, R> Collector<T, ?, R> flatMapping(
Function<? super T, ? extends Stream<? extends U>> mapper, Collector<? super U, A, R> downstream) {
BiConsumer<A, ? super U> downstreamAccumulator = downstream.accumulator();
Predicate<A> finished = finished(downstream);
if (finished != null) {
return new CancellableCollectorImpl<>(downstream.supplier(), (acc, t) -> {
if (finished.test(acc))
return;
try (Stream<? extends U> stream = mapper.apply(t)) {
if (stream != null) {
stream.spliterator().forEachRemaining(u -> {
downstreamAccumulator.accept(acc, u);
if (finished.test(acc))
throw new CancelException();
});
}
} catch (CancelException ex) {
// ignore
}
}, downstream.combiner(), downstream.finisher(), finished, downstream.characteristics());
}
return Collector.of(downstream.supplier(), (acc, t) -> {
try (Stream<? extends U> stream = mapper.apply(t)) {
if (stream != null) {
stream.spliterator().forEachRemaining(u -> downstreamAccumulator.accept(acc, u));
}
}
}, downstream.combiner(), downstream.finisher(),
downstream.characteristics().toArray(new Characteristics[downstream.characteristics().size()]));
}
/**
* Returns a {@code Collector} which passes only those elements to the
* specified downstream collector which match given predicate.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> if downstream collector is short-circuiting.
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.filter(predicate).collect(downstream)}. This collector is
* mostly useful as a downstream collector in cascaded operation involving
* {@link #pairing(Collector, Collector, BiFunction)} collector.
*
* @param <T>
* the type of the input elements
* @param <A>
* intermediate accumulation type of the downstream collector
* @param <R>
* result type of collector
* @param predicate
* a filter function to be applied to the input elements
* @param downstream
* a collector which will accept filtered values
* @return a collector which applies the predicate to the input elements and
* provides the elements for which predicate returned true to the
* downstream collector
* @see #pairing(Collector, Collector, BiFunction)
* @since 0.4.0
*/
public static <T, A, R> Collector<T, ?, R> filtering(Predicate<? super T> predicate, Collector<T, A, R> downstream) {
BiConsumer<A, T> downstreamAccumulator = downstream.accumulator();
BiConsumer<A, T> accumulator = (acc, t) -> {
if (predicate.test(t))
downstreamAccumulator.accept(acc, t);
};
Predicate<A> finished = finished(downstream);
if (finished != null) {
return new CancellableCollectorImpl<>(downstream.supplier(), accumulator, downstream.combiner(),
downstream.finisher(), finished, downstream.characteristics());
}
return Collector.of(downstream.supplier(), accumulator, downstream.combiner(), downstream.finisher(),
downstream.characteristics().toArray(new Characteristics[downstream.characteristics().size()]));
}
/**
* Returns a {@code Collector} which performs the bitwise-and operation of a
* integer-valued function applied to the input elements. If no elements are
* present, the result is empty {@link OptionalInt}.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a>: it may not process all the elements if the result is zero.
*
* @param <T>
* the type of the input elements
* @param mapper
* a function extracting the property to be processed
* @return a {@code Collector} that produces the bitwise-and operation of a
* derived property
* @since 0.4.0
*/
public static <T> Collector<T, ?, OptionalInt> andingInt(ToIntFunction<T> mapper) {
return new CancellableCollectorImpl<>(PrimitiveBox::new, (acc, t) -> {
if (!acc.b) {
acc.i = mapper.applyAsInt(t);
acc.b = true;
} else {
acc.i &= mapper.applyAsInt(t);
}
}, (acc1, acc2) -> {
if (!acc1.b)
return acc2;
if (!acc2.b)
return acc1;
acc1.i &= acc2.i;
return acc1;
}, PrimitiveBox::asInt, acc -> acc.b && acc.i == 0, UNORDERED_CHARACTERISTICS);
}
/**
* Returns a {@code Collector} which performs the bitwise-and operation of a
* long-valued function applied to the input elements. If no elements are
* present, the result is empty {@link OptionalLong}.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a>: it may not process all the elements if the result is zero.
*
* @param <T>
* the type of the input elements
* @param mapper
* a function extracting the property to be processed
* @return a {@code Collector} that produces the bitwise-and operation of a
* derived property
* @since 0.4.0
*/
public static <T> Collector<T, ?, OptionalLong> andingLong(ToLongFunction<T> mapper) {
return new CancellableCollectorImpl<>(PrimitiveBox::new, (acc, t) -> {
if (!acc.b) {
acc.l = mapper.applyAsLong(t);
acc.b = true;
} else {
acc.l &= mapper.applyAsLong(t);
}
}, (acc1, acc2) -> {
if (!acc1.b)
return acc2;
if (!acc2.b)
return acc1;
acc1.l &= acc2.l;
return acc1;
}, PrimitiveBox::asLong, acc -> acc.b && acc.l == 0, UNORDERED_CHARACTERISTICS);
}
/**
* Returns a {@code Collector} which computes a common prefix of input
* {@code CharSequence} objects returning the result as {@code String}. For
* empty input the empty {@code String} is returned.
*
* <p>
* The returned {@code Collector} handles specially Unicode surrogate pairs:
* the returned prefix may end with <a
* href="http://www.unicode.org/glossary/#high_surrogate_code_unit"> Unicode
* high-surrogate code unit</a> only if it's not succeeded by <a
* href="http://www.unicode.org/glossary/#low_surrogate_code_unit"> Unicode
* low-surrogate code unit</a> in any of input sequences. Normally the
* ending high-surrogate code unit is removed from prefix.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a>: it may not process all the elements if the common prefix
* is empty.
*
* @return a {@code Collector} which computes a common prefix.
* @since 0.5.0
*/
public static Collector<CharSequence, ?, String> commonPrefix() {
BiConsumer<ObjIntBox<CharSequence>, CharSequence> accumulator = (acc, t) -> {
if (acc.b == -1) {
acc.a = t;
acc.b = t.length();
} else if (acc.b > 0) {
if (t.length() < acc.b)
acc.b = t.length();
for (int i = 0; i < acc.b; i++) {
if (acc.a.charAt(i) != t.charAt(i)) {
if (i > 0 && Character.isHighSurrogate(t.charAt(i - 1))
&& (Character.isLowSurrogate(t.charAt(i)) || Character.isLowSurrogate(acc.a.charAt(i))))
i--;
acc.b = i;
break;
}
}
}
};
return new CancellableCollectorImpl<>(() -> new ObjIntBox<>(null, -1), accumulator, (acc1, acc2) -> {
if (acc1.b == -1)
return acc2;
if (acc2.b != -1)
accumulator.accept(acc1, acc2.a.subSequence(0, acc2.b));
return acc1;
}, acc -> acc.a == null ? "" : acc.a.subSequence(0, acc.b).toString(), acc -> acc.b == 0,
UNORDERED_CHARACTERISTICS);
}
/**
* Returns a {@code Collector} which computes a common suffix of input
* {@code CharSequence} objects returning the result as {@code String}. For
* empty input the empty {@code String} is returned.
*
* <p>
* The returned {@code Collector} handles specially Unicode surrogate pairs:
* the returned suffix may start with <a
* href="http://www.unicode.org/glossary/#low_surrogate_code_unit"> Unicode
* low-surrogate code unit</a> only if it's not preceded by <a
* href="http://www.unicode.org/glossary/#high_surrogate_code_unit"> Unicode
* high-surrogate code unit</a> in any of input sequences. Normally the
* starting low-surrogate code unit is removed from suffix.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a>: it may not process all the elements if the common suffix
* is empty.
*
* @return a {@code Collector} which computes a common suffix.
* @since 0.5.0
*/
public static Collector<CharSequence, ?, String> commonSuffix() {
BiConsumer<ObjIntBox<CharSequence>, CharSequence> accumulator = (acc, t) -> {
if (acc.b == -1) {
acc.a = t;
acc.b = t.length();
} else if (acc.b > 0) {
int alen = acc.a.length();
int blen = t.length();
if (blen < acc.b)
acc.b = blen;
for (int i = 0; i < acc.b; i++) {
if (acc.a.charAt(alen - 1 - i) != t.charAt(blen - 1 - i)) {
if (i > 0
&& Character.isLowSurrogate(t.charAt(blen - i))
&& (Character.isHighSurrogate(t.charAt(blen - 1 - i)) || Character.isHighSurrogate(acc.a
.charAt(alen - 1 - i))))
i--;
acc.b = i;
break;
}
}
}
};
return new CancellableCollectorImpl<>(() -> new ObjIntBox<>(null, -1), accumulator, (acc1, acc2) -> {
if (acc1.b == -1)
return acc2;
if (acc2.b != -1)
accumulator.accept(acc1, acc2.a.subSequence(acc2.a.length() - acc2.b, acc2.a.length()));
return acc1;
}, acc -> acc.a == null ? "" : acc.a.subSequence(acc.a.length() - acc.b, acc.a.length()).toString(),
acc -> acc.b == 0, UNORDERED_CHARACTERISTICS);
}
}
| src/main/java/one/util/streamex/MoreCollectors.java | /*
* Copyright 2015 Tagir Valeev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package one.util.streamex;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.OptionalInt;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
import java.util.stream.Collector;
import java.util.stream.Collector.Characteristics;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import one.util.streamex.StreamExInternals.ObjIntBox;
import static one.util.streamex.StreamExInternals.*;
/**
* Implementations of several collectors in addition to ones available in JDK.
*
* @author Tagir Valeev
* @see Collectors
* @see Joining
* @since 0.3.2
*/
public final class MoreCollectors {
private MoreCollectors() {
throw new UnsupportedOperationException();
}
/**
* Returns a {@code Collector} which just ignores the input and calls the
* provided supplier once to return the output.
*
* @param <T>
* the type of input elements
* @param <U>
* the type of output
* @param supplier
* the supplier of the output
* @return a {@code Collector} which just ignores the input and calls the
* provided supplier once to return the output.
*/
private static <T, U> Collector<T, ?, U> empty(Supplier<U> supplier) {
return new CancellableCollectorImpl<>(() -> NONE, (acc, t) -> {
// empty
}, selectFirst(), acc -> supplier.get(), acc -> true, EnumSet.allOf(Characteristics.class));
}
private static <T> Collector<T, ?, List<T>> empty() {
return empty(ArrayList<T>::new);
}
/**
* Returns a {@code Collector} that accumulates the input elements into a
* new array.
*
* The operation performed by the returned collector is equivalent to
* {@code stream.toArray(generator)}. This collector is mostly useful as a
* downstream collector.
*
* @param <T>
* the type of the input elements
* @param generator
* a function which produces a new array of the desired type and
* the provided length
* @return a {@code Collector} which collects all the input elements into an
* array, in encounter order
*/
public static <T> Collector<T, ?, T[]> toArray(IntFunction<T[]> generator) {
return Collectors.collectingAndThen(Collectors.toList(), list -> list.toArray(generator.apply(list.size())));
}
/**
* Returns a {@code Collector} which produces a boolean array containing the
* results of applying the given predicate to the input elements, in
* encounter order.
*
* @param <T>
* the type of the input elements
* @param predicate
* a non-interfering, stateless predicate to apply to each input
* element. The result values of this predicate are collected to
* the resulting boolean array.
* @return a {@code Collector} which collects the results of the predicate
* function to the boolean array, in encounter order.
* @since 0.3.8
*/
public static <T> Collector<T, ?, boolean[]> toBooleanArray(Predicate<T> predicate) {
return PartialCollector.booleanArray().asRef((box, t) -> {
if (predicate.test(t))
box.a.set(box.b);
box.b = StrictMath.addExact(box.b, 1);
});
}
/**
* Returns a {@code Collector} that accumulates the input enum values into a
* new {@code EnumSet}.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a>: it may not process all the elements if the resulting set
* contains all possible enum values.
*
* @param <T>
* the type of the input elements
* @param enumClass
* the class of input enum values
* @return a {@code Collector} which collects all the input elements into a
* {@code EnumSet}
*/
public static <T extends Enum<T>> Collector<T, ?, EnumSet<T>> toEnumSet(Class<T> enumClass) {
int size = EnumSet.allOf(enumClass).size();
return new CancellableCollectorImpl<>(() -> EnumSet.noneOf(enumClass), EnumSet::add, (s1, s2) -> {
s1.addAll(s2);
return s1;
}, Function.identity(), set -> set.size() == size, UNORDERED_ID_CHARACTERISTICS);
}
/**
* Returns a {@code Collector} which counts a number of distinct values the
* mapper function returns for the stream elements.
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.map(mapper).distinct().count()}. This collector is mostly
* useful as a downstream collector.
*
* @param <T>
* the type of the input elements
* @param mapper
* a function which classifies input elements.
* @return a collector which counts a number of distinct classes the mapper
* function returns for the stream elements.
*/
public static <T> Collector<T, ?, Integer> distinctCount(Function<? super T, ?> mapper) {
return Collectors.collectingAndThen(Collectors.mapping(mapper, Collectors.toSet()), Set::size);
}
/**
* Returns a {@code Collector} which collects into the {@link List} the
* input elements for which given mapper function returns distinct results.
*
* <p>
* For ordered source the order of collected elements is preserved. If the
* same result is returned by mapper function for several elements, only the
* first element is included into the resulting list.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code List} returned.
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.distinct(mapper).toList()}, but may work faster.
*
* @param <T>
* the type of the input elements
* @param mapper
* a function which classifies input elements.
* @return a collector which collects distinct elements to the {@code List}.
* @since 0.3.8
*/
public static <T> Collector<T, ?, List<T>> distinctBy(Function<? super T, ?> mapper) {
return Collector.<T, Map<Object, T>, List<T>> of(LinkedHashMap::new,
(map, t) -> map.putIfAbsent(mapper.apply(t), t), (m1, m2) -> {
for (Entry<Object, T> e : m2.entrySet()) {
m1.putIfAbsent(e.getKey(), e.getValue());
}
return m1;
}, map -> new ArrayList<>(map.values()));
}
/**
* Returns a {@code Collector} accepting elements of type {@code T} that
* counts the number of input elements and returns result as {@code Integer}
* . If no elements are present, the result is 0.
*
* @param <T>
* the type of the input elements
* @return a {@code Collector} that counts the input elements
* @since 0.3.3
* @see Collectors#counting()
*/
public static <T> Collector<T, ?, Integer> countingInt() {
return PartialCollector.intSum().asRef((acc, t) -> acc[0]++);
}
/**
* Returns a {@code Collector} which aggregates the results of two supplied
* collectors using the supplied finisher function.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> if both downstream collectors are short-circuiting. The
* collection might stop when both downstream collectors report that the
* collection is complete.
*
* @param <T>
* the type of the input elements
* @param <A1>
* the intermediate accumulation type of the first collector
* @param <A2>
* the intermediate accumulation type of the second collector
* @param <R1>
* the result type of the first collector
* @param <R2>
* the result type of the second collector
* @param <R>
* the final result type
* @param c1
* the first collector
* @param c2
* the second collector
* @param finisher
* the function which merges two results into the single one.
* @return a {@code Collector} which aggregates the results of two supplied
* collectors.
*/
public static <T, A1, A2, R1, R2, R> Collector<T, ?, R> pairing(Collector<? super T, A1, R1> c1,
Collector<? super T, A2, R2> c2, BiFunction<? super R1, ? super R2, ? extends R> finisher) {
EnumSet<Characteristics> c = EnumSet.noneOf(Characteristics.class);
c.addAll(c1.characteristics());
c.retainAll(c2.characteristics());
c.remove(Characteristics.IDENTITY_FINISH);
Supplier<A1> c1Supplier = c1.supplier();
Supplier<A2> c2Supplier = c2.supplier();
BiConsumer<A1, ? super T> c1Accumulator = c1.accumulator();
BiConsumer<A2, ? super T> c2Accumulator = c2.accumulator();
BinaryOperator<A1> c1Combiner = c1.combiner();
BinaryOperator<A2> c2combiner = c2.combiner();
Supplier<PairBox<A1, A2>> supplier = () -> new PairBox<>(c1Supplier.get(), c2Supplier.get());
BiConsumer<PairBox<A1, A2>, T> accumulator = (acc, v) -> {
c1Accumulator.accept(acc.a, v);
c2Accumulator.accept(acc.b, v);
};
BinaryOperator<PairBox<A1, A2>> combiner = (acc1, acc2) -> {
acc1.a = c1Combiner.apply(acc1.a, acc2.a);
acc1.b = c2combiner.apply(acc1.b, acc2.b);
return acc1;
};
Function<PairBox<A1, A2>, R> resFinisher = acc -> {
R1 r1 = c1.finisher().apply(acc.a);
R2 r2 = c2.finisher().apply(acc.b);
return finisher.apply(r1, r2);
};
Predicate<A1> c1Finished = finished(c1);
Predicate<A2> c2Finished = finished(c2);
if (c1Finished != null && c2Finished != null) {
Predicate<PairBox<A1, A2>> finished = acc -> c1Finished.test(acc.a) && c2Finished.test(acc.b);
return new CancellableCollectorImpl<>(supplier, accumulator, combiner, resFinisher, finished, c);
}
return Collector.of(supplier, accumulator, combiner, resFinisher, c.toArray(new Characteristics[c.size()]));
}
/**
* Returns a {@code Collector} which finds all the elements which are equal
* to each other and bigger than any other element according to the
* specified {@link Comparator}. The found elements are reduced using the
* specified downstream {@code Collector}.
*
* @param <T>
* the type of the input elements
* @param <A>
* the intermediate accumulation type of the downstream collector
* @param <D>
* the result type of the downstream reduction
* @param comparator
* a {@code Comparator} to compare the elements
* @param downstream
* a {@code Collector} implementing the downstream reduction
* @return a {@code Collector} which finds all the maximal elements.
* @see #maxAll(Comparator)
* @see #maxAll(Collector)
* @see #maxAll()
*/
public static <T, A, D> Collector<T, ?, D> maxAll(Comparator<? super T> comparator,
Collector<? super T, A, D> downstream) {
Supplier<A> downstreamSupplier = downstream.supplier();
BiConsumer<A, ? super T> downstreamAccumulator = downstream.accumulator();
BinaryOperator<A> downstreamCombiner = downstream.combiner();
Supplier<PairBox<A, T>> supplier = () -> new PairBox<>(downstreamSupplier.get(), none());
BiConsumer<PairBox<A, T>, T> accumulator = (acc, t) -> {
if (acc.b == NONE) {
downstreamAccumulator.accept(acc.a, t);
acc.b = t;
} else {
int cmp = comparator.compare(t, acc.b);
if (cmp > 0) {
acc.a = downstreamSupplier.get();
acc.b = t;
}
if (cmp >= 0)
downstreamAccumulator.accept(acc.a, t);
}
};
BinaryOperator<PairBox<A, T>> combiner = (acc1, acc2) -> {
if (acc2.b == NONE) {
return acc1;
}
if (acc1.b == NONE) {
return acc2;
}
int cmp = comparator.compare(acc1.b, acc2.b);
if (cmp > 0) {
return acc1;
}
if (cmp < 0) {
return acc2;
}
acc1.a = downstreamCombiner.apply(acc1.a, acc2.a);
return acc1;
};
Function<PairBox<A, T>, D> finisher = acc -> downstream.finisher().apply(acc.a);
return Collector.of(supplier, accumulator, combiner, finisher);
}
/**
* Returns a {@code Collector} which finds all the elements which are equal
* to each other and bigger than any other element according to the
* specified {@link Comparator}. The found elements are collected to
* {@link List}.
*
* @param <T>
* the type of the input elements
* @param comparator
* a {@code Comparator} to compare the elements
* @return a {@code Collector} which finds all the maximal elements and
* collects them to the {@code List}.
* @see #maxAll(Comparator, Collector)
* @see #maxAll()
*/
public static <T> Collector<T, ?, List<T>> maxAll(Comparator<? super T> comparator) {
return maxAll(comparator, Collectors.toList());
}
/**
* Returns a {@code Collector} which finds all the elements which are equal
* to each other and bigger than any other element according to the natural
* order. The found elements are reduced using the specified downstream
* {@code Collector}.
*
* @param <T>
* the type of the input elements
* @param <A>
* the intermediate accumulation type of the downstream collector
* @param <D>
* the result type of the downstream reduction
* @param downstream
* a {@code Collector} implementing the downstream reduction
* @return a {@code Collector} which finds all the maximal elements.
* @see #maxAll(Comparator, Collector)
* @see #maxAll(Comparator)
* @see #maxAll()
*/
public static <T extends Comparable<? super T>, A, D> Collector<T, ?, D> maxAll(Collector<T, A, D> downstream) {
return maxAll(Comparator.<T> naturalOrder(), downstream);
}
/**
* Returns a {@code Collector} which finds all the elements which are equal
* to each other and bigger than any other element according to the natural
* order. The found elements are collected to {@link List}.
*
* @param <T>
* the type of the input elements
* @return a {@code Collector} which finds all the maximal elements and
* collects them to the {@code List}.
* @see #maxAll(Comparator)
* @see #maxAll(Collector)
*/
public static <T extends Comparable<? super T>> Collector<T, ?, List<T>> maxAll() {
return maxAll(Comparator.<T> naturalOrder(), Collectors.toList());
}
/**
* Returns a {@code Collector} which finds all the elements which are equal
* to each other and smaller than any other element according to the
* specified {@link Comparator}. The found elements are reduced using the
* specified downstream {@code Collector}.
*
* @param <T>
* the type of the input elements
* @param <A>
* the intermediate accumulation type of the downstream collector
* @param <D>
* the result type of the downstream reduction
* @param comparator
* a {@code Comparator} to compare the elements
* @param downstream
* a {@code Collector} implementing the downstream reduction
* @return a {@code Collector} which finds all the minimal elements.
* @see #minAll(Comparator)
* @see #minAll(Collector)
* @see #minAll()
*/
public static <T, A, D> Collector<T, ?, D> minAll(Comparator<? super T> comparator, Collector<T, A, D> downstream) {
return maxAll(comparator.reversed(), downstream);
}
/**
* Returns a {@code Collector} which finds all the elements which are equal
* to each other and smaller than any other element according to the
* specified {@link Comparator}. The found elements are collected to
* {@link List}.
*
* @param <T>
* the type of the input elements
* @param comparator
* a {@code Comparator} to compare the elements
* @return a {@code Collector} which finds all the minimal elements and
* collects them to the {@code List}.
* @see #minAll(Comparator, Collector)
* @see #minAll()
*/
public static <T> Collector<T, ?, List<T>> minAll(Comparator<? super T> comparator) {
return maxAll(comparator.reversed(), Collectors.toList());
}
/**
* Returns a {@code Collector} which finds all the elements which are equal
* to each other and smaller than any other element according to the natural
* order. The found elements are reduced using the specified downstream
* {@code Collector}.
*
* @param <T>
* the type of the input elements
* @param <A>
* the intermediate accumulation type of the downstream collector
* @param <D>
* the result type of the downstream reduction
* @param downstream
* a {@code Collector} implementing the downstream reduction
* @return a {@code Collector} which finds all the minimal elements.
* @see #minAll(Comparator, Collector)
* @see #minAll(Comparator)
* @see #minAll()
*/
public static <T extends Comparable<? super T>, A, D> Collector<T, ?, D> minAll(Collector<T, A, D> downstream) {
return maxAll(Comparator.<T> reverseOrder(), downstream);
}
/**
* Returns a {@code Collector} which finds all the elements which are equal
* to each other and smaller than any other element according to the natural
* order. The found elements are collected to {@link List}.
*
* @param <T>
* the type of the input elements
* @return a {@code Collector} which finds all the minimal elements and
* collects them to the {@code List}.
* @see #minAll(Comparator)
* @see #minAll(Collector)
*/
public static <T extends Comparable<? super T>> Collector<T, ?, List<T>> minAll() {
return maxAll(Comparator.<T> reverseOrder(), Collectors.toList());
}
/**
* Returns a {@code Collector} which collects the stream element if stream
* contains exactly one element.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a>.
*
* @param <T>
* the type of the input elements
* @return a collector which returns an {@link Optional} describing the only
* element of the stream. For empty stream or stream containing more
* than one element an empty {@code Optional} is returned.
* @since 0.4.0
*/
public static <T> Collector<T, ?, Optional<T>> onlyOne() {
return new CancellableCollectorImpl<T, Box<Optional<T>>, Optional<T>>(() -> new Box<Optional<T>>(null),
(box, t) -> box.a = box.a == null ? Optional.of(t) : Optional.empty(),
(box1, box2) -> box1.a == null ? box2 : box2.a == null ? box1 : new Box<>(Optional.empty()),
box -> box.a == null ? Optional.empty() : box.a, box -> box.a != null && !box.a.isPresent(),
UNORDERED_CHARACTERISTICS);
}
/**
* Returns a {@code Collector} which collects only the first stream element
* if any.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a>.
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.findFirst()}. This collector is mostly useful as a
* downstream collector.
*
* @param <T>
* the type of the input elements
* @return a collector which returns an {@link Optional} which describes the
* first element of the stream. For empty stream an empty
* {@code Optional} is returned.
*/
public static <T> Collector<T, ?, Optional<T>> first() {
return new CancellableCollectorImpl<>(() -> new Box<T>(none()), (box, t) -> {
if (box.a == NONE)
box.a = t;
}, (box1, box2) -> box1.a == NONE ? box2 : box1, box -> box.a == NONE ? Optional.empty() : Optional.of(box.a),
box -> box.a != NONE, NO_CHARACTERISTICS);
}
/**
* Returns a {@code Collector} which collects only the last stream element
* if any.
*
* @param <T>
* the type of the input elements
* @return a collector which returns an {@link Optional} which describes the
* last element of the stream. For empty stream an empty
* {@code Optional} is returned.
*/
public static <T> Collector<T, ?, Optional<T>> last() {
return Collectors.reducing((u, v) -> v);
}
/**
* Returns a {@code Collector} which collects at most specified number of
* the first stream elements into the {@link List}.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a>.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code List} returned.
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.limit(n).collect(Collectors.toList())}. This collector is
* mostly useful as a downstream collector.
*
* @param <T>
* the type of the input elements
* @param n
* maximum number of stream elements to preserve
* @return a collector which returns a {@code List} containing the first n
* stream elements or less if the stream was shorter.
*/
public static <T> Collector<T, ?, List<T>> head(int n) {
if (n <= 0)
return empty();
return new CancellableCollectorImpl<>(ArrayList::new, (acc, t) -> {
if (acc.size() < n)
acc.add(t);
}, (acc1, acc2) -> {
acc1.addAll(acc2.subList(0, Math.min(acc2.size(), n - acc1.size())));
return acc1;
}, Function.identity(), acc -> acc.size() >= n, ID_CHARACTERISTICS);
}
/**
* Returns a {@code Collector} which collects at most specified number of
* the last stream elements into the {@link List}.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code List} returned.
*
* <p>
* When supplied {@code n} is less or equal to zero, this method returns a
* <a href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> which ignores the input and produces an empty list.
*
* @param <T>
* the type of the input elements
* @param n
* maximum number of stream elements to preserve
* @return a collector which returns a {@code List} containing the last n
* stream elements or less if the stream was shorter.
*/
public static <T> Collector<T, ?, List<T>> tail(int n) {
if (n <= 0)
return empty();
return Collector.<T, Deque<T>, List<T>> of(ArrayDeque::new, (acc, t) -> {
if (acc.size() == n)
acc.pollFirst();
acc.addLast(t);
}, (acc1, acc2) -> {
while (acc2.size() < n && !acc1.isEmpty()) {
acc2.addFirst(acc1.pollLast());
}
return acc2;
}, ArrayList<T>::new);
}
/**
* Returns a {@code Collector} which collects at most specified number of
* the greatest stream elements according to the specified
* {@link Comparator} into the {@link List}. The resulting {@code List} is
* sorted in comparator reverse order (greatest element is the first).
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.sorted(comparator.reversed()).limit(n).collect(Collectors.toList())}
* , but can be performed much faster if the input is not sorted and
* {@code n} is much less than the stream size.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code List} returned.
*
* <p>
* When supplied {@code n} is less or equal to zero, this method returns a
* <a href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> which ignores the input and produces an empty list.
*
* @param <T>
* the type of the input elements
* @param comparator
* the comparator to compare the elements by
* @param n
* maximum number of stream elements to preserve
* @return a collector which returns a {@code List} containing the greatest
* n stream elements or less if the stream was shorter.
*/
public static <T> Collector<T, ?, List<T>> greatest(Comparator<? super T> comparator, int n) {
if (n <= 0)
return empty();
BiConsumer<PriorityQueue<T>, T> accumulator = (queue, t) -> {
if (queue.size() < n)
queue.add(t);
else if (comparator.compare(queue.peek(), t) < 0) {
queue.poll();
queue.add(t);
}
};
return Collector.of(() -> new PriorityQueue<>(comparator), accumulator, (q1, q2) -> {
for (T t : q2) {
accumulator.accept(q1, t);
}
return q1;
}, queue -> {
List<T> result = new ArrayList<>(queue);
result.sort(comparator.reversed());
return result;
});
}
/**
* Returns a {@code Collector} which collects at most specified number of
* the greatest stream elements according to the natural order into the
* {@link List}. The resulting {@code List} is sorted in reverse order
* (greatest element is the first).
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.sorted(Comparator.reverseOrder()).limit(n).collect(Collectors.toList())}
* , but can be performed much faster if the input is not sorted and
* {@code n} is much less than the stream size.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code List} returned.
*
* <p>
* When supplied {@code n} is less or equal to zero, this method returns a
* <a href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> which ignores the input and produces an empty list.
*
* @param <T>
* the type of the input elements
* @param n
* maximum number of stream elements to preserve
* @return a collector which returns a {@code List} containing the greatest
* n stream elements or less if the stream was shorter.
*/
public static <T extends Comparable<? super T>> Collector<T, ?, List<T>> greatest(int n) {
return greatest(Comparator.<T> naturalOrder(), n);
}
/**
* Returns a {@code Collector} which collects at most specified number of
* the least stream elements according to the specified {@link Comparator}
* into the {@link List}. The resulting {@code List} is sorted in comparator
* order (least element is the first).
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.sorted(comparator).limit(n).collect(Collectors.toList())},
* but can be performed much faster if the input is not sorted and {@code n}
* is much less than the stream size.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code List} returned.
*
* <p>
* When supplied {@code n} is less or equal to zero, this method returns a
* <a href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> which ignores the input and produces an empty list.
*
* @param <T>
* the type of the input elements
* @param comparator
* the comparator to compare the elements by
* @param n
* maximum number of stream elements to preserve
* @return a collector which returns a {@code List} containing the least n
* stream elements or less if the stream was shorter.
*/
public static <T> Collector<T, ?, List<T>> least(Comparator<? super T> comparator, int n) {
return greatest(comparator.reversed(), n);
}
/**
* Returns a {@code Collector} which collects at most specified number of
* the least stream elements according to the natural order into the
* {@link List}. The resulting {@code List} is sorted in natural order
* (least element is the first).
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.sorted().limit(n).collect(Collectors.toList())}, but can be
* performed much faster if the input is not sorted and {@code n} is much
* less than the stream size.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code List} returned.
*
* <p>
* When supplied {@code n} is less or equal to zero, this method returns a
* <a href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> which ignores the input and produces an empty list.
*
* @param <T>
* the type of the input elements
* @param n
* maximum number of stream elements to preserve
* @return a collector which returns a {@code List} containing the least n
* stream elements or less if the stream was shorter.
*/
public static <T extends Comparable<? super T>> Collector<T, ?, List<T>> least(int n) {
return greatest(Comparator.<T> reverseOrder(), n);
}
/**
* Returns a {@code Collector} which finds the index of the minimal stream
* element according to the specified {@link Comparator}. If there are
* several minimal elements, the index of the first one is returned.
*
* @param <T>
* the type of the input elements
* @param comparator
* a {@code Comparator} to compare the elements
* @return a {@code Collector} which finds the index of the minimal element.
* @see #minIndex()
* @since 0.3.5
*/
public static <T> Collector<T, ?, OptionalLong> minIndex(Comparator<? super T> comparator) {
class Container {
T value;
long count = 0;
long index = -1;
}
BiConsumer<Container, T> accumulator = (c, t) -> {
if (c.index == -1 || comparator.compare(c.value, t) > 0) {
c.value = t;
c.index = c.count;
}
c.count++;
};
BinaryOperator<Container> combiner = (c1, c2) -> {
if (c1.index == -1 || (c2.index != -1 && comparator.compare(c1.value, c2.value) > 0)) {
c2.index += c1.count;
c2.count += c1.count;
return c2;
}
c1.count += c2.count;
return c1;
};
Function<Container, OptionalLong> finisher = c -> c.index == -1 ? OptionalLong.empty() : OptionalLong
.of(c.index);
return Collector.of(Container::new, accumulator, combiner, finisher);
}
/**
* Returns a {@code Collector} which finds the index of the minimal stream
* element according to the elements natural order. If there are several
* minimal elements, the index of the first one is returned.
*
* @param <T>
* the type of the input elements
* @return a {@code Collector} which finds the index of the minimal element.
* @see #minIndex(Comparator)
* @since 0.3.5
*/
public static <T extends Comparable<? super T>> Collector<T, ?, OptionalLong> minIndex() {
return minIndex(Comparator.naturalOrder());
}
/**
* Returns a {@code Collector} which finds the index of the maximal stream
* element according to the specified {@link Comparator}. If there are
* several maximal elements, the index of the first one is returned.
*
* @param <T>
* the type of the input elements
* @param comparator
* a {@code Comparator} to compare the elements
* @return a {@code Collector} which finds the index of the maximal element.
* @see #maxIndex()
* @since 0.3.5
*/
public static <T> Collector<T, ?, OptionalLong> maxIndex(Comparator<? super T> comparator) {
return minIndex(comparator.reversed());
}
/**
* Returns a {@code Collector} which finds the index of the maximal stream
* element according to the elements natural order. If there are several
* maximal elements, the index of the first one is returned.
*
* @param <T>
* the type of the input elements
* @return a {@code Collector} which finds the index of the maximal element.
* @see #maxIndex(Comparator)
* @since 0.3.5
*/
public static <T extends Comparable<? super T>> Collector<T, ?, OptionalLong> maxIndex() {
return minIndex(Comparator.reverseOrder());
}
/**
* Returns a {@code Collector} implementing a cascaded "group by" operation
* on input elements of type {@code T}, for classification function which
* maps input elements to the enum values. The downstream reduction for
* repeating keys is performed using the specified downstream
* {@code Collector}.
*
* <p>
* Unlike the {@link Collectors#groupingBy(Function, Collector)} collector
* this collector produces an {@link EnumMap} which contains all possible
* keys including keys which were never returned by the classification
* function. These keys are mapped to the default collector value which is
* equivalent to collecting an empty stream with the same collector.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> if the downstream collector is short-circuiting. The
* collection might stop when for every possible enum key the downstream
* collection is known to be finished.
*
* @param <T>
* the type of the input elements
* @param <K>
* the type of the enum values returned by the classifier
* @param <A>
* the intermediate accumulation type of the downstream collector
* @param <D>
* the result type of the downstream reduction
* @param enumClass
* the class of enum values returned by the classifier
* @param classifier
* a classifier function mapping input elements to enum values
* @param downstream
* a {@code Collector} implementing the downstream reduction
* @return a {@code Collector} implementing the cascaded group-by operation
* @see Collectors#groupingBy(Function, Collector)
* @see #groupingBy(Function, Set, Supplier, Collector)
* @since 0.3.7
*/
public static <T, K extends Enum<K>, A, D> Collector<T, ?, EnumMap<K, D>> groupingByEnum(Class<K> enumClass,
Function<? super T, K> classifier, Collector<? super T, A, D> downstream) {
return groupingBy(classifier, EnumSet.allOf(enumClass), () -> new EnumMap<>(enumClass), downstream);
}
/**
* Returns a {@code Collector} implementing a cascaded "group by" operation
* on input elements of type {@code T}, grouping elements according to a
* classification function, and then performing a reduction operation on the
* values associated with a given key using the specified downstream
* {@code Collector}.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code Map} returned.
*
* <p>
* The main difference of this collector from
* {@link Collectors#groupingBy(Function, Collector)} is that it accepts
* additional domain parameter which is the {@code Set} of all possible map
* keys. If the mapper function produces the key out of domain, an
* {@code IllegalStateException} will occur. If the mapper function does not
* produce some of domain keys at all, they are also added to the result.
* These keys are mapped to the default collector value which is equivalent
* to collecting an empty stream with the same collector.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> if the downstream collector is short-circuiting. The
* collection might stop when for every possible key from the domain the
* downstream collection is known to be finished.
*
* @param <T>
* the type of the input elements
* @param <K>
* the type of the keys
* @param <A>
* the intermediate accumulation type of the downstream collector
* @param <D>
* the result type of the downstream reduction
* @param classifier
* a classifier function mapping input elements to keys
* @param domain
* a domain of all possible key values
* @param downstream
* a {@code Collector} implementing the downstream reduction
* @return a {@code Collector} implementing the cascaded group-by operation
* with given domain
*
* @see #groupingBy(Function, Set, Supplier, Collector)
* @see #groupingByEnum(Class, Function, Collector)
* @since 0.4.0
*/
public static <T, K, D, A> Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier,
Set<K> domain, Collector<? super T, A, D> downstream) {
return groupingBy(classifier, domain, HashMap::new, downstream);
}
/**
* Returns a {@code Collector} implementing a cascaded "group by" operation
* on input elements of type {@code T}, grouping elements according to a
* classification function, and then performing a reduction operation on the
* values associated with a given key using the specified downstream
* {@code Collector}. The {@code Map} produced by the Collector is created
* with the supplied factory function.
*
* <p>
* The main difference of this collector from
* {@link Collectors#groupingBy(Function, Supplier, Collector)} is that it
* accepts additional domain parameter which is the {@code Set} of all
* possible map keys. If the mapper function produces the key out of domain,
* an {@code IllegalStateException} will occur. If the mapper function does
* not produce some of domain keys at all, they are also added to the
* result. These keys are mapped to the default collector value which is
* equivalent to collecting an empty stream with the same collector.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> if the downstream collector is short-circuiting. The
* collection might stop when for every possible key from the domain the
* downstream collection is known to be finished.
*
* @param <T>
* the type of the input elements
* @param <K>
* the type of the keys
* @param <A>
* the intermediate accumulation type of the downstream collector
* @param <D>
* the result type of the downstream reduction
* @param <M>
* the type of the resulting {@code Map}
* @param classifier
* a classifier function mapping input elements to keys
* @param domain
* a domain of all possible key values
* @param downstream
* a {@code Collector} implementing the downstream reduction
* @param mapFactory
* a function which, when called, produces a new empty
* {@code Map} of the desired type
* @return a {@code Collector} implementing the cascaded group-by operation
* with given domain
*
* @see #groupingBy(Function, Set, Collector)
* @see #groupingByEnum(Class, Function, Collector)
* @since 0.4.0
*/
public static <T, K, D, A, M extends Map<K, D>> Collector<T, ?, M> groupingBy(
Function<? super T, ? extends K> classifier, Set<K> domain, Supplier<M> mapFactory,
Collector<? super T, A, D> downstream) {
Supplier<A> downstreamSupplier = downstream.supplier();
Collector<T, ?, M> groupingBy;
Function<K, A> supplier = k -> {
if (!domain.contains(k))
throw new IllegalStateException("Classifier returned value '" + k + "' which is out of domain");
return downstreamSupplier.get();
};
BiConsumer<A, ? super T> downstreamAccumulator = downstream.accumulator();
BiConsumer<Map<K, A>, T> accumulator = (m, t) -> {
K key = Objects.requireNonNull(classifier.apply(t));
A container = m.computeIfAbsent(key, supplier);
downstreamAccumulator.accept(container, t);
};
PartialCollector<Map<K, A>, M> partial = PartialCollector.grouping(mapFactory, downstream);
Predicate<A> downstreamFinished = finished(downstream);
if (downstreamFinished != null) {
int size = domain.size();
groupingBy = partial.asCancellable(accumulator, map -> {
if (map.size() < size)
return false;
for (A container : map.values()) {
if (!downstreamFinished.test(container))
return false;
}
return true;
});
} else {
groupingBy = partial.asRef(accumulator);
}
return collectingAndThen(groupingBy, map -> {
Function<A, D> finisher = downstream.finisher();
domain.forEach(key -> map.computeIfAbsent(key, k -> finisher.apply(downstreamSupplier.get())));
return map;
});
}
/**
* Returns a {@code Collector} which collects the intersection of the input
* collections into the newly-created {@link Set}.
*
* <p>
* The returned collector produces an empty set if the input is empty or
* intersection of the input collections is empty.
*
* <p>
* There are no guarantees on the type, mutability, serializability, or
* thread-safety of the {@code Set} returned.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a>: it may not process all the elements if the resulting
* intersection is empty.
*
* @param <T>
* the type of the elements in the input collections
* @param <S>
* the type of the input collections
* @return a {@code Collector} which finds all the minimal elements and
* collects them to the {@code List}.
* @since 0.4.0
*/
public static <T, S extends Collection<T>> Collector<S, ?, Set<T>> intersecting() {
return new CancellableCollectorImpl<>(() -> new Box<Set<T>>(null), (b, t) -> {
if (b.a == null) {
b.a = new HashSet<>(t);
} else {
b.a.retainAll(t);
}
}, (b1, b2) -> {
if (b1.a == null)
return b2;
if (b2.a != null)
b1.a.retainAll(b2.a);
return b1;
}, b -> b.a == null ? Collections.emptySet() : b.a, b -> b.a != null && b.a.isEmpty(),
UNORDERED_CHARACTERISTICS);
}
/**
* Adapts a {@code Collector} to perform an additional finishing
* transformation.
*
* <p>
* Unlike {@link Collectors#collectingAndThen(Collector, Function)} this
* method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> if the downstream collector is short-circuiting.
*
* @param <T>
* the type of the input elements
* @param <A>
* intermediate accumulation type of the downstream collector
* @param <R>
* result type of the downstream collector
* @param <RR>
* result type of the resulting collector
* @param downstream
* a collector
* @param finisher
* a function to be applied to the final result of the downstream
* collector
* @return a collector which performs the action of the downstream
* collector, followed by an additional finishing step
* @see Collectors#collectingAndThen(Collector, Function)
* @since 0.4.0
*/
public static <T, A, R, RR> Collector<T, A, RR> collectingAndThen(Collector<T, A, R> downstream,
Function<R, RR> finisher) {
Predicate<A> finished = finished(downstream);
if (finished != null) {
return new CancellableCollectorImpl<>(downstream.supplier(), downstream.accumulator(),
downstream.combiner(), downstream.finisher().andThen(finisher), finished, downstream
.characteristics().contains(Characteristics.UNORDERED) ? UNORDERED_CHARACTERISTICS
: NO_CHARACTERISTICS);
}
return Collectors.collectingAndThen(downstream, finisher);
}
/**
* Returns a {@code Collector} which partitions the input elements according
* to a {@code Predicate}, reduces the values in each partition according to
* another {@code Collector}, and organizes them into a
* {@code Map<Boolean, D>} whose values are the result of the downstream
* reduction.
*
* <p>
* Unlike {@link Collectors#partitioningBy(Predicate, Collector)} this
* method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> if the downstream collector is short-circuiting.
*
* @param <T>
* the type of the input elements
* @param <A>
* the intermediate accumulation type of the downstream collector
* @param <D>
* the result type of the downstream reduction
* @param predicate
* a predicate used for classifying input elements
* @param downstream
* a {@code Collector} implementing the downstream reduction
* @return a {@code Collector} implementing the cascaded partitioning
* operation
* @since 0.4.0
* @see Collectors#partitioningBy(Predicate, Collector)
*/
public static <T, D, A> Collector<T, ?, Map<Boolean, D>> partitioningBy(Predicate<? super T> predicate,
Collector<? super T, A, D> downstream) {
Predicate<A> finished = finished(downstream);
if (finished != null) {
BiConsumer<A, ? super T> accumulator = downstream.accumulator();
return BooleanMap.partialCollector(downstream).asCancellable(
(map, t) -> accumulator.accept(predicate.test(t) ? map.trueValue : map.falseValue, t),
map -> finished.test(map.trueValue) && finished.test(map.falseValue));
}
return Collectors.partitioningBy(predicate, downstream);
}
/**
* Adapts a {@code Collector} accepting elements of type {@code U} to one
* accepting elements of type {@code T} by applying a mapping function to
* each input element before accumulation.
*
* <p>
* Unlike {@link Collectors#mapping(Function, Collector)} this method
* returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> if the downstream collector is short-circuiting.
*
* @param <T>
* the type of the input elements
* @param <U>
* type of elements accepted by downstream collector
* @param <A>
* intermediate accumulation type of the downstream collector
* @param <R>
* result type of collector
* @param mapper
* a function to be applied to the input elements
* @param downstream
* a collector which will accept mapped values
* @return a collector which applies the mapping function to the input
* elements and provides the mapped results to the downstream
* collector
* @see Collectors#mapping(Function, Collector)
* @since 0.4.0
*/
public static <T, U, A, R> Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper,
Collector<? super U, A, R> downstream) {
Predicate<A> finished = finished(downstream);
if (finished != null) {
BiConsumer<A, ? super U> downstreamAccumulator = downstream.accumulator();
return new CancellableCollectorImpl<>(downstream.supplier(), (acc, t) -> {
if (!finished.test(acc))
downstreamAccumulator.accept(acc, mapper.apply(t));
}, downstream.combiner(), downstream.finisher(), finished, downstream.characteristics());
}
return Collectors.mapping(mapper, downstream);
}
/**
* Adapts a {@code Collector} accepting elements of type {@code U} to one
* accepting elements of type {@code T} by applying a flat mapping function
* to each input element before accumulation. The flat mapping function maps
* an input element to a {@link Stream stream} covering zero or more output
* elements that are then accumulated downstream. Each mapped stream is
* {@link java.util.stream.BaseStream#close() closed} after its contents
* have been placed downstream. (If a mapped stream is {@code null} an empty
* stream is used, instead.)
*
* This method is similar to {@code Collectors.flatMapping} method which
* appears in JDK 9. However when downstream collector is <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting</a>,
* this method will also return a short-circuiting collector.
*
* @param <T>
* the type of the input elements
* @param <U>
* type of elements accepted by downstream collector
* @param <A>
* intermediate accumulation type of the downstream collector
* @param <R>
* result type of collector
* @param mapper
* a function to be applied to the input elements, which returns
* a stream of results
* @param downstream
* a collector which will receive the elements of the stream
* returned by mapper
* @return a collector which applies the mapping function to the input
* elements and provides the flat mapped results to the downstream
* collector
* @since 0.4.1
*/
public static <T, U, A, R> Collector<T, ?, R> flatMapping(
Function<? super T, ? extends Stream<? extends U>> mapper, Collector<? super U, A, R> downstream) {
BiConsumer<A, ? super U> downstreamAccumulator = downstream.accumulator();
Predicate<A> finished = finished(downstream);
if (finished != null) {
return new CancellableCollectorImpl<>(downstream.supplier(), (acc, t) -> {
if (finished.test(acc))
return;
try (Stream<? extends U> stream = mapper.apply(t)) {
if (stream != null) {
stream.spliterator().forEachRemaining(u -> {
downstreamAccumulator.accept(acc, u);
if (finished.test(acc))
throw new CancelException();
});
}
} catch (CancelException ex) {
// ignore
}
}, downstream.combiner(), downstream.finisher(), finished, downstream.characteristics());
}
return Collector.of(downstream.supplier(), (acc, t) -> {
try (Stream<? extends U> stream = mapper.apply(t)) {
if (stream != null) {
stream.spliterator().forEachRemaining(u -> downstreamAccumulator.accept(acc, u));
}
}
}, downstream.combiner(), downstream.finisher(),
downstream.characteristics().toArray(new Characteristics[downstream.characteristics().size()]));
}
/**
* Returns a {@code Collector} which passes only those elements to the
* specified downstream collector which match given predicate.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a> if downstream collector is short-circuiting.
*
* <p>
* The operation performed by the returned collector is equivalent to
* {@code stream.filter(predicate).collect(downstream)}. This collector is
* mostly useful as a downstream collector in cascaded operation involving
* {@link #pairing(Collector, Collector, BiFunction)} collector.
*
* @param <T>
* the type of the input elements
* @param <A>
* intermediate accumulation type of the downstream collector
* @param <R>
* result type of collector
* @param predicate
* a filter function to be applied to the input elements
* @param downstream
* a collector which will accept filtered values
* @return a collector which applies the predicate to the input elements and
* provides the elements for which predicate returned true to the
* downstream collector
* @see #pairing(Collector, Collector, BiFunction)
* @since 0.4.0
*/
public static <T, A, R> Collector<T, ?, R> filtering(Predicate<? super T> predicate, Collector<T, A, R> downstream) {
BiConsumer<A, T> downstreamAccumulator = downstream.accumulator();
BiConsumer<A, T> accumulator = (acc, t) -> {
if (predicate.test(t))
downstreamAccumulator.accept(acc, t);
};
Predicate<A> finished = finished(downstream);
if (finished != null) {
return new CancellableCollectorImpl<>(downstream.supplier(), accumulator, downstream.combiner(),
downstream.finisher(), finished, downstream.characteristics());
}
return Collector.of(downstream.supplier(), accumulator, downstream.combiner(), downstream.finisher(),
downstream.characteristics().toArray(new Characteristics[downstream.characteristics().size()]));
}
/**
* Returns a {@code Collector} which performs the bitwise-and operation of a
* integer-valued function applied to the input elements. If no elements are
* present, the result is empty {@link OptionalInt}.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a>: it may not process all the elements if the result is zero.
*
* @param <T>
* the type of the input elements
* @param mapper
* a function extracting the property to be processed
* @return a {@code Collector} that produces the bitwise-and operation of a
* derived property
* @since 0.4.0
*/
public static <T> Collector<T, ?, OptionalInt> andingInt(ToIntFunction<T> mapper) {
return new CancellableCollectorImpl<>(PrimitiveBox::new, (acc, t) -> {
if (!acc.b) {
acc.i = mapper.applyAsInt(t);
acc.b = true;
} else {
acc.i &= mapper.applyAsInt(t);
}
}, (acc1, acc2) -> {
if (!acc1.b)
return acc2;
if (!acc2.b)
return acc1;
acc1.i &= acc2.i;
return acc1;
}, PrimitiveBox::asInt, acc -> acc.b && acc.i == 0, UNORDERED_CHARACTERISTICS);
}
/**
* Returns a {@code Collector} which performs the bitwise-and operation of a
* long-valued function applied to the input elements. If no elements are
* present, the result is empty {@link OptionalLong}.
*
* <p>
* This method returns a <a
* href="package-summary.html#ShortCircuitReduction">short-circuiting
* collector</a>: it may not process all the elements if the result is zero.
*
* @param <T>
* the type of the input elements
* @param mapper
* a function extracting the property to be processed
* @return a {@code Collector} that produces the bitwise-and operation of a
* derived property
* @since 0.4.0
*/
public static <T> Collector<T, ?, OptionalLong> andingLong(ToLongFunction<T> mapper) {
return new CancellableCollectorImpl<>(PrimitiveBox::new, (acc, t) -> {
if (!acc.b) {
acc.l = mapper.applyAsLong(t);
acc.b = true;
} else {
acc.l &= mapper.applyAsLong(t);
}
}, (acc1, acc2) -> {
if (!acc1.b)
return acc2;
if (!acc2.b)
return acc1;
acc1.l &= acc2.l;
return acc1;
}, PrimitiveBox::asLong, acc -> acc.b && acc.l == 0, UNORDERED_CHARACTERISTICS);
}
public static Collector<CharSequence, ?, String> commonPrefix() {
BiConsumer<ObjIntBox<CharSequence>, CharSequence> accumulator = (acc, t) -> {
if (acc.b == -1) {
acc.a = t;
acc.b = t.length();
} else if (acc.b > 0) {
if (t.length() < acc.b)
acc.b = t.length();
for (int i = 0; i < acc.b; i++) {
if (acc.a.charAt(i) != t.charAt(i)) {
if (i > 0 && Character.isHighSurrogate(t.charAt(i - 1))
&& (Character.isLowSurrogate(t.charAt(i)) || Character.isLowSurrogate(acc.a.charAt(i))))
i--;
acc.b = i;
break;
}
}
}
};
return new CancellableCollectorImpl<CharSequence, ObjIntBox<CharSequence>, String>(() -> new ObjIntBox<>(null,
-1), accumulator, (acc1, acc2) -> {
if (acc1.b == -1)
return acc2;
if (acc2.b != -1)
accumulator.accept(acc1, acc2.a.subSequence(0, acc2.b));
return acc1;
}, acc -> acc.a == null ? "" : acc.a.subSequence(0, acc.b).toString(), acc -> acc.b == 0,
UNORDERED_CHARACTERISTICS);
}
public static Collector<CharSequence, ?, String> commonSuffix() {
BiConsumer<ObjIntBox<CharSequence>, CharSequence> accumulator = (acc, t) -> {
if (acc.b == -1) {
acc.a = t;
acc.b = t.length();
} else if (acc.b > 0) {
int alen = acc.a.length();
int blen = t.length();
if (blen < acc.b)
acc.b = blen;
for (int i = 0; i < acc.b; i++) {
if (acc.a.charAt(alen - 1 - i) != t.charAt(blen - 1 - i)) {
if (i > 0
&& Character.isLowSurrogate(t.charAt(blen - i))
&& (Character.isHighSurrogate(t.charAt(blen - 1 - i)) || Character.isHighSurrogate(acc.a
.charAt(alen - 1 - i))))
i--;
acc.b = i;
break;
}
}
}
};
return new CancellableCollectorImpl<CharSequence, ObjIntBox<CharSequence>, String>(() -> new ObjIntBox<>(null,
-1), accumulator, (acc1, acc2) -> {
if (acc1.b == -1)
return acc2;
if (acc2.b != -1)
accumulator.accept(acc1, acc2.a.subSequence(acc2.a.length() - acc2.b, acc2.a.length()));
return acc1;
}, acc -> acc.a == null ? "" : acc.a.subSequence(acc.a.length() - acc.b, acc.a.length()).toString(),
acc -> acc.b == 0, UNORDERED_CHARACTERISTICS);
}
}
| [#25] JavaDoc for commonPrefix/commonSuffix | src/main/java/one/util/streamex/MoreCollectors.java | [#25] JavaDoc for commonPrefix/commonSuffix |
|
Java | apache-2.0 | 4b0bf8e29ba9485691d910dc53c244c2c6e967b8 | 0 | RackerWilliams/xercesj,jimma/xerces,jimma/xerces,ronsigal/xerces,RackerWilliams/xercesj,ronsigal/xerces,RackerWilliams/xercesj,ronsigal/xerces,jimma/xerces | /*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2003, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.xinclude;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Vector;
import java.net.*;
import java.io.*;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.XMLEntityManager;
import org.apache.xerces.impl.XMLErrorReporter;
import org.apache.xerces.util.AugmentationsImpl;
import org.apache.xerces.util.IntStack;
import org.apache.xerces.util.ObjectFactory;
import org.apache.xerces.util.ParserConfigurationSettings;
import org.apache.xerces.util.URI;
import org.apache.xerces.util.XMLAttributesImpl;
import org.apache.xerces.util.XMLResourceIdentifierImpl;
import org.apache.xerces.util.XMLSymbols;
import org.apache.xerces.util.URI.MalformedURIException;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLDTDHandler;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLResourceIdentifier;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLComponent;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLDTDFilter;
import org.apache.xerces.xni.parser.XMLDTDSource;
import org.apache.xerces.xni.parser.XMLDocumentFilter;
import org.apache.xerces.xni.parser.XMLDocumentSource;
import org.apache.xerces.xni.parser.XMLEntityResolver;
import org.apache.xerces.xni.parser.XMLInputSource;
import org.apache.xerces.xni.parser.XMLParserConfiguration;
/**
* <p>
* This is a pipeline component which performs XInclude handling, according to the
* W3C specification for XML Inclusions.
* </p>
* <p>
* This component analyzes each event in the pipeline, looking for <include>
* elements. An <include> element is one which has a namespace of
* <code>http://www.w3.org/2003/XInclude</code> and a localname of <code>include</code>.
* When it finds an <include> element, it attempts to include the file specified
* in the <code>href</code> attribute of the element. If inclusion succeeds, all
* children of the <include> element are ignored (with the exception of
* checking for invalid children as outlined in the specification). If the inclusion
* fails, the <fallback> child of the <include> element is processed.
* </p>
* <p>
* See the <a href="http://www.w3.org/TR/xinclude/">XInclude specification</a> for
* more information on how XInclude is to be used.
* </p>
* <p>
* This component requires the following features and properties from the
* component manager that uses it:
* <ul>
* <li>http://xml.org/sax/features/allow-dtd-events-after-endDTD</li>
* <li>http://apache.org/xml/properties/internal/error-reporter</li>
* <li>http://apache.org/xml/properties/internal/entity-resolver</li>
* </ul>
* Furthermore, the <code>NamespaceContext</code> used in the pipeline is required
* to be an instance of <code>XIncludeNamespaceSupport</code>.
* </p>
* <p>
* Currently, this implementation has only partial support for the XInclude specification.
* Specifically, it is missing support for XPointer document fragments. Thus, only whole
* documents can be included using this component in the pipeline.
* </p>
* @author Peter McCracken, IBM
* @see XIncludeNamespaceSupport
*/
public class XIncludeHandler
implements XMLComponent, XMLDocumentFilter, XMLDTDFilter {
public final static String XINCLUDE_DEFAULT_CONFIGURATION =
"org.apache.xerces.parsers.XIncludeParserConfiguration";
public final static String HTTP_ACCEPT = "Accept";
public final static String HTTP_ACCEPT_LANGUAGE = "Accept-Language";
public final static String HTTP_ACCEPT_CHARSET = "Accept-Charset";
public final static String XINCLUDE_NS_URI =
"http://www.w3.org/2003/XInclude".intern();
public final static String XINCLUDE_NS_URI_OLD =
"http://www.w3.org/2001/XInclude".intern();
public final static String XINCLUDE_INCLUDE = "include".intern();
public final static String XINCLUDE_FALLBACK = "fallback".intern();
public final static String XINCLUDE_PARSE_XML = "xml".intern();
public final static String XINCLUDE_PARSE_TEXT = "text".intern();
public final static String XINCLUDE_ATTR_HREF = "href".intern();
public final static String XINCLUDE_ATTR_PARSE = "parse".intern();
public final static String XINCLUDE_ATTR_ENCODING = "encoding".intern();
// Top Level Information Items have [included] property in infoset
public final static String XINCLUDE_INCLUDED = "[included]".intern();
/** The identifier for the Augmentation that contains the current base URI */
public final static String CURRENT_BASE_URI = "currentBaseURI";
// used for adding [base URI] attributes
public final static String XINCLUDE_BASE = "base";
public final static QName XML_BASE_QNAME =
new QName(
XMLSymbols.PREFIX_XML,
XINCLUDE_BASE,
XMLSymbols.PREFIX_XML + ":" + XINCLUDE_BASE,
NamespaceContext.XML_URI);
public final static QName NEW_NS_ATTR_QNAME =
new QName(
XMLSymbols.PREFIX_XMLNS,
"",
XMLSymbols.PREFIX_XMLNS + ":",
NamespaceContext.XMLNS_URI);
// Processing States
private final static int STATE_NORMAL_PROCESSING = 1;
// we go into this state after a successful include (thus we ignore the children
// of the include) or after a fallback
private final static int STATE_IGNORE = 2;
// we go into this state after a failed include. If we don't encounter a fallback
// before we reach the end include tag, it's a fatal error
private final static int STATE_EXPECT_FALLBACK = 3;
// recognized features and properties
/** Feature identifier: allow notation and unparsed entity events to be sent out of order. */
protected static final String ALLOW_UE_AND_NOTATION_EVENTS =
Constants.SAX_FEATURE_PREFIX
+ Constants.ALLOW_DTD_EVENTS_AFTER_ENDDTD_FEATURE;
/** Property identifier: error reporter. */
protected static final String ERROR_REPORTER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY;
/** Property identifier: grammar pool . */
protected static final String ENTITY_RESOLVER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY;
/** Recognized features. */
private static final String[] RECOGNIZED_FEATURES =
{ ALLOW_UE_AND_NOTATION_EVENTS };
/** Feature defaults. */
private static final Boolean[] FEATURE_DEFAULTS = { Boolean.TRUE };
/** Recognized properties. */
private static final String[] RECOGNIZED_PROPERTIES =
{ ERROR_REPORTER, ENTITY_RESOLVER };
/** Property defaults. */
private static final Object[] PROPERTY_DEFAULTS = { null, null };
// instance variables
// for XMLDocumentFilter
protected XMLDocumentHandler fDocumentHandler;
protected XMLDocumentSource fDocumentSource;
// for XMLDTDFilter
protected XMLDTDHandler fDTDHandler;
protected XMLDTDSource fDTDSource;
// for XIncludeHandler
protected XIncludeHandler fParentXIncludeHandler;
// It's "feels wrong" to store this value here. However,
// calculating it can be time consuming, so we cache it.
// It's never going to change in the lifetime of this XIncludeHandler
protected String fParentRelativeURI;
// we cache the child parser configuration, so we don't have to re-create
// the objects when the parser is re-used
protected XMLParserConfiguration fChildConfig;
protected XMLLocator fDocLocation;
protected XIncludeNamespaceSupport fNamespaceContext;
protected XMLErrorReporter fErrorReporter;
protected XMLEntityResolver fEntityResolver;
// these are needed for XML Base processing
protected XMLResourceIdentifier fCurrentBaseURI;
protected IntStack baseURIScope;
protected Stack baseURI;
protected Stack literalSystemID;
protected Stack expandedSystemID;
// used for passing features on to child XIncludeHandler objects
protected ParserConfigurationSettings fSettings;
// The current element depth. We start at depth 0 (before we've reached any elements)
// The first element is at depth 1.
private int fDepth;
// this value must be at least 1
private static final int INITIAL_SIZE = 8;
// Used to ensure that fallbacks are always children of include elements,
// and that include elements are never children of other include elements.
// An index contains true if the ancestor of the current element which resides
// at that depth was an include element.
private boolean[] fSawInclude = new boolean[INITIAL_SIZE];
// Ensures that only one fallback element can be at a single depth.
// An index contains true if we have seen any fallback elements at that depth,
// and it is only reset to false when the end tag of the parent is encountered.
private boolean[] fSawFallback = new boolean[INITIAL_SIZE];
// The state of the processor at each given depth.
private int[] fState = new int[INITIAL_SIZE];
// buffering the necessary DTD events
private Vector fNotations;
private Vector fUnparsedEntities;
// for SAX compatibility.
// Has the value of the ALLOW_UE_AND_NOTATION_EVENTS feature
private boolean fSendUEAndNotationEvents;
// track the version of the document being parsed
private boolean fIsXML11;
// track whether a DTD is being parsed
private boolean fInDTD;
// track whether a warning has already been reported for
// use of the old http://www.w3.org/2001/XInclude namespace.
private boolean fOldNamespaceWarningIssued;
// Constructors
public XIncludeHandler() {
fDepth = 0;
fSawFallback[fDepth] = false;
fSawInclude[fDepth] = false;
fState[fDepth] = STATE_NORMAL_PROCESSING;
fNotations = new Vector();
fUnparsedEntities = new Vector();
baseURIScope = new IntStack();
baseURI = new Stack();
literalSystemID = new Stack();
expandedSystemID = new Stack();
fCurrentBaseURI = new XMLResourceIdentifierImpl();
}
// XMLComponent methods
public void reset(XMLComponentManager componentManager)
throws XNIException {
fNamespaceContext = null;
fDepth = 0;
fNotations = new Vector();
fUnparsedEntities = new Vector();
fParentRelativeURI = null;
fIsXML11 = false;
fInDTD = false;
fOldNamespaceWarningIssued = false;
baseURIScope.clear();
baseURI.clear();
literalSystemID.clear();
expandedSystemID.clear();
// clear the previous settings from the arrays
for (int i = 0; i < fState.length; i++) {
// these three arrays will always be the same length, so this is safe
fSawFallback[i] = false;
fSawInclude[i] = false;
fState[i] = STATE_NORMAL_PROCESSING;
}
try {
fSendUEAndNotationEvents =
componentManager.getFeature(ALLOW_UE_AND_NOTATION_EVENTS);
if (fChildConfig != null) {
fChildConfig.setFeature(
ALLOW_UE_AND_NOTATION_EVENTS,
fSendUEAndNotationEvents);
}
}
catch (XMLConfigurationException e) {
}
try {
XMLErrorReporter value =
(XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER);
if (value != null) {
setErrorReporter(value);
if (fChildConfig != null) {
fChildConfig.setProperty(ERROR_REPORTER, value);
}
}
}
catch (XMLConfigurationException e) {
fErrorReporter = null;
}
try {
XMLEntityResolver value =
(XMLEntityResolver)componentManager.getProperty(
ENTITY_RESOLVER);
if (value != null) {
fEntityResolver = value;
if (fChildConfig != null) {
fChildConfig.setProperty(ENTITY_RESOLVER, value);
}
}
}
catch (XMLConfigurationException e) {
fEntityResolver = null;
}
fSettings = new ParserConfigurationSettings();
copyFeatures(componentManager, fSettings);
// Don't reset fChildConfig -- we don't want it to share the same components.
// It will be reset when it is actually used to parse something.
} // reset(XMLComponentManager)
/**
* Returns a list of feature identifiers that are recognized by
* this component. This method may return null if no features
* are recognized by this component.
*/
public String[] getRecognizedFeatures() {
return RECOGNIZED_FEATURES;
} // getRecognizedFeatures():String[]
/**
* Sets the state of a feature. This method is called by the component
* manager any time after reset when a feature changes state.
* <p>
* <strong>Note:</strong> Components should silently ignore features
* that do not affect the operation of the component.
*
* @param featureId The feature identifier.
* @param state The state of the feature.
*
* @throws SAXNotRecognizedException The component should not throw
* this exception.
* @throws SAXNotSupportedException The component should not throw
* this exception.
*/
public void setFeature(String featureId, boolean state)
throws XMLConfigurationException {
if (featureId.equals(ALLOW_UE_AND_NOTATION_EVENTS)) {
fSendUEAndNotationEvents = state;
}
if (fSettings != null) {
fSettings.setFeature(featureId, state);
}
} // setFeature(String,boolean)
/**
* Returns a list of property identifiers that are recognized by
* this component. This method may return null if no properties
* are recognized by this component.
*/
public String[] getRecognizedProperties() {
return RECOGNIZED_PROPERTIES;
} // getRecognizedProperties():String[]
/**
* Sets the value of a property. This method is called by the component
* manager any time after reset when a property changes value.
* <p>
* <strong>Note:</strong> Components should silently ignore properties
* that do not affect the operation of the component.
*
* @param propertyId The property identifier.
* @param value The value of the property.
*
* @throws SAXNotRecognizedException The component should not throw
* this exception.
* @throws SAXNotSupportedException The component should not throw
* this exception.
*/
public void setProperty(String propertyId, Object value)
throws XMLConfigurationException {
if (propertyId.equals(ERROR_REPORTER)) {
setErrorReporter((XMLErrorReporter)value);
if (fChildConfig != null) {
fChildConfig.setProperty(propertyId, value);
}
}
if (propertyId.equals(ENTITY_RESOLVER)) {
fEntityResolver = (XMLEntityResolver)value;
if (fChildConfig != null) {
fChildConfig.setProperty(propertyId, value);
}
}
} // setProperty(String,Object)
/**
* Returns the default state for a feature, or null if this
* component does not want to report a default value for this
* feature.
*
* @param featureId The feature identifier.
*
* @since Xerces 2.2.0
*/
public Boolean getFeatureDefault(String featureId) {
for (int i = 0; i < RECOGNIZED_FEATURES.length; i++) {
if (RECOGNIZED_FEATURES[i].equals(featureId)) {
return FEATURE_DEFAULTS[i];
}
}
return null;
} // getFeatureDefault(String):Boolean
/**
* Returns the default state for a property, or null if this
* component does not want to report a default value for this
* property.
*
* @param propertyId The property identifier.
*
* @since Xerces 2.2.0
*/
public Object getPropertyDefault(String propertyId) {
for (int i = 0; i < RECOGNIZED_PROPERTIES.length; i++) {
if (RECOGNIZED_PROPERTIES[i].equals(propertyId)) {
return PROPERTY_DEFAULTS[i];
}
}
return null;
} // getPropertyDefault(String):Object
public void setDocumentHandler(XMLDocumentHandler handler) {
fDocumentHandler = handler;
}
public XMLDocumentHandler getDocumentHandler() {
return fDocumentHandler;
}
// XMLDocumentHandler methods
/**
* Event sent at the start of the document.
*
* A fatal error will occur here, if it is detected that this document has been processed
* before.
*
* This event is only passed on to the document handler if this is the root document.
*/
public void startDocument(
XMLLocator locator,
String encoding,
NamespaceContext namespaceContext,
Augmentations augs)
throws XNIException {
// we do this to ensure that the proper location is reported in errors
// otherwise, the locator from the root document would always be used
fErrorReporter.setDocumentLocator(locator);
if (!isRootDocument()
&& fParentXIncludeHandler.searchForRecursiveIncludes(locator)) {
reportFatalError(
"RecursiveInclude",
new Object[] { locator.getExpandedSystemId()});
}
if (!(namespaceContext instanceof XIncludeNamespaceSupport)) {
reportFatalError("IncompatibleNamespaceContext");
}
fNamespaceContext = (XIncludeNamespaceSupport)namespaceContext;
fDocLocation = locator;
// initialize the current base URI
fCurrentBaseURI.setBaseSystemId(locator.getBaseSystemId());
fCurrentBaseURI.setExpandedSystemId(locator.getExpandedSystemId());
fCurrentBaseURI.setLiteralSystemId(locator.getLiteralSystemId());
saveBaseURI();
if (augs == null) {
augs = new AugmentationsImpl();
}
augs.putItem(CURRENT_BASE_URI, fCurrentBaseURI);
if (isRootDocument() && fDocumentHandler != null) {
fDocumentHandler.startDocument(
locator,
encoding,
namespaceContext,
augs);
}
}
public void xmlDecl(
String version,
String encoding,
String standalone,
Augmentations augs)
throws XNIException {
fIsXML11 = "1.1".equals(version);
if (isRootDocument() && fDocumentHandler != null) {
fDocumentHandler.xmlDecl(version, encoding, standalone, augs);
}
}
public void doctypeDecl(
String rootElement,
String publicId,
String systemId,
Augmentations augs)
throws XNIException {
if (isRootDocument() && fDocumentHandler != null) {
fDocumentHandler.doctypeDecl(rootElement, publicId, systemId, augs);
}
}
public void comment(XMLString text, Augmentations augs)
throws XNIException {
if (!fInDTD) {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
fDepth++;
augs = modifyAugmentations(augs);
fDocumentHandler.comment(text, augs);
fDepth--;
}
}
else if (fDTDHandler != null) {
fDTDHandler.comment(text, augs);
}
}
public void processingInstruction(
String target,
XMLString data,
Augmentations augs)
throws XNIException {
if (!fInDTD) {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
// we need to change the depth like this so that modifyAugmentations() works
fDepth++;
augs = modifyAugmentations(augs);
fDocumentHandler.processingInstruction(target, data, augs);
fDepth--;
}
}
else if (fDTDHandler != null) {
fDTDHandler.processingInstruction(target, data, augs);
}
}
public void startElement(
QName element,
XMLAttributes attributes,
Augmentations augs)
throws XNIException {
fDepth++;
setState(getState(fDepth - 1));
// we process the xml:base attributes regardless of what type of element it is
processXMLBaseAttributes(attributes);
if (isIncludeElement(element)) {
boolean success = this.handleIncludeElement(attributes);
if (success) {
setState(STATE_IGNORE);
}
else {
setState(STATE_EXPECT_FALLBACK);
}
}
else if (isFallbackElement(element)) {
this.handleFallbackElement();
}
else if (
fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
augs = modifyAugmentations(augs);
attributes = processAttributes(attributes);
fDocumentHandler.startElement(element, attributes, augs);
}
}
public void emptyElement(
QName element,
XMLAttributes attributes,
Augmentations augs)
throws XNIException {
fDepth++;
setState(getState(fDepth - 1));
// we process the xml:base attributes regardless of what type of element it is
processXMLBaseAttributes(attributes);
if (isIncludeElement(element)) {
boolean success = this.handleIncludeElement(attributes);
if (success) {
setState(STATE_IGNORE);
}
else {
reportFatalError("NoFallback");
}
}
else if (isFallbackElement(element)) {
this.handleFallbackElement();
}
else if (hasXIncludeNamespace(element)) {
if (getSawInclude(fDepth - 1)) {
reportFatalError(
"IncludeChild",
new Object[] { element.rawname });
}
}
else if (
fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
augs = modifyAugmentations(augs);
attributes = processAttributes(attributes);
fDocumentHandler.emptyElement(element, attributes, augs);
}
// reset the out of scope stack elements
setSawFallback(fDepth + 1, false);
setSawInclude(fDepth + 1, false);
// check if an xml:base has gone out of scope
if (baseURIScope.size() > 0 && fDepth == baseURIScope.peek()) {
// pop the values from the stack
restoreBaseURI();
}
fDepth--;
}
public void endElement(QName element, Augmentations augs)
throws XNIException {
if (isIncludeElement(element)) {
// if we're ending an include element, and we were expecting a fallback
// we check to see if the children of this include element contained a fallback
if (getState() == STATE_EXPECT_FALLBACK
&& !getSawFallback(fDepth + 1)) {
reportFatalError("NoFallback");
}
}
if (isFallbackElement(element)) {
// the state would have been set to normal processing if we were expecting the fallback element
// now that we're done processing it, we should ignore all the other children of the include element
if (getState() == STATE_NORMAL_PROCESSING) {
setState(STATE_IGNORE);
}
}
else if (
fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
fDocumentHandler.endElement(element, augs);
}
// reset the out of scope stack elements
setSawFallback(fDepth + 1, false);
setSawInclude(fDepth + 1, false);
// check if an xml:base has gone out of scope
if (baseURIScope.size() > 0 && fDepth == baseURIScope.peek()) {
// pop the values from the stack
restoreBaseURI();
}
fDepth--;
}
public void startGeneralEntity(
String name,
XMLResourceIdentifier resId,
String encoding,
Augmentations augs)
throws XNIException {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
fDocumentHandler.startGeneralEntity(name, resId, encoding, augs);
}
}
public void textDecl(String version, String encoding, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
fDocumentHandler.textDecl(version, encoding, augs);
}
}
public void endGeneralEntity(String name, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
fDocumentHandler.endGeneralEntity(name, augs);
}
}
public void characters(XMLString text, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
// we need to change the depth like this so that modifyAugmentations() works
fDepth++;
augs = modifyAugmentations(augs);
fDocumentHandler.characters(text, augs);
fDepth--;
}
}
public void ignorableWhitespace(XMLString text, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
fDocumentHandler.ignorableWhitespace(text, augs);
}
}
public void startCDATA(Augmentations augs) throws XNIException {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
fDocumentHandler.startCDATA(augs);
}
}
public void endCDATA(Augmentations augs) throws XNIException {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
fDocumentHandler.endCDATA(augs);
}
}
public void endDocument(Augmentations augs) throws XNIException {
if (isRootDocument() && fDocumentHandler != null) {
fDocumentHandler.endDocument(augs);
}
}
public void setDocumentSource(XMLDocumentSource source) {
fDocumentSource = source;
}
public XMLDocumentSource getDocumentSource() {
return fDocumentSource;
}
// DTDHandler methods
// We are only interested in the notation and unparsed entity declarations,
// the rest we just pass on
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#attributeDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], java.lang.String, org.apache.xerces.xni.XMLString, org.apache.xerces.xni.XMLString, org.apache.xerces.xni.Augmentations)
*/
public void attributeDecl(
String elementName,
String attributeName,
String type,
String[] enumeration,
String defaultType,
XMLString defaultValue,
XMLString nonNormalizedDefaultValue,
Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.attributeDecl(
elementName,
attributeName,
type,
enumeration,
defaultType,
defaultValue,
nonNormalizedDefaultValue,
augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#elementDecl(java.lang.String, java.lang.String, org.apache.xerces.xni.Augmentations)
*/
public void elementDecl(
String name,
String contentModel,
Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.elementDecl(name, contentModel, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#endAttlist(org.apache.xerces.xni.Augmentations)
*/
public void endAttlist(Augmentations augmentations) throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.endAttlist(augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#endConditional(org.apache.xerces.xni.Augmentations)
*/
public void endConditional(Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.endConditional(augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#endDTD(org.apache.xerces.xni.Augmentations)
*/
public void endDTD(Augmentations augmentations) throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.endDTD(augmentations);
}
fInDTD = false;
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#endExternalSubset(org.apache.xerces.xni.Augmentations)
*/
public void endExternalSubset(Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.endExternalSubset(augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#endParameterEntity(java.lang.String, org.apache.xerces.xni.Augmentations)
*/
public void endParameterEntity(String name, Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.endParameterEntity(name, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#externalEntityDecl(java.lang.String, org.apache.xerces.xni.XMLResourceIdentifier, org.apache.xerces.xni.Augmentations)
*/
public void externalEntityDecl(
String name,
XMLResourceIdentifier identifier,
Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.externalEntityDecl(name, identifier, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#getDTDSource()
*/
public XMLDTDSource getDTDSource() {
return fDTDSource;
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#ignoredCharacters(org.apache.xerces.xni.XMLString, org.apache.xerces.xni.Augmentations)
*/
public void ignoredCharacters(XMLString text, Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.ignoredCharacters(text, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#internalEntityDecl(java.lang.String, org.apache.xerces.xni.XMLString, org.apache.xerces.xni.XMLString, org.apache.xerces.xni.Augmentations)
*/
public void internalEntityDecl(
String name,
XMLString text,
XMLString nonNormalizedText,
Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.internalEntityDecl(
name,
text,
nonNormalizedText,
augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#notationDecl(java.lang.String, org.apache.xerces.xni.XMLResourceIdentifier, org.apache.xerces.xni.Augmentations)
*/
public void notationDecl(
String name,
XMLResourceIdentifier identifier,
Augmentations augmentations)
throws XNIException {
this.addNotation(name, identifier, augmentations);
if (fDTDHandler != null) {
fDTDHandler.notationDecl(name, identifier, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#setDTDSource(org.apache.xerces.xni.parser.XMLDTDSource)
*/
public void setDTDSource(XMLDTDSource source) {
fDTDSource = source;
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#startAttlist(java.lang.String, org.apache.xerces.xni.Augmentations)
*/
public void startAttlist(String elementName, Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.startAttlist(elementName, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#startConditional(short, org.apache.xerces.xni.Augmentations)
*/
public void startConditional(short type, Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.startConditional(type, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#startDTD(org.apache.xerces.xni.XMLLocator, org.apache.xerces.xni.Augmentations)
*/
public void startDTD(XMLLocator locator, Augmentations augmentations)
throws XNIException {
fInDTD = true;
if (fDTDHandler != null) {
fDTDHandler.startDTD(locator, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#startExternalSubset(org.apache.xerces.xni.XMLResourceIdentifier, org.apache.xerces.xni.Augmentations)
*/
public void startExternalSubset(
XMLResourceIdentifier identifier,
Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.startExternalSubset(identifier, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#startParameterEntity(java.lang.String, org.apache.xerces.xni.XMLResourceIdentifier, java.lang.String, org.apache.xerces.xni.Augmentations)
*/
public void startParameterEntity(
String name,
XMLResourceIdentifier identifier,
String encoding,
Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.startParameterEntity(
name,
identifier,
encoding,
augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#unparsedEntityDecl(java.lang.String, org.apache.xerces.xni.XMLResourceIdentifier, java.lang.String, org.apache.xerces.xni.Augmentations)
*/
public void unparsedEntityDecl(
String name,
XMLResourceIdentifier identifier,
String notation,
Augmentations augmentations)
throws XNIException {
this.addUnparsedEntity(name, identifier, notation, augmentations);
if (fDTDHandler != null) {
fDTDHandler.unparsedEntityDecl(
name,
identifier,
notation,
augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.parser.XMLDTDSource#getDTDHandler()
*/
public XMLDTDHandler getDTDHandler() {
return fDTDHandler;
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.parser.XMLDTDSource#setDTDHandler(org.apache.xerces.xni.XMLDTDHandler)
*/
public void setDTDHandler(XMLDTDHandler handler) {
fDTDHandler = handler;
}
// XIncludeHandler methods
private void setErrorReporter(XMLErrorReporter reporter) {
fErrorReporter = reporter;
if (fErrorReporter != null) {
fErrorReporter.putMessageFormatter(
XIncludeMessageFormatter.XINCLUDE_DOMAIN,
new XIncludeMessageFormatter());
// this ensures the proper location is displayed in error messages
if (fDocLocation != null) {
fErrorReporter.setDocumentLocator(fDocLocation);
}
}
}
protected void handleFallbackElement() {
setSawInclude(fDepth, false);
fNamespaceContext.setContextInvalid();
if (!getSawInclude(fDepth - 1)) {
reportFatalError("FallbackParent");
}
if (getSawFallback(fDepth)) {
reportFatalError("MultipleFallbacks");
}
else {
setSawFallback(fDepth, true);
}
// Either the state is STATE_EXPECT_FALLBACK or it's STATE_IGNORE.
// If we're ignoring, we want to stay ignoring. But if we're expecting this fallback element,
// we want to signal that we should process the children.
if (getState() == STATE_EXPECT_FALLBACK) {
setState(STATE_NORMAL_PROCESSING);
}
}
protected boolean handleIncludeElement(XMLAttributes attributes)
throws XNIException {
setSawInclude(fDepth, true);
fNamespaceContext.setContextInvalid();
if (getSawInclude(fDepth - 1)) {
reportFatalError("IncludeChild", new Object[] { XINCLUDE_INCLUDE });
}
if (getState() == STATE_IGNORE)
return true;
// TODO: does Java use IURIs by default?
// [Definition: An internationalized URI reference, or IURI, is a URI reference that directly uses [Unicode] characters.]
// TODO: figure out what section 4.1.1 of the XInclude spec is talking about
// has to do with disallowed ASCII character escaping
// this ties in with the above IURI section, but I suspect Java already does it
String href = attributes.getValue(XINCLUDE_ATTR_HREF);
String parse = attributes.getValue(XINCLUDE_ATTR_PARSE);
if (href == null) {
reportFatalError("HrefMissing");
}
if (parse == null) {
parse = XINCLUDE_PARSE_XML;
}
XMLInputSource includedSource = null;
if (fEntityResolver != null) {
try {
XMLResourceIdentifier resourceIdentifier =
new XMLResourceIdentifierImpl(
null,
href,
fCurrentBaseURI.getExpandedSystemId(),
XMLEntityManager.expandSystemId(
href,
fCurrentBaseURI.getExpandedSystemId(),
false));
includedSource =
fEntityResolver.resolveEntity(resourceIdentifier);
}
catch (IOException e) {
reportResourceError(
"XMLResourceError",
new Object[] { href, e.getMessage()});
return false;
}
}
if (includedSource == null) {
includedSource =
new XMLInputSource(
null,
href,
fCurrentBaseURI.getExpandedSystemId());
}
if (parse.equals(XINCLUDE_PARSE_XML)) {
// Instead of always creating a new configuration, the first one can be reused
if (fChildConfig == null) {
String parserName = XINCLUDE_DEFAULT_CONFIGURATION;
fChildConfig =
(XMLParserConfiguration)ObjectFactory.newInstance(
parserName,
ObjectFactory.findClassLoader(),
true);
// use the same error reporter
fChildConfig.setProperty(ERROR_REPORTER, fErrorReporter);
// use the same namespace context
fChildConfig.setProperty(
Constants.XERCES_PROPERTY_PREFIX
+ Constants.NAMESPACE_CONTEXT_PROPERTY,
fNamespaceContext);
XIncludeHandler newHandler =
(XIncludeHandler)fChildConfig.getProperty(
Constants.XERCES_PROPERTY_PREFIX
+ Constants.XINCLUDE_HANDLER_PROPERTY);
newHandler.setParent(this);
newHandler.setDocumentHandler(this.getDocumentHandler());
}
//disabled for now.
//setHttpProperties(includedSource,attributes);
// set all features on parserConfig to match this parser configuration
copyFeatures(fSettings, fChildConfig);
// we don't want a schema validator on the new pipeline,
// so we set it to false, regardless of what was copied above
fChildConfig.setFeature(
Constants.XERCES_FEATURE_PREFIX
+ Constants.SCHEMA_VALIDATION_FEATURE,
false);
try {
fNamespaceContext.pushScope();
fChildConfig.parse(includedSource);
// necessary to make sure proper location is reported in errors
if (fErrorReporter != null) {
fErrorReporter.setDocumentLocator(fDocLocation);
}
}
catch (XNIException e) {
// necessary to make sure proper location is reported in errors
if (fErrorReporter != null) {
fErrorReporter.setDocumentLocator(fDocLocation);
}
reportFatalError("XMLParseError", new Object[] { href });
}
catch (IOException e) {
// necessary to make sure proper location is reported in errors
if (fErrorReporter != null) {
fErrorReporter.setDocumentLocator(fDocLocation);
}
// An IOException indicates that we had trouble reading the file, not
// that it was an invalid XML file. So we send a resource error, not a
// fatal error.
reportResourceError(
"XMLResourceError",
new Object[] { href, e.getMessage()});
return false;
}
finally {
fNamespaceContext.popScope();
}
}
else if (parse.equals(XINCLUDE_PARSE_TEXT)) {
// we only care about encoding for parse="text"
String encoding = attributes.getValue(XINCLUDE_ATTR_ENCODING);
includedSource.setEncoding(encoding);
XIncludeTextReader reader = null;
//disabled for now.
//setHttpProperties(includedSource,attributes);
try {
if (fIsXML11) {
reader = new XInclude11TextReader(includedSource, this);
}
else {
reader = new XIncludeTextReader(includedSource, this);
}
reader.setErrorReporter(fErrorReporter);
reader.parse();
}
catch (IOException e) {
reportResourceError(
"TextResourceError",
new Object[] { href, e.getMessage()});
return false;
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException e) {
reportResourceError(
"TextResourceError",
new Object[] { href, e.getMessage()});
return false;
}
}
}
}
else {
reportFatalError("InvalidParseValue", new Object[] { parse });
}
return true;
}
/**
* Returns true if the element has the namespace "http://www.w3.org/2003/XInclude"
* @param element the element to check
* @return true if the element has the namespace "http://www.w3.org/2003/XInclude"
*/
protected boolean hasXIncludeNamespace(QName element) {
// REVISIT: The namespace of this element should be bound
// already. Why are we looking it up from the namespace
// context? -- mrglavas
return element.uri == XINCLUDE_NS_URI
|| fNamespaceContext.getURI(element.prefix) == XINCLUDE_NS_URI;
}
/**
* Returns true if the element has the namespace "http://www.w3.org/2001/XInclude"
* @param element the element to check
* @return true if the element has the namespace "http://www.w3.org/2001/XInclude"
*/
protected boolean hasXInclude2001Namespace(QName element) {
// REVISIT: The namespace of this element should be bound
// already. Why are we looking it up from the namespace
// context? -- mrglavas
return element.uri == XINCLUDE_NS_URI_OLD
|| fNamespaceContext.getURI(element.prefix) == XINCLUDE_NS_URI_OLD;
}
/**
* Checks if the element is an <include> element. The element must have
* the XInclude namespace, and a local name of "include". If the local name
* is "include" and the namespace name is the old XInclude namespace
* "http://www.w3.org/2001/XInclude" a warning is issued the first time
* an element from the old namespace is encountered.
*
* @param element the element to check
* @return true if the element is an <include> element
* @see #hasXIncludeNamespace(QName)
*/
protected boolean isIncludeElement(QName element) {
if (element.localpart.equals(XINCLUDE_INCLUDE)) {
if (hasXIncludeNamespace(element)) {
return true;
}
else if (!fOldNamespaceWarningIssued && hasXInclude2001Namespace(element)) {
reportError("OldXIncludeNamespace", null, XMLErrorReporter.SEVERITY_WARNING);
fOldNamespaceWarningIssued = true;
}
}
return false;
}
/**
* Checks if the element is an <fallback> element. The element must have
* the XInclude namespace, and a local name of "fallback". If the local name
* is "fallback" and the namespace name is the old XInclude namespace
* "http://www.w3.org/2001/XInclude" a warning is issued the first time
* an element from the old namespace is encountered.
*
* @param element the element to check
* @return true if the element is an <fallback; element
* @see #hasXIncludeNamespace(QName)
*/
protected boolean isFallbackElement(QName element) {
if (element.localpart.equals(XINCLUDE_FALLBACK)) {
if (hasXIncludeNamespace(element)) {
return true;
}
else if (!fOldNamespaceWarningIssued && hasXInclude2001Namespace(element)) {
reportError("OldXIncludeNamespace", null, XMLErrorReporter.SEVERITY_WARNING);
fOldNamespaceWarningIssued = true;
}
}
return false;
}
/**
* Returns true if the current [base URI] is the same as the [base URI] that
* was in effect on the include parent. This method should <em>only</em> be called
* when the current element is a top level included element, i.e. the direct child
* of a fallback element, or the root elements in an included document.
* The "include parent" is the element which, in the result infoset, will be the
* direct parent of the current element.
* @return true if the [base URIs] are the same string
*/
protected boolean sameBaseURIAsIncludeParent() {
String parentBaseURI = getIncludeParentBaseURI();
String baseURI = fCurrentBaseURI.getExpandedSystemId();
// REVISIT: should we use File#sameFile() ?
// I think the benefit of using it is that it resolves host names
// instead of just doing a string comparison.
// TODO: [base URI] is still an open issue with the working group.
// They're deciding if xml:base should be added if the [base URI] is different in terms
// of resolving relative references, or if it should be added if they are different at all.
// Revisit this after a final decision has been made.
// The decision also affects whether we output the file name of the URI, or just the path.
return parentBaseURI.equals(baseURI);
}
/**
* Checks if the file indicated by the given XMLLocator has already been included
* in the current stack.
* @param includedSource the source to check for inclusion
* @return true if the source has already been included
*/
protected boolean searchForRecursiveIncludes(XMLLocator includedSource) {
String includedSystemId = includedSource.getExpandedSystemId();
if (includedSystemId == null) {
try {
includedSystemId =
XMLEntityManager.expandSystemId(
includedSource.getLiteralSystemId(),
includedSource.getBaseSystemId(),
false);
}
catch (MalformedURIException e) {
reportFatalError("ExpandedSystemId");
}
}
if (includedSystemId.equals(fCurrentBaseURI.getExpandedSystemId())) {
return true;
}
if (fParentXIncludeHandler == null) {
return false;
}
return fParentXIncludeHandler.searchForRecursiveIncludes(
includedSource);
}
/**
* Returns true if the current element is a top level included item. This means
* it's either the child of a fallback element, or the top level item in an
* included document
* @return true if the current element is a top level included item
*/
protected boolean isTopLevelIncludedItem() {
return isTopLevelIncludedItemViaInclude()
|| isTopLevelIncludedItemViaFallback();
}
protected boolean isTopLevelIncludedItemViaInclude() {
return fDepth == 1 && !isRootDocument();
}
protected boolean isTopLevelIncludedItemViaFallback() {
// Technically, this doesn't check if the parent was a fallback, it also
// would return true if any of the parent's sibling elements were fallbacks.
// However, this doesn't matter, since we will always be ignoring elements
// whose parent's siblings were fallbacks.
return getSawFallback(fDepth - 1);
}
/**
* Processes the XMLAttributes object of startElement() calls. Performs the following tasks:
* <ul>
* <li> If the element is a top level included item whose [base URI] is different from the
* [base URI] of the include parent, then an xml:base attribute is added to specify the
* true [base URI]
* <li> For all namespace prefixes which are in-scope in an included item, but not in scope
* in the include parent, a xmlns:prefix attribute is added
* <li> For all attributes with a type of ENTITY, ENTITIES or NOTATIONS, the notations and
* unparsed entities are processed as described in the spec, sections 4.5.1 and 4.5.2
* </ul>
* @param attributes
* @return
*/
protected XMLAttributes processAttributes(XMLAttributes attributes) {
if (isTopLevelIncludedItem()) {
// Modify attributes to fix the base URI (spec 4.5.5).
// We only do it to top level included elements, which have a different
// base URI than their include parent.
if (!sameBaseURIAsIncludeParent()) {
if (attributes == null) {
attributes = new XMLAttributesImpl();
}
// This causes errors with schema validation, if the schema doesn't
// specify that these elements can have an xml:base attribute
// TODO: add a user option to turn this off?
String uri = null;
try {
uri = this.getRelativeBaseURI();
}
catch (MalformedURIException e) {
// this shouldn't ever happen, since by definition, we had to traverse
// the same URIs to even get to this place
uri = fCurrentBaseURI.getExpandedSystemId();
}
int index =
attributes.addAttribute(
XML_BASE_QNAME,
XMLSymbols.fCDATASymbol,
uri);
attributes.setSpecified(index, true);
}
// Modify attributes of included items to do namespace-fixup. (spec 4.5.4)
Enumeration inscopeNS = fNamespaceContext.getAllPrefixes();
while (inscopeNS.hasMoreElements()) {
String prefix = (String)inscopeNS.nextElement();
String parentURI =
fNamespaceContext.getURIFromIncludeParent(prefix);
String uri = fNamespaceContext.getURI(prefix);
if (parentURI != uri && attributes != null) {
if (prefix == XMLSymbols.EMPTY_STRING) {
if (attributes
.getValue(
NamespaceContext.XMLNS_URI,
XMLSymbols.PREFIX_XMLNS)
== null) {
if (attributes == null) {
attributes = new XMLAttributesImpl();
}
QName ns = (QName)NEW_NS_ATTR_QNAME.clone();
ns.localpart = XMLSymbols.PREFIX_XMLNS;
ns.rawname = XMLSymbols.PREFIX_XMLNS;
attributes.addAttribute(
ns,
XMLSymbols.fCDATASymbol,
uri);
}
}
else if (
attributes.getValue(NamespaceContext.XMLNS_URI, prefix)
== null) {
if (attributes == null) {
attributes = new XMLAttributesImpl();
}
QName ns = (QName)NEW_NS_ATTR_QNAME.clone();
ns.localpart = prefix;
ns.rawname += prefix;
attributes.addAttribute(
ns,
XMLSymbols.fCDATASymbol,
uri);
}
}
}
}
if (attributes != null) {
int length = attributes.getLength();
for (int i = 0; i < length; i++) {
String type = attributes.getType(i);
String value = attributes.getValue(i);
if (type == XMLSymbols.fENTITYSymbol) {
this.checkUnparsedEntity(value);
}
if (type == XMLSymbols.fENTITIESSymbol) {
// 4.5.1 - Unparsed Entities
StringTokenizer st = new StringTokenizer(value);
while (st.hasMoreTokens()) {
String entName = st.nextToken();
this.checkUnparsedEntity(entName);
}
}
else if (type == XMLSymbols.fNOTATIONSymbol) {
// 4.5.2 - Notations
this.checkNotation(value);
}
/* We actually don't need to do anything for 4.5.3, because at this stage the
* value of the attribute is just a string. It will be taken care of later
* in the pipeline, when the IDREFs are actually resolved against IDs.
*
* if (type == XMLSymbols.fIDREFSymbol || type == XMLSymbols.fIDREFSSymbol) { }
*/
}
}
return attributes;
}
/**
* Returns a URI, relative to the include parent's base URI, of the current
* [base URI]. For instance, if the current [base URI] was "dir1/dir2/file.xml"
* and the include parent's [base URI] was "dir/", this would return "dir2/file.xml".
* @return the relative URI
*/
protected String getRelativeBaseURI() throws MalformedURIException {
int includeParentDepth = getIncludeParentDepth();
String relativeURI = this.getRelativeURI(includeParentDepth);
if (isRootDocument()) {
return relativeURI;
}
else {
if (relativeURI.equals("")) {
relativeURI = fCurrentBaseURI.getLiteralSystemId();
}
if (includeParentDepth == 0) {
if (fParentRelativeURI == null) {
fParentRelativeURI =
fParentXIncludeHandler.getRelativeBaseURI();
}
if (fParentRelativeURI.equals("")) {
return relativeURI;
}
URI uri = new URI("file", fParentRelativeURI);
uri = new URI(uri, relativeURI);
return uri.getPath();
}
else {
return relativeURI;
}
}
}
/**
* Returns the [base URI] of the include parent.
* @return the base URI of the include parent.
*/
private String getIncludeParentBaseURI() {
int depth = getIncludeParentDepth();
if (!isRootDocument() && depth == 0) {
return fParentXIncludeHandler.getIncludeParentBaseURI();
}
else {
return this.getBaseURI(depth);
}
}
/**
* Returns the depth of the include parent. Here, the include parent is
* calculated as the last non-include or non-fallback element. It is assumed
* this method is called when the current element is a top level included item.
* Returning 0 indicates that the top level element in this document
* was an include element.
* @return the depth of the top level include element
*/
private int getIncludeParentDepth() {
// We don't start at fDepth, since it is either the top level included item,
// or an include element, when this method is called.
for (int i = fDepth - 1; i >= 0; i--) {
// This technically might not always return the first non-include/fallback
// element that it comes to, since sawFallback() returns true if a fallback
// was ever encountered at that depth. However, if a fallback was encountered
// at that depth, and it wasn't the direct descendant of the current element
// then we can't be in a situation where we're calling this method (because
// we'll always be in STATE_IGNORE)
if (!getSawInclude(i) && !getSawFallback(i)) {
return i;
}
}
// shouldn't get here, since depth 0 should never have an include element or
// a fallback element
return 0;
}
/**
* Modify the augmentations. Add an [included] infoset item, if the current
* element is a top level included item.
* @param augs the Augmentations to modify.
* @return the modified Augmentations
*/
protected Augmentations modifyAugmentations(Augmentations augs) {
return modifyAugmentations(augs, false);
}
/**
* Modify the augmentations. Add an [included] infoset item, if <code>force</code>
* is true, or if the current element is a top level included item.
* @param augs the Augmentations to modify.
* @param force whether to force modification
* @return the modified Augmentations
*/
protected Augmentations modifyAugmentations(
Augmentations augs,
boolean force) {
if (force || isTopLevelIncludedItem()) {
if (augs == null) {
augs = new AugmentationsImpl();
}
augs.putItem(XINCLUDE_INCLUDED, Boolean.TRUE);
}
return augs;
}
protected int getState(int depth) {
return fState[depth];
}
protected int getState() {
return fState[fDepth];
}
protected void setState(int state) {
if (fDepth >= fState.length) {
int[] newarray = new int[fDepth * 2];
System.arraycopy(fState, 0, newarray, 0, fState.length);
fState = newarray;
}
fState[fDepth] = state;
}
/**
* Records that an <fallback> was encountered at the specified depth,
* as an ancestor of the current element, or as a sibling of an ancestor of the
* current element.
*
* @param depth
* @param val
*/
protected void setSawFallback(int depth, boolean val) {
if (depth >= fSawFallback.length) {
boolean[] newarray = new boolean[depth * 2];
System.arraycopy(fSawFallback, 0, newarray, 0, fSawFallback.length);
fSawFallback = newarray;
}
fSawFallback[depth] = val;
}
/**
* Returns whether an <fallback> was encountered at the specified depth,
* as an ancestor of the current element, or as a sibling of an ancestor of the
* current element.
*
* @param depth
*/
protected boolean getSawFallback(int depth) {
if (depth >= fSawFallback.length) {
return false;
}
return fSawFallback[depth];
}
/**
* Records that an <include> was encountered at the specified depth,
* as an ancestor of the current item.
*
* @param depth
* @param val
*/
protected void setSawInclude(int depth, boolean val) {
if (depth >= fSawInclude.length) {
boolean[] newarray = new boolean[depth * 2];
System.arraycopy(fSawInclude, 0, newarray, 0, fSawInclude.length);
fSawInclude = newarray;
}
fSawInclude[depth] = val;
}
/**
* Return whether an <include> was encountered at the specified depth,
* as an ancestor of the current item.
*
* @param depth
* @return
*/
protected boolean getSawInclude(int depth) {
if (depth >= fSawInclude.length) {
return false;
}
return fSawInclude[depth];
}
protected void reportResourceError(String key) {
this.reportFatalError(key, null);
}
protected void reportResourceError(String key, Object[] args) {
this.reportError(key, args, XMLErrorReporter.SEVERITY_WARNING);
}
protected void reportFatalError(String key) {
this.reportFatalError(key, null);
}
protected void reportFatalError(String key, Object[] args) {
this.reportError(key, args, XMLErrorReporter.SEVERITY_FATAL_ERROR);
}
private void reportError(String key, Object[] args, short severity) {
if (fErrorReporter != null) {
fErrorReporter.reportError(
XIncludeMessageFormatter.XINCLUDE_DOMAIN,
key,
args,
severity);
}
// we won't worry about when error reporter is null, since there should always be
// at least the default error reporter
}
/**
* Set the parent of this XIncludeHandler in the tree
* @param parent
*/
protected void setParent(XIncludeHandler parent) {
fParentXIncludeHandler = parent;
}
// used to know whether to pass declarations to the document handler
protected boolean isRootDocument() {
return fParentXIncludeHandler == null;
}
/**
* Caches an unparsed entity.
* @param name the name of the unparsed entity
* @param identifier the location of the unparsed entity
* @param augmentations any Augmentations that were on the original unparsed entity declaration
*/
protected void addUnparsedEntity(
String name,
XMLResourceIdentifier identifier,
String notation,
Augmentations augmentations) {
UnparsedEntity ent = new UnparsedEntity();
ent.name = name;
ent.systemId = identifier.getLiteralSystemId();
ent.publicId = identifier.getPublicId();
ent.baseURI = identifier.getBaseSystemId();
ent.notation = notation;
ent.augmentations = augmentations;
fUnparsedEntities.add(ent);
}
/**
* Caches a notation.
* @param name the name of the notation
* @param identifier the location of the notation
* @param augmentations any Augmentations that were on the original notation declaration
*/
protected void addNotation(
String name,
XMLResourceIdentifier identifier,
Augmentations augmentations) {
Notation not = new Notation();
not.name = name;
not.systemId = identifier.getLiteralSystemId();
not.publicId = identifier.getPublicId();
not.baseURI = identifier.getBaseSystemId();
not.augmentations = augmentations;
fNotations.add(not);
}
/**
* Checks if an UnparsedEntity with the given name was declared in the DTD of the document
* for the current pipeline. If so, then the notation for the UnparsedEntity is checked.
* If that turns out okay, then the UnparsedEntity is passed to the root pipeline to
* be checked for conflicts, and sent to the root DTDHandler.
*
* @param entName the name of the UnparsedEntity to check
*/
protected void checkUnparsedEntity(String entName) {
UnparsedEntity ent = new UnparsedEntity();
ent.name = entName;
int index = fUnparsedEntities.indexOf(ent);
if (index != -1) {
ent = (UnparsedEntity)fUnparsedEntities.get(index);
// first check the notation of the unparsed entity
checkNotation(ent.notation);
checkAndSendUnparsedEntity(ent);
}
}
/**
* Checks if a Notation with the given name was declared in the DTD of the document
* for the current pipeline. If so, that Notation is passed to the root pipeline to
* be checked for conflicts, and sent to the root DTDHandler
*
* @param notName the name of the Notation to check
*/
protected void checkNotation(String notName) {
Notation not = new Notation();
not.name = notName;
int index = fNotations.indexOf(not);
if (index != -1) {
not = (Notation)fNotations.get(index);
checkAndSendNotation(not);
}
}
/**
* The purpose of this method is to check if an UnparsedEntity conflicts with a previously
* declared entity in the current pipeline stack. If there is no conflict, the
* UnparsedEntity is sent by the root pipeline.
*
* @param ent the UnparsedEntity to check for conflicts
*/
protected void checkAndSendUnparsedEntity(UnparsedEntity ent) {
if (isRootDocument()) {
int index = fUnparsedEntities.indexOf(ent);
if (index == -1) {
// There is no unparsed entity with the same name that we have sent.
// Calling unparsedEntityDecl() will add the entity to our local store,
// and also send the unparsed entity to the DTDHandler
XMLResourceIdentifier id =
new XMLResourceIdentifierImpl(
ent.publicId,
ent.systemId,
ent.baseURI,
null);
this.addUnparsedEntity(
ent.name,
id,
ent.notation,
ent.augmentations);
if (fSendUEAndNotationEvents && fDTDHandler != null) {
fDTDHandler.unparsedEntityDecl(
ent.name,
id,
ent.notation,
ent.augmentations);
}
}
else {
UnparsedEntity localEntity =
(UnparsedEntity)fUnparsedEntities.get(index);
if (!ent.isDuplicate(localEntity)) {
reportFatalError(
"NonDuplicateUnparsedEntity",
new Object[] { ent.name });
}
}
}
else {
fParentXIncludeHandler.checkAndSendUnparsedEntity(ent);
}
}
/**
* The purpose of this method is to check if a Notation conflicts with a previously
* declared notation in the current pipeline stack. If there is no conflict, the
* Notation is sent by the root pipeline.
*
* @param not the Notation to check for conflicts
*/
protected void checkAndSendNotation(Notation not) {
if (isRootDocument()) {
int index = fNotations.indexOf(not);
if (index == -1) {
// There is no notation with the same name that we have sent.
XMLResourceIdentifier id =
new XMLResourceIdentifierImpl(
not.publicId,
not.systemId,
not.baseURI,
null);
this.addNotation(not.name, id, not.augmentations);
if (fSendUEAndNotationEvents && fDTDHandler != null) {
fDTDHandler.notationDecl(not.name, id, not.augmentations);
}
}
else {
Notation localNotation = (Notation)fNotations.get(index);
if (!not.isDuplicate(localNotation)) {
reportFatalError(
"NonDuplicateNotation",
new Object[] { not.name });
}
}
}
else {
fParentXIncludeHandler.checkAndSendNotation(not);
}
}
// It would be nice if we didn't have to repeat code like this, but there's no interface that has
// setFeature() and addRecognizedFeatures() that the objects have in common.
protected void copyFeatures(
XMLComponentManager from,
ParserConfigurationSettings to) {
Enumeration features = Constants.getXercesFeatures();
copyFeatures1(features, Constants.XERCES_FEATURE_PREFIX, from, to);
features = Constants.getSAXFeatures();
copyFeatures1(features, Constants.SAX_FEATURE_PREFIX, from, to);
}
protected void copyFeatures(
XMLComponentManager from,
XMLParserConfiguration to) {
Enumeration features = Constants.getXercesFeatures();
copyFeatures1(features, Constants.XERCES_FEATURE_PREFIX, from, to);
features = Constants.getSAXFeatures();
copyFeatures1(features, Constants.SAX_FEATURE_PREFIX, from, to);
}
private void copyFeatures1(
Enumeration features,
String featurePrefix,
XMLComponentManager from,
ParserConfigurationSettings to) {
while (features.hasMoreElements()) {
String featureId = featurePrefix + (String)features.nextElement();
to.addRecognizedFeatures(new String[] { featureId });
try {
to.setFeature(featureId, from.getFeature(featureId));
}
catch (XMLConfigurationException e) {
// componentManager doesn't support this feature,
// so we won't worry about it
}
}
}
private void copyFeatures1(
Enumeration features,
String featurePrefix,
XMLComponentManager from,
XMLParserConfiguration to) {
while (features.hasMoreElements()) {
String featureId = featurePrefix + (String)features.nextElement();
boolean value = from.getFeature(featureId);
try {
to.setFeature(featureId, value);
}
catch (XMLConfigurationException e) {
// componentManager doesn't support this feature,
// so we won't worry about it
}
}
}
// This is a storage class to hold information about the notations.
// We're not using XMLNotationDecl because we don't want to lose the augmentations.
protected class Notation {
public String name;
public String systemId;
public String baseURI;
public String publicId;
public Augmentations augmentations;
// equals() returns true if two Notations have the same name.
// Useful for searching Vectors for notations with the same name
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj instanceof Notation) {
Notation other = (Notation)obj;
return name.equals(other.name);
}
return false;
}
// from 4.5.2
// Notation items with the same [name], [system identifier],
// [public identifier], and [declaration base URI] are considered
// to be duplicate
public boolean isDuplicate(Object obj) {
if (obj != null && obj instanceof Notation) {
Notation other = (Notation)obj;
return name.equals(other.name)
&& (systemId == other.systemId
|| (systemId != null && systemId.equals(other.systemId)))
&& (publicId == other.publicId
|| (publicId != null && publicId.equals(other.publicId)))
&& (baseURI == other.baseURI
|| (baseURI != null && baseURI.equals(other.baseURI)));
}
return false;
}
}
// This is a storage class to hold information about the unparsed entities.
// We're not using XMLEntityDecl because we don't want to lose the augmentations.
protected class UnparsedEntity {
public String name;
public String systemId;
public String baseURI;
public String publicId;
public String notation;
public Augmentations augmentations;
// equals() returns true if two UnparsedEntities have the same name.
// Useful for searching Vectors for entities with the same name
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj instanceof UnparsedEntity) {
UnparsedEntity other = (UnparsedEntity)obj;
return name.equals(other.name);
}
return false;
}
// from 4.5.1:
// Unparsed entity items with the same [name], [system identifier],
// [public identifier], [declaration base URI], [notation name], and
// [notation] are considered to be duplicate
public boolean isDuplicate(Object obj) {
if (obj != null && obj instanceof UnparsedEntity) {
UnparsedEntity other = (UnparsedEntity)obj;
return name.equals(other.name)
&& (systemId == other.systemId
|| (systemId != null && systemId.equals(other.systemId)))
&& (publicId == other.publicId
|| (publicId != null && publicId.equals(other.publicId)))
&& (baseURI == other.baseURI
|| (baseURI != null && baseURI.equals(other.baseURI)))
&& (notation == other.notation
|| (notation != null && notation.equals(other.notation)));
}
return false;
}
}
// The following methods are used for XML Base processing
/**
* Saves the current base URI to the top of the stack.
*/
protected void saveBaseURI() {
baseURIScope.push(fDepth);
baseURI.push(fCurrentBaseURI.getBaseSystemId());
literalSystemID.push(fCurrentBaseURI.getLiteralSystemId());
expandedSystemID.push(fCurrentBaseURI.getExpandedSystemId());
}
/**
* Discards the URIs at the top of the stack, and restores the ones beneath it.
*/
protected void restoreBaseURI() {
baseURI.pop();
literalSystemID.pop();
expandedSystemID.pop();
baseURIScope.pop();
fCurrentBaseURI.setBaseSystemId((String)baseURI.peek());
fCurrentBaseURI.setLiteralSystemId((String)literalSystemID.peek());
fCurrentBaseURI.setExpandedSystemId((String)expandedSystemID.peek());
}
/**
* Gets the base URI that was in use at that depth
* @param depth
* @return the base URI
*/
public String getBaseURI(int depth) {
int scope = scopeOf(depth);
return (String)expandedSystemID.elementAt(scope);
}
/**
* Returns a relative URI, which when resolved against the base URI at the
* specified depth, will create the current base URI.
* This is accomplished by merged the literal system IDs.
* @param depth the depth at which to start creating the relative URI
* @return a relative URI to convert the base URI at the given depth to the current
* base URI
*/
public String getRelativeURI(int depth) throws MalformedURIException {
// The literal system id at the location given by "start" is *in focus* at
// the given depth. So we need to adjust it to the next scope, so that we
// only process out of focus literal system ids
int start = scopeOf(depth) + 1;
if (start == baseURIScope.size()) {
// If that is the last system id, then we don't need a relative URI
return "";
}
URI uri = new URI("file", (String)literalSystemID.elementAt(start));
for (int i = start + 1; i < baseURIScope.size(); i++) {
uri = new URI(uri, (String)literalSystemID.elementAt(i));
}
return uri.getPath();
}
// We need to find two consecutive elements in the scope stack,
// such that the first is lower than 'depth' (or equal), and the
// second is higher.
private int scopeOf(int depth) {
for (int i = baseURIScope.size() - 1; i >= 0; i--) {
if (baseURIScope.elementAt(i) <= depth)
return i;
}
// we should never get here, because 0 was put on the stack in startDocument()
return -1;
}
/**
* Search for a xml:base attribute, and if one is found, put the new base URI into
* effect.
*/
protected void processXMLBaseAttributes(XMLAttributes attributes) {
String baseURIValue =
attributes.getValue(NamespaceContext.XML_URI, "base");
if (baseURIValue != null) {
try {
String expandedValue =
XMLEntityManager.expandSystemId(
baseURIValue,
fCurrentBaseURI.getExpandedSystemId(),
false);
fCurrentBaseURI.setLiteralSystemId(baseURIValue);
fCurrentBaseURI.setBaseSystemId(
fCurrentBaseURI.getExpandedSystemId());
fCurrentBaseURI.setExpandedSystemId(expandedValue);
// push the new values on the stack
saveBaseURI();
}
catch (MalformedURIException e) {
// REVISIT: throw error here
}
}
}
/**
Set the Accept,Accept-Language,Accept-CharSet
*/
protected void setHttpProperties(XMLInputSource source,XMLAttributes attributes){
try{
String httpAcceptLang = attributes.getValue(HTTP_ACCEPT_LANGUAGE);
String httpAccept = attributes.getValue(HTTP_ACCEPT);
String httpAcceptchar = attributes.getValue(HTTP_ACCEPT_CHARSET);
InputStream stream = source.getByteStream();
if (stream == null) {
URL location = new URL(source.getSystemId());
URLConnection connect = location.openConnection();
if (connect instanceof HttpURLConnection) {
if( httpAcceptLang !=null && !httpAcceptLang.equals(""))
connect.setRequestProperty(HTTP_ACCEPT_LANGUAGE,httpAcceptLang);
if( httpAccept !=null && !httpAccept.equals(""))
connect.setRequestProperty(HTTP_ACCEPT,httpAccept);
if( httpAcceptchar !=null && !httpAcceptchar.equals(""))
connect.setRequestProperty(HTTP_ACCEPT_CHARSET,httpAcceptchar);
}
stream = connect.getInputStream();
source.setByteStream(stream);
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
| src/org/apache/xerces/xinclude/XIncludeHandler.java | /*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 2003, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.xinclude;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Vector;
import java.net.*;
import java.io.*;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.XMLEntityManager;
import org.apache.xerces.impl.XMLErrorReporter;
import org.apache.xerces.util.AugmentationsImpl;
import org.apache.xerces.util.IntStack;
import org.apache.xerces.util.ObjectFactory;
import org.apache.xerces.util.ParserConfigurationSettings;
import org.apache.xerces.util.URI;
import org.apache.xerces.util.XMLAttributesImpl;
import org.apache.xerces.util.XMLResourceIdentifierImpl;
import org.apache.xerces.util.XMLSymbols;
import org.apache.xerces.util.URI.MalformedURIException;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLDTDHandler;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLResourceIdentifier;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLComponent;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLDTDFilter;
import org.apache.xerces.xni.parser.XMLDTDSource;
import org.apache.xerces.xni.parser.XMLDocumentFilter;
import org.apache.xerces.xni.parser.XMLDocumentSource;
import org.apache.xerces.xni.parser.XMLEntityResolver;
import org.apache.xerces.xni.parser.XMLInputSource;
import org.apache.xerces.xni.parser.XMLParserConfiguration;
/**
* <p>
* This is a pipeline component which performs XInclude handling, according to the
* W3C specification for XML Inclusions.
* </p>
* <p>
* This component analyzes each event in the pipeline, looking for <include>
* elements. An <include> element is one which has a namespace of
* <code>http://www.w3.org/2003/XInclude</code> and a localname of <code>include</code>.
* When it finds an <include> element, it attempts to include the file specified
* in the <code>href</code> attribute of the element. If inclusion succeeds, all
* children of the <include> element are ignored (with the exception of
* checking for invalid children as outlined in the specification). If the inclusion
* fails, the <fallback> child of the <include> element is processed.
* </p>
* <p>
* See the <a href="http://www.w3.org/TR/xinclude/">XInclude specification</a> for
* more information on how XInclude is to be used.
* </p>
* <p>
* This component requires the following features and properties from the
* component manager that uses it:
* <ul>
* <li>http://xml.org/sax/features/allow-dtd-events-after-endDTD</li>
* <li>http://apache.org/xml/properties/internal/error-reporter</li>
* <li>http://apache.org/xml/properties/internal/entity-resolver</li>
* </ul>
* Furthermore, the <code>NamespaceContext</code> used in the pipeline is required
* to be an instance of <code>XIncludeNamespaceSupport</code>.
* </p>
* <p>
* Currently, this implementation has only partial support for the XInclude specification.
* Specifically, it is missing support for XPointer document fragments. Thus, only whole
* documents can be included using this component in the pipeline.
* </p>
* @author Peter McCracken, IBM
* @see XIncludeNamespaceSupport
*/
public class XIncludeHandler
implements XMLComponent, XMLDocumentFilter, XMLDTDFilter {
public final static String XINCLUDE_DEFAULT_CONFIGURATION =
"org.apache.xerces.parsers.XIncludeParserConfiguration";
public final static String HTTP_ACCEPT = "Accept";
public final static String HTTP_ACCEPT_LANGUAGE = "Accept-Language";
public final static String HTTP_ACCEPT_CHARSET = "Accept-Charset";
public final static String XINCLUDE_NS_URI =
"http://www.w3.org/2003/XInclude".intern();
public final static String XINCLUDE_NS_URI_OLD =
"http://www.w3.org/2001/XInclude".intern();
public final static String XINCLUDE_INCLUDE = "include".intern();
public final static String XINCLUDE_FALLBACK = "fallback".intern();
public final static String XINCLUDE_PARSE_XML = "xml".intern();
public final static String XINCLUDE_PARSE_TEXT = "text".intern();
public final static String XINCLUDE_ATTR_HREF = "href".intern();
public final static String XINCLUDE_ATTR_PARSE = "parse".intern();
public final static String XINCLUDE_ATTR_ENCODING = "encoding".intern();
// Top Level Information Items have [included] property in infoset
public final static String XINCLUDE_INCLUDED = "[included]".intern();
/** The identifier for the Augmentation that contains the current base URI */
public final static String CURRENT_BASE_URI = "currentBaseURI";
// used for adding [base URI] attributes
public final static String XINCLUDE_BASE = "base";
public final static QName XML_BASE_QNAME =
new QName(
XMLSymbols.PREFIX_XML,
XINCLUDE_BASE,
XMLSymbols.PREFIX_XML + ":" + XINCLUDE_BASE,
NamespaceContext.XML_URI);
public final static QName NEW_NS_ATTR_QNAME =
new QName(
XMLSymbols.PREFIX_XMLNS,
"",
XMLSymbols.PREFIX_XMLNS + ":",
NamespaceContext.XMLNS_URI);
// Processing States
private final static int STATE_NORMAL_PROCESSING = 1;
// we go into this state after a successful include (thus we ignore the children
// of the include) or after a fallback
private final static int STATE_IGNORE = 2;
// we go into this state after a failed include. If we don't encounter a fallback
// before we reach the end include tag, it's a fatal error
private final static int STATE_EXPECT_FALLBACK = 3;
// recognized features and properties
/** Feature identifier: allow notation and unparsed entity events to be sent out of order. */
protected static final String ALLOW_UE_AND_NOTATION_EVENTS =
Constants.SAX_FEATURE_PREFIX
+ Constants.ALLOW_DTD_EVENTS_AFTER_ENDDTD_FEATURE;
/** Property identifier: error reporter. */
protected static final String ERROR_REPORTER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY;
/** Property identifier: grammar pool . */
protected static final String ENTITY_RESOLVER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY;
/** Recognized features. */
private static final String[] RECOGNIZED_FEATURES =
{ ALLOW_UE_AND_NOTATION_EVENTS };
/** Feature defaults. */
private static final Boolean[] FEATURE_DEFAULTS = { Boolean.TRUE };
/** Recognized properties. */
private static final String[] RECOGNIZED_PROPERTIES =
{ ERROR_REPORTER, ENTITY_RESOLVER };
/** Property defaults. */
private static final Object[] PROPERTY_DEFAULTS = { null, null };
// instance variables
// for XMLDocumentFilter
protected XMLDocumentHandler fDocumentHandler;
protected XMLDocumentSource fDocumentSource;
// for XMLDTDFilter
protected XMLDTDHandler fDTDHandler;
protected XMLDTDSource fDTDSource;
// for XIncludeHandler
protected XIncludeHandler fParentXIncludeHandler;
// It's "feels wrong" to store this value here. However,
// calculating it can be time consuming, so we cache it.
// It's never going to change in the lifetime of this XIncludeHandler
protected String fParentRelativeURI;
// we cache the child parser configuration, so we don't have to re-create
// the objects when the parser is re-used
protected XMLParserConfiguration fChildConfig;
protected XMLLocator fDocLocation;
protected XIncludeNamespaceSupport fNamespaceContext;
protected XMLErrorReporter fErrorReporter;
protected XMLEntityResolver fEntityResolver;
// these are needed for XML Base processing
protected XMLResourceIdentifier fCurrentBaseURI;
protected IntStack baseURIScope;
protected Stack baseURI;
protected Stack literalSystemID;
protected Stack expandedSystemID;
// used for passing features on to child XIncludeHandler objects
protected ParserConfigurationSettings fSettings;
// The current element depth. We start at depth 0 (before we've reached any elements)
// The first element is at depth 1.
private int fDepth;
// this value must be at least 1
private static final int INITIAL_SIZE = 8;
// Used to ensure that fallbacks are always children of include elements,
// and that include elements are never children of other include elements.
// An index contains true if the ancestor of the current element which resides
// at that depth was an include element.
private boolean[] fSawInclude = new boolean[INITIAL_SIZE];
// Ensures that only one fallback element can be at a single depth.
// An index contains true if we have seen any fallback elements at that depth,
// and it is only reset to false when the end tag of the parent is encountered.
private boolean[] fSawFallback = new boolean[INITIAL_SIZE];
// The state of the processor at each given depth.
private int[] fState = new int[INITIAL_SIZE];
// buffering the necessary DTD events
private Vector fNotations;
private Vector fUnparsedEntities;
// for SAX compatibility.
// Has the value of the ALLOW_UE_AND_NOTATION_EVENTS feature
private boolean fSendUEAndNotationEvents;
// track the version of the document being parsed
private boolean fIsXML11;
// track whether a warning has already been reported for
// use of the old http://www.w3.org/2001/XInclude namespace.
private boolean fOldNamespaceWarningIssued;
// Constructors
public XIncludeHandler() {
fDepth = 0;
fSawFallback[fDepth] = false;
fSawInclude[fDepth] = false;
fState[fDepth] = STATE_NORMAL_PROCESSING;
fNotations = new Vector();
fUnparsedEntities = new Vector();
baseURIScope = new IntStack();
baseURI = new Stack();
literalSystemID = new Stack();
expandedSystemID = new Stack();
fCurrentBaseURI = new XMLResourceIdentifierImpl();
}
// XMLComponent methods
public void reset(XMLComponentManager componentManager)
throws XNIException {
fNamespaceContext = null;
fDepth = 0;
fNotations = new Vector();
fUnparsedEntities = new Vector();
fParentRelativeURI = null;
fIsXML11 = false;
fOldNamespaceWarningIssued = false;
baseURIScope.clear();
baseURI.clear();
literalSystemID.clear();
expandedSystemID.clear();
// clear the previous settings from the arrays
for (int i = 0; i < fState.length; i++) {
// these three arrays will always be the same length, so this is safe
fSawFallback[i] = false;
fSawInclude[i] = false;
fState[i] = STATE_NORMAL_PROCESSING;
}
try {
fSendUEAndNotationEvents =
componentManager.getFeature(ALLOW_UE_AND_NOTATION_EVENTS);
if (fChildConfig != null) {
fChildConfig.setFeature(
ALLOW_UE_AND_NOTATION_EVENTS,
fSendUEAndNotationEvents);
}
}
catch (XMLConfigurationException e) {
}
try {
XMLErrorReporter value =
(XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER);
if (value != null) {
setErrorReporter(value);
if (fChildConfig != null) {
fChildConfig.setProperty(ERROR_REPORTER, value);
}
}
}
catch (XMLConfigurationException e) {
fErrorReporter = null;
}
try {
XMLEntityResolver value =
(XMLEntityResolver)componentManager.getProperty(
ENTITY_RESOLVER);
if (value != null) {
fEntityResolver = value;
if (fChildConfig != null) {
fChildConfig.setProperty(ENTITY_RESOLVER, value);
}
}
}
catch (XMLConfigurationException e) {
fEntityResolver = null;
}
fSettings = new ParserConfigurationSettings();
copyFeatures(componentManager, fSettings);
// Don't reset fChildConfig -- we don't want it to share the same components.
// It will be reset when it is actually used to parse something.
} // reset(XMLComponentManager)
/**
* Returns a list of feature identifiers that are recognized by
* this component. This method may return null if no features
* are recognized by this component.
*/
public String[] getRecognizedFeatures() {
return RECOGNIZED_FEATURES;
} // getRecognizedFeatures():String[]
/**
* Sets the state of a feature. This method is called by the component
* manager any time after reset when a feature changes state.
* <p>
* <strong>Note:</strong> Components should silently ignore features
* that do not affect the operation of the component.
*
* @param featureId The feature identifier.
* @param state The state of the feature.
*
* @throws SAXNotRecognizedException The component should not throw
* this exception.
* @throws SAXNotSupportedException The component should not throw
* this exception.
*/
public void setFeature(String featureId, boolean state)
throws XMLConfigurationException {
if (featureId.equals(ALLOW_UE_AND_NOTATION_EVENTS)) {
fSendUEAndNotationEvents = state;
}
if (fSettings != null) {
fSettings.setFeature(featureId, state);
}
} // setFeature(String,boolean)
/**
* Returns a list of property identifiers that are recognized by
* this component. This method may return null if no properties
* are recognized by this component.
*/
public String[] getRecognizedProperties() {
return RECOGNIZED_PROPERTIES;
} // getRecognizedProperties():String[]
/**
* Sets the value of a property. This method is called by the component
* manager any time after reset when a property changes value.
* <p>
* <strong>Note:</strong> Components should silently ignore properties
* that do not affect the operation of the component.
*
* @param propertyId The property identifier.
* @param value The value of the property.
*
* @throws SAXNotRecognizedException The component should not throw
* this exception.
* @throws SAXNotSupportedException The component should not throw
* this exception.
*/
public void setProperty(String propertyId, Object value)
throws XMLConfigurationException {
if (propertyId.equals(ERROR_REPORTER)) {
setErrorReporter((XMLErrorReporter)value);
if (fChildConfig != null) {
fChildConfig.setProperty(propertyId, value);
}
}
if (propertyId.equals(ENTITY_RESOLVER)) {
fEntityResolver = (XMLEntityResolver)value;
if (fChildConfig != null) {
fChildConfig.setProperty(propertyId, value);
}
}
} // setProperty(String,Object)
/**
* Returns the default state for a feature, or null if this
* component does not want to report a default value for this
* feature.
*
* @param featureId The feature identifier.
*
* @since Xerces 2.2.0
*/
public Boolean getFeatureDefault(String featureId) {
for (int i = 0; i < RECOGNIZED_FEATURES.length; i++) {
if (RECOGNIZED_FEATURES[i].equals(featureId)) {
return FEATURE_DEFAULTS[i];
}
}
return null;
} // getFeatureDefault(String):Boolean
/**
* Returns the default state for a property, or null if this
* component does not want to report a default value for this
* property.
*
* @param propertyId The property identifier.
*
* @since Xerces 2.2.0
*/
public Object getPropertyDefault(String propertyId) {
for (int i = 0; i < RECOGNIZED_PROPERTIES.length; i++) {
if (RECOGNIZED_PROPERTIES[i].equals(propertyId)) {
return PROPERTY_DEFAULTS[i];
}
}
return null;
} // getPropertyDefault(String):Object
public void setDocumentHandler(XMLDocumentHandler handler) {
fDocumentHandler = handler;
}
public XMLDocumentHandler getDocumentHandler() {
return fDocumentHandler;
}
// XMLDocumentHandler methods
/**
* Event sent at the start of the document.
*
* A fatal error will occur here, if it is detected that this document has been processed
* before.
*
* This event is only passed on to the document handler if this is the root document.
*/
public void startDocument(
XMLLocator locator,
String encoding,
NamespaceContext namespaceContext,
Augmentations augs)
throws XNIException {
// we do this to ensure that the proper location is reported in errors
// otherwise, the locator from the root document would always be used
fErrorReporter.setDocumentLocator(locator);
if (!isRootDocument()
&& fParentXIncludeHandler.searchForRecursiveIncludes(locator)) {
reportFatalError(
"RecursiveInclude",
new Object[] { locator.getExpandedSystemId()});
}
if (!(namespaceContext instanceof XIncludeNamespaceSupport)) {
reportFatalError("IncompatibleNamespaceContext");
}
fNamespaceContext = (XIncludeNamespaceSupport)namespaceContext;
fDocLocation = locator;
// initialize the current base URI
fCurrentBaseURI.setBaseSystemId(locator.getBaseSystemId());
fCurrentBaseURI.setExpandedSystemId(locator.getExpandedSystemId());
fCurrentBaseURI.setLiteralSystemId(locator.getLiteralSystemId());
saveBaseURI();
if (augs == null) {
augs = new AugmentationsImpl();
}
augs.putItem(CURRENT_BASE_URI, fCurrentBaseURI);
if (isRootDocument() && fDocumentHandler != null) {
fDocumentHandler.startDocument(
locator,
encoding,
namespaceContext,
augs);
}
}
public void xmlDecl(
String version,
String encoding,
String standalone,
Augmentations augs)
throws XNIException {
fIsXML11 = "1.1".equals(version);
if (isRootDocument() && fDocumentHandler != null) {
fDocumentHandler.xmlDecl(version, encoding, standalone, augs);
}
}
public void doctypeDecl(
String rootElement,
String publicId,
String systemId,
Augmentations augs)
throws XNIException {
if (isRootDocument() && fDocumentHandler != null) {
fDocumentHandler.doctypeDecl(rootElement, publicId, systemId, augs);
}
}
public void comment(XMLString text, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
fDepth++;
augs = modifyAugmentations(augs);
fDocumentHandler.comment(text, augs);
fDepth--;
}
}
public void processingInstruction(
String target,
XMLString data,
Augmentations augs)
throws XNIException {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
// we need to change the depth like this so that modifyAugmentations() works
fDepth++;
augs = modifyAugmentations(augs);
fDocumentHandler.processingInstruction(target, data, augs);
fDepth--;
}
}
public void startElement(
QName element,
XMLAttributes attributes,
Augmentations augs)
throws XNIException {
fDepth++;
setState(getState(fDepth - 1));
// we process the xml:base attributes regardless of what type of element it is
processXMLBaseAttributes(attributes);
if (isIncludeElement(element)) {
boolean success = this.handleIncludeElement(attributes);
if (success) {
setState(STATE_IGNORE);
}
else {
setState(STATE_EXPECT_FALLBACK);
}
}
else if (isFallbackElement(element)) {
this.handleFallbackElement();
}
else if (
fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
augs = modifyAugmentations(augs);
attributes = processAttributes(attributes);
fDocumentHandler.startElement(element, attributes, augs);
}
}
public void emptyElement(
QName element,
XMLAttributes attributes,
Augmentations augs)
throws XNIException {
fDepth++;
setState(getState(fDepth - 1));
// we process the xml:base attributes regardless of what type of element it is
processXMLBaseAttributes(attributes);
if (isIncludeElement(element)) {
boolean success = this.handleIncludeElement(attributes);
if (success) {
setState(STATE_IGNORE);
}
else {
reportFatalError("NoFallback");
}
}
else if (isFallbackElement(element)) {
this.handleFallbackElement();
}
else if (hasXIncludeNamespace(element)) {
if (getSawInclude(fDepth - 1)) {
reportFatalError(
"IncludeChild",
new Object[] { element.rawname });
}
}
else if (
fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
augs = modifyAugmentations(augs);
attributes = processAttributes(attributes);
fDocumentHandler.emptyElement(element, attributes, augs);
}
// reset the out of scope stack elements
setSawFallback(fDepth + 1, false);
setSawInclude(fDepth + 1, false);
// check if an xml:base has gone out of scope
if (baseURIScope.size() > 0 && fDepth == baseURIScope.peek()) {
// pop the values from the stack
restoreBaseURI();
}
fDepth--;
}
public void endElement(QName element, Augmentations augs)
throws XNIException {
if (isIncludeElement(element)) {
// if we're ending an include element, and we were expecting a fallback
// we check to see if the children of this include element contained a fallback
if (getState() == STATE_EXPECT_FALLBACK
&& !getSawFallback(fDepth + 1)) {
reportFatalError("NoFallback");
}
}
if (isFallbackElement(element)) {
// the state would have been set to normal processing if we were expecting the fallback element
// now that we're done processing it, we should ignore all the other children of the include element
if (getState() == STATE_NORMAL_PROCESSING) {
setState(STATE_IGNORE);
}
}
else if (
fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
fDocumentHandler.endElement(element, augs);
}
// reset the out of scope stack elements
setSawFallback(fDepth + 1, false);
setSawInclude(fDepth + 1, false);
// check if an xml:base has gone out of scope
if (baseURIScope.size() > 0 && fDepth == baseURIScope.peek()) {
// pop the values from the stack
restoreBaseURI();
}
fDepth--;
}
public void startGeneralEntity(
String name,
XMLResourceIdentifier resId,
String encoding,
Augmentations augs)
throws XNIException {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
fDocumentHandler.startGeneralEntity(name, resId, encoding, augs);
}
}
public void textDecl(String version, String encoding, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
fDocumentHandler.textDecl(version, encoding, augs);
}
}
public void endGeneralEntity(String name, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
fDocumentHandler.endGeneralEntity(name, augs);
}
}
public void characters(XMLString text, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
// we need to change the depth like this so that modifyAugmentations() works
fDepth++;
augs = modifyAugmentations(augs);
fDocumentHandler.characters(text, augs);
fDepth--;
}
}
public void ignorableWhitespace(XMLString text, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
fDocumentHandler.ignorableWhitespace(text, augs);
}
}
public void startCDATA(Augmentations augs) throws XNIException {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
fDocumentHandler.startCDATA(augs);
}
}
public void endCDATA(Augmentations augs) throws XNIException {
if (fDocumentHandler != null
&& getState() == STATE_NORMAL_PROCESSING) {
fDocumentHandler.endCDATA(augs);
}
}
public void endDocument(Augmentations augs) throws XNIException {
if (isRootDocument() && fDocumentHandler != null) {
fDocumentHandler.endDocument(augs);
}
}
public void setDocumentSource(XMLDocumentSource source) {
fDocumentSource = source;
}
public XMLDocumentSource getDocumentSource() {
return fDocumentSource;
}
// DTDHandler methods
// We are only interested in the notation and unparsed entity declarations,
// the rest we just pass on
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#attributeDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String[], java.lang.String, org.apache.xerces.xni.XMLString, org.apache.xerces.xni.XMLString, org.apache.xerces.xni.Augmentations)
*/
public void attributeDecl(
String elementName,
String attributeName,
String type,
String[] enumeration,
String defaultType,
XMLString defaultValue,
XMLString nonNormalizedDefaultValue,
Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.attributeDecl(
elementName,
attributeName,
type,
enumeration,
defaultType,
defaultValue,
nonNormalizedDefaultValue,
augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#elementDecl(java.lang.String, java.lang.String, org.apache.xerces.xni.Augmentations)
*/
public void elementDecl(
String name,
String contentModel,
Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.elementDecl(name, contentModel, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#endAttlist(org.apache.xerces.xni.Augmentations)
*/
public void endAttlist(Augmentations augmentations) throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.endAttlist(augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#endConditional(org.apache.xerces.xni.Augmentations)
*/
public void endConditional(Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.endConditional(augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#endDTD(org.apache.xerces.xni.Augmentations)
*/
public void endDTD(Augmentations augmentations) throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.endDTD(augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#endExternalSubset(org.apache.xerces.xni.Augmentations)
*/
public void endExternalSubset(Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.endExternalSubset(augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#endParameterEntity(java.lang.String, org.apache.xerces.xni.Augmentations)
*/
public void endParameterEntity(String name, Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.endParameterEntity(name, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#externalEntityDecl(java.lang.String, org.apache.xerces.xni.XMLResourceIdentifier, org.apache.xerces.xni.Augmentations)
*/
public void externalEntityDecl(
String name,
XMLResourceIdentifier identifier,
Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.externalEntityDecl(name, identifier, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#getDTDSource()
*/
public XMLDTDSource getDTDSource() {
return fDTDSource;
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#ignoredCharacters(org.apache.xerces.xni.XMLString, org.apache.xerces.xni.Augmentations)
*/
public void ignoredCharacters(XMLString text, Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.ignoredCharacters(text, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#internalEntityDecl(java.lang.String, org.apache.xerces.xni.XMLString, org.apache.xerces.xni.XMLString, org.apache.xerces.xni.Augmentations)
*/
public void internalEntityDecl(
String name,
XMLString text,
XMLString nonNormalizedText,
Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.internalEntityDecl(
name,
text,
nonNormalizedText,
augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#notationDecl(java.lang.String, org.apache.xerces.xni.XMLResourceIdentifier, org.apache.xerces.xni.Augmentations)
*/
public void notationDecl(
String name,
XMLResourceIdentifier identifier,
Augmentations augmentations)
throws XNIException {
this.addNotation(name, identifier, augmentations);
if (fDTDHandler != null) {
fDTDHandler.notationDecl(name, identifier, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#setDTDSource(org.apache.xerces.xni.parser.XMLDTDSource)
*/
public void setDTDSource(XMLDTDSource source) {
fDTDSource = source;
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#startAttlist(java.lang.String, org.apache.xerces.xni.Augmentations)
*/
public void startAttlist(String elementName, Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.startAttlist(elementName, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#startConditional(short, org.apache.xerces.xni.Augmentations)
*/
public void startConditional(short type, Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.startConditional(type, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#startDTD(org.apache.xerces.xni.XMLLocator, org.apache.xerces.xni.Augmentations)
*/
public void startDTD(XMLLocator locator, Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.startDTD(locator, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#startExternalSubset(org.apache.xerces.xni.XMLResourceIdentifier, org.apache.xerces.xni.Augmentations)
*/
public void startExternalSubset(
XMLResourceIdentifier identifier,
Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.startExternalSubset(identifier, augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#startParameterEntity(java.lang.String, org.apache.xerces.xni.XMLResourceIdentifier, java.lang.String, org.apache.xerces.xni.Augmentations)
*/
public void startParameterEntity(
String name,
XMLResourceIdentifier identifier,
String encoding,
Augmentations augmentations)
throws XNIException {
if (fDTDHandler != null) {
fDTDHandler.startParameterEntity(
name,
identifier,
encoding,
augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.XMLDTDHandler#unparsedEntityDecl(java.lang.String, org.apache.xerces.xni.XMLResourceIdentifier, java.lang.String, org.apache.xerces.xni.Augmentations)
*/
public void unparsedEntityDecl(
String name,
XMLResourceIdentifier identifier,
String notation,
Augmentations augmentations)
throws XNIException {
this.addUnparsedEntity(name, identifier, notation, augmentations);
if (fDTDHandler != null) {
fDTDHandler.unparsedEntityDecl(
name,
identifier,
notation,
augmentations);
}
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.parser.XMLDTDSource#getDTDHandler()
*/
public XMLDTDHandler getDTDHandler() {
return fDTDHandler;
}
/* (non-Javadoc)
* @see org.apache.xerces.xni.parser.XMLDTDSource#setDTDHandler(org.apache.xerces.xni.XMLDTDHandler)
*/
public void setDTDHandler(XMLDTDHandler handler) {
fDTDHandler = handler;
}
// XIncludeHandler methods
private void setErrorReporter(XMLErrorReporter reporter) {
fErrorReporter = reporter;
if (fErrorReporter != null) {
fErrorReporter.putMessageFormatter(
XIncludeMessageFormatter.XINCLUDE_DOMAIN,
new XIncludeMessageFormatter());
// this ensures the proper location is displayed in error messages
if (fDocLocation != null) {
fErrorReporter.setDocumentLocator(fDocLocation);
}
}
}
protected void handleFallbackElement() {
setSawInclude(fDepth, false);
fNamespaceContext.setContextInvalid();
if (!getSawInclude(fDepth - 1)) {
reportFatalError("FallbackParent");
}
if (getSawFallback(fDepth)) {
reportFatalError("MultipleFallbacks");
}
else {
setSawFallback(fDepth, true);
}
// Either the state is STATE_EXPECT_FALLBACK or it's STATE_IGNORE.
// If we're ignoring, we want to stay ignoring. But if we're expecting this fallback element,
// we want to signal that we should process the children.
if (getState() == STATE_EXPECT_FALLBACK) {
setState(STATE_NORMAL_PROCESSING);
}
}
protected boolean handleIncludeElement(XMLAttributes attributes)
throws XNIException {
setSawInclude(fDepth, true);
fNamespaceContext.setContextInvalid();
if (getSawInclude(fDepth - 1)) {
reportFatalError("IncludeChild", new Object[] { XINCLUDE_INCLUDE });
}
if (getState() == STATE_IGNORE)
return true;
// TODO: does Java use IURIs by default?
// [Definition: An internationalized URI reference, or IURI, is a URI reference that directly uses [Unicode] characters.]
// TODO: figure out what section 4.1.1 of the XInclude spec is talking about
// has to do with disallowed ASCII character escaping
// this ties in with the above IURI section, but I suspect Java already does it
String href = attributes.getValue(XINCLUDE_ATTR_HREF);
String parse = attributes.getValue(XINCLUDE_ATTR_PARSE);
if (href == null) {
reportFatalError("HrefMissing");
}
if (parse == null) {
parse = XINCLUDE_PARSE_XML;
}
XMLInputSource includedSource = null;
if (fEntityResolver != null) {
try {
XMLResourceIdentifier resourceIdentifier =
new XMLResourceIdentifierImpl(
null,
href,
fCurrentBaseURI.getExpandedSystemId(),
XMLEntityManager.expandSystemId(
href,
fCurrentBaseURI.getExpandedSystemId(),
false));
includedSource =
fEntityResolver.resolveEntity(resourceIdentifier);
}
catch (IOException e) {
reportResourceError(
"XMLResourceError",
new Object[] { href, e.getMessage()});
return false;
}
}
if (includedSource == null) {
includedSource =
new XMLInputSource(
null,
href,
fCurrentBaseURI.getExpandedSystemId());
}
if (parse.equals(XINCLUDE_PARSE_XML)) {
// Instead of always creating a new configuration, the first one can be reused
if (fChildConfig == null) {
String parserName = XINCLUDE_DEFAULT_CONFIGURATION;
fChildConfig =
(XMLParserConfiguration)ObjectFactory.newInstance(
parserName,
ObjectFactory.findClassLoader(),
true);
// use the same error reporter
fChildConfig.setProperty(ERROR_REPORTER, fErrorReporter);
// use the same namespace context
fChildConfig.setProperty(
Constants.XERCES_PROPERTY_PREFIX
+ Constants.NAMESPACE_CONTEXT_PROPERTY,
fNamespaceContext);
XIncludeHandler newHandler =
(XIncludeHandler)fChildConfig.getProperty(
Constants.XERCES_PROPERTY_PREFIX
+ Constants.XINCLUDE_HANDLER_PROPERTY);
newHandler.setParent(this);
newHandler.setDocumentHandler(this.getDocumentHandler());
}
//disabled for now.
//setHttpProperties(includedSource,attributes);
// set all features on parserConfig to match this parser configuration
copyFeatures(fSettings, fChildConfig);
// we don't want a schema validator on the new pipeline,
// so we set it to false, regardless of what was copied above
fChildConfig.setFeature(
Constants.XERCES_FEATURE_PREFIX
+ Constants.SCHEMA_VALIDATION_FEATURE,
false);
try {
fNamespaceContext.pushScope();
fChildConfig.parse(includedSource);
// necessary to make sure proper location is reported in errors
if (fErrorReporter != null) {
fErrorReporter.setDocumentLocator(fDocLocation);
}
}
catch (XNIException e) {
// necessary to make sure proper location is reported in errors
if (fErrorReporter != null) {
fErrorReporter.setDocumentLocator(fDocLocation);
}
reportFatalError("XMLParseError", new Object[] { href });
}
catch (IOException e) {
// necessary to make sure proper location is reported in errors
if (fErrorReporter != null) {
fErrorReporter.setDocumentLocator(fDocLocation);
}
// An IOException indicates that we had trouble reading the file, not
// that it was an invalid XML file. So we send a resource error, not a
// fatal error.
reportResourceError(
"XMLResourceError",
new Object[] { href, e.getMessage()});
return false;
}
finally {
fNamespaceContext.popScope();
}
}
else if (parse.equals(XINCLUDE_PARSE_TEXT)) {
// we only care about encoding for parse="text"
String encoding = attributes.getValue(XINCLUDE_ATTR_ENCODING);
includedSource.setEncoding(encoding);
XIncludeTextReader reader = null;
//disabled for now.
//setHttpProperties(includedSource,attributes);
try {
if (fIsXML11) {
reader = new XInclude11TextReader(includedSource, this);
}
else {
reader = new XIncludeTextReader(includedSource, this);
}
reader.setErrorReporter(fErrorReporter);
reader.parse();
}
catch (IOException e) {
reportResourceError(
"TextResourceError",
new Object[] { href, e.getMessage()});
return false;
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException e) {
reportResourceError(
"TextResourceError",
new Object[] { href, e.getMessage()});
return false;
}
}
}
}
else {
reportFatalError("InvalidParseValue", new Object[] { parse });
}
return true;
}
/**
* Returns true if the element has the namespace "http://www.w3.org/2003/XInclude"
* @param element the element to check
* @return true if the element has the namespace "http://www.w3.org/2003/XInclude"
*/
protected boolean hasXIncludeNamespace(QName element) {
// REVISIT: The namespace of this element should be bound
// already. Why are we looking it up from the namespace
// context? -- mrglavas
return element.uri == XINCLUDE_NS_URI
|| fNamespaceContext.getURI(element.prefix) == XINCLUDE_NS_URI;
}
/**
* Returns true if the element has the namespace "http://www.w3.org/2001/XInclude"
* @param element the element to check
* @return true if the element has the namespace "http://www.w3.org/2001/XInclude"
*/
protected boolean hasXInclude2001Namespace(QName element) {
// REVISIT: The namespace of this element should be bound
// already. Why are we looking it up from the namespace
// context? -- mrglavas
return element.uri == XINCLUDE_NS_URI_OLD
|| fNamespaceContext.getURI(element.prefix) == XINCLUDE_NS_URI_OLD;
}
/**
* Checks if the element is an <include> element. The element must have
* the XInclude namespace, and a local name of "include". If the local name
* is "include" and the namespace name is the old XInclude namespace
* "http://www.w3.org/2001/XInclude" a warning is issued the first time
* an element from the old namespace is encountered.
*
* @param element the element to check
* @return true if the element is an <include> element
* @see #hasXIncludeNamespace(QName)
*/
protected boolean isIncludeElement(QName element) {
if (element.localpart.equals(XINCLUDE_INCLUDE)) {
if (hasXIncludeNamespace(element)) {
return true;
}
else if (!fOldNamespaceWarningIssued && hasXInclude2001Namespace(element)) {
reportError("OldXIncludeNamespace", null, XMLErrorReporter.SEVERITY_WARNING);
fOldNamespaceWarningIssued = true;
}
}
return false;
}
/**
* Checks if the element is an <fallback> element. The element must have
* the XInclude namespace, and a local name of "fallback". If the local name
* is "fallback" and the namespace name is the old XInclude namespace
* "http://www.w3.org/2001/XInclude" a warning is issued the first time
* an element from the old namespace is encountered.
*
* @param element the element to check
* @return true if the element is an <fallback; element
* @see #hasXIncludeNamespace(QName)
*/
protected boolean isFallbackElement(QName element) {
if (element.localpart.equals(XINCLUDE_FALLBACK)) {
if (hasXIncludeNamespace(element)) {
return true;
}
else if (!fOldNamespaceWarningIssued && hasXInclude2001Namespace(element)) {
reportError("OldXIncludeNamespace", null, XMLErrorReporter.SEVERITY_WARNING);
fOldNamespaceWarningIssued = true;
}
}
return false;
}
/**
* Returns true if the current [base URI] is the same as the [base URI] that
* was in effect on the include parent. This method should <em>only</em> be called
* when the current element is a top level included element, i.e. the direct child
* of a fallback element, or the root elements in an included document.
* The "include parent" is the element which, in the result infoset, will be the
* direct parent of the current element.
* @return true if the [base URIs] are the same string
*/
protected boolean sameBaseURIAsIncludeParent() {
String parentBaseURI = getIncludeParentBaseURI();
String baseURI = fCurrentBaseURI.getExpandedSystemId();
// REVISIT: should we use File#sameFile() ?
// I think the benefit of using it is that it resolves host names
// instead of just doing a string comparison.
// TODO: [base URI] is still an open issue with the working group.
// They're deciding if xml:base should be added if the [base URI] is different in terms
// of resolving relative references, or if it should be added if they are different at all.
// Revisit this after a final decision has been made.
// The decision also affects whether we output the file name of the URI, or just the path.
return parentBaseURI.equals(baseURI);
}
/**
* Checks if the file indicated by the given XMLLocator has already been included
* in the current stack.
* @param includedSource the source to check for inclusion
* @return true if the source has already been included
*/
protected boolean searchForRecursiveIncludes(XMLLocator includedSource) {
String includedSystemId = includedSource.getExpandedSystemId();
if (includedSystemId == null) {
try {
includedSystemId =
XMLEntityManager.expandSystemId(
includedSource.getLiteralSystemId(),
includedSource.getBaseSystemId(),
false);
}
catch (MalformedURIException e) {
reportFatalError("ExpandedSystemId");
}
}
if (includedSystemId.equals(fCurrentBaseURI.getExpandedSystemId())) {
return true;
}
if (fParentXIncludeHandler == null) {
return false;
}
return fParentXIncludeHandler.searchForRecursiveIncludes(
includedSource);
}
/**
* Returns true if the current element is a top level included item. This means
* it's either the child of a fallback element, or the top level item in an
* included document
* @return true if the current element is a top level included item
*/
protected boolean isTopLevelIncludedItem() {
return isTopLevelIncludedItemViaInclude()
|| isTopLevelIncludedItemViaFallback();
}
protected boolean isTopLevelIncludedItemViaInclude() {
return fDepth == 1 && !isRootDocument();
}
protected boolean isTopLevelIncludedItemViaFallback() {
// Technically, this doesn't check if the parent was a fallback, it also
// would return true if any of the parent's sibling elements were fallbacks.
// However, this doesn't matter, since we will always be ignoring elements
// whose parent's siblings were fallbacks.
return getSawFallback(fDepth - 1);
}
/**
* Processes the XMLAttributes object of startElement() calls. Performs the following tasks:
* <ul>
* <li> If the element is a top level included item whose [base URI] is different from the
* [base URI] of the include parent, then an xml:base attribute is added to specify the
* true [base URI]
* <li> For all namespace prefixes which are in-scope in an included item, but not in scope
* in the include parent, a xmlns:prefix attribute is added
* <li> For all attributes with a type of ENTITY, ENTITIES or NOTATIONS, the notations and
* unparsed entities are processed as described in the spec, sections 4.5.1 and 4.5.2
* </ul>
* @param attributes
* @return
*/
protected XMLAttributes processAttributes(XMLAttributes attributes) {
if (isTopLevelIncludedItem()) {
// Modify attributes to fix the base URI (spec 4.5.5).
// We only do it to top level included elements, which have a different
// base URI than their include parent.
if (!sameBaseURIAsIncludeParent()) {
if (attributes == null) {
attributes = new XMLAttributesImpl();
}
// This causes errors with schema validation, if the schema doesn't
// specify that these elements can have an xml:base attribute
// TODO: add a user option to turn this off?
String uri = null;
try {
uri = this.getRelativeBaseURI();
}
catch (MalformedURIException e) {
// this shouldn't ever happen, since by definition, we had to traverse
// the same URIs to even get to this place
uri = fCurrentBaseURI.getExpandedSystemId();
}
int index =
attributes.addAttribute(
XML_BASE_QNAME,
XMLSymbols.fCDATASymbol,
uri);
attributes.setSpecified(index, true);
}
// Modify attributes of included items to do namespace-fixup. (spec 4.5.4)
Enumeration inscopeNS = fNamespaceContext.getAllPrefixes();
while (inscopeNS.hasMoreElements()) {
String prefix = (String)inscopeNS.nextElement();
String parentURI =
fNamespaceContext.getURIFromIncludeParent(prefix);
String uri = fNamespaceContext.getURI(prefix);
if (parentURI != uri && attributes != null) {
if (prefix == XMLSymbols.EMPTY_STRING) {
if (attributes
.getValue(
NamespaceContext.XMLNS_URI,
XMLSymbols.PREFIX_XMLNS)
== null) {
if (attributes == null) {
attributes = new XMLAttributesImpl();
}
QName ns = (QName)NEW_NS_ATTR_QNAME.clone();
ns.localpart = XMLSymbols.PREFIX_XMLNS;
ns.rawname = XMLSymbols.PREFIX_XMLNS;
attributes.addAttribute(
ns,
XMLSymbols.fCDATASymbol,
uri);
}
}
else if (
attributes.getValue(NamespaceContext.XMLNS_URI, prefix)
== null) {
if (attributes == null) {
attributes = new XMLAttributesImpl();
}
QName ns = (QName)NEW_NS_ATTR_QNAME.clone();
ns.localpart = prefix;
ns.rawname += prefix;
attributes.addAttribute(
ns,
XMLSymbols.fCDATASymbol,
uri);
}
}
}
}
if (attributes != null) {
int length = attributes.getLength();
for (int i = 0; i < length; i++) {
String type = attributes.getType(i);
String value = attributes.getValue(i);
if (type == XMLSymbols.fENTITYSymbol) {
this.checkUnparsedEntity(value);
}
if (type == XMLSymbols.fENTITIESSymbol) {
// 4.5.1 - Unparsed Entities
StringTokenizer st = new StringTokenizer(value);
while (st.hasMoreTokens()) {
String entName = st.nextToken();
this.checkUnparsedEntity(entName);
}
}
else if (type == XMLSymbols.fNOTATIONSymbol) {
// 4.5.2 - Notations
this.checkNotation(value);
}
/* We actually don't need to do anything for 4.5.3, because at this stage the
* value of the attribute is just a string. It will be taken care of later
* in the pipeline, when the IDREFs are actually resolved against IDs.
*
* if (type == XMLSymbols.fIDREFSymbol || type == XMLSymbols.fIDREFSSymbol) { }
*/
}
}
return attributes;
}
/**
* Returns a URI, relative to the include parent's base URI, of the current
* [base URI]. For instance, if the current [base URI] was "dir1/dir2/file.xml"
* and the include parent's [base URI] was "dir/", this would return "dir2/file.xml".
* @return the relative URI
*/
protected String getRelativeBaseURI() throws MalformedURIException {
int includeParentDepth = getIncludeParentDepth();
String relativeURI = this.getRelativeURI(includeParentDepth);
if (isRootDocument()) {
return relativeURI;
}
else {
if (relativeURI.equals("")) {
relativeURI = fCurrentBaseURI.getLiteralSystemId();
}
if (includeParentDepth == 0) {
if (fParentRelativeURI == null) {
fParentRelativeURI =
fParentXIncludeHandler.getRelativeBaseURI();
}
if (fParentRelativeURI.equals("")) {
return relativeURI;
}
URI uri = new URI("file", fParentRelativeURI);
uri = new URI(uri, relativeURI);
return uri.getPath();
}
else {
return relativeURI;
}
}
}
/**
* Returns the [base URI] of the include parent.
* @return the base URI of the include parent.
*/
private String getIncludeParentBaseURI() {
int depth = getIncludeParentDepth();
if (!isRootDocument() && depth == 0) {
return fParentXIncludeHandler.getIncludeParentBaseURI();
}
else {
return this.getBaseURI(depth);
}
}
/**
* Returns the depth of the include parent. Here, the include parent is
* calculated as the last non-include or non-fallback element. It is assumed
* this method is called when the current element is a top level included item.
* Returning 0 indicates that the top level element in this document
* was an include element.
* @return the depth of the top level include element
*/
private int getIncludeParentDepth() {
// We don't start at fDepth, since it is either the top level included item,
// or an include element, when this method is called.
for (int i = fDepth - 1; i >= 0; i--) {
// This technically might not always return the first non-include/fallback
// element that it comes to, since sawFallback() returns true if a fallback
// was ever encountered at that depth. However, if a fallback was encountered
// at that depth, and it wasn't the direct descendant of the current element
// then we can't be in a situation where we're calling this method (because
// we'll always be in STATE_IGNORE)
if (!getSawInclude(i) && !getSawFallback(i)) {
return i;
}
}
// shouldn't get here, since depth 0 should never have an include element or
// a fallback element
return 0;
}
/**
* Modify the augmentations. Add an [included] infoset item, if the current
* element is a top level included item.
* @param augs the Augmentations to modify.
* @return the modified Augmentations
*/
protected Augmentations modifyAugmentations(Augmentations augs) {
return modifyAugmentations(augs, false);
}
/**
* Modify the augmentations. Add an [included] infoset item, if <code>force</code>
* is true, or if the current element is a top level included item.
* @param augs the Augmentations to modify.
* @param force whether to force modification
* @return the modified Augmentations
*/
protected Augmentations modifyAugmentations(
Augmentations augs,
boolean force) {
if (force || isTopLevelIncludedItem()) {
if (augs == null) {
augs = new AugmentationsImpl();
}
augs.putItem(XINCLUDE_INCLUDED, Boolean.TRUE);
}
return augs;
}
protected int getState(int depth) {
return fState[depth];
}
protected int getState() {
return fState[fDepth];
}
protected void setState(int state) {
if (fDepth >= fState.length) {
int[] newarray = new int[fDepth * 2];
System.arraycopy(fState, 0, newarray, 0, fState.length);
fState = newarray;
}
fState[fDepth] = state;
}
/**
* Records that an <fallback> was encountered at the specified depth,
* as an ancestor of the current element, or as a sibling of an ancestor of the
* current element.
*
* @param depth
* @param val
*/
protected void setSawFallback(int depth, boolean val) {
if (depth >= fSawFallback.length) {
boolean[] newarray = new boolean[depth * 2];
System.arraycopy(fSawFallback, 0, newarray, 0, fSawFallback.length);
fSawFallback = newarray;
}
fSawFallback[depth] = val;
}
/**
* Returns whether an <fallback> was encountered at the specified depth,
* as an ancestor of the current element, or as a sibling of an ancestor of the
* current element.
*
* @param depth
*/
protected boolean getSawFallback(int depth) {
if (depth >= fSawFallback.length) {
return false;
}
return fSawFallback[depth];
}
/**
* Records that an <include> was encountered at the specified depth,
* as an ancestor of the current item.
*
* @param depth
* @param val
*/
protected void setSawInclude(int depth, boolean val) {
if (depth >= fSawInclude.length) {
boolean[] newarray = new boolean[depth * 2];
System.arraycopy(fSawInclude, 0, newarray, 0, fSawInclude.length);
fSawInclude = newarray;
}
fSawInclude[depth] = val;
}
/**
* Return whether an <include> was encountered at the specified depth,
* as an ancestor of the current item.
*
* @param depth
* @return
*/
protected boolean getSawInclude(int depth) {
if (depth >= fSawInclude.length) {
return false;
}
return fSawInclude[depth];
}
protected void reportResourceError(String key) {
this.reportFatalError(key, null);
}
protected void reportResourceError(String key, Object[] args) {
this.reportError(key, args, XMLErrorReporter.SEVERITY_WARNING);
}
protected void reportFatalError(String key) {
this.reportFatalError(key, null);
}
protected void reportFatalError(String key, Object[] args) {
this.reportError(key, args, XMLErrorReporter.SEVERITY_FATAL_ERROR);
}
private void reportError(String key, Object[] args, short severity) {
if (fErrorReporter != null) {
fErrorReporter.reportError(
XIncludeMessageFormatter.XINCLUDE_DOMAIN,
key,
args,
severity);
}
// we won't worry about when error reporter is null, since there should always be
// at least the default error reporter
}
/**
* Set the parent of this XIncludeHandler in the tree
* @param parent
*/
protected void setParent(XIncludeHandler parent) {
fParentXIncludeHandler = parent;
}
// used to know whether to pass declarations to the document handler
protected boolean isRootDocument() {
return fParentXIncludeHandler == null;
}
/**
* Caches an unparsed entity.
* @param name the name of the unparsed entity
* @param identifier the location of the unparsed entity
* @param augmentations any Augmentations that were on the original unparsed entity declaration
*/
protected void addUnparsedEntity(
String name,
XMLResourceIdentifier identifier,
String notation,
Augmentations augmentations) {
UnparsedEntity ent = new UnparsedEntity();
ent.name = name;
ent.systemId = identifier.getLiteralSystemId();
ent.publicId = identifier.getPublicId();
ent.baseURI = identifier.getBaseSystemId();
ent.notation = notation;
ent.augmentations = augmentations;
fUnparsedEntities.add(ent);
}
/**
* Caches a notation.
* @param name the name of the notation
* @param identifier the location of the notation
* @param augmentations any Augmentations that were on the original notation declaration
*/
protected void addNotation(
String name,
XMLResourceIdentifier identifier,
Augmentations augmentations) {
Notation not = new Notation();
not.name = name;
not.systemId = identifier.getLiteralSystemId();
not.publicId = identifier.getPublicId();
not.baseURI = identifier.getBaseSystemId();
not.augmentations = augmentations;
fNotations.add(not);
}
/**
* Checks if an UnparsedEntity with the given name was declared in the DTD of the document
* for the current pipeline. If so, then the notation for the UnparsedEntity is checked.
* If that turns out okay, then the UnparsedEntity is passed to the root pipeline to
* be checked for conflicts, and sent to the root DTDHandler.
*
* @param entName the name of the UnparsedEntity to check
*/
protected void checkUnparsedEntity(String entName) {
UnparsedEntity ent = new UnparsedEntity();
ent.name = entName;
int index = fUnparsedEntities.indexOf(ent);
if (index != -1) {
ent = (UnparsedEntity)fUnparsedEntities.get(index);
// first check the notation of the unparsed entity
checkNotation(ent.notation);
checkAndSendUnparsedEntity(ent);
}
}
/**
* Checks if a Notation with the given name was declared in the DTD of the document
* for the current pipeline. If so, that Notation is passed to the root pipeline to
* be checked for conflicts, and sent to the root DTDHandler
*
* @param notName the name of the Notation to check
*/
protected void checkNotation(String notName) {
Notation not = new Notation();
not.name = notName;
int index = fNotations.indexOf(not);
if (index != -1) {
not = (Notation)fNotations.get(index);
checkAndSendNotation(not);
}
}
/**
* The purpose of this method is to check if an UnparsedEntity conflicts with a previously
* declared entity in the current pipeline stack. If there is no conflict, the
* UnparsedEntity is sent by the root pipeline.
*
* @param ent the UnparsedEntity to check for conflicts
*/
protected void checkAndSendUnparsedEntity(UnparsedEntity ent) {
if (isRootDocument()) {
int index = fUnparsedEntities.indexOf(ent);
if (index == -1) {
// There is no unparsed entity with the same name that we have sent.
// Calling unparsedEntityDecl() will add the entity to our local store,
// and also send the unparsed entity to the DTDHandler
XMLResourceIdentifier id =
new XMLResourceIdentifierImpl(
ent.publicId,
ent.systemId,
ent.baseURI,
null);
this.addUnparsedEntity(
ent.name,
id,
ent.notation,
ent.augmentations);
if (fSendUEAndNotationEvents && fDTDHandler != null) {
fDTDHandler.unparsedEntityDecl(
ent.name,
id,
ent.notation,
ent.augmentations);
}
}
else {
UnparsedEntity localEntity =
(UnparsedEntity)fUnparsedEntities.get(index);
if (!ent.isDuplicate(localEntity)) {
reportFatalError(
"NonDuplicateUnparsedEntity",
new Object[] { ent.name });
}
}
}
else {
fParentXIncludeHandler.checkAndSendUnparsedEntity(ent);
}
}
/**
* The purpose of this method is to check if a Notation conflicts with a previously
* declared notation in the current pipeline stack. If there is no conflict, the
* Notation is sent by the root pipeline.
*
* @param not the Notation to check for conflicts
*/
protected void checkAndSendNotation(Notation not) {
if (isRootDocument()) {
int index = fNotations.indexOf(not);
if (index == -1) {
// There is no notation with the same name that we have sent.
XMLResourceIdentifier id =
new XMLResourceIdentifierImpl(
not.publicId,
not.systemId,
not.baseURI,
null);
this.addNotation(not.name, id, not.augmentations);
if (fSendUEAndNotationEvents && fDTDHandler != null) {
fDTDHandler.notationDecl(not.name, id, not.augmentations);
}
}
else {
Notation localNotation = (Notation)fNotations.get(index);
if (!not.isDuplicate(localNotation)) {
reportFatalError(
"NonDuplicateNotation",
new Object[] { not.name });
}
}
}
else {
fParentXIncludeHandler.checkAndSendNotation(not);
}
}
// It would be nice if we didn't have to repeat code like this, but there's no interface that has
// setFeature() and addRecognizedFeatures() that the objects have in common.
protected void copyFeatures(
XMLComponentManager from,
ParserConfigurationSettings to) {
Enumeration features = Constants.getXercesFeatures();
copyFeatures1(features, Constants.XERCES_FEATURE_PREFIX, from, to);
features = Constants.getSAXFeatures();
copyFeatures1(features, Constants.SAX_FEATURE_PREFIX, from, to);
}
protected void copyFeatures(
XMLComponentManager from,
XMLParserConfiguration to) {
Enumeration features = Constants.getXercesFeatures();
copyFeatures1(features, Constants.XERCES_FEATURE_PREFIX, from, to);
features = Constants.getSAXFeatures();
copyFeatures1(features, Constants.SAX_FEATURE_PREFIX, from, to);
}
private void copyFeatures1(
Enumeration features,
String featurePrefix,
XMLComponentManager from,
ParserConfigurationSettings to) {
while (features.hasMoreElements()) {
String featureId = featurePrefix + (String)features.nextElement();
to.addRecognizedFeatures(new String[] { featureId });
try {
to.setFeature(featureId, from.getFeature(featureId));
}
catch (XMLConfigurationException e) {
// componentManager doesn't support this feature,
// so we won't worry about it
}
}
}
private void copyFeatures1(
Enumeration features,
String featurePrefix,
XMLComponentManager from,
XMLParserConfiguration to) {
while (features.hasMoreElements()) {
String featureId = featurePrefix + (String)features.nextElement();
boolean value = from.getFeature(featureId);
try {
to.setFeature(featureId, value);
}
catch (XMLConfigurationException e) {
// componentManager doesn't support this feature,
// so we won't worry about it
}
}
}
// This is a storage class to hold information about the notations.
// We're not using XMLNotationDecl because we don't want to lose the augmentations.
protected class Notation {
public String name;
public String systemId;
public String baseURI;
public String publicId;
public Augmentations augmentations;
// equals() returns true if two Notations have the same name.
// Useful for searching Vectors for notations with the same name
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj instanceof Notation) {
Notation other = (Notation)obj;
return name.equals(other.name);
}
return false;
}
// from 4.5.2
// Notation items with the same [name], [system identifier],
// [public identifier], and [declaration base URI] are considered
// to be duplicate
public boolean isDuplicate(Object obj) {
if (obj != null && obj instanceof Notation) {
Notation other = (Notation)obj;
return name.equals(other.name)
&& (systemId == other.systemId
|| (systemId != null && systemId.equals(other.systemId)))
&& (publicId == other.publicId
|| (publicId != null && publicId.equals(other.publicId)))
&& (baseURI == other.baseURI
|| (baseURI != null && baseURI.equals(other.baseURI)));
}
return false;
}
}
// This is a storage class to hold information about the unparsed entities.
// We're not using XMLEntityDecl because we don't want to lose the augmentations.
protected class UnparsedEntity {
public String name;
public String systemId;
public String baseURI;
public String publicId;
public String notation;
public Augmentations augmentations;
// equals() returns true if two UnparsedEntities have the same name.
// Useful for searching Vectors for entities with the same name
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj instanceof UnparsedEntity) {
UnparsedEntity other = (UnparsedEntity)obj;
return name.equals(other.name);
}
return false;
}
// from 4.5.1:
// Unparsed entity items with the same [name], [system identifier],
// [public identifier], [declaration base URI], [notation name], and
// [notation] are considered to be duplicate
public boolean isDuplicate(Object obj) {
if (obj != null && obj instanceof UnparsedEntity) {
UnparsedEntity other = (UnparsedEntity)obj;
return name.equals(other.name)
&& (systemId == other.systemId
|| (systemId != null && systemId.equals(other.systemId)))
&& (publicId == other.publicId
|| (publicId != null && publicId.equals(other.publicId)))
&& (baseURI == other.baseURI
|| (baseURI != null && baseURI.equals(other.baseURI)))
&& (notation == other.notation
|| (notation != null && notation.equals(other.notation)));
}
return false;
}
}
// The following methods are used for XML Base processing
/**
* Saves the current base URI to the top of the stack.
*/
protected void saveBaseURI() {
baseURIScope.push(fDepth);
baseURI.push(fCurrentBaseURI.getBaseSystemId());
literalSystemID.push(fCurrentBaseURI.getLiteralSystemId());
expandedSystemID.push(fCurrentBaseURI.getExpandedSystemId());
}
/**
* Discards the URIs at the top of the stack, and restores the ones beneath it.
*/
protected void restoreBaseURI() {
baseURI.pop();
literalSystemID.pop();
expandedSystemID.pop();
baseURIScope.pop();
fCurrentBaseURI.setBaseSystemId((String)baseURI.peek());
fCurrentBaseURI.setLiteralSystemId((String)literalSystemID.peek());
fCurrentBaseURI.setExpandedSystemId((String)expandedSystemID.peek());
}
/**
* Gets the base URI that was in use at that depth
* @param depth
* @return the base URI
*/
public String getBaseURI(int depth) {
int scope = scopeOf(depth);
return (String)expandedSystemID.elementAt(scope);
}
/**
* Returns a relative URI, which when resolved against the base URI at the
* specified depth, will create the current base URI.
* This is accomplished by merged the literal system IDs.
* @param depth the depth at which to start creating the relative URI
* @return a relative URI to convert the base URI at the given depth to the current
* base URI
*/
public String getRelativeURI(int depth) throws MalformedURIException {
// The literal system id at the location given by "start" is *in focus* at
// the given depth. So we need to adjust it to the next scope, so that we
// only process out of focus literal system ids
int start = scopeOf(depth) + 1;
if (start == baseURIScope.size()) {
// If that is the last system id, then we don't need a relative URI
return "";
}
URI uri = new URI("file", (String)literalSystemID.elementAt(start));
for (int i = start + 1; i < baseURIScope.size(); i++) {
uri = new URI(uri, (String)literalSystemID.elementAt(i));
}
return uri.getPath();
}
// We need to find two consecutive elements in the scope stack,
// such that the first is lower than 'depth' (or equal), and the
// second is higher.
private int scopeOf(int depth) {
for (int i = baseURIScope.size() - 1; i >= 0; i--) {
if (baseURIScope.elementAt(i) <= depth)
return i;
}
// we should never get here, because 0 was put on the stack in startDocument()
return -1;
}
/**
* Search for a xml:base attribute, and if one is found, put the new base URI into
* effect.
*/
protected void processXMLBaseAttributes(XMLAttributes attributes) {
String baseURIValue =
attributes.getValue(NamespaceContext.XML_URI, "base");
if (baseURIValue != null) {
try {
String expandedValue =
XMLEntityManager.expandSystemId(
baseURIValue,
fCurrentBaseURI.getExpandedSystemId(),
false);
fCurrentBaseURI.setLiteralSystemId(baseURIValue);
fCurrentBaseURI.setBaseSystemId(
fCurrentBaseURI.getExpandedSystemId());
fCurrentBaseURI.setExpandedSystemId(expandedValue);
// push the new values on the stack
saveBaseURI();
}
catch (MalformedURIException e) {
// REVISIT: throw error here
}
}
}
/**
Set the Accept,Accept-Language,Accept-CharSet
*/
protected void setHttpProperties(XMLInputSource source,XMLAttributes attributes){
try{
String httpAcceptLang = attributes.getValue(HTTP_ACCEPT_LANGUAGE);
String httpAccept = attributes.getValue(HTTP_ACCEPT);
String httpAcceptchar = attributes.getValue(HTTP_ACCEPT_CHARSET);
InputStream stream = source.getByteStream();
if (stream == null) {
URL location = new URL(source.getSystemId());
URLConnection connect = location.openConnection();
if (connect instanceof HttpURLConnection) {
if( httpAcceptLang !=null && !httpAcceptLang.equals(""))
connect.setRequestProperty(HTTP_ACCEPT_LANGUAGE,httpAcceptLang);
if( httpAccept !=null && !httpAccept.equals(""))
connect.setRequestProperty(HTTP_ACCEPT,httpAccept);
if( httpAcceptchar !=null && !httpAcceptchar.equals(""))
connect.setRequestProperty(HTTP_ACCEPT_CHARSET,httpAcceptchar);
}
stream = connect.getInputStream();
source.setByteStream(stream);
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
| Fixing Bug #24318:
http://nagoya.apache.org/bugzilla/show_bug.cgi?id=24318
Comments and PIs from the DTD should be directed to the DTDHandler.
git-svn-id: 21df804813e9d3638e43477f308dd0be51e5f30f@319610 13f79535-47bb-0310-9956-ffa450edef68
| src/org/apache/xerces/xinclude/XIncludeHandler.java | Fixing Bug #24318: http://nagoya.apache.org/bugzilla/show_bug.cgi?id=24318 |
|
Java | apache-2.0 | 7ef1a487927bc7c09e2270626e915b4940b1d7fc | 0 | smulikHakipod/MusiQ | import java.util.List;
public class Queue {
List<SongEntry> song_entries;
Integer current_song;
public SongEntry GetNext() {return null;}
public SongEntry GetPrevious() {return null;}
public SongEntry GetSong() {return null;}
public SongEntry GetSong(int pos) {return null;}
public void AddSong(SongEntry song) {}
public void Remove(Integer pos) {}
public void Reorder(Integer a, Integer b) {}
public void Clear() {}
}
| App/Java/Core/src/Queue.java | import com.sun.tools.javac.util.List;
public class Queue {
List<SongEntry> song_entries;
Integer current_song;
public SongEntry GetNext() {return null;}
public SongEntry GetPrevious() {return null;}
public SongEntry GetSong() {return null;}
public SongEntry GetSong(int pos) {return null;}
public void AddSong(SongEntry song) {}
public void Remove(Integer pos) {}
public void Reorder(Integer a, Integer b) {}
public void Clear() {}
}
| using util instead of sun
| App/Java/Core/src/Queue.java | using util instead of sun |
|
Java | apache-2.0 | 6f16c469563b221ff5d71a999f011475fad25882 | 0 | winningsix/hive,WANdisco/amplab-hive,asonipsl/hive,wisgood/hive,WANdisco/amplab-hive,winningsix/hive,winningsix/hive,winningsix/hive,WANdisco/amplab-hive,asonipsl/hive,WANdisco/amplab-hive,WANdisco/hive,wisgood/hive,wisgood/hive,WANdisco/amplab-hive,WANdisco/hive,wisgood/hive,wisgood/hive,asonipsl/hive,WANdisco/hive,WANdisco/hive,WANdisco/amplab-hive,winningsix/hive,WANdisco/hive,WANdisco/hive,wisgood/hive,WANdisco/amplab-hive,WANdisco/amplab-hive,asonipsl/hive,asonipsl/hive,wisgood/hive,winningsix/hive,WANdisco/hive,WANdisco/hive,asonipsl/hive,winningsix/hive,asonipsl/hive,winningsix/hive,asonipsl/hive,wisgood/hive | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.exec.tez;
import java.io.IOException;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.exec.MapJoinOperator;
import org.apache.hadoop.hive.ql.exec.MapredContext;
import org.apache.hadoop.hive.ql.exec.mr.ExecMapperContext;
import org.apache.hadoop.hive.ql.exec.persistence.HashMapWrapper;
import org.apache.hadoop.hive.ql.exec.persistence.MapJoinKey;
import org.apache.hadoop.hive.ql.exec.persistence.MapJoinRowContainer;
import org.apache.hadoop.hive.ql.exec.persistence.MapJoinTableContainer;
import org.apache.hadoop.hive.ql.exec.persistence.MapJoinTableContainerSerDe;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.plan.MapJoinDesc;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.io.Writable;
import org.apache.tez.runtime.api.LogicalInput;
import org.apache.tez.runtime.library.api.KeyValueReader;
/**
* HashTableLoader for Tez constructs the hashtable from records read from
* a broadcast edge.
*/
public class HashTableLoader implements org.apache.hadoop.hive.ql.exec.HashTableLoader {
private static final Log LOG = LogFactory.getLog(MapJoinOperator.class.getName());
public HashTableLoader() {
}
@Override
public void load(ExecMapperContext context,
Configuration hconf,
MapJoinDesc desc,
byte posBigTable,
MapJoinTableContainer[] mapJoinTables,
MapJoinTableContainerSerDe[] mapJoinTableSerdes) throws HiveException {
TezContext tezContext = (TezContext) MapredContext.get();
Map<Integer, String> parentToInput = desc.getParentToInput();
int hashTableThreshold = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVEHASHTABLETHRESHOLD);
float hashTableLoadFactor = HiveConf.getFloatVar(hconf,
HiveConf.ConfVars.HIVEHASHTABLELOADFACTOR);
for (int pos = 0; pos < mapJoinTables.length; pos++) {
if (pos == posBigTable) {
continue;
}
LogicalInput input = tezContext.getInput(parentToInput.get(pos));
try {
KeyValueReader kvReader = (KeyValueReader) input.getReader();
MapJoinTableContainer tableContainer = new HashMapWrapper(hashTableThreshold,
hashTableLoadFactor);
// simply read all the kv pairs into the hashtable.
while (kvReader.next()) {
MapJoinKey key = new MapJoinKey();
key.read(mapJoinTableSerdes[pos].getKeyContext(), (Writable)kvReader.getCurrentKey());
MapJoinRowContainer values = tableContainer.get(key);
if(values == null){
values = new MapJoinRowContainer();
tableContainer.put(key, values);
}
values.read(mapJoinTableSerdes[pos].getValueContext(), (Writable)kvReader.getCurrentValue());
}
mapJoinTables[pos] = tableContainer;
} catch (IOException e) {
throw new HiveException(e);
} catch (SerDeException e) {
throw new HiveException(e);
} catch (Exception e) {
throw new HiveException(e);
}
}
}
}
| ql/src/java/org/apache/hadoop/hive/ql/exec/tez/HashTableLoader.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.exec.tez;
import java.io.IOException;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.exec.MapJoinOperator;
import org.apache.hadoop.hive.ql.exec.MapredContext;
import org.apache.hadoop.hive.ql.exec.mr.ExecMapperContext;
import org.apache.hadoop.hive.ql.exec.persistence.HashMapWrapper;
import org.apache.hadoop.hive.ql.exec.persistence.MapJoinKey;
import org.apache.hadoop.hive.ql.exec.persistence.MapJoinRowContainer;
import org.apache.hadoop.hive.ql.exec.persistence.MapJoinTableContainer;
import org.apache.hadoop.hive.ql.exec.persistence.MapJoinTableContainerSerDe;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.plan.MapJoinDesc;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.io.Writable;
import org.apache.tez.runtime.api.LogicalInput;
import org.apache.tez.runtime.library.api.KeyValueReader;
/**
* HashTableLoader for Tez constructs the hashtable from records read from
* a broadcast edge.
*/
public class HashTableLoader implements org.apache.hadoop.hive.ql.exec.HashTableLoader {
private static final Log LOG = LogFactory.getLog(MapJoinOperator.class.getName());
public HashTableLoader() {
}
@Override
public void load(ExecMapperContext context,
Configuration hconf,
MapJoinDesc desc,
byte posBigTable,
MapJoinTableContainer[] mapJoinTables,
MapJoinTableContainerSerDe[] mapJoinTableSerdes) throws HiveException {
TezContext tezContext = (TezContext) MapredContext.get();
Map<Integer, String> parentToInput = desc.getParentToInput();
int hashTableThreshold = HiveConf.getIntVar(hconf, HiveConf.ConfVars.HIVEHASHTABLETHRESHOLD);
float hashTableLoadFactor = HiveConf.getFloatVar(hconf,
HiveConf.ConfVars.HIVEHASHTABLELOADFACTOR);
for (int pos = 0; pos < mapJoinTables.length; pos++) {
if (pos == posBigTable) {
continue;
}
LogicalInput input = tezContext.getInput(parentToInput.get(pos));
try {
KeyValueReader kvReader = (KeyValueReader) input.getReader();
MapJoinTableContainer tableContainer = new HashMapWrapper(hashTableThreshold,
hashTableLoadFactor);
// simply read all the kv pairs into the hashtable.
while (kvReader.next()) {
MapJoinKey key = new MapJoinKey();
key.read(mapJoinTableSerdes[pos].getKeyContext(), (Writable)kvReader.getCurrentKey());
MapJoinRowContainer values = new MapJoinRowContainer();
values.read(mapJoinTableSerdes[pos].getValueContext(), (Writable)kvReader.getCurrentValue());
tableContainer.put(key, values);
}
mapJoinTables[pos] = tableContainer;
} catch (IOException e) {
throw new HiveException(e);
} catch (SerDeException e) {
throw new HiveException(e);
} catch (Exception e) {
throw new HiveException(e);
}
}
}
}
| HIVE-5808: broadcast join in tez discards duplicate records from the broadcasted table (Thejas M Nair via Gunther Hagleitner)
git-svn-id: 4e1464cfe7fb51a36d74cdb269026d9b896c8df9@1541369 13f79535-47bb-0310-9956-ffa450edef68
| ql/src/java/org/apache/hadoop/hive/ql/exec/tez/HashTableLoader.java | HIVE-5808: broadcast join in tez discards duplicate records from the broadcasted table (Thejas M Nair via Gunther Hagleitner) |
|
Java | apache-2.0 | ba02b46e293931b7d44849b2d4126afdf3556b41 | 0 | apache/samza,prateekm/samza,apache/samza,prateekm/samza,abhishekshivanna/samza,apache/samza,prateekm/samza,prateekm/samza,lhaiesp/samza,lhaiesp/samza,abhishekshivanna/samza,apache/samza,prateekm/samza,apache/samza,abhishekshivanna/samza,lhaiesp/samza,lhaiesp/samza,abhishekshivanna/samza,lhaiesp/samza,abhishekshivanna/samza | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.samza.execution;
import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.samza.SamzaException;
import org.apache.samza.application.descriptors.ApplicationDescriptor;
import org.apache.samza.application.descriptors.ApplicationDescriptorImpl;
import org.apache.samza.application.LegacyTaskApplication;
import org.apache.samza.config.ApplicationConfig;
import org.apache.samza.config.ClusterManagerConfig;
import org.apache.samza.config.Config;
import org.apache.samza.config.JobConfig;
import org.apache.samza.config.MapConfig;
import org.apache.samza.config.ShellCommandConfig;
import org.apache.samza.config.StreamConfig;
import org.apache.samza.config.TaskConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is a temporary helper class to include all common logic to generate {@link JobConfig}s for high- and low-level
* applications in {@link org.apache.samza.runtime.LocalApplicationRunner} and {@link org.apache.samza.runtime.RemoteApplicationRunner}.
*
* TODO: Fix SAMZA-1811 to consolidate this class with {@link ExecutionPlanner}
*/
public abstract class JobPlanner {
private static final Logger LOG = LoggerFactory.getLogger(JobPlanner.class);
protected final ApplicationDescriptorImpl<? extends ApplicationDescriptor> appDesc;
protected final Config userConfig;
JobPlanner(ApplicationDescriptorImpl<? extends ApplicationDescriptor> descriptor) {
this.appDesc = descriptor;
this.userConfig = descriptor.getConfig();
}
public abstract List<JobConfig> prepareJobs();
StreamManager buildAndStartStreamManager(Config config) {
StreamManager streamManager = new StreamManager(config);
streamManager.start();
return streamManager;
}
ExecutionPlan getExecutionPlan() {
return getExecutionPlan(null);
}
/* package private */
ExecutionPlan getExecutionPlan(String runId) {
Map<String, String> allowedUserConfig = new HashMap<>(userConfig);
Map<String, String> generatedConfig = new HashMap<>();
// TODO: This should all be consolidated with ExecutionPlanner after fixing SAMZA-1811
// Don't generate any configurations for LegacyTaskApplications
if (!LegacyTaskApplication.class.isAssignableFrom(appDesc.getAppClass())) {
// Don't allow overriding task.inputs to a blank string
if (StringUtils.isBlank(userConfig.get(TaskConfig.INPUT_STREAMS))) {
allowedUserConfig.remove(TaskConfig.INPUT_STREAMS);
}
generatedConfig.putAll(getGeneratedConfig(runId));
}
if (ApplicationConfig.ApplicationMode.BATCH.name().equals(generatedConfig.get(ApplicationConfig.APP_MODE))) {
allowedUserConfig.remove(ClusterManagerConfig.JOB_HOST_AFFINITY_ENABLED);
}
// merge user-provided configuration with generated configuration. generated configuration has lower priority.
Config mergedConfig = JobNodeConfigurationGenerator.mergeConfig(allowedUserConfig, generatedConfig);
// creating the StreamManager to get all input/output streams' metadata for planning
StreamManager streamManager = buildAndStartStreamManager(mergedConfig);
try {
ExecutionPlanner planner = new ExecutionPlanner(mergedConfig, streamManager);
return planner.plan(appDesc);
} finally {
streamManager.stop();
}
}
/**
* Write the execution plan JSON to a file
* @param planJson JSON representation of the plan
*/
final void writePlanJsonFile(String planJson) {
try {
String content = "plan='" + planJson + "'";
String planPath = System.getenv(ShellCommandConfig.EXECUTION_PLAN_DIR());
if (planPath != null && !planPath.isEmpty()) {
// Write the plan json to plan path
File file = new File(planPath + "/plan.json");
file.setReadable(true, false);
PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.println(content);
writer.close();
}
} catch (Exception e) {
LOG.warn("Failed to write execution plan json to file", e);
}
}
private Map<String, String> getGeneratedConfig(String runId) {
Map<String, String> generatedConfig = new HashMap<>();
if (StringUtils.isNoneEmpty(runId)) {
generatedConfig.put(ApplicationConfig.APP_RUN_ID, runId);
}
Map<String, String> systemStreamConfigs = generateSystemStreamConfigs(appDesc);
generatedConfig.putAll(systemStreamConfigs);
StreamConfig streamConfig = new StreamConfig(new MapConfig(generatedConfig));
Set<String> inputStreamIds = new HashSet<>(appDesc.getInputStreamIds());
inputStreamIds.removeAll(appDesc.getOutputStreamIds()); // exclude intermediate streams
final ApplicationConfig.ApplicationMode mode;
if (inputStreamIds.isEmpty()) {
mode = ApplicationConfig.ApplicationMode.STREAM; // use stream by default
} else {
mode = inputStreamIds.stream().allMatch(streamConfig::getIsBounded)
? ApplicationConfig.ApplicationMode.BATCH
: ApplicationConfig.ApplicationMode.STREAM;
}
generatedConfig.put(ApplicationConfig.APP_MODE, mode.name());
// adding app.class in the configuration, unless it is LegacyTaskApplication
if (!LegacyTaskApplication.class.getName().equals(appDesc.getAppClass().getName())) {
generatedConfig.put(ApplicationConfig.APP_CLASS, appDesc.getAppClass().getName());
}
return generatedConfig;
}
private Map<String, String> generateSystemStreamConfigs(ApplicationDescriptorImpl<? extends ApplicationDescriptor> appDesc) {
Map<String, String> systemStreamConfigs = new HashMap<>();
appDesc.getInputDescriptors().forEach((key, value) -> systemStreamConfigs.putAll(value.toConfig()));
appDesc.getOutputDescriptors().forEach((key, value) -> systemStreamConfigs.putAll(value.toConfig()));
appDesc.getSystemDescriptors().forEach(sd -> systemStreamConfigs.putAll(sd.toConfig()));
appDesc.getDefaultSystemDescriptor().ifPresent(dsd ->
systemStreamConfigs.put(JobConfig.JOB_DEFAULT_SYSTEM, dsd.getSystemName()));
return systemStreamConfigs;
}
/**
* Generates configs for a single job in app, job.id from app.id and job.name from app.name config
* If both job.id and app.id is defined, app.id takes precedence and job.id is set to value of app.id
* If both job.name and app.name is defined, app.name takes precedence and job.name is set to value of app.name
*
* @param userConfigs configs passed from user
*
*/
public static MapConfig generateSingleJobConfig(Map<String, String> userConfigs) {
Map<String, String> generatedConfig = new HashMap<>(userConfigs);
if (!userConfigs.containsKey(JobConfig.JOB_NAME) && !userConfigs.containsKey(ApplicationConfig.APP_NAME)) {
throw new SamzaException("Samza app name should not be null, Please set either app.name (preferred) or job.name (deprecated) in configs");
}
if (userConfigs.containsKey(JobConfig.JOB_ID)) {
LOG.warn("{} is a deprecated configuration, use app.id instead.", JobConfig.JOB_ID);
}
if (userConfigs.containsKey(JobConfig.JOB_NAME)) {
LOG.warn("{} is a deprecated configuration, use use app.name instead.", JobConfig.JOB_NAME);
}
if (userConfigs.containsKey(ApplicationConfig.APP_NAME)) {
String appName = userConfigs.get(ApplicationConfig.APP_NAME);
LOG.info("app.name is defined, generating job.name equal to app.name value: {}", appName);
generatedConfig.put(JobConfig.JOB_NAME, appName);
}
if (userConfigs.containsKey(ApplicationConfig.APP_ID)) {
String appId = userConfigs.get(ApplicationConfig.APP_ID);
LOG.info("app.id is defined, generating job.id equal to app.name value: {}", appId);
generatedConfig.put(JobConfig.JOB_ID, appId);
}
return new MapConfig(generatedConfig);
}
}
| samza-core/src/main/java/org/apache/samza/execution/JobPlanner.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.samza.execution;
import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.samza.SamzaException;
import org.apache.samza.application.descriptors.ApplicationDescriptor;
import org.apache.samza.application.descriptors.ApplicationDescriptorImpl;
import org.apache.samza.application.LegacyTaskApplication;
import org.apache.samza.config.ApplicationConfig;
import org.apache.samza.config.Config;
import org.apache.samza.config.JobConfig;
import org.apache.samza.config.MapConfig;
import org.apache.samza.config.ShellCommandConfig;
import org.apache.samza.config.StreamConfig;
import org.apache.samza.config.TaskConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is a temporary helper class to include all common logic to generate {@link JobConfig}s for high- and low-level
* applications in {@link org.apache.samza.runtime.LocalApplicationRunner} and {@link org.apache.samza.runtime.RemoteApplicationRunner}.
*
* TODO: Fix SAMZA-1811 to consolidate this class with {@link ExecutionPlanner}
*/
public abstract class JobPlanner {
private static final Logger LOG = LoggerFactory.getLogger(JobPlanner.class);
protected final ApplicationDescriptorImpl<? extends ApplicationDescriptor> appDesc;
protected final Config userConfig;
JobPlanner(ApplicationDescriptorImpl<? extends ApplicationDescriptor> descriptor) {
this.appDesc = descriptor;
this.userConfig = descriptor.getConfig();
}
public abstract List<JobConfig> prepareJobs();
StreamManager buildAndStartStreamManager(Config config) {
StreamManager streamManager = new StreamManager(config);
streamManager.start();
return streamManager;
}
ExecutionPlan getExecutionPlan() {
return getExecutionPlan(null);
}
/* package private */
ExecutionPlan getExecutionPlan(String runId) {
Map<String, String> allowedUserConfig = new HashMap<>(userConfig);
Map<String, String> generatedConfig = new HashMap<>();
// TODO: This should all be consolidated with ExecutionPlanner after fixing SAMZA-1811
// Don't generate any configurations for LegacyTaskApplications
if (!LegacyTaskApplication.class.isAssignableFrom(appDesc.getAppClass())) {
// Don't allow overriding task.inputs to a blank string
if (StringUtils.isBlank(userConfig.get(TaskConfig.INPUT_STREAMS))) {
allowedUserConfig.remove(TaskConfig.INPUT_STREAMS);
}
generatedConfig.putAll(getGeneratedConfig(runId));
}
// merge user-provided configuration with generated configuration. generated configuration has lower priority.
Config mergedConfig = JobNodeConfigurationGenerator.mergeConfig(allowedUserConfig, generatedConfig);
// creating the StreamManager to get all input/output streams' metadata for planning
StreamManager streamManager = buildAndStartStreamManager(mergedConfig);
try {
ExecutionPlanner planner = new ExecutionPlanner(mergedConfig, streamManager);
return planner.plan(appDesc);
} finally {
streamManager.stop();
}
}
/**
* Write the execution plan JSON to a file
* @param planJson JSON representation of the plan
*/
final void writePlanJsonFile(String planJson) {
try {
String content = "plan='" + planJson + "'";
String planPath = System.getenv(ShellCommandConfig.EXECUTION_PLAN_DIR());
if (planPath != null && !planPath.isEmpty()) {
// Write the plan json to plan path
File file = new File(planPath + "/plan.json");
file.setReadable(true, false);
PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.println(content);
writer.close();
}
} catch (Exception e) {
LOG.warn("Failed to write execution plan json to file", e);
}
}
private Map<String, String> getGeneratedConfig(String runId) {
Map<String, String> generatedConfig = new HashMap<>();
if (StringUtils.isNoneEmpty(runId)) {
generatedConfig.put(ApplicationConfig.APP_RUN_ID, runId);
}
StreamConfig streamConfig = new StreamConfig(userConfig);
Set<String> inputStreamIds = new HashSet<>(appDesc.getInputStreamIds());
inputStreamIds.removeAll(appDesc.getOutputStreamIds()); // exclude intermediate streams
ApplicationConfig.ApplicationMode mode =
inputStreamIds.stream().allMatch(streamConfig::getIsBounded)
? ApplicationConfig.ApplicationMode.BATCH
: ApplicationConfig.ApplicationMode.STREAM;
generatedConfig.put(ApplicationConfig.APP_MODE, mode.name());
Map<String, String> systemStreamConfigs = generateSystemStreamConfigs(appDesc);
generatedConfig.putAll(systemStreamConfigs);
// adding app.class in the configuration, unless it is LegacyTaskApplication
if (!LegacyTaskApplication.class.getName().equals(appDesc.getAppClass().getName())) {
generatedConfig.put(ApplicationConfig.APP_CLASS, appDesc.getAppClass().getName());
}
return generatedConfig;
}
private Map<String, String> generateSystemStreamConfigs(ApplicationDescriptorImpl<? extends ApplicationDescriptor> appDesc) {
Map<String, String> systemStreamConfigs = new HashMap<>();
appDesc.getInputDescriptors().forEach((key, value) -> systemStreamConfigs.putAll(value.toConfig()));
appDesc.getOutputDescriptors().forEach((key, value) -> systemStreamConfigs.putAll(value.toConfig()));
appDesc.getSystemDescriptors().forEach(sd -> systemStreamConfigs.putAll(sd.toConfig()));
appDesc.getDefaultSystemDescriptor().ifPresent(dsd ->
systemStreamConfigs.put(JobConfig.JOB_DEFAULT_SYSTEM, dsd.getSystemName()));
return systemStreamConfigs;
}
/**
* Generates configs for a single job in app, job.id from app.id and job.name from app.name config
* If both job.id and app.id is defined, app.id takes precedence and job.id is set to value of app.id
* If both job.name and app.name is defined, app.name takes precedence and job.name is set to value of app.name
*
* @param userConfigs configs passed from user
*
*/
public static MapConfig generateSingleJobConfig(Map<String, String> userConfigs) {
Map<String, String> generatedConfig = new HashMap<>(userConfigs);
if (!userConfigs.containsKey(JobConfig.JOB_NAME) && !userConfigs.containsKey(ApplicationConfig.APP_NAME)) {
throw new SamzaException("Samza app name should not be null, Please set either app.name (preferred) or job.name (deprecated) in configs");
}
if (userConfigs.containsKey(JobConfig.JOB_ID)) {
LOG.warn("{} is a deprecated configuration, use app.id instead.", JobConfig.JOB_ID);
}
if (userConfigs.containsKey(JobConfig.JOB_NAME)) {
LOG.warn("{} is a deprecated configuration, use use app.name instead.", JobConfig.JOB_NAME);
}
if (userConfigs.containsKey(ApplicationConfig.APP_NAME)) {
String appName = userConfigs.get(ApplicationConfig.APP_NAME);
LOG.info("app.name is defined, generating job.name equal to app.name value: {}", appName);
generatedConfig.put(JobConfig.JOB_NAME, appName);
}
if (userConfigs.containsKey(ApplicationConfig.APP_ID)) {
String appId = userConfigs.get(ApplicationConfig.APP_ID);
LOG.info("app.id is defined, generating job.id equal to app.name value: {}", appId);
generatedConfig.put(JobConfig.JOB_ID, appId);
}
return new MapConfig(generatedConfig);
}
}
| SAMZA-2377: Batch mode should be computed based on generated configs (#1215)
| samza-core/src/main/java/org/apache/samza/execution/JobPlanner.java | SAMZA-2377: Batch mode should be computed based on generated configs (#1215) |
|
Java | apache-2.0 | 18a603d932adcb0c1a8c79546acd937e3dd36f51 | 0 | vanitasvitae/smack-omemo,kkroid/OnechatSmack,unisontech/Smack,hy9902/Smack,dpr-odoo/Smack,chuangWu/Smack,unisontech/Smack,igorexax3mal/Smack,esl/Smack,lovely3x/Smack,vanitasvitae/Smack,ishan1604/Smack,igniterealtime/Smack,mar-v-in/Smack,ishan1604/Smack,TTalkIM/Smack,kkroid/OnechatSmack,unisontech/Smack,igorexax3mal/Smack,u20024804/Smack,Tibo-lg/Smack,chuangWu/Smack,vanitasvitae/smack-omemo,Flowdalic/Smack,cjpx00008/Smack,TTalkIM/Smack,ayne/Smack,andrey42/Smack,lovely3x/Smack,andrey42/Smack,hy9902/Smack,opg7371/Smack,annovanvliet/Smack,mar-v-in/Smack,hy9902/Smack,igniterealtime/Smack,esl/Smack,TTalkIM/Smack,deeringc/Smack,magnetsystems/message-smack,deeringc/Smack,magnetsystems/message-smack,dpr-odoo/Smack,qingsong-xu/Smack,Flowdalic/Smack,vanitasvitae/Smack,vito-c/Smack,qingsong-xu/Smack,vanitasvitae/smack-omemo,magnetsystems/message-smack,xuIcream/Smack,vanitasvitae/Smack,kkroid/OnechatSmack,ayne/Smack,esl/Smack,ishan1604/Smack,Tibo-lg/Smack,qingsong-xu/Smack,opg7371/Smack,cjpx00008/Smack,annovanvliet/Smack,cjpx00008/Smack,Tibo-lg/Smack,xuIcream/Smack,ayne/Smack,opg7371/Smack,mar-v-in/Smack,lovely3x/Smack,igniterealtime/Smack,u20024804/Smack,annovanvliet/Smack,vito-c/Smack,xuIcream/Smack,chuangWu/Smack,u20024804/Smack,deeringc/Smack,igorexax3mal/Smack,andrey42/Smack,dpr-odoo/Smack,Flowdalic/Smack | /**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright 2003-2007 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.RosterPacket;
import java.util.*;
/**
* Each user in your roster is represented by a roster entry, which contains the user's
* JID and a name or nickname you assign.
*
* @author Matt Tucker
*/
public class RosterEntry {
private String user;
private String name;
private RosterPacket.ItemType type;
private RosterPacket.ItemStatus status;
final private Roster roster;
final private Connection connection;
/**
* Creates a new roster entry.
*
* @param user the user.
* @param name the nickname for the entry.
* @param type the subscription type.
* @param status the subscription status (related to subscriptions pending to be approbed).
* @param connection a connection to the XMPP server.
*/
RosterEntry(String user, String name, RosterPacket.ItemType type,
RosterPacket.ItemStatus status, Roster roster, Connection connection) {
this.user = user;
this.name = name;
this.type = type;
this.status = status;
this.roster = roster;
this.connection = connection;
}
/**
* Returns the JID of the user associated with this entry.
*
* @return the user associated with this entry.
*/
public String getUser() {
return user;
}
/**
* Returns the name associated with this entry.
*
* @return the name.
*/
public String getName() {
return name;
}
/**
* Sets the name associated with this entry.
*
* @param name the name.
*/
public void setName(String name) {
// Do nothing if the name hasn't changed.
if (name != null && name.equals(this.name)) {
return;
}
this.name = name;
RosterPacket packet = new RosterPacket();
packet.setType(IQ.Type.SET);
packet.addRosterItem(toRosterItem(this));
connection.sendPacket(packet);
}
/**
* Updates the state of the entry with the new values.
*
* @param name the nickname for the entry.
* @param type the subscription type.
* @param status the subscription status (related to subscriptions pending to be approbed).
*/
void updateState(String name, RosterPacket.ItemType type, RosterPacket.ItemStatus status) {
this.name = name;
this.type = type;
this.status = status;
}
/**
* Returns an unmodifiable collection of the roster groups that this entry belongs to.
*
* @return an iterator for the groups this entry belongs to.
*/
public Collection<RosterGroup> getGroups() {
List<RosterGroup> results = new ArrayList<RosterGroup>();
// Loop through all roster groups and find the ones that contain this
// entry. This algorithm should be fine
for (RosterGroup group: roster.getGroups()) {
if (group.contains(this)) {
results.add(group);
}
}
return Collections.unmodifiableCollection(results);
}
/**
* Returns the roster subscription type of the entry. When the type is
* RosterPacket.ItemType.none or RosterPacket.ItemType.from,
* refer to {@link RosterEntry getStatus()} to see if a subscription request
* is pending.
*
* @return the type.
*/
public RosterPacket.ItemType getType() {
return type;
}
/**
* Returns the roster subscription status of the entry. When the status is
* RosterPacket.ItemStatus.SUBSCRIPTION_PENDING, the contact has to answer the
* subscription request.
*
* @return the status.
*/
public RosterPacket.ItemStatus getStatus() {
return status;
}
public String toString() {
StringBuilder buf = new StringBuilder();
if (name != null) {
buf.append(name).append(": ");
}
buf.append(user);
Collection<RosterGroup> groups = getGroups();
if (!groups.isEmpty()) {
buf.append(" [");
Iterator<RosterGroup> iter = groups.iterator();
RosterGroup group = iter.next();
buf.append(group.getName());
while (iter.hasNext()) {
buf.append(", ");
group = iter.next();
buf.append(group.getName());
}
buf.append("]");
}
return buf.toString();
}
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object != null && object instanceof RosterEntry) {
return user.equals(((RosterEntry)object).getUser());
}
else {
return false;
}
}
@Override
public int hashCode() {
return this.user.hashCode();
}
/**
* Indicates whether some other object is "equal to" this by comparing all members.
* <p>
* The {@link #equals(Object)} method returns <code>true</code> if the user JIDs are equal.
*
* @param obj the reference object with which to compare.
* @return <code>true</code> if this object is the same as the obj argument; <code>false</code>
* otherwise.
*/
public boolean equalsDeep(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RosterEntry other = (RosterEntry) obj;
if (name == null) {
if (other.name != null)
return false;
}
else if (!name.equals(other.name))
return false;
if (status == null) {
if (other.status != null)
return false;
}
else if (!status.equals(other.status))
return false;
if (type == null) {
if (other.type != null)
return false;
}
else if (!type.equals(other.type))
return false;
if (user == null) {
if (other.user != null)
return false;
}
else if (!user.equals(other.user))
return false;
return true;
}
static RosterPacket.Item toRosterItem(RosterEntry entry) {
RosterPacket.Item item = new RosterPacket.Item(entry.getUser(), entry.getName());
item.setItemType(entry.getType());
item.setItemStatus(entry.getStatus());
// Set the correct group names for the item.
for (RosterGroup group : entry.getGroups()) {
item.addGroupName(group.getName());
}
return item;
}
} | source/org/jivesoftware/smack/RosterEntry.java | /**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright 2003-2007 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.RosterPacket;
import java.util.*;
/**
* Each user in your roster is represented by a roster entry, which contains the user's
* JID and a name or nickname you assign.
*
* @author Matt Tucker
*/
public class RosterEntry {
private String user;
private String name;
private RosterPacket.ItemType type;
private RosterPacket.ItemStatus status;
final private Roster roster;
final private Connection connection;
/**
* Creates a new roster entry.
*
* @param user the user.
* @param name the nickname for the entry.
* @param type the subscription type.
* @param status the subscription status (related to subscriptions pending to be approbed).
* @param connection a connection to the XMPP server.
*/
RosterEntry(String user, String name, RosterPacket.ItemType type,
RosterPacket.ItemStatus status, Roster roster, Connection connection) {
this.user = user;
this.name = name;
this.type = type;
this.status = status;
this.roster = roster;
this.connection = connection;
}
/**
* Returns the JID of the user associated with this entry.
*
* @return the user associated with this entry.
*/
public String getUser() {
return user;
}
/**
* Returns the name associated with this entry.
*
* @return the name.
*/
public String getName() {
return name;
}
/**
* Sets the name associated with this entry.
*
* @param name the name.
*/
public void setName(String name) {
// Do nothing if the name hasn't changed.
if (name != null && name.equals(this.name)) {
return;
}
this.name = name;
RosterPacket packet = new RosterPacket();
packet.setType(IQ.Type.SET);
packet.addRosterItem(toRosterItem(this));
connection.sendPacket(packet);
}
/**
* Updates the state of the entry with the new values.
*
* @param name the nickname for the entry.
* @param type the subscription type.
* @param status the subscription status (related to subscriptions pending to be approbed).
*/
void updateState(String name, RosterPacket.ItemType type, RosterPacket.ItemStatus status) {
this.name = name;
this.type = type;
this.status = status;
}
/**
* Returns an unmodifiable collection of the roster groups that this entry belongs to.
*
* @return an iterator for the groups this entry belongs to.
*/
public Collection<RosterGroup> getGroups() {
List<RosterGroup> results = new ArrayList<RosterGroup>();
// Loop through all roster groups and find the ones that contain this
// entry. This algorithm should be fine
for (RosterGroup group: roster.getGroups()) {
if (group.contains(this)) {
results.add(group);
}
}
return Collections.unmodifiableCollection(results);
}
/**
* Returns the roster subscription type of the entry. When the type is
* RosterPacket.ItemType.none or RosterPacket.ItemType.from,
* refer to {@link RosterEntry getStatus()} to see if a subscription request
* is pending.
*
* @return the type.
*/
public RosterPacket.ItemType getType() {
return type;
}
/**
* Returns the roster subscription status of the entry. When the status is
* RosterPacket.ItemStatus.SUBSCRIPTION_PENDING, the contact has to answer the
* subscription request.
*
* @return the status.
*/
public RosterPacket.ItemStatus getStatus() {
return status;
}
public String toString() {
StringBuilder buf = new StringBuilder();
if (name != null) {
buf.append(name).append(": ");
}
buf.append(user);
Collection<RosterGroup> groups = getGroups();
if (!groups.isEmpty()) {
buf.append(" [");
Iterator<RosterGroup> iter = groups.iterator();
RosterGroup group = iter.next();
buf.append(group.getName());
while (iter.hasNext()) {
buf.append(", ");
group = iter.next();
buf.append(group.getName());
}
buf.append("]");
}
return buf.toString();
}
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object != null && object instanceof RosterEntry) {
return user.equals(((RosterEntry)object).getUser());
}
else {
return false;
}
}
/**
* Indicates whether some other object is "equal to" this by comparing all members.
* <p>
* The {@link #equals(Object)} method returns <code>true</code> if the user JIDs are equal.
*
* @param obj the reference object with which to compare.
* @return <code>true</code> if this object is the same as the obj argument; <code>false</code>
* otherwise.
*/
public boolean equalsDeep(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RosterEntry other = (RosterEntry) obj;
if (name == null) {
if (other.name != null)
return false;
}
else if (!name.equals(other.name))
return false;
if (status == null) {
if (other.status != null)
return false;
}
else if (!status.equals(other.status))
return false;
if (type == null) {
if (other.type != null)
return false;
}
else if (!type.equals(other.type))
return false;
if (user == null) {
if (other.user != null)
return false;
}
else if (!user.equals(other.user))
return false;
return true;
}
static RosterPacket.Item toRosterItem(RosterEntry entry) {
RosterPacket.Item item = new RosterPacket.Item(entry.getUser(), entry.getName());
item.setItemType(entry.getType());
item.setItemStatus(entry.getStatus());
// Set the correct group names for the item.
for (RosterGroup group : entry.getGroups()) {
item.addGroupName(group.getName());
}
return item;
}
} | SMACK-428 add 'public int RosterEntry.hashCode()'
git-svn-id: b5a24b162d892e1c06088ae436f559ada2d58cf8@13662 b35dd754-fafc-0310-a699-88a17e54d16e
| source/org/jivesoftware/smack/RosterEntry.java | SMACK-428 add 'public int RosterEntry.hashCode()' |
|
Java | apache-2.0 | c20e9df05106a23320348f9ff4f31be42f6d244c | 0 | seven332/Gukize | /*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gukize;
/*
* Created by Hippo on 8/22/2016.
*/
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.SystemClock;
import android.support.annotation.NonNull;
// TODO mImageBitmap.reset() and mImageBitmap.advance() may
// TODO take a long time. Put them to a new thread?
public class ImageDrawable extends Drawable implements Animatable, Runnable {
private ImageBitmap mImageBitmap;
private Paint mPaint;
/** Whether the drawable has an animation callback posted. */
private boolean mRunning;
/** Whether the drawable should animate when visible. */
private boolean mAnimating;
public ImageDrawable(@NonNull ImageBitmap imageBitmap) {
mImageBitmap = imageBitmap;
mPaint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG);
}
public ImageBitmap getImageBitmap() {
return mImageBitmap;
}
@Override
public boolean setVisible(boolean visible, boolean restart) {
final boolean changed = super.setVisible(visible, restart);
if (mImageBitmap.isAnimated()) {
if (visible) {
if (restart || changed) {
final boolean next = !restart && mRunning;
setFrame(next, true, mAnimating);
}
} else {
unscheduleSelf(this);
}
}
return changed;
}
/**
* Starts the animation, looping if necessary. This method has no effect
* if the animation is running.
* <p>
* <strong>Note:</strong> Do not call this in the
* {@link android.app.Activity#onCreate} method of your activity, because
* the {@link AnimationDrawable} is not yet fully attached to the window.
* If you want to play the animation immediately without requiring
* interaction, then you might want to call it from the
* {@link android.app.Activity#onWindowFocusChanged} method in your
* activity, which will get called when Android brings your window into
* focus.
*
* @see #isRunning()
* @see #stop()
*/
@Override
public void start() {
mAnimating = true;
if (mImageBitmap.isAnimated() && !isRunning()) {
// Start from 0th frame.
setFrame(false, false, true);
}
}
/**
* Stops the animation. This method has no effect if the animation is not
* running.
*
* @see #isRunning()
* @see #start()
*/
@Override
public void stop() {
mAnimating = false;
if (mImageBitmap.isAnimated() && isRunning()) {
unscheduleSelf(this);
}
}
/**
* Indicates whether the animation is currently running or not.
*
* @return true if the animation is running, false otherwise
*/
@Override
public boolean isRunning() {
return mRunning;
}
/**
* This method exists for implementation purpose only and should not be
* called directly. Invoke {@link #start()} instead.
*
* @see #start()
*/
@Override
public void run() {
setFrame(true, false, true);
}
private void setFrame(boolean resetOrNext, boolean unschedule, boolean animate) {
// Check recycled
if (mImageBitmap.isRecycled()) {
return;
}
mAnimating = animate;
if (resetOrNext) {
mImageBitmap.advance();
} else {
mImageBitmap.reset();
}
invalidateSelf();
if (unschedule || animate) {
unscheduleSelf(this);
}
if (animate) {
mRunning = true;
scheduleSelf(this, SystemClock.uptimeMillis() + mImageBitmap.getCurrentDelay());
}
}
@Override
public void unscheduleSelf(@NonNull Runnable what) {
mRunning = false;
super.unscheduleSelf(what);
}
@Override
public void draw(@NonNull Canvas canvas) {
final Bitmap bitmap = mImageBitmap.getBitmap();
if (bitmap != null) {
canvas.drawBitmap(bitmap, null, getBounds(), mPaint);
}
}
@Override
public void setAlpha(int alpha) {
mPaint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
mPaint.setColorFilter(colorFilter);
}
@Override
public int getOpacity() {
return mImageBitmap.isOpaque() ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT;
}
@Override
public int getIntrinsicWidth() {
return mImageBitmap.getWidth();
}
@Override
public int getIntrinsicHeight() {
return mImageBitmap.getHeight();
}
}
| library/src/main/java/com/hippo/gukize/ImageDrawable.java | /*
* Copyright 2016 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.gukize;
/*
* Created by Hippo on 8/22/2016.
*/
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.SystemClock;
import android.support.annotation.NonNull;
public class ImageDrawable extends Drawable implements Animatable, Runnable {
private ImageBitmap mImageBitmap;
private Paint mPaint;
/** Whether the drawable has an animation callback posted. */
private boolean mRunning;
/** Whether the drawable should animate when visible. */
private boolean mAnimating;
public ImageDrawable(@NonNull ImageBitmap imageBitmap) {
mImageBitmap = imageBitmap;
mPaint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG);
}
public ImageBitmap getImageBitmap() {
return mImageBitmap;
}
@Override
public boolean setVisible(boolean visible, boolean restart) {
final boolean changed = super.setVisible(visible, restart);
if (mImageBitmap.isAnimated()) {
if (visible) {
if (restart || changed) {
final boolean next = !restart && mRunning;
setFrame(next, true, mAnimating);
}
} else {
unscheduleSelf(this);
}
}
return changed;
}
/**
* Starts the animation, looping if necessary. This method has no effect
* if the animation is running.
* <p>
* <strong>Note:</strong> Do not call this in the
* {@link android.app.Activity#onCreate} method of your activity, because
* the {@link AnimationDrawable} is not yet fully attached to the window.
* If you want to play the animation immediately without requiring
* interaction, then you might want to call it from the
* {@link android.app.Activity#onWindowFocusChanged} method in your
* activity, which will get called when Android brings your window into
* focus.
*
* @see #isRunning()
* @see #stop()
*/
@Override
public void start() {
mAnimating = true;
if (mImageBitmap.isAnimated() && !isRunning()) {
// Start from 0th frame.
setFrame(false, false, true);
}
}
/**
* Stops the animation. This method has no effect if the animation is not
* running.
*
* @see #isRunning()
* @see #start()
*/
@Override
public void stop() {
mAnimating = false;
if (mImageBitmap.isAnimated() && isRunning()) {
unscheduleSelf(this);
}
}
/**
* Indicates whether the animation is currently running or not.
*
* @return true if the animation is running, false otherwise
*/
@Override
public boolean isRunning() {
return mRunning;
}
/**
* This method exists for implementation purpose only and should not be
* called directly. Invoke {@link #start()} instead.
*
* @see #start()
*/
@Override
public void run() {
setFrame(true, false, true);
}
private void setFrame(boolean resetOrNext, boolean unschedule, boolean animate) {
// Check recycled
if (mImageBitmap.isRecycled()) {
return;
}
mAnimating = animate;
if (resetOrNext) {
mImageBitmap.advance();
} else {
mImageBitmap.reset();
}
invalidateSelf();
if (unschedule || animate) {
unscheduleSelf(this);
}
if (animate) {
mRunning = true;
scheduleSelf(this, SystemClock.uptimeMillis() + mImageBitmap.getCurrentDelay());
}
}
@Override
public void unscheduleSelf(@NonNull Runnable what) {
mRunning = false;
super.unscheduleSelf(what);
}
@Override
public void draw(@NonNull Canvas canvas) {
final Bitmap bitmap = mImageBitmap.getBitmap();
if (bitmap != null) {
canvas.drawBitmap(bitmap, null, getBounds(), mPaint);
}
}
@Override
public void setAlpha(int alpha) {
mPaint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
mPaint.setColorFilter(colorFilter);
}
@Override
public int getOpacity() {
return mImageBitmap.isOpaque() ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT;
}
@Override
public int getIntrinsicWidth() {
return mImageBitmap.getWidth();
}
@Override
public int getIntrinsicHeight() {
return mImageBitmap.getHeight();
}
}
| Add TODO
| library/src/main/java/com/hippo/gukize/ImageDrawable.java | Add TODO |
|
Java | apache-2.0 | 92b4d68b6fc2d022bc8299adf5d36c25f5bed4f2 | 0 | chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.web;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.management.*;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
import org.apache.activemq.broker.jmx.*;
import org.springframework.util.StringUtils;
/**
* A useful base class for an implementation of {@link BrokerFacade}
*
*
*/
public abstract class BrokerFacadeSupport implements BrokerFacade {
public abstract ManagementContext getManagementContext();
public abstract Set queryNames(ObjectName name, QueryExp query) throws Exception;
public abstract Object newProxyInstance( ObjectName objectName, Class interfaceClass, boolean notificationBroadcaster) throws Exception;
public Collection<QueueViewMBean> getQueues() throws Exception {
BrokerViewMBean broker = getBrokerAdmin();
if (broker == null) {
return Collections.EMPTY_LIST;
}
ObjectName[] queues = broker.getQueues();
return getManagedObjects(queues, QueueViewMBean.class);
}
public Collection<TopicViewMBean> getTopics() throws Exception {
BrokerViewMBean broker = getBrokerAdmin();
if (broker == null) {
return Collections.EMPTY_LIST;
}
ObjectName[] queues = broker.getTopics();
return getManagedObjects(queues, TopicViewMBean.class);
}
public Collection<DurableSubscriptionViewMBean> getDurableTopicSubscribers() throws Exception {
BrokerViewMBean broker = getBrokerAdmin();
if (broker == null) {
return Collections.EMPTY_LIST;
}
ObjectName[] queues = broker.getDurableTopicSubscribers();
return getManagedObjects(queues, DurableSubscriptionViewMBean.class);
}
public Collection<DurableSubscriptionViewMBean> getInactiveDurableTopicSubscribers() throws Exception {
BrokerViewMBean broker = getBrokerAdmin();
if (broker == null) {
return Collections.EMPTY_LIST;
}
ObjectName[] queues = broker.getInactiveDurableTopicSubscribers();
return getManagedObjects(queues, DurableSubscriptionViewMBean.class);
}
public QueueViewMBean getQueue(String name) throws Exception {
return (QueueViewMBean) getDestinationByName(getQueues(), name);
}
public TopicViewMBean getTopic(String name) throws Exception {
return (TopicViewMBean) getDestinationByName(getTopics(), name);
}
protected DestinationViewMBean getDestinationByName(Collection<? extends DestinationViewMBean> collection,
String name) {
Iterator<? extends DestinationViewMBean> iter = collection.iterator();
while (iter.hasNext()) {
DestinationViewMBean destinationViewMBean = iter.next();
if (name.equals(destinationViewMBean.getName())) {
return destinationViewMBean;
}
}
return null;
}
@SuppressWarnings("unchecked")
protected <T> Collection<T> getManagedObjects(ObjectName[] names, Class<T> type) throws Exception {
List<T> answer = new ArrayList<T>();
for (int i = 0; i < names.length; i++) {
ObjectName name = names[i];
T value = (T) newProxyInstance(name, type, true);
if (value != null) {
answer.add(value);
}
}
return answer;
}
@SuppressWarnings("unchecked")
public Collection<ConnectionViewMBean> getConnections() throws Exception {
String brokerName = getBrokerName();
ObjectName query = new ObjectName("org.apache.activemq:BrokerName=" + brokerName + ",Type=Connection,ConnectorName=*,Connection=*");
Set<ObjectName> queryResult = queryNames(query, null);
return getManagedObjects(queryResult.toArray(new ObjectName[queryResult.size()]), ConnectionViewMBean.class);
}
@SuppressWarnings("unchecked")
public Collection<String> getConnections(String connectorName) throws Exception {
String brokerName = getBrokerName();
ObjectName query = new ObjectName("org.apache.activemq:BrokerName=" + brokerName
+ ",Type=Connection,ConnectorName=" + connectorName + ",Connection=*");
Set<ObjectName> queryResult = queryNames(query, null);
Collection<String> result = new ArrayList<String>(queryResult.size());
for (ObjectName on : queryResult) {
String name = StringUtils.replace(on.getKeyProperty("Connection"), "_", ":");
result.add(name);
}
return result;
}
@SuppressWarnings("unchecked")
public ConnectionViewMBean getConnection(String connectionName) throws Exception {
connectionName = StringUtils.replace(connectionName, ":", "_");
String brokerName = getBrokerName();
ObjectName query = new ObjectName("org.apache.activemq:BrokerName=" + brokerName
+ ",Type=Connection,*,Connection=" + connectionName);
Set<ObjectName> queryResult = queryNames(query, null);
if (queryResult.size() == 0)
return null;
ObjectName objectName = queryResult.iterator().next();
return (ConnectionViewMBean) newProxyInstance(objectName, ConnectionViewMBean.class,
true);
}
@SuppressWarnings("unchecked")
public Collection<String> getConnectors() throws Exception {
String brokerName = getBrokerName();
ObjectName query = new ObjectName("org.apache.activemq:BrokerName=" + brokerName + ",Type=Connector,*");
Set<ObjectName> queryResult = queryNames(query, null);
Collection<String> result = new ArrayList<String>(queryResult.size());
for (ObjectName on : queryResult)
result.add(on.getKeyProperty("ConnectorName"));
return result;
}
public ConnectorViewMBean getConnector(String name) throws Exception {
String brokerName = getBrokerName();
ObjectName objectName = new ObjectName("org.apache.activemq:BrokerName=" + brokerName
+ ",Type=Connector,ConnectorName=" + name);
return (ConnectorViewMBean) newProxyInstance(objectName, ConnectorViewMBean.class, true);
}
@SuppressWarnings("unchecked")
public Collection<NetworkConnectorViewMBean> getNetworkConnectors() throws Exception {
String brokerName = getBrokerName();
ObjectName query = new ObjectName("org.apache.activemq:BrokerName=" + brokerName + ",Type=NetworkConnector,*");
Set<ObjectName> queryResult = queryNames(query, null);
return getManagedObjects(queryResult.toArray(new ObjectName[queryResult.size()]),
NetworkConnectorViewMBean.class);
}
public Collection<NetworkBridgeViewMBean> getNetworkBridges() throws Exception {
String brokerName = getBrokerName();
ObjectName query = new ObjectName("org.apache.activemq:BrokerName=" + brokerName + ",Type=NetworkBridge,*");
Set<ObjectName> queryResult = queryNames(query, null);
return getManagedObjects(queryResult.toArray(new ObjectName[queryResult.size()]),
NetworkBridgeViewMBean.class);
}
@SuppressWarnings("unchecked")
public Collection<SubscriptionViewMBean> getQueueConsumers(String queueName) throws Exception {
String brokerName = getBrokerName();
queueName = StringUtils.replace(queueName, "\"", "_");
ObjectName query = new ObjectName("org.apache.activemq:BrokerName=" + brokerName
+ ",Type=Subscription,destinationType=Queue,destinationName=" + queueName + ",*");
Set<ObjectName> queryResult = queryNames(query, null);
return getManagedObjects(queryResult.toArray(new ObjectName[queryResult.size()]), SubscriptionViewMBean.class);
}
@SuppressWarnings("unchecked")
public Collection<SubscriptionViewMBean> getConsumersOnConnection(String connectionName) throws Exception {
connectionName = StringUtils.replace(connectionName, ":", "_");
String brokerName = getBrokerName();
ObjectName query = new ObjectName("org.apache.activemq:BrokerName=" + brokerName
+ ",Type=Subscription,clientId=" + connectionName + ",*");
Set<ObjectName> queryResult = queryNames(query, null);
return getManagedObjects(queryResult.toArray(new ObjectName[queryResult.size()]), SubscriptionViewMBean.class);
}
public JobSchedulerViewMBean getJobScheduler() throws Exception {
ObjectName name = getBrokerAdmin().getJMSJobScheduler();
return (JobSchedulerViewMBean) newProxyInstance(name, JobSchedulerViewMBean.class, true);
}
public Collection<JobFacade> getScheduledJobs() throws Exception {
JobSchedulerViewMBean jobScheduler = getJobScheduler();
List<JobFacade> result = new ArrayList<JobFacade>();
TabularData table = jobScheduler.getAllJobs();
for (Object object : table.values()) {
CompositeData cd = (CompositeData) object;
JobFacade jf = new JobFacade(cd);
result.add(jf);
}
return result;
}
public boolean isJobSchedulerStarted() {
try {
JobSchedulerViewMBean jobScheduler = getJobScheduler();
return true;
} catch (Exception e) {
return false;
}
}
}
| activemq-web/src/main/java/org/apache/activemq/web/BrokerFacadeSupport.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.web;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.management.ObjectName;
import javax.management.QueryExp;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
import org.apache.activemq.broker.jmx.*;
import org.springframework.util.StringUtils;
/**
* A useful base class for an implementation of {@link BrokerFacade}
*
*
*/
public abstract class BrokerFacadeSupport implements BrokerFacade {
public abstract ManagementContext getManagementContext();
public abstract Set queryNames(ObjectName name, QueryExp query) throws Exception;
public abstract Object newProxyInstance( ObjectName objectName, Class interfaceClass, boolean notificationBroadcaster) throws Exception;
public Collection<QueueViewMBean> getQueues() throws Exception {
BrokerViewMBean broker = getBrokerAdmin();
if (broker == null) {
return Collections.EMPTY_LIST;
}
ObjectName[] queues = broker.getQueues();
return getManagedObjects(queues, QueueViewMBean.class);
}
public Collection<TopicViewMBean> getTopics() throws Exception {
BrokerViewMBean broker = getBrokerAdmin();
if (broker == null) {
return Collections.EMPTY_LIST;
}
ObjectName[] queues = broker.getTopics();
return getManagedObjects(queues, TopicViewMBean.class);
}
public Collection<DurableSubscriptionViewMBean> getDurableTopicSubscribers() throws Exception {
BrokerViewMBean broker = getBrokerAdmin();
if (broker == null) {
return Collections.EMPTY_LIST;
}
ObjectName[] queues = broker.getDurableTopicSubscribers();
return getManagedObjects(queues, DurableSubscriptionViewMBean.class);
}
public Collection<DurableSubscriptionViewMBean> getInactiveDurableTopicSubscribers() throws Exception {
BrokerViewMBean broker = getBrokerAdmin();
if (broker == null) {
return Collections.EMPTY_LIST;
}
ObjectName[] queues = broker.getInactiveDurableTopicSubscribers();
return getManagedObjects(queues, DurableSubscriptionViewMBean.class);
}
public QueueViewMBean getQueue(String name) throws Exception {
return (QueueViewMBean) getDestinationByName(getQueues(), name);
}
public TopicViewMBean getTopic(String name) throws Exception {
return (TopicViewMBean) getDestinationByName(getTopics(), name);
}
protected DestinationViewMBean getDestinationByName(Collection<? extends DestinationViewMBean> collection,
String name) {
Iterator<? extends DestinationViewMBean> iter = collection.iterator();
while (iter.hasNext()) {
DestinationViewMBean destinationViewMBean = iter.next();
if (name.equals(destinationViewMBean.getName())) {
return destinationViewMBean;
}
}
return null;
}
@SuppressWarnings("unchecked")
protected <T> Collection<T> getManagedObjects(ObjectName[] names, Class<T> type) throws Exception {
List<T> answer = new ArrayList<T>();
for (int i = 0; i < names.length; i++) {
ObjectName name = names[i];
T value = (T) newProxyInstance(name, type, true);
if (value != null) {
answer.add(value);
}
}
return answer;
}
@SuppressWarnings("unchecked")
public Collection<ConnectionViewMBean> getConnections() throws Exception {
String brokerName = getBrokerName();
ObjectName query = new ObjectName("org.apache.activemq:BrokerName=" + brokerName + ",Type=Connection,*");
Set<ObjectName> queryResult = queryNames(query, null);
return getManagedObjects(queryResult.toArray(new ObjectName[queryResult.size()]), ConnectionViewMBean.class);
}
@SuppressWarnings("unchecked")
public Collection<String> getConnections(String connectorName) throws Exception {
String brokerName = getBrokerName();
ObjectName query = new ObjectName("org.apache.activemq:BrokerName=" + brokerName
+ ",Type=Connection,ConnectorName=" + connectorName + ",*");
Set<ObjectName> queryResult = queryNames(query, null);
Collection<String> result = new ArrayList<String>(queryResult.size());
for (ObjectName on : queryResult) {
String name = StringUtils.replace(on.getKeyProperty("Connection"), "_", ":");
result.add(name);
}
return result;
}
@SuppressWarnings("unchecked")
public ConnectionViewMBean getConnection(String connectionName) throws Exception {
connectionName = StringUtils.replace(connectionName, ":", "_");
String brokerName = getBrokerName();
ObjectName query = new ObjectName("org.apache.activemq:BrokerName=" + brokerName
+ ",Type=Connection,*,Connection=" + connectionName);
Set<ObjectName> queryResult = queryNames(query, null);
if (queryResult.size() == 0)
return null;
ObjectName objectName = queryResult.iterator().next();
return (ConnectionViewMBean) newProxyInstance(objectName, ConnectionViewMBean.class,
true);
}
@SuppressWarnings("unchecked")
public Collection<String> getConnectors() throws Exception {
String brokerName = getBrokerName();
ObjectName query = new ObjectName("org.apache.activemq:BrokerName=" + brokerName + ",Type=Connector,*");
Set<ObjectName> queryResult = queryNames(query, null);
Collection<String> result = new ArrayList<String>(queryResult.size());
for (ObjectName on : queryResult)
result.add(on.getKeyProperty("ConnectorName"));
return result;
}
public ConnectorViewMBean getConnector(String name) throws Exception {
String brokerName = getBrokerName();
ObjectName objectName = new ObjectName("org.apache.activemq:BrokerName=" + brokerName
+ ",Type=Connector,ConnectorName=" + name);
return (ConnectorViewMBean) newProxyInstance(objectName, ConnectorViewMBean.class, true);
}
@SuppressWarnings("unchecked")
public Collection<NetworkConnectorViewMBean> getNetworkConnectors() throws Exception {
String brokerName = getBrokerName();
ObjectName query = new ObjectName("org.apache.activemq:BrokerName=" + brokerName + ",Type=NetworkConnector,*");
Set<ObjectName> queryResult = queryNames(query, null);
return getManagedObjects(queryResult.toArray(new ObjectName[queryResult.size()]),
NetworkConnectorViewMBean.class);
}
public Collection<NetworkBridgeViewMBean> getNetworkBridges() throws Exception {
String brokerName = getBrokerName();
ObjectName query = new ObjectName("org.apache.activemq:BrokerName=" + brokerName + ",Type=NetworkBridge,*");
Set<ObjectName> queryResult = queryNames(query, null);
return getManagedObjects(queryResult.toArray(new ObjectName[queryResult.size()]),
NetworkBridgeViewMBean.class);
}
@SuppressWarnings("unchecked")
public Collection<SubscriptionViewMBean> getQueueConsumers(String queueName) throws Exception {
String brokerName = getBrokerName();
queueName = StringUtils.replace(queueName, "\"", "_");
ObjectName query = new ObjectName("org.apache.activemq:BrokerName=" + brokerName
+ ",Type=Subscription,destinationType=Queue,destinationName=" + queueName + ",*");
Set<ObjectName> queryResult = queryNames(query, null);
return getManagedObjects(queryResult.toArray(new ObjectName[queryResult.size()]), SubscriptionViewMBean.class);
}
@SuppressWarnings("unchecked")
public Collection<SubscriptionViewMBean> getConsumersOnConnection(String connectionName) throws Exception {
connectionName = StringUtils.replace(connectionName, ":", "_");
String brokerName = getBrokerName();
ObjectName query = new ObjectName("org.apache.activemq:BrokerName=" + brokerName
+ ",Type=Subscription,clientId=" + connectionName + ",*");
Set<ObjectName> queryResult = queryNames(query, null);
return getManagedObjects(queryResult.toArray(new ObjectName[queryResult.size()]), SubscriptionViewMBean.class);
}
public JobSchedulerViewMBean getJobScheduler() throws Exception {
ObjectName name = getBrokerAdmin().getJMSJobScheduler();
return (JobSchedulerViewMBean) newProxyInstance(name, JobSchedulerViewMBean.class, true);
}
public Collection<JobFacade> getScheduledJobs() throws Exception {
JobSchedulerViewMBean jobScheduler = getJobScheduler();
List<JobFacade> result = new ArrayList<JobFacade>();
TabularData table = jobScheduler.getAllJobs();
for (Object object : table.values()) {
CompositeData cd = (CompositeData) object;
JobFacade jf = new JobFacade(cd);
result.add(jf);
}
return result;
}
public boolean isJobSchedulerStarted() {
try {
JobSchedulerViewMBean jobScheduler = getJobScheduler();
return true;
} catch (Exception e) {
return false;
}
}
}
| https://issues.apache.org/jira/browse/AMQ-3381 - connections.jsp double rows
git-svn-id: d2a93f579bd4835921162e9a69396c846e49961c@1141034 13f79535-47bb-0310-9956-ffa450edef68
| activemq-web/src/main/java/org/apache/activemq/web/BrokerFacadeSupport.java | https://issues.apache.org/jira/browse/AMQ-3381 - connections.jsp double rows |
|
Java | apache-2.0 | e477b8bb4574f0e3b8e3d6d5bfe8218b1801b8e6 | 0 | gxa/gxa,gxa/gxa,gxa/gxa,gxa/gxa,gxa/gxa | package uk.ac.ebi.gxa.loader.steps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.MAGETABInvestigation;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.SDRF;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.SDRFNode;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.ScanNode;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.SourceNode;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.attribute.CharacteristicsAttribute;
import uk.ac.ebi.arrayexpress2.magetab.utils.MAGETABUtils;
import uk.ac.ebi.arrayexpress2.magetab.utils.SDRFUtils;
import uk.ac.ebi.gxa.analytics.compute.AtlasComputeService;
import uk.ac.ebi.gxa.analytics.compute.ComputeTask;
import uk.ac.ebi.gxa.analytics.compute.RUtil;
import uk.ac.ebi.gxa.loader.AtlasLoaderException;
import uk.ac.ebi.gxa.loader.cache.AtlasLoadCache;
import uk.ac.ebi.gxa.loader.dao.LoaderDAO;
import uk.ac.ebi.gxa.loader.datamatrix.DataMatrixFileBuffer;
import uk.ac.ebi.gxa.utils.FileUtil;
import uk.ac.ebi.microarray.atlas.model.Assay;
import uk.ac.ebi.rcloud.server.RServices;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HTSArrayDataStep {
private final static Logger log = LoggerFactory.getLogger(HTSArrayDataStep.class);
private static final String RDATA = "eset_notstd_rpkm.RData";
public static String displayName() {
return "Processing HTS data";
}
public void readHTSData(MAGETABInvestigation investigation, AtlasComputeService computeService, AtlasLoadCache cache, LoaderDAO dao) throws AtlasLoaderException {
log.info("Starting HTS data load");
// sdrf location
URL sdrfURL = investigation.SDRF.getLocation();
//run files through the pipeline
File outFilePath = runPipeline(sdrfURL, computeService);
// try to get the relative filename
URL dataMatrixURL = convertPathToULR(sdrfURL, outFilePath);
DataMatrixFileBuffer buffer = cache.getDataMatrixFileBuffer(dataMatrixURL, null, false);
// find the type of nodes we need - lookup from data matrix buffer
String refNodeName = buffer.getReferenceColumnName();
// fetch the references from the buffer
List<String> refNames = buffer.getReferences();
// for each refName, identify the assay the expression values relate to
for (int refIndex = 0; refIndex < refNames.size(); ++refIndex) {
String refName = refNames.get(refIndex);
log.debug("Attempting to attach expression values to next reference " + refName);
if (refNodeName.equals("scanname")) {
// this requires mapping the assay upstream of this node to the scan
// no need to block, since if we are reading data, we've parsed the scans already
// SDRFNode refNode = investigation.SDRF.lookupNode(refName, refNodeName);
ScanNode refNode = lookupScanNodeWithComment(investigation.SDRF, "ENA_RUN", refName);
if (refNode == null) {
// generate error item and throw exception
throw new AtlasLoaderException("Could not find " + refName + " [" + refNodeName + "] in SDRF");
}
String enaRunName = refNode.comments.get("ENA_RUN");
Assay assay = cache.fetchAssay(enaRunName);
if (assay != null) {
log.trace("Updating assay {} with expression values, must be stored first...", assay);
cache.setAssayDataMatrixRef(assay, buffer.getStorage(), refIndex);
if (assay.getArrayDesign() == null) {
assay.setArrayDesign(dao.getArrayDesignShallow(findArrayDesignAcc(refNode)));
}
} else {
// generate error item and throw exception
throw new AtlasLoaderException("Data file references elements that are not present in the SDRF (" + refNodeName + ", " + refName + ")");
}
}
}
if (!outFilePath.delete()) {
log.error("Temp file " + outFilePath + " wasn't deleted!");
}
}
private static ScanNode lookupScanNodeWithComment(SDRF sdrf, String commentType, String commentName) {
Collection<? extends SDRFNode> nodes = sdrf.lookupNodes(MAGETABUtils.digestHeader("scanname"));
for (SDRFNode node : nodes) {
ScanNode scanNode = (ScanNode) node;
Map<String, String> comments = scanNode.comments;
String commentValue = comments.get(commentType);
if (commentValue != null && commentValue.equals(commentName)) {
return scanNode;
}
}
// if we get to here, either we have no node of this type or none with the same name
return null;
}
private static URL convertPathToULR(URL sdrfURL, File outFilePath) throws AtlasLoaderException {
URL dataMatrixURL;// NB. making sure we replace File separators with '/' to guard against windows issues
try {
dataMatrixURL = sdrfURL.getPort() == -1
? new URL(sdrfURL.getProtocol(),
sdrfURL.getHost(),
outFilePath.toString().replaceAll("\\\\", "/"))
: new URL(sdrfURL.getProtocol(),
sdrfURL.getHost(),
sdrfURL.getPort(),
outFilePath.toString().replaceAll("\\\\", "/"));
} catch (MalformedURLException e) {
// generate error item and throw exception
throw new AtlasLoaderException(
"Cannot formulate the URL to retrieve the " +
"DerivedArrayDataMatrix," +
" this file could not be found relative to " + sdrfURL);
}
// now, obtain a buffer for this dataMatrixFile
log.debug("Opening buffer of data matrix file at " + dataMatrixURL);
return dataMatrixURL;
}
private static File runPipeline(URL sdrfURL, AtlasComputeService computeService) throws AtlasLoaderException {
//ToDo: this code will be removed once a whole pipeline is integrated
// The directory structure is like that:
// EXP_ACC
// -data
// -- *.idf
// -- *.sdrf
// -esetcount.RData
File sdrfFilePath = new File(sdrfURL.getFile());
File inFilePath = new File(sdrfFilePath.getParentFile().getParentFile(), RDATA);
if (!inFilePath.exists()) {
//Try to look for RData in the same directory as sdrf file
inFilePath = new File(sdrfFilePath.getParentFile(), RDATA);
if (!inFilePath.exists()) {
throw new AtlasLoaderException("File with R object (" + RDATA + ") is not found neither in " +
sdrfFilePath.getParentFile() + " nor in " + sdrfFilePath.getParentFile().getParentFile() + " directories.");
}
}
File tempDir = FileUtil.getTempDirectory();
if (!tempDir.setWritable(true, false)) {
log.error("Directory {} cannot be set to writable by all!", tempDir);
throw new AtlasLoaderException("Cannot set to writable by all directory " + tempDir + " which is needed to keep temp data from R pipeline.");
}
File outFilePath = new File(tempDir, "out.txt");
log.debug("Output file " + outFilePath);
final String inFile = inFilePath.getAbsolutePath();
final String outFile = outFilePath.getAbsolutePath();
RRunner rRunner = new RRunner(inFile, outFile);
computeService.computeTask(rRunner);
//Sometimes R finishes writing file with a delay
boolean fileExists = false;
try {
for (int i = 0; i < 100; i++) {
Thread.sleep(2000);
if (outFilePath.exists()) {
fileExists = true;
break;
}
}
} catch (InterruptedException e) {
log.info(e.getMessage(), e);
//this exception can be ignored
}
if (!fileExists) {
throw new AtlasLoaderException("File " + outFilePath + " hasn't been created");
}
return outFilePath;
}
private static Map<String, String> organismToArrayDesign = new HashMap<String, String>(20);
static {
organismToArrayDesign.put("Homo sapiens", "A-ENST-3");
organismToArrayDesign.put("Mus musculus", "A-ENST-4");
organismToArrayDesign.put("drosophila melanogaster", "A-ENST-5");
organismToArrayDesign.put("danio rerio", "A-ENST-6");
organismToArrayDesign.put("rattus norvegicus", "A-ENST-7");
organismToArrayDesign.put("ciona savignyi", "A-ENST-8");
organismToArrayDesign.put("equus caballus", "A-ENST-9");
organismToArrayDesign.put("sus scrofa", "A-ENST-10");
organismToArrayDesign.put("gallus gallus", "A-ENST-11");
organismToArrayDesign.put("saccharomyces cerevisiae", "A-ENST-12");
}
//ToDo: this is only temp solution! Array design will not be used for RNA-seq experiments
private static String findArrayDesignAcc(SDRFNode node) throws AtlasLoaderException {
Collection<SourceNode> nodeCollection = SDRFUtils.findUpstreamNodes(node, SourceNode.class);
for (SourceNode sourceNode : nodeCollection) {
for (CharacteristicsAttribute characteristic : sourceNode.characteristics) {
if ("Organism".equals(characteristic.type)) {
String arrayDesignAcc = organismToArrayDesign.get(characteristic.getNodeName());
if (arrayDesignAcc == null) {
throw new AtlasLoaderException("Cannot find virtual array design for organism " + characteristic.getNodeName());
}
return arrayDesignAcc;
}
}
}
throw new AtlasLoaderException("No organism is specified in " + node.getNodeName());
}
private static class RRunner implements ComputeTask<Void> {
public final String infname;
public final String outfname;
private RRunner(String inputFile, String outputFile) {
this.infname = inputFile;
this.outfname = outputFile;
}
public Void compute(RServices rs) throws RemoteException {
rs.sourceFromBuffer("infname = '" + infname + "'");
rs.sourceFromBuffer("outfname = '" + outfname + "'");
rs.sourceFromBuffer(RUtil.getRCodeFromResource("R/htsProcessPipeline.R"));
rs.sourceFromBuffer("esetToTextFile(infname = infname, outfname = outfname)");
return null;
}
}
}
| atlas-loader/src/main/java/uk/ac/ebi/gxa/loader/steps/HTSArrayDataStep.java | package uk.ac.ebi.gxa.loader.steps;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.MAGETABInvestigation;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.SDRF;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.SDRFNode;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.ScanNode;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.SourceNode;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.attribute.CharacteristicsAttribute;
import uk.ac.ebi.arrayexpress2.magetab.utils.MAGETABUtils;
import uk.ac.ebi.arrayexpress2.magetab.utils.SDRFUtils;
import uk.ac.ebi.gxa.analytics.compute.AtlasComputeService;
import uk.ac.ebi.gxa.analytics.compute.ComputeTask;
import uk.ac.ebi.gxa.analytics.compute.RUtil;
import uk.ac.ebi.gxa.loader.AtlasLoaderException;
import uk.ac.ebi.gxa.loader.cache.AtlasLoadCache;
import uk.ac.ebi.gxa.loader.dao.LoaderDAO;
import uk.ac.ebi.gxa.loader.datamatrix.DataMatrixFileBuffer;
import uk.ac.ebi.gxa.utils.FileUtil;
import uk.ac.ebi.microarray.atlas.model.Assay;
import uk.ac.ebi.rcloud.server.RServices;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class HTSArrayDataStep {
private final static Logger log = LoggerFactory.getLogger(HTSArrayDataStep.class);
private static final String RDATA = "eset_notstd_rpkm.RData";
public static String displayName() {
return "Processing HTS data";
}
public void readHTSData(MAGETABInvestigation investigation, AtlasComputeService computeService, AtlasLoadCache cache, LoaderDAO dao) throws AtlasLoaderException {
log.info("Starting HTS data load");
// sdrf location
URL sdrfURL = investigation.SDRF.getLocation();
//run files through the pipeline
File outFilePath = runPipeline(sdrfURL, computeService);
// try to get the relative filename
URL dataMatrixURL = convertPathToULR(sdrfURL, outFilePath);
DataMatrixFileBuffer buffer = cache.getDataMatrixFileBuffer(dataMatrixURL, null, false);
// find the type of nodes we need - lookup from data matrix buffer
String refNodeName = buffer.getReferenceColumnName();
// fetch the references from the buffer
List<String> refNames = buffer.getReferences();
// for each refName, identify the assay the expression values relate to
for (int refIndex = 0; refIndex < refNames.size(); ++refIndex) {
String refName = refNames.get(refIndex);
log.debug("Attempting to attach expression values to next reference " + refName);
if (refNodeName.equals("scanname")) {
// this requires mapping the assay upstream of this node to the scan
// no need to block, since if we are reading data, we've parsed the scans already
// SDRFNode refNode = investigation.SDRF.lookupNode(refName, refNodeName);
ScanNode refNode = lookupScanNodeWithComment(investigation.SDRF, "ENA_RUN", refName);
if (refNode == null) {
// generate error item and throw exception
throw new AtlasLoaderException("Could not find " + refName + " [" + refNodeName + "] in SDRF");
}
String enaRunName = refNode.comments.get("ENA_RUN");
Assay assay = cache.fetchAssay(enaRunName);
if (assay != null) {
log.trace("Updating assay {} with expression values, must be stored first...", assay);
cache.setAssayDataMatrixRef(assay, buffer.getStorage(), refIndex);
if (assay.getArrayDesign() == null) {
assay.setArrayDesign(dao.getArrayDesignShallow(findArrayDesignName(refNode)));
}
} else {
// generate error item and throw exception
throw new AtlasLoaderException("Data file references elements that are not present in the SDRF (" + refNodeName + ", " + refName + ")");
}
}
}
if (!outFilePath.delete()) {
log.error("Temp file " + outFilePath + " wasn't deleted!");
}
}
private static ScanNode lookupScanNodeWithComment(SDRF sdrf, String commentType, String commentName) {
Collection<? extends SDRFNode> nodes = sdrf.lookupNodes(MAGETABUtils.digestHeader("scanname"));
for (SDRFNode node : nodes) {
ScanNode scanNode = (ScanNode) node;
Map<String, String> comments = scanNode.comments;
String commentValue = comments.get(commentType);
if (commentValue != null && commentValue.equals(commentName)) {
return scanNode;
}
}
// if we get to here, either we have no node of this type or none with the same name
return null;
}
private static URL convertPathToULR(URL sdrfURL, File outFilePath) throws AtlasLoaderException {
URL dataMatrixURL;// NB. making sure we replace File separators with '/' to guard against windows issues
try {
dataMatrixURL = sdrfURL.getPort() == -1
? new URL(sdrfURL.getProtocol(),
sdrfURL.getHost(),
outFilePath.toString().replaceAll("\\\\", "/"))
: new URL(sdrfURL.getProtocol(),
sdrfURL.getHost(),
sdrfURL.getPort(),
outFilePath.toString().replaceAll("\\\\", "/"));
} catch (MalformedURLException e) {
// generate error item and throw exception
throw new AtlasLoaderException(
"Cannot formulate the URL to retrieve the " +
"DerivedArrayDataMatrix," +
" this file could not be found relative to " + sdrfURL);
}
// now, obtain a buffer for this dataMatrixFile
log.debug("Opening buffer of data matrix file at " + dataMatrixURL);
return dataMatrixURL;
}
private static File runPipeline(URL sdrfURL, AtlasComputeService computeService) throws AtlasLoaderException {
//ToDo: this code will be removed once a whole pipeline is integrated
// The directory structure is like that:
// EXP_ACC
// -data
// -- *.idf
// -- *.sdrf
// -esetcount.RData
File sdrfFilePath = new File(sdrfURL.getFile());
File inFilePath = new File(sdrfFilePath.getParentFile().getParentFile(), RDATA);
if (!inFilePath.exists()) {
//Try to look for RData in the same directory as sdrf file
inFilePath = new File(sdrfFilePath.getParentFile(), RDATA);
if (!inFilePath.exists()) {
throw new AtlasLoaderException("File with R object (" + RDATA + ") is not found neither in " +
sdrfFilePath.getParentFile() + " nor in " + sdrfFilePath.getParentFile().getParentFile() + " directories.");
}
}
File tempDir = FileUtil.getTempDirectory();
if (!tempDir.setWritable(true, false)) {
log.error("Directory {} cannot be set to writable by all!", tempDir);
throw new AtlasLoaderException("Cannot set to writable by all directory " + tempDir + " which is needed to keep temp data from R pipeline.");
}
File outFilePath = new File(tempDir, "out.txt");
log.debug("Output file " + outFilePath);
final String inFile = inFilePath.getAbsolutePath();
final String outFile = outFilePath.getAbsolutePath();
RRunner rRunner = new RRunner(inFile, outFile);
computeService.computeTask(rRunner);
//Sometimes R finishes writing file with a delay
boolean fileExists = false;
try {
for (int i = 0; i < 100; i++) {
Thread.sleep(2000);
if (outFilePath.exists()) {
fileExists = true;
break;
}
}
} catch (InterruptedException e) {
log.info(e.getMessage(), e);
//this exception can be ignored
}
if (!fileExists) {
throw new AtlasLoaderException("File " + outFilePath + " hasn't been created");
}
return outFilePath;
}
//ToDo: this is only temp solution! Array design will not be user for RNA-seq experiments
private static String findArrayDesignName(SDRFNode node) {
Collection<SourceNode> nodeCollection = SDRFUtils.findUpstreamNodes(node, SourceNode.class);
for (SourceNode sourceNode : nodeCollection) {
for (CharacteristicsAttribute characteristic : sourceNode.characteristics) {
if ("Organism".equals(characteristic.type)) {
if ("Homo sapiens".equalsIgnoreCase(characteristic.getNodeName())) {
return "A-ENST-3";
} else if ("Mus musculus".equalsIgnoreCase(characteristic.getNodeName())) {
return "A-ENST-4";
} else if ("drosophila melanogaster".equalsIgnoreCase(characteristic.getNodeName())) {
return "A-ENST-5";
} else if ("danio rerio".equalsIgnoreCase(characteristic.getNodeName())) {
return "A-ENST-6";
} else if ("rattus norvegicus".equalsIgnoreCase(characteristic.getNodeName())) {
return "A-ENST-7";
} else if ("ciona savignyi".equalsIgnoreCase(characteristic.getNodeName())) {
return "A-ENST-8";
} else if ("equus caballus".equalsIgnoreCase(characteristic.getNodeName())) {
return "A-ENST-9";
} else if ("sus scrofa".equalsIgnoreCase(characteristic.getNodeName())) {
return "A-ENST-10";
}
}
}
}
return StringUtils.EMPTY;
}
private static class RRunner implements ComputeTask<Void> {
public final String infname;
public final String outfname;
private RRunner(String inputFile, String outputFile) {
this.infname = inputFile;
this.outfname = outputFile;
}
public Void compute(RServices rs) throws RemoteException {
rs.sourceFromBuffer("infname = '" + infname + "'");
rs.sourceFromBuffer("outfname = '" + outfname + "'");
rs.sourceFromBuffer(RUtil.getRCodeFromResource("R/htsProcessPipeline.R"));
rs.sourceFromBuffer("esetToTextFile(infname = infname, outfname = outfname)");
return null;
}
}
}
| introduced map, exception is thrown if no array design corresponding to organism found
| atlas-loader/src/main/java/uk/ac/ebi/gxa/loader/steps/HTSArrayDataStep.java | introduced map, exception is thrown if no array design corresponding to organism found |
|
Java | apache-2.0 | b784f3c49bc0c8d2f080de19e785629a8374d8c7 | 0 | collectivemedia/celos,collectivemedia/celos,collectivemedia/celos | package com.collective.celos.ui;
import junit.framework.Assert;
import org.apache.commons.cli.*;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
public class UICommandLineParserTest {
@Test
public void testParsesOk() throws Exception {
UICommandLineParser parser = new UICommandLineParser();
String[] clParams = ("--celos http://localhost:8888 --port 1234").split(" ");
UICommandLine commandLine = parser.parse(clParams);
Assert.assertEquals(commandLine.getCelosUrl(), new URL("http://localhost:8888"));
Assert.assertEquals(commandLine.getPort(), 1234);
}
@Test(expected = IllegalArgumentException.class)
public void testPortMissing() throws Exception {
UICommandLineParser parser = new UICommandLineParser();
String[] clParams = ("--celos localhost:8888").split(" ");
parser.parse(clParams);
}
@Test(expected = IllegalArgumentException.class)
public void testCelosURLMissing() throws Exception {
UICommandLineParser parser = new UICommandLineParser();
String[] clParams = ("--port 8888").split(" ");
parser.parse(clParams);
}
@Test(expected = MalformedURLException.class)
public void testWrongAddress() throws Exception {
UICommandLineParser parser = new UICommandLineParser();
String[] clParams = ("--celos localhost:8888 --port 1234").split(" ");
parser.parse(clParams);
}
@Test(expected = NumberFormatException.class)
public void testWrongPort() throws Exception {
UICommandLineParser parser = new UICommandLineParser();
String[] clParams = ("--celos http://localhost:8888 --port abc").split(" ");
parser.parse(clParams);
}
}
| celos-ui/src/test/java/com/collective/celos/ui/UICommandLineParserTest.java | package com.collective.celos.ui;
import junit.framework.Assert;
import org.apache.commons.cli.*;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
public class UICommandLineParserTest {
@Test
public void testParsesOk() throws Exception {
UICommandLineParser parser = new UICommandLineParser();
String[] clParams = ("--celosAddr http://localhost:8888 --port 1234").split(" ");
UICommandLine commandLine = parser.parse(clParams);
Assert.assertEquals(commandLine.getCelosUrl(), new URL("http://localhost:8888"));
Assert.assertEquals(commandLine.getPort(), 1234);
}
@Test(expected = IllegalArgumentException.class)
public void testPortMissing() throws Exception {
UICommandLineParser parser = new UICommandLineParser();
String[] clParams = ("--celosAddr localhost:8888").split(" ");
parser.parse(clParams);
}
@Test(expected = IllegalArgumentException.class)
public void testCelosURLMissing() throws Exception {
UICommandLineParser parser = new UICommandLineParser();
String[] clParams = ("--port 8888").split(" ");
parser.parse(clParams);
}
@Test(expected = MalformedURLException.class)
public void testWrongAddress() throws Exception {
UICommandLineParser parser = new UICommandLineParser();
String[] clParams = ("--celosAddr localhost:8888 --port 1234").split(" ");
parser.parse(clParams);
}
@Test(expected = NumberFormatException.class)
public void testWrongPort() throws Exception {
UICommandLineParser parser = new UICommandLineParser();
String[] clParams = ("--celosAddr http://localhost:8888 --port abc").split(" ");
parser.parse(clParams);
}
}
| fix test
| celos-ui/src/test/java/com/collective/celos/ui/UICommandLineParserTest.java | fix test |
|
Java | apache-2.0 | 01559c4cdfe4179d8ddce8bc98e2670ca0489bee | 0 | joh12041/graphhopper,joh12041/graphhopper,joh12041/graphhopper,joh12041/graphhopper | package com.graphhopper.reader.osm;
import com.graphhopper.GHRequest;
import com.graphhopper.GHResponse;
import com.graphhopper.GraphHopper;
import com.graphhopper.PathWrapper;
import com.graphhopper.matching.MapMatching;
import com.graphhopper.matching.MatchResult;
import com.graphhopper.routing.AlgorithmOptions;
import com.graphhopper.routing.Path;
import com.graphhopper.routing.util.EncodingManager;
import com.graphhopper.routing.util.HintsMap;
import com.graphhopper.util.*;
import java.util.*;
import java.io.*;
import java.util.List;
/**
* Created by isaac on 09/14/16.
*/
public class runKSP {
String city;
String route_type;
ArrayList<FileWriter> outputFiles;
private String osmFile = "./reader-osm/files/";
private String graphFolder = "./reader-osm/target/tmp/";
private String inputPointsFN = "../data/intermediate/";
private String outputPointsFN = "../data/testing/";
private String gvfnStem = "../data/intermediate/";
private String gctfnStem = "../geometries/";
private ArrayList<String> gridValuesFNs = new ArrayList<>();
private ArrayList<String> gridCTsFNs = new ArrayList<>();
private HashMap<String, Integer> gvHeaderMap;
private HashMap<String, Float> gridBeauty;
private HashMap<String, Integer> gridCT;
private GraphHopper hopper;
private MapMatching mapMatching;
private String outputheader = "ID,name,polyline_points,total_time_in_sec,total_distance_in_meters,number_of_steps,maneuvers,beauty,simplicity,numCTs" +
System.getProperty("line.separator");
public runKSP(String city, String route_type) {
this.city = city;
this.route_type = route_type;
this.outputFiles = new ArrayList<>(4);
}
public void setCity(String city) {
this.city = city;
}
public void setRouteType(String route_type) {
this.route_type = route_type;
}
public PathWrapper GPXToPath(ArrayList<GPXEntry> gpxEntries) {
PathWrapper matchGHRsp = new PathWrapper();
try {
MatchResult mr = mapMatching.doWork(gpxEntries);
Path path = mapMatching.calcPath(mr);
new PathMerger().doWork(matchGHRsp, Collections.singletonList(path), new TranslationMap().doImport().getWithFallBack(Locale.US));
}
catch (RuntimeException e) {
System.out.println("Broken GPX trace.");
System.out.println(e.getMessage());
}
return matchGHRsp;
}
public void PointsToPath(String fin, String fout) throws IOException {
Scanner sc_in = new Scanner(new File(fin));
String[] pointsHeader = sc_in.nextLine().split(",");
int idIdx = -1;
int nameIdx = -1;
int latIdx = -1;
int lonIdx = -1;
int timeIdx = -1;
for (int i=0; i<pointsHeader.length; i++) {
if (pointsHeader[i].equalsIgnoreCase("ID")) {
idIdx = i;
}
else if (pointsHeader[i].equalsIgnoreCase("name")) {
nameIdx = i;
}
else if (pointsHeader[i].equalsIgnoreCase("lat")) {
latIdx = i;
}
else if (pointsHeader[i].equalsIgnoreCase("lon")) {
lonIdx = i;
}
else if (pointsHeader[i].equalsIgnoreCase("millis")) {
timeIdx = i;
}
else {
System.out.println("Unexpected header value: " + pointsHeader[i]);
}
}
String optimized = "";
if (fin.indexOf("google") > -1) {
optimized = optimized + "Goog";
} else if (fin.indexOf("mapquest") > -1) {
optimized = optimized + "MapQ";
} else {
System.out.println("Don't recognize platform: " + fin);
}
if (fin.indexOf("alt") > -1) {
optimized = optimized + " altn";
} else if (fin.indexOf("main") > -1) {
optimized = optimized + " main";
} else {
System.out.println("Don't recognize route type: " + fin);
}
String line;
String[] vals;
String routeID = "";
String prevRouteID = "";
String name = "";
String prevName = "";
String label = "";
String prevLabel = "";
double lat;
double lon;
long time;
ArrayList<GPXEntry> pointsList = new ArrayList<>();
PathWrapper path;
FileWriter sc_out = new FileWriter(fout, true);
sc_out.write(outputheader);
int i = 0;
float score;
while (sc_in.hasNext()) {
line = sc_in.nextLine();
vals = line.split(",");
routeID = vals[idIdx];
name = vals[nameIdx];
if (name.equalsIgnoreCase("alternative 2") || name.equalsIgnoreCase("alternative 3")) {
continue;
}
lat = Double.valueOf(vals[latIdx]);
lon = Double.valueOf(vals[lonIdx]);
time = Long.valueOf(vals[timeIdx]);
label = routeID + "|" + name;
GPXEntry pt = new GPXEntry(lat, lon, time);
if (label.equalsIgnoreCase(prevLabel)) {
pointsList.add(pt);
}
else if (pointsList.size() > 0) {
path = GPXToPath(pointsList);
if (path.getDistance() > 0) {
score = getBeauty(path);
writeOutput(sc_out, i, optimized, prevName, prevRouteID, path, score, getNumCTs(path));
}
pointsList.clear();
pointsList.add(pt);
i++;
if (i % 10 == 0) {
for (FileWriter fw : outputFiles) {
fw.flush();
}
}
} else {
System.out.println("First point.");
pointsList.add(pt);
}
prevRouteID = routeID;
prevName = name;
prevLabel = label;
}
if (pointsList.size() > 0) {
path = GPXToPath(pointsList);
if (path.getDistance() > 0) {
score = getBeauty(path);
writeOutput(sc_out, i, optimized, prevName, prevRouteID, path, score, getNumCTs(path));
}
}
sc_out.close();
sc_in.close();
}
//TODO: find some way to match path to virtual nodes at start/finish or hope map-matcher updates
public PathWrapper trimPath(PathWrapper path, ArrayList<GPXEntry> original) {
return new PathWrapper();
}
public void setDataSources() throws Exception {
if (city.equals("sf")) {
osmFile = osmFile + "san-francisco-bay_california.osm.pbf";
graphFolder = graphFolder + "ghosm_sf_noch";
inputPointsFN = inputPointsFN + "sf_" + route_type + "_od_pairs.csv";
outputPointsFN = outputPointsFN + "sf_" + route_type + "_gh_routes.csv";
gridValuesFNs.add(gvfnStem + "06075_logfractionempath_ft.csv");
gridCTsFNs.add(gctfnStem + "06075_ct_grid.csv");
} else if (city.equals("nyc")) {
osmFile = osmFile + "new-york_new-york.osm.pbf";
graphFolder = graphFolder + "ghosm_nyc_noch";
inputPointsFN = inputPointsFN + "nyc_" + route_type + "_od_pairs.csv";
outputPointsFN = outputPointsFN + "nyc_" + route_type + "_gh_routes.csv";
gridValuesFNs.add(gvfnStem + "36005_logfractionempath_ft.csv");
gridValuesFNs.add(gvfnStem + "36047_logfractionempath_ft.csv");
gridValuesFNs.add(gvfnStem + "36061_logfractionempath_ft.csv");
gridValuesFNs.add(gvfnStem + "36081_logfractionempath_ft.csv");
gridValuesFNs.add(gvfnStem + "36085_logfractionempath_ft.csv");
gridCTsFNs.add(gctfnStem + "nyc_ct_grid.csv");
} else if (city.equals("bos")) {
osmFile = osmFile + "boston_massachusetts.osm.pbf";
graphFolder = graphFolder + "ghosm_bos_noch";
inputPointsFN = inputPointsFN + "bos_" + route_type + "_od_pairs.csv";
outputPointsFN = outputPointsFN + "bos_" + route_type + "_gh_routes.csv";
gridValuesFNs.add(gvfnStem + "25025_beauty_twitter.csv");
gridCTsFNs.add(gctfnStem + "25025_ct_grid.csv");
} else {
throw new Exception("Invalid Parameters: city must be of 'SF','NYC', or 'BOS' and route_type of 'grid' or 'rand'");
}
}
public void getGridValues() throws Exception {
gvHeaderMap = new HashMap<>();
gridBeauty = new HashMap<>();
for (String fn : gridValuesFNs) {
Scanner sc_in = new Scanner(new File(fn));
String[] gvHeader = sc_in.nextLine().split(",");
int i = 0;
for (String col : gvHeader) {
gvHeaderMap.put(col, i);
i++;
}
String line;
String[] vals;
String rc;
float beauty;
while (sc_in.hasNext()) {
line = sc_in.nextLine();
vals = line.split(",");
try {
rc = vals[gvHeaderMap.get("rid")] + "," + vals[gvHeaderMap.get("cid")];
beauty = Float.valueOf(vals[gvHeaderMap.get("beauty")]);
gridBeauty.put(rc, beauty);
} catch (NullPointerException ex) {
System.out.println(ex.getMessage());
System.out.println(line);
continue;
}
}
}
}
public void getGridCTs() throws Exception {
gridCT = new HashMap<>();
for (String fn : gridCTsFNs) {
Scanner sc_in = new Scanner(new File(fn));
sc_in.nextLine();
String line;
String[] vals;
String rc;
int ct;
while (sc_in.hasNext()) {
line = sc_in.nextLine();
vals = line.split(",");
try {
rc = vals[1] + "," + vals[0];
ct = Integer.valueOf(vals[2]);
gridCT.put(rc, ct);
} catch (NullPointerException ex) {
System.out.println(ex.getMessage());
System.out.println(line);
continue;
}
}
}
}
public void prepareGraphHopper() {
// create one GraphHopper instance
hopper = new GraphHopperOSM().forDesktop().setCHEnabled(false);
hopper.setDataReaderFile(osmFile);
// where to store graphhopper files?
hopper.setGraphHopperLocation(graphFolder);
hopper.setEncodingManager(new EncodingManager("car"));
// now this can take minutes if it imports or a few seconds for loading
// of course this is dependent on the area you import
hopper.importOrLoad();
}
public void prepMapMatcher() {
// create MapMatching object, can and should be shared accross threads
AlgorithmOptions algoOpts = AlgorithmOptions.start().
algorithm(Parameters.Algorithms.DIJKSTRA).
traversalMode(hopper.getTraversalMode()).
hints(new HintsMap().put("weighting", "fastest").put("vehicle", "car")).
build();
mapMatching = new MapMatching(hopper, algoOpts);
mapMatching.setTransitionProbabilityBeta(0.00959442);
// mapMatching.setTransitionProbabilityBeta(0.000959442);
mapMatching.setMeasurementErrorSigma(100);
}
public void writeOutput(FileWriter fw, int i, String optimized, String name, String od_id, PathWrapper bestPath, float score, int numCTs) throws IOException {
// points, distance in meters and time in seconds (convert from ms) of the full path
PointList pointList = bestPath.getPoints();
int simplicity = bestPath.getSimplicity();
double distance = Math.round(bestPath.getDistance() * 100) / 100;
long timeInSec = bestPath.getTime() / 1000;
InstructionList il = bestPath.getInstructions();
int numDirections = il.getSize();
// iterate over every turn instruction
ArrayList<String> maneuvers = new ArrayList<>();
for (Instruction instruction : il) {
maneuvers.add(instruction.getSimpleTurnDescription());
}
fw.write(od_id + "," + name + "," + "\"[" + pointList + "]\"," + timeInSec + "," + distance + "," + numDirections +
",\"" + maneuvers.toString() + "\"" + "," + score + "," + simplicity + "," + numCTs + System.getProperty("line.separator"));
System.out.println(i + " (" + optimized + "): Distance: " + distance + "m;\tTime: " + timeInSec + "sec;\t# Directions: " + numDirections + ";\tSimplicity: " + simplicity + ";\tScore: " + score + ";\tNumCts: " + numCTs);
}
public int getNumCTs(PathWrapper path) {
HashSet<String> roundedPoints = path.roundPoints();
HashSet<Integer> cts = new HashSet<>();
for (String pt : roundedPoints) {
if (gridCT.containsKey(pt)) {
cts.add(gridCT.get(pt));
}
}
return cts.size();
}
public float getBeauty(PathWrapper path) {
HashSet<String> roundedPoints = path.roundPoints();
float score = 0;
for (String pt : roundedPoints) {
if (gridBeauty.containsKey(pt)) {
score = score + gridBeauty.get(pt);
}
}
score = score / roundedPoints.size();
return score;
}
public void process_routes() throws Exception {
ArrayList<float[]> inputPoints = new ArrayList<float[]>();
ArrayList<String> id_to_points = new ArrayList<String>();
// Prep Filewriters (Optimized, Worst-but-same-distance, Fastest, Simplest)
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_beauty.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_ugly.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_simple.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_fast.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_shortest.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_alt.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_besi.csv"), true));
for (FileWriter fw : outputFiles) {
fw.write(outputheader);
}
// Bring in origin-destination pairs for processing
Scanner sc_in = new Scanner(new File(inputPointsFN));
String header = sc_in.nextLine();
String od_id;
float laF;
float loF;
float laT;
float loT;
float idx = 0;
System.out.println("Input data points header: " + header);
while (sc_in.hasNext()) {
idx = idx + 1;
String line = sc_in.nextLine();
String[] vals = line.split(",");
od_id = vals[0];
loF = Float.valueOf(vals[1]);
laF = Float.valueOf(vals[2]);
loT = Float.valueOf(vals[3]);
laT = Float.valueOf(vals[4]);
inputPoints.add(new float[]{laF, loF, laT, loT, idx});
id_to_points.add(od_id);
}
int numPairs = inputPoints.size();
System.out.println(numPairs + " origin-destination pairs.");
// Loop through origin-destination pairs, processing each one for beauty, non-beautiful matched, fastest, and simplest
float[] points;
int routes_skipped = 0;
for (int i=0; i<numPairs; i++) {
if (i % 50 == 0) {
for (FileWriter fw : outputFiles) {
fw.flush();
}
}
// Get Routes
points = inputPoints.get(i);
od_id = id_to_points.get(i);
GHRequest req = new GHRequest(points[0], points[1], points[2], points[3]). // latFrom, lonFrom, latTo, lonTo
setWeighting("fastest").
setVehicle("car").
setLocale(Locale.US).
setAlgorithm("ksp");
GHResponse rsp = hopper.route(req);
// first check for errors
if (rsp.hasErrors()) {
// handle them!
System.out.println(rsp.getErrors().toString());
System.out.println(i + ": Skipping.");
String outputRow = od_id + ",main," + "\"[(" + points[0] + "," + points[1] + "),(" + points[2] + "," + points[3]
+ ")]\"," + "-1,-1,-1,[],-1,-1,-1" + System.getProperty("line.separator");
for (FileWriter fw: outputFiles) {
fw.write(outputRow);
}
routes_skipped++;
continue;
}
// Get All Routes (up to 10K right now)
List<PathWrapper> paths = rsp.getAll();
System.out.println("Num Responses: " + paths.size());
// Score each route on beauty to determine most beautiful
int j = 0;
float bestscore = -1000;
int routeidx = -1;
for (PathWrapper path : paths) {
float score = getBeauty(path);
if (score > bestscore) {
bestscore = score;
routeidx = j;
}
j++;
}
writeOutput(outputFiles.get(0), i, "Best", "beauty", od_id, paths.get(routeidx), bestscore, getNumCTs(paths.get(routeidx)));
float maxBeauty = bestscore;
// Find least-beautiful route within similar distance constraints
double beautyDistance = paths.get(routeidx).getDistance();
j = 0;
bestscore = 1000;
routeidx = -1;
double uglydistance;
for (PathWrapper path : paths) {
uglydistance = path.getDistance();
if (uglydistance / beautyDistance < 1.05 && uglydistance / beautyDistance > 0.95) {
float score = getBeauty(path);
if (score < bestscore) {
bestscore = score;
routeidx = j;
}
}
j++;
}
writeOutput(outputFiles.get(1), i, "Wrst", "ugly", od_id, paths.get(routeidx), bestscore, getNumCTs(paths.get(routeidx)));
// Simplest Route
j = 0;
bestscore = 10000;
routeidx = 0;
float beauty = -1;
for (PathWrapper path : paths) {
int score = path.getSimplicity();
if (score < bestscore) {
bestscore = score;
routeidx = j;
beauty = getBeauty(path);
}
j++;
}
writeOutput(outputFiles.get(2), i, "Simp", "simple", od_id, paths.get(routeidx), beauty, getNumCTs(paths.get(routeidx)));
float minSimplicity = bestscore;
// Fastest Route
PathWrapper bestPath = paths.get(0);
beauty = getBeauty(bestPath);
writeOutput(outputFiles.get(3), i, "Fast", "Fastest", od_id, bestPath, beauty, getNumCTs(bestPath));
// Beautifully simple route
j = 0;
bestscore = 0;
routeidx = 0;
float combined;
for (PathWrapper path : paths) {
combined = (minSimplicity / path.getSimplicity()) + (getBeauty(path) / maxBeauty);
if (combined > bestscore) {
bestscore = combined;
routeidx = j;
}
j++;
}
writeOutput(outputFiles.get(6), i, "BeSi", "beauty-simple", od_id, paths.get(routeidx), getBeauty(paths.get(routeidx)), getNumCTs(paths.get(routeidx)));
// Shortest Route
req = new GHRequest(points[0], points[1], points[2], points[3]). // latFrom, lonFrom, latTo, lonTo
setWeighting("shortest").
setVehicle("car").
setLocale(Locale.US).
setAlgorithm("dijkstrabi");
rsp = hopper.route(req);
// first check for errors
if (rsp.hasErrors()) {
// handle them!
System.out.println(rsp.getErrors().toString());
System.out.println(i + ": Skipping shortest path.");
continue;
}
// Get shortest path
bestPath = rsp.getBest();
beauty = getBeauty(bestPath);
writeOutput(outputFiles.get(4), i, "Shrt", "shortest", od_id, bestPath, beauty, getNumCTs(bestPath));
// Alternative Route
req = new GHRequest(points[0], points[1], points[2], points[3]). // latFrom, lonFrom, latTo, lonTo
setWeighting("fastest").
setVehicle("car").
setLocale(Locale.US).
setAlgorithm("alternative_route");
rsp = hopper.route(req);
// first check for errors
if (rsp.hasErrors()) {
// handle them!
System.out.println(rsp.getErrors().toString());
System.out.println(i + ": Skipping alternative path.");
String outputRow = od_id + ",alternative," + "\"[(" + points[0] + "," + points[1] + "),(" + points[2] + "," + points[3]
+ ")]\"," + "-1,-1,-1,[],-1,-1,-1" + System.getProperty("line.separator");
FileWriter fw = outputFiles.get(5);
fw.write(outputRow);
continue;
}
// Get Alt Routes (should be 2, of which first is the fastest path)
paths = rsp.getAll();
if (paths.size() < 2) {
System.out.println(i + ": Did not return an alternative path.");
String outputRow = od_id + ",alternative," + "\"[(" + points[0] + "," + points[1] + "),(" + points[2] + "," + points[3]
+ ")]\"," + "-1,-1,-1,[],-1,-1,-1" + System.getProperty("line.separator");
outputFiles.get(5).write(outputRow);
continue;
}
PathWrapper altpath = paths.get(1);
beauty = getBeauty(altpath);
writeOutput(outputFiles.get(5), i, "Altn", "altn", od_id, altpath, beauty, getNumCTs(altpath));
}
// Finished analysis: close filewriters and indicate how many paths skipped
System.out.println(routes_skipped + " routes skipped out of " + numPairs);
for (FileWriter fw : outputFiles) {
fw.close();
}
}
public static void main(String[] args) throws Exception {
// PBFs from: https://mapzen.com/data/metro-extracts/
String city = args[0];
runKSP ksp = new runKSP(city, "grid");
// SF Grid
//runKSP ksp = new runKSP("SF", "grid");
// SF Random
//runKSP ksp = new runKSP("SF", "rand");
// NYC Grid
//runKSP ksp = new runKSP("NYC", "grid");
// NYC Random
//runKSP ksp = new runKSP("NYC", "rand");
// BOS Check
//runKSP ksp = new runKSP("BOS", "check");
ksp.setDataSources();
ksp.getGridValues();
ksp.prepareGraphHopper();
ksp.getGridCTs();
ksp.prepMapMatcher(); // score external API routes
String inputfolder = "../data/intermediate/";
String outputfolder = "../data/output/";
ArrayList<String> platforms = new ArrayList<>();
platforms.add("google");
platforms.add("mapquest");
ArrayList<String> conditions = new ArrayList<>();
conditions.add("traffic");
conditions.add("notraffic");
ArrayList<String> routetypes = new ArrayList<>();
routetypes.add("main");
routetypes.add("alt");
for (String platform : platforms) {
for (String condition : conditions) {
for (String routetype : routetypes) {
ksp.PointsToPath(inputfolder + city + "_grid_" + platform + "_" + condition + "_routes_" + routetype + "_gpx.csv", outputfolder + city + "_grid_" + platform + "_" + condition + "_routes_" + routetype + "_ghenhanced_sigma100_transitionDefault.csv");
}
}
}
//ksp.setDataSources();
//ksp.getGridValues();
//ksp.prepareGraphHopper();
//ksp.getGridCTs();
//ksp.process_routes(); // get Graphhopper routes
}
}
| reader-osm/src/main/java/com/graphhopper/reader/osm/runKSP.java | package com.graphhopper.reader.osm;
import com.graphhopper.GHRequest;
import com.graphhopper.GHResponse;
import com.graphhopper.GraphHopper;
import com.graphhopper.PathWrapper;
import com.graphhopper.matching.MapMatching;
import com.graphhopper.matching.MatchResult;
import com.graphhopper.routing.AlgorithmOptions;
import com.graphhopper.routing.Path;
import com.graphhopper.routing.util.EncodingManager;
import com.graphhopper.routing.util.HintsMap;
import com.graphhopper.util.*;
import java.util.*;
import java.io.*;
import java.util.List;
/**
* Created by isaac on 09/14/16.
*/
public class runKSP {
String city;
String route_type;
ArrayList<FileWriter> outputFiles;
private String osmFile = "./reader-osm/files/";
private String graphFolder = "./reader-osm/target/tmp/";
private String inputPointsFN = "../data/intermediate/";
private String outputPointsFN = "../data/testing/";
private String gvfnStem = "../data/intermediate/";
private String gctfnStem = "../geometries/";
private ArrayList<String> gridValuesFNs = new ArrayList<>();
private ArrayList<String> gridCTsFNs = new ArrayList<>();
private HashMap<String, Integer> gvHeaderMap;
private HashMap<String, Float> gridBeauty;
private HashMap<String, Integer> gridCT;
private GraphHopper hopper;
private MapMatching mapMatching;
private String outputheader = "ID,name,polyline_points,total_time_in_sec,total_distance_in_meters,number_of_steps,maneuvers,beauty,simplicity,numCTs" +
System.getProperty("line.separator");
public runKSP(String city, String route_type) {
this.city = city;
this.route_type = route_type;
this.outputFiles = new ArrayList<>(4);
}
public void setCity(String city) {
this.city = city;
}
public void setRouteType(String route_type) {
this.route_type = route_type;
}
public PathWrapper GPXToPath(ArrayList<GPXEntry> gpxEntries) {
PathWrapper matchGHRsp = new PathWrapper();
try {
MatchResult mr = mapMatching.doWork(gpxEntries);
Path path = mapMatching.calcPath(mr);
new PathMerger().doWork(matchGHRsp, Collections.singletonList(path), new TranslationMap().doImport().getWithFallBack(Locale.US));
}
catch (RuntimeException e) {
System.out.println("Broken GPX trace.");
System.out.println(e.getMessage());
}
return matchGHRsp;
}
public void PointsToPath(String fin, String fout) throws IOException {
Scanner sc_in = new Scanner(new File(fin));
String[] pointsHeader = sc_in.nextLine().split(",");
int idIdx = -1;
int nameIdx = -1;
int latIdx = -1;
int lonIdx = -1;
int timeIdx = -1;
for (int i=0; i<pointsHeader.length; i++) {
if (pointsHeader[i].equalsIgnoreCase("ID")) {
idIdx = i;
}
else if (pointsHeader[i].equalsIgnoreCase("name")) {
nameIdx = i;
}
else if (pointsHeader[i].equalsIgnoreCase("lat")) {
latIdx = i;
}
else if (pointsHeader[i].equalsIgnoreCase("lon")) {
lonIdx = i;
}
else if (pointsHeader[i].equalsIgnoreCase("millis")) {
timeIdx = i;
}
else {
System.out.println("Unexpected header value: " + pointsHeader[i]);
}
}
String optimized = "";
if (fin.indexOf("google") > -1) {
optimized = optimized + "Goog";
} else if (fin.indexOf("mapquest") > -1) {
optimized = optimized + "MapQ";
} else {
System.out.println("Don't recognize platform: " + fin);
}
if (fin.indexOf("alt") > -1) {
optimized = optimized + " altn";
} else if (fin.indexOf("main") > -1) {
optimized = optimized + " main";
} else {
System.out.println("Don't recognize route type: " + fin);
}
String line;
String[] vals;
String routeID = "";
String prevRouteID = "";
String name = "";
String prevName = "";
String label = "";
String prevLabel = "";
double lat;
double lon;
long time;
ArrayList<GPXEntry> pointsList = new ArrayList<>();
PathWrapper path;
FileWriter sc_out = new FileWriter(fout, true);
sc_out.write(outputheader);
int i = 0;
float score;
while (sc_in.hasNext()) {
line = sc_in.nextLine();
vals = line.split(",");
routeID = vals[idIdx];
name = vals[nameIdx];
if (name.equalsIgnoreCase("alternative 2") || name.equalsIgnoreCase("alternative 3")) {
continue;
}
lat = Double.valueOf(vals[latIdx]);
lon = Double.valueOf(vals[lonIdx]);
time = Long.valueOf(vals[timeIdx]);
label = routeID + "|" + name;
GPXEntry pt = new GPXEntry(lat, lon, time);
if (label.equalsIgnoreCase(prevLabel)) {
pointsList.add(pt);
}
else if (pointsList.size() > 0) {
path = GPXToPath(pointsList);
if (path.getDistance() > 0) {
score = getBeauty(path);
writeOutput(sc_out, i, optimized, prevName, prevRouteID, path, score, getNumCTs(path));
}
pointsList.clear();
pointsList.add(pt);
i++;
if (i % 10 == 0) {
for (FileWriter fw : outputFiles) {
fw.flush();
}
}
} else {
System.out.println("First point.");
pointsList.add(pt);
}
prevRouteID = routeID;
prevName = name;
prevLabel = label;
}
if (pointsList.size() > 0) {
path = GPXToPath(pointsList);
if (path.getDistance() > 0) {
score = getBeauty(path);
writeOutput(sc_out, i, optimized, prevName, prevRouteID, path, score, getNumCTs(path));
}
}
sc_out.close();
sc_in.close();
}
//TODO: find some way to match path to virtual nodes at start/finish or hope map-matcher updates
public PathWrapper trimPath(PathWrapper path, ArrayList<GPXEntry> original) {
return new PathWrapper();
}
public void setDataSources() throws Exception {
if (city.equals("SF")) {
osmFile = osmFile + "san-francisco-bay_california.osm.pbf";
graphFolder = graphFolder + "ghosm_sf_noch";
inputPointsFN = inputPointsFN + "sf_" + route_type + "_od_pairs.csv";
outputPointsFN = outputPointsFN + "sf_" + route_type + "_gh_routes.csv";
gridValuesFNs.add(gvfnStem + "06075_logfractionempath_ft.csv");
gridCTsFNs.add(gctfnStem + "06075_ct_grid.csv");
} else if (city.equals("NYC")) {
osmFile = osmFile + "new-york_new-york.osm.pbf";
graphFolder = graphFolder + "ghosm_nyc_noch";
inputPointsFN = inputPointsFN + "nyc_" + route_type + "_od_pairs.csv";
outputPointsFN = outputPointsFN + "nyc_" + route_type + "_gh_routes.csv";
gridValuesFNs.add(gvfnStem + "36005_logfractionempath_ft.csv");
gridValuesFNs.add(gvfnStem + "36047_logfractionempath_ft.csv");
gridValuesFNs.add(gvfnStem + "36061_logfractionempath_ft.csv");
gridValuesFNs.add(gvfnStem + "36081_logfractionempath_ft.csv");
gridValuesFNs.add(gvfnStem + "36085_logfractionempath_ft.csv");
gridCTsFNs.add(gctfnStem + "nyc_ct_grid.csv");
} else if (city.equals("BOS")) {
osmFile = osmFile + "boston_massachusetts.osm.pbf";
graphFolder = graphFolder + "ghosm_bos_noch";
inputPointsFN = inputPointsFN + "bos_" + route_type + "_od_pairs.csv";
outputPointsFN = outputPointsFN + "bos_" + route_type + "_gh_routes.csv";
gridValuesFNs.add(gvfnStem + "25025_beauty_twitter.csv");
gridCTsFNs.add(gctfnStem + "25025_ct_grid.csv");
} else {
throw new Exception("Invalid Parameters: city must be of 'SF','NYC', or 'BOS' and route_type of 'grid' or 'rand'");
}
}
public void getGridValues() throws Exception {
gvHeaderMap = new HashMap<>();
gridBeauty = new HashMap<>();
for (String fn : gridValuesFNs) {
Scanner sc_in = new Scanner(new File(fn));
String[] gvHeader = sc_in.nextLine().split(",");
int i = 0;
for (String col : gvHeader) {
gvHeaderMap.put(col, i);
i++;
}
String line;
String[] vals;
String rc;
float beauty;
while (sc_in.hasNext()) {
line = sc_in.nextLine();
vals = line.split(",");
try {
rc = vals[gvHeaderMap.get("rid")] + "," + vals[gvHeaderMap.get("cid")];
beauty = Float.valueOf(vals[gvHeaderMap.get("beauty")]);
gridBeauty.put(rc, beauty);
} catch (NullPointerException ex) {
System.out.println(ex.getMessage());
System.out.println(line);
continue;
}
}
}
}
public void getGridCTs() throws Exception {
gridCT = new HashMap<>();
for (String fn : gridCTsFNs) {
Scanner sc_in = new Scanner(new File(fn));
sc_in.nextLine();
String line;
String[] vals;
String rc;
int ct;
while (sc_in.hasNext()) {
line = sc_in.nextLine();
vals = line.split(",");
try {
rc = vals[1] + "," + vals[0];
ct = Integer.valueOf(vals[2]);
gridCT.put(rc, ct);
} catch (NullPointerException ex) {
System.out.println(ex.getMessage());
System.out.println(line);
continue;
}
}
}
}
public void prepareGraphHopper() {
// create one GraphHopper instance
hopper = new GraphHopperOSM().forDesktop().setCHEnabled(false);
hopper.setDataReaderFile(osmFile);
// where to store graphhopper files?
hopper.setGraphHopperLocation(graphFolder);
hopper.setEncodingManager(new EncodingManager("car"));
// now this can take minutes if it imports or a few seconds for loading
// of course this is dependent on the area you import
hopper.importOrLoad();
}
public void prepMapMatcher() {
// create MapMatching object, can and should be shared accross threads
AlgorithmOptions algoOpts = AlgorithmOptions.start().
algorithm(Parameters.Algorithms.DIJKSTRA).
traversalMode(hopper.getTraversalMode()).
hints(new HintsMap().put("weighting", "fastest").put("vehicle", "car")).
build();
mapMatching = new MapMatching(hopper, algoOpts);
mapMatching.setTransitionProbabilityBeta(0.00959442);
// mapMatching.setTransitionProbabilityBeta(0.000959442);
mapMatching.setMeasurementErrorSigma(100);
}
public void writeOutput(FileWriter fw, int i, String optimized, String name, String od_id, PathWrapper bestPath, float score, int numCTs) throws IOException {
// points, distance in meters and time in seconds (convert from ms) of the full path
PointList pointList = bestPath.getPoints();
int simplicity = bestPath.getSimplicity();
double distance = Math.round(bestPath.getDistance() * 100) / 100;
long timeInSec = bestPath.getTime() / 1000;
InstructionList il = bestPath.getInstructions();
int numDirections = il.getSize();
// iterate over every turn instruction
ArrayList<String> maneuvers = new ArrayList<>();
for (Instruction instruction : il) {
maneuvers.add(instruction.getSimpleTurnDescription());
}
fw.write(od_id + "," + name + "," + "\"[" + pointList + "]\"," + timeInSec + "," + distance + "," + numDirections +
",\"" + maneuvers.toString() + "\"" + "," + score + "," + simplicity + "," + numCTs + System.getProperty("line.separator"));
System.out.println(i + " (" + optimized + "): Distance: " + distance + "m;\tTime: " + timeInSec + "sec;\t# Directions: " + numDirections + ";\tSimplicity: " + simplicity + ";\tScore: " + score + ";\tNumCts: " + numCTs);
}
public int getNumCTs(PathWrapper path) {
HashSet<String> roundedPoints = path.roundPoints();
HashSet<Integer> cts = new HashSet<>();
for (String pt : roundedPoints) {
if (gridCT.containsKey(pt)) {
cts.add(gridCT.get(pt));
}
}
return cts.size();
}
public float getBeauty(PathWrapper path) {
HashSet<String> roundedPoints = path.roundPoints();
float score = 0;
for (String pt : roundedPoints) {
if (gridBeauty.containsKey(pt)) {
score = score + gridBeauty.get(pt);
}
}
score = score / roundedPoints.size();
return score;
}
public void process_routes() throws Exception {
ArrayList<float[]> inputPoints = new ArrayList<float[]>();
ArrayList<String> id_to_points = new ArrayList<String>();
// Prep Filewriters (Optimized, Worst-but-same-distance, Fastest, Simplest)
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_beauty.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_ugly.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_simple.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_fast.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_shortest.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_alt.csv"), true));
outputFiles.add(new FileWriter(outputPointsFN.replaceFirst(".csv","_besi.csv"), true));
for (FileWriter fw : outputFiles) {
fw.write(outputheader);
}
// Bring in origin-destination pairs for processing
Scanner sc_in = new Scanner(new File(inputPointsFN));
String header = sc_in.nextLine();
String od_id;
float laF;
float loF;
float laT;
float loT;
float idx = 0;
System.out.println("Input data points header: " + header);
while (sc_in.hasNext()) {
idx = idx + 1;
String line = sc_in.nextLine();
String[] vals = line.split(",");
od_id = vals[0];
loF = Float.valueOf(vals[1]);
laF = Float.valueOf(vals[2]);
loT = Float.valueOf(vals[3]);
laT = Float.valueOf(vals[4]);
inputPoints.add(new float[]{laF, loF, laT, loT, idx});
id_to_points.add(od_id);
}
int numPairs = inputPoints.size();
System.out.println(numPairs + " origin-destination pairs.");
// Loop through origin-destination pairs, processing each one for beauty, non-beautiful matched, fastest, and simplest
float[] points;
int routes_skipped = 0;
for (int i=0; i<numPairs; i++) {
if (i % 50 == 0) {
for (FileWriter fw : outputFiles) {
fw.flush();
}
}
// Get Routes
points = inputPoints.get(i);
od_id = id_to_points.get(i);
GHRequest req = new GHRequest(points[0], points[1], points[2], points[3]). // latFrom, lonFrom, latTo, lonTo
setWeighting("fastest").
setVehicle("car").
setLocale(Locale.US).
setAlgorithm("ksp");
GHResponse rsp = hopper.route(req);
// first check for errors
if (rsp.hasErrors()) {
// handle them!
System.out.println(rsp.getErrors().toString());
System.out.println(i + ": Skipping.");
String outputRow = od_id + ",main," + "\"[(" + points[0] + "," + points[1] + "),(" + points[2] + "," + points[3]
+ ")]\"," + "-1,-1,-1,[],-1,-1,-1" + System.getProperty("line.separator");
for (FileWriter fw: outputFiles) {
fw.write(outputRow);
}
routes_skipped++;
continue;
}
// Get All Routes (up to 10K right now)
List<PathWrapper> paths = rsp.getAll();
System.out.println("Num Responses: " + paths.size());
// Score each route on beauty to determine most beautiful
int j = 0;
float bestscore = -1000;
int routeidx = -1;
for (PathWrapper path : paths) {
float score = getBeauty(path);
if (score > bestscore) {
bestscore = score;
routeidx = j;
}
j++;
}
writeOutput(outputFiles.get(0), i, "Best", "beauty", od_id, paths.get(routeidx), bestscore, getNumCTs(paths.get(routeidx)));
float maxBeauty = bestscore;
// Find least-beautiful route within similar distance constraints
double beautyDistance = paths.get(routeidx).getDistance();
j = 0;
bestscore = 1000;
routeidx = -1;
double uglydistance;
for (PathWrapper path : paths) {
uglydistance = path.getDistance();
if (uglydistance / beautyDistance < 1.05 && uglydistance / beautyDistance > 0.95) {
float score = getBeauty(path);
if (score < bestscore) {
bestscore = score;
routeidx = j;
}
}
j++;
}
writeOutput(outputFiles.get(1), i, "Wrst", "ugly", od_id, paths.get(routeidx), bestscore, getNumCTs(paths.get(routeidx)));
// Simplest Route
j = 0;
bestscore = 10000;
routeidx = 0;
float beauty = -1;
for (PathWrapper path : paths) {
int score = path.getSimplicity();
if (score < bestscore) {
bestscore = score;
routeidx = j;
beauty = getBeauty(path);
}
j++;
}
writeOutput(outputFiles.get(2), i, "Simp", "simple", od_id, paths.get(routeidx), beauty, getNumCTs(paths.get(routeidx)));
float minSimplicity = bestscore;
// Fastest Route
PathWrapper bestPath = paths.get(0);
beauty = getBeauty(bestPath);
writeOutput(outputFiles.get(3), i, "Fast", "Fastest", od_id, bestPath, beauty, getNumCTs(bestPath));
// Beautifully simple route
j = 0;
bestscore = 0;
routeidx = 0;
float combined;
for (PathWrapper path : paths) {
combined = (minSimplicity / path.getSimplicity()) + (getBeauty(path) / maxBeauty);
if (combined > bestscore) {
bestscore = combined;
routeidx = j;
}
j++;
}
writeOutput(outputFiles.get(6), i, "BeSi", "beauty-simple", od_id, paths.get(routeidx), getBeauty(paths.get(routeidx)), getNumCTs(paths.get(routeidx)));
// Shortest Route
req = new GHRequest(points[0], points[1], points[2], points[3]). // latFrom, lonFrom, latTo, lonTo
setWeighting("shortest").
setVehicle("car").
setLocale(Locale.US).
setAlgorithm("dijkstrabi");
rsp = hopper.route(req);
// first check for errors
if (rsp.hasErrors()) {
// handle them!
System.out.println(rsp.getErrors().toString());
System.out.println(i + ": Skipping shortest path.");
continue;
}
// Get shortest path
bestPath = rsp.getBest();
beauty = getBeauty(bestPath);
writeOutput(outputFiles.get(4), i, "Shrt", "shortest", od_id, bestPath, beauty, getNumCTs(bestPath));
// Alternative Route
req = new GHRequest(points[0], points[1], points[2], points[3]). // latFrom, lonFrom, latTo, lonTo
setWeighting("fastest").
setVehicle("car").
setLocale(Locale.US).
setAlgorithm("alternative_route");
rsp = hopper.route(req);
// first check for errors
if (rsp.hasErrors()) {
// handle them!
System.out.println(rsp.getErrors().toString());
System.out.println(i + ": Skipping alternative path.");
String outputRow = od_id + ",alternative," + "\"[(" + points[0] + "," + points[1] + "),(" + points[2] + "," + points[3]
+ ")]\"," + "-1,-1,-1,[],-1,-1,-1" + System.getProperty("line.separator");
FileWriter fw = outputFiles.get(5);
fw.write(outputRow);
continue;
}
// Get Alt Routes (should be 2, of which first is the fastest path)
paths = rsp.getAll();
if (paths.size() < 2) {
System.out.println(i + ": Did not return an alternative path.");
String outputRow = od_id + ",alternative," + "\"[(" + points[0] + "," + points[1] + "),(" + points[2] + "," + points[3]
+ ")]\"," + "-1,-1,-1,[],-1,-1,-1" + System.getProperty("line.separator");
outputFiles.get(5).write(outputRow);
continue;
}
PathWrapper altpath = paths.get(1);
beauty = getBeauty(altpath);
writeOutput(outputFiles.get(5), i, "Altn", "altn", od_id, altpath, beauty, getNumCTs(altpath));
}
// Finished analysis: close filewriters and indicate how many paths skipped
System.out.println(routes_skipped + " routes skipped out of " + numPairs);
for (FileWriter fw : outputFiles) {
fw.close();
}
}
public static void main(String[] args) throws Exception {
// PBFs from: https://mapzen.com/data/metro-extracts/
// SF Grid
runKSP ksp = new runKSP("SF", "grid");
// SF Random
//runKSP ksp = new runKSP("SF", "rand");
// NYC Grid
//runKSP ksp = new runKSP("NYC", "grid");
// NYC Random
//runKSP ksp = new runKSP("NYC", "rand");
// BOS Check
//runKSP ksp = new runKSP("BOS", "check");
ksp.setDataSources();
ksp.getGridValues();
ksp.prepareGraphHopper();
ksp.getGridCTs();
ksp.prepMapMatcher(); // score external API routes
String city = args[0];
String inputfolder = "../data/intermediate/";
String outputfolder = "../data/output/";
ArrayList<String> platforms = new ArrayList<>();
platforms.add("google");
platforms.add("mapquest");
ArrayList<String> conditions = new ArrayList<>();
conditions.add("traffic");
conditions.add("notraffic");
ArrayList<String> routetypes = new ArrayList<>();
routetypes.add("main");
routetypes.add("alt");
for (String platform : platforms) {
for (String condition : conditions) {
for (String routetype : routetypes) {
ksp.PointsToPath(inputfolder + city + "_grid_" + platform + "_" + condition + "_routes_" + routetype + "_gpx.csv", outputfolder + city + "_grid_" + platform + "_" + condition + "_routes_" + routetype + "_ghenhanced_sigma100_transitionDefault.csv");
}
}
}
//ksp.setDataSources();
//ksp.getGridValues();
//ksp.prepareGraphHopper();
//ksp.getGridCTs();
//ksp.process_routes(); // get Graphhopper routes
}
}
| city as arg
| reader-osm/src/main/java/com/graphhopper/reader/osm/runKSP.java | city as arg |
|
Java | apache-2.0 | 905cd8268289695534a45eabf77d646a351432be | 0 | Addepar/buck,JoelMarcey/buck,kageiit/buck,nguyentruongtho/buck,JoelMarcey/buck,zpao/buck,zpao/buck,JoelMarcey/buck,Addepar/buck,JoelMarcey/buck,Addepar/buck,Addepar/buck,kageiit/buck,JoelMarcey/buck,JoelMarcey/buck,nguyentruongtho/buck,JoelMarcey/buck,nguyentruongtho/buck,Addepar/buck,kageiit/buck,Addepar/buck,JoelMarcey/buck,Addepar/buck,kageiit/buck,zpao/buck,facebook/buck,Addepar/buck,Addepar/buck,nguyentruongtho/buck,facebook/buck,zpao/buck,Addepar/buck,nguyentruongtho/buck,JoelMarcey/buck,zpao/buck,zpao/buck,JoelMarcey/buck,kageiit/buck,zpao/buck,facebook/buck,Addepar/buck,nguyentruongtho/buck,JoelMarcey/buck,facebook/buck,kageiit/buck,nguyentruongtho/buck,JoelMarcey/buck,facebook/buck,Addepar/buck,facebook/buck,Addepar/buck,facebook/buck,kageiit/buck,JoelMarcey/buck | /*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.features.d;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.impl.NoopBuildRuleWithDeclaredAndExtraDeps;
import com.facebook.buck.cxx.Archive;
import com.facebook.buck.cxx.CxxDescriptionEnhancer;
import com.facebook.buck.cxx.toolchain.CxxPlatform;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkable;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableGroup;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableInfo;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableInput;
import com.facebook.buck.cxx.toolchain.nativelink.PlatformMappedCache;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
/** A {@link NativeLinkableGroup} for d libraries. */
public class DLibrary extends NoopBuildRuleWithDeclaredAndExtraDeps implements NativeLinkableGroup {
private final ActionGraphBuilder graphBuilder;
private final DIncludes includes;
private final PlatformMappedCache<NativeLinkableInfo> linkableCache = new PlatformMappedCache<>();
public DLibrary(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleParams params,
ActionGraphBuilder graphBuilder,
DIncludes includes) {
super(buildTarget, projectFilesystem, params);
this.graphBuilder = graphBuilder;
this.includes = includes;
}
@Override
public NativeLinkableInfo getNativeLinkable(
CxxPlatform cxxPlatform, ActionGraphBuilder graphBuilder) {
return linkableCache.get(
cxxPlatform,
() -> {
ImmutableList<NativeLinkable> exportedDeps =
FluentIterable.from(getDeclaredDeps())
.filter(NativeLinkableGroup.class)
.transform(g -> g.getNativeLinkable(cxxPlatform, graphBuilder))
.toList();
Archive archive =
(Archive)
DLibrary.this.graphBuilder.requireRule(
getBuildTarget()
.withAppendedFlavors(
cxxPlatform.getFlavor(), CxxDescriptionEnhancer.STATIC_FLAVOR));
NativeLinkableInput linkableInput =
NativeLinkableInput.of(
ImmutableList.of(archive.toArg()), ImmutableSet.of(), ImmutableSet.of());
return new NativeLinkableInfo(
getBuildTarget(),
ImmutableList.of(),
exportedDeps,
Linkage.STATIC,
ImmutableMap.of(),
NativeLinkableInfo.fixedDelegate(linkableInput),
NativeLinkableInfo.defaults());
});
}
public DIncludes getIncludes() {
graphBuilder.requireRule(
getBuildTarget().withAppendedFlavors(DDescriptionUtils.SOURCE_LINK_TREE));
return includes;
}
}
| src/com/facebook/buck/features/d/DLibrary.java | /*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.features.d;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.TargetConfiguration;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.core.rules.impl.NoopBuildRuleWithDeclaredAndExtraDeps;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.cxx.Archive;
import com.facebook.buck.cxx.CxxDescriptionEnhancer;
import com.facebook.buck.cxx.toolchain.CxxPlatform;
import com.facebook.buck.cxx.toolchain.linker.Linker;
import com.facebook.buck.cxx.toolchain.nativelink.LegacyNativeLinkableGroup;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableGroup;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableInput;
import com.facebook.buck.cxx.toolchain.nativelink.PlatformLockedNativeLinkableGroup;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
/** A {@link NativeLinkableGroup} for d libraries. */
public class DLibrary extends NoopBuildRuleWithDeclaredAndExtraDeps
implements LegacyNativeLinkableGroup {
private final ActionGraphBuilder graphBuilder;
private final DIncludes includes;
private final PlatformLockedNativeLinkableGroup.Cache linkableCache =
LegacyNativeLinkableGroup.getNativeLinkableCache(this);
public DLibrary(
BuildTarget buildTarget,
ProjectFilesystem projectFilesystem,
BuildRuleParams params,
ActionGraphBuilder graphBuilder,
DIncludes includes) {
super(buildTarget, projectFilesystem, params);
this.graphBuilder = graphBuilder;
this.includes = includes;
}
@Override
public PlatformLockedNativeLinkableGroup.Cache getNativeLinkableCompatibilityCache() {
return linkableCache;
}
@Override
public Iterable<NativeLinkableGroup> getNativeLinkableDeps(BuildRuleResolver ruleResolver) {
return ImmutableList.of();
}
@Override
public Iterable<NativeLinkableGroup> getNativeLinkableExportedDeps(
BuildRuleResolver ruleResolver) {
return FluentIterable.from(getDeclaredDeps()).filter(NativeLinkableGroup.class);
}
@Override
public NativeLinkableInput getNativeLinkableInput(
CxxPlatform cxxPlatform,
Linker.LinkableDepType type,
boolean forceLinkWhole,
ActionGraphBuilder graphBuilder,
TargetConfiguration targetConfiguration) {
Archive archive =
(Archive)
this.graphBuilder.requireRule(
getBuildTarget()
.withAppendedFlavors(
cxxPlatform.getFlavor(), CxxDescriptionEnhancer.STATIC_FLAVOR));
return NativeLinkableInput.of(
ImmutableList.of(archive.toArg()), ImmutableSet.of(), ImmutableSet.of());
}
@Override
public NativeLinkableGroup.Linkage getPreferredLinkage(CxxPlatform cxxPlatform) {
return Linkage.STATIC;
}
@Override
public ImmutableMap<String, SourcePath> getSharedLibraries(
CxxPlatform cxxPlatform, ActionGraphBuilder graphBuilder) {
return ImmutableMap.of();
}
public DIncludes getIncludes() {
graphBuilder.requireRule(
getBuildTarget().withAppendedFlavors(DDescriptionUtils.SOURCE_LINK_TREE));
return includes;
}
}
| Convert DLibrary from LegacyNativeLinkableGroup -> NativeLinkableInfo
Summary: ^
Reviewed By: bobyangyf
shipit-source-id: d3650a312e
| src/com/facebook/buck/features/d/DLibrary.java | Convert DLibrary from LegacyNativeLinkableGroup -> NativeLinkableInfo |
|
Java | apache-2.0 | 0cc3f42e217f7fe1a975b05a046fd697a5c24054 | 0 | crate/crate,crate/crate,crate/crate,EvilMcJerkface/crate,EvilMcJerkface/crate,EvilMcJerkface/crate | /*
* Licensed to Crate under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. Crate licenses this file
* to you under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial
* agreement.
*/
package io.crate.integrationtests;
import io.crate.action.sql.SQLActionException;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESIntegTestCase;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
@ESIntegTestCase.ClusterScope(numClientNodes = 0)
public class SysNodesITest extends SQLTransportIntegrationTest {
@Override
protected Settings nodeSettings(int nodeOrdinal) {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put("http.enabled", true)
.build();
}
@Test
public void testNoMatchingNode() throws Exception {
execute("select id, name, hostname from sys.nodes where id = 'does-not-exist'");
assertThat(response.rowCount(), is(0L));
}
@Test
public void testScalarEvaluatesInErrorOnSysNodes() throws Exception {
expectedException.expect(SQLActionException.class);
expectedException.expectMessage(" / by zero");
execute("select 1/0 from sys.nodes");
}
@Test
public void testRestUrl() throws Exception {
execute("select rest_url from sys.nodes");
assertThat((String) response.rows()[0][0], startsWith("127.0.0.1:"));
}
}
| sql/src/test/java/io/crate/integrationtests/SysNodesITest.java | /*
* Licensed to Crate under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. Crate licenses this file
* to you under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial
* agreement.
*/
package io.crate.integrationtests;
import io.crate.action.sql.SQLActionException;
import org.elasticsearch.common.settings.Settings;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
public class SysNodesITest extends SQLTransportIntegrationTest {
@Override
protected Settings nodeSettings(int nodeOrdinal) {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal))
.put("http.enabled", true)
.build();
}
@Test
public void testNoMatchingNode() throws Exception {
execute("select id, name, hostname from sys.nodes where id = 'does-not-exist'");
assertThat(response.rowCount(), is(0L));
}
@Test
public void testScalarEvaluatesInErrorOnSysNodes() throws Exception {
expectedException.expect(SQLActionException.class);
expectedException.expectMessage(" / by zero");
execute("select 1/0 from sys.nodes");
}
@Test
public void testRestUrl() throws Exception {
execute("select rest_url from sys.nodes");
assertThat((String) response.rows()[0][0], startsWith("127.0.0.1:"));
}
}
| prevents sys.nodes itest from running on a client node
follow up commit of ddc17dc996d4ae744549e65f6216a85ef766ce61
| sql/src/test/java/io/crate/integrationtests/SysNodesITest.java | prevents sys.nodes itest from running on a client node |
|
Java | apache-2.0 | 826e84b0879772916c3bf0895d78f4682b9b0f1c | 0 | blstream/StudyBox_Android | package com.blstream.studybox.activities;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputEditText;
import android.support.v7.widget.AppCompatButton;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.blstream.studybox.ConnectionStatusReceiver;
import com.blstream.studybox.R;
import com.blstream.studybox.login_view.LoginView;
import com.blstream.studybox.login_view.LoginViewState;
import com.blstream.studybox.model.AuthCredentials;
import com.blstream.studybox.registration_view.RegistrationPresenter;
import com.blstream.studybox.registration_view.RegistrationView;
import com.hannesdorfmann.mosby.mvp.viewstate.MvpViewStateActivity;
import com.hannesdorfmann.mosby.mvp.viewstate.ViewState;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class RegistrationActivity
extends MvpViewStateActivity<LoginView, RegistrationPresenter>
implements RegistrationView {
private ConnectionStatusReceiver connectionStatusReceiver;
private final static float ENABLED_BUTTON_ALPHA = 1.0f;
private final static float DISABLED_BUTTON_ALPHA = 0.5f;
@Bind(R.id.text_view_failure)
TextView textViewFailure;
@Bind(R.id.input_email)
TextInputEditText inputEmail;
@Bind(R.id.input_password)
TextInputEditText inputPassword;
@Bind(R.id.input_repeat_password)
TextInputEditText inputRepeatPassword;
@Bind(R.id.progress_bar_sign_up)
ProgressBar signUpProgressBar;
@Bind(R.id.btn_sign_up)
AppCompatButton buttonSignUp;
@Bind(R.id.link_cancel)
TextView linkCancel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
connectionStatusReceiver = new ConnectionStatusReceiver();
ButterKnife.bind(this);
}
@OnClick(R.id.btn_sign_up)
public void OnSignUpClick() {
if (connectionStatusReceiver.isConnected()) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString();
presenter.validateCredential(new AuthCredentials(email, password));
}
}
@OnClick(R.id.link_cancel)
public void OnCancelClick() {
}
@Override
protected void onResume(){
super.onResume();
registerReceiver(connectionStatusReceiver, ConnectionStatusReceiver.filter);
}
@NonNull
@Override
public RegistrationPresenter createPresenter() {
return new RegistrationPresenter();
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(connectionStatusReceiver);
}
@Override
public void onNewViewStateInstance() {
showLoginForm();
}
@Override
public void showPasswordInconsistent() {
}
@Override
public void showLoginForm() {
LoginViewState vs = (LoginViewState) viewState;
vs.setShowLoginForm();
setSignUpFormEnabled(true);
textViewFailure.setVisibility(View.GONE);
signUpProgressBar.setVisibility(View.GONE);
}
@Override
public void showAuthError() {
setError(getString(R.string.auth_error));
}
@Override
public void showNetworkError() {
setError(getString(R.string.network_error));
}
@Override
public void showUnexpectedError() {
setError(getString(R.string.unexpected_error));
}
@Override
public void showEmptyEmailError() {
setFieldError(inputEmail, getString(R.string.empty_field));
}
@Override
public void showEmptyPasswordError() {
setFieldError(inputPassword, getString(R.string.empty_field));
}
@Override
public void showInvalidEmailError() {
setFieldError(inputEmail, getString(R.string.invalid_email));
}
@Override
public void showInvalidPasswordError() {
setFieldError(inputPassword, getString(R.string.invalid_password));
}
@Override
public void showTooShortPasswordError() {
setFieldError(inputPassword, getString(R.string.too_short_password));
}
@Override
public void showLoading() {
LoginViewState vs = (LoginViewState) viewState;
vs.setShowLoading();
setSignUpFormEnabled(false);
textViewFailure.setVisibility(View.GONE);
signUpProgressBar.setVisibility(View.VISIBLE);
}
@Override
public void loginSuccessful() {
Intent intent = new Intent(RegistrationActivity.this, DecksActivity.class);
startActivity(intent);
finish();
}
@Override
public Context getContext() {
return RegistrationActivity.this;
}
@NonNull
@Override
public ViewState<LoginView> createViewState() {
return new LoginViewState();
}
private void setError(String message) {
LoginViewState vs = (LoginViewState) viewState;
vs.setShowError();
setSignUpFormEnabled(true);
textViewFailure.setText(message);
textViewFailure.setVisibility(View.VISIBLE);
signUpProgressBar.setVisibility(View.GONE);
}
private void setFieldError(TextInputEditText field, String message) {
LoginViewState vs = (LoginViewState) viewState;
vs.setShowLoginForm();
setSignUpFormEnabled(true);
field.setError(message);
field.requestFocus();
textViewFailure.setVisibility(View.GONE);
signUpProgressBar.setVisibility(View.GONE);
}
private void setSignUpFormEnabled(boolean enabled) {
inputEmail.setEnabled(enabled);
inputPassword.setEnabled(enabled);
inputRepeatPassword.setEnabled(enabled);
buttonSignUp.setEnabled(enabled);
linkCancel.setEnabled(enabled);
if (enabled) {
buttonSignUp.setAlpha(ENABLED_BUTTON_ALPHA);
} else {
buttonSignUp.setAlpha(DISABLED_BUTTON_ALPHA);
}
}
/**
* Applies custom font to every activity that overrides this method
*/
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
}
| app/src/main/java/com/blstream/studybox/activities/RegistrationActivity.java | package com.blstream.studybox.activities;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.AppCompatButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.blstream.studybox.ConnectionStatusReceiver;
import com.blstream.studybox.R;
import com.blstream.studybox.login_view.LoginView;
import com.blstream.studybox.login_view.LoginViewState;
import com.blstream.studybox.model.AuthCredentials;
import com.blstream.studybox.registration_view.RegistrationPresenter;
import com.blstream.studybox.registration_view.RegistrationView;
import com.hannesdorfmann.mosby.mvp.viewstate.MvpViewStateActivity;
import com.hannesdorfmann.mosby.mvp.viewstate.ViewState;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class RegistrationActivity
extends MvpViewStateActivity<LoginView, RegistrationPresenter>
implements RegistrationView {
private ConnectionStatusReceiver connectionStatusReceiver;
@Bind(R.id.text_view_failure)
TextView textViewFailure;
@Bind(R.id.input_layout_email)
TextInputLayout inputLayoutEmail;
@Bind(R.id.input_layout_password)
TextInputLayout inputLayoutPassword;
@Bind(R.id.input_layout_repeat_password)
TextInputLayout inputLayoutRepeatPassword;
@Bind(R.id.input_email)
TextInputEditText inputEmail;
@Bind(R.id.input_password)
TextInputEditText inputPassword;
@Bind(R.id.input_repeat_password)
TextInputEditText inputRepeatPassword;
@Bind(R.id.text_view_failure)
TextView viewError;
@Bind(R.id.progress_bar_sign_up)
ProgressBar signUpProgressBar;
@Bind(R.id.btn_sign_up)
AppCompatButton buttonSignUp;
@Bind(R.id.link_cancel)
TextView linkCancel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
connectionStatusReceiver = new ConnectionStatusReceiver();
ButterKnife.bind(this);
}
@OnClick(R.id.btn_sign_up)
public void OnSignUpClick() {
if (connectionStatusReceiver.isConnected()) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString();
presenter.validateCredential(new AuthCredentials(email, password));
}
}
@OnClick(R.id.link_cancel)
public void OnCancelClick() {
}
@Override
protected void onResume(){
super.onResume();
registerReceiver(connectionStatusReceiver, ConnectionStatusReceiver.filter);
}
@NonNull
@Override
public RegistrationPresenter createPresenter() {
return new RegistrationPresenter();
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(connectionStatusReceiver);
}
@Override
public void onNewViewStateInstance() {
}
@Override
public void showPasswordInconsistent() {
}
@Override
public void showLoginForm() {
}
@Override
public void showAuthError() {
}
@Override
public void showNetworkError() {
}
@Override
public void showUnexpectedError() {
}
@Override
public void showEmptyEmailError() {
setFieldError(inputEmail, getString(R.string.empty_field));
}
@Override
public void showEmptyPasswordError() {
setFieldError(inputPassword, getString(R.string.empty_field));
}
@Override
public void showInvalidEmailError() {
setFieldError(inputEmail, getString(R.string.invalid_email));
}
@Override
public void showInvalidPasswordError() {
}
@Override
public void showTooShortPasswordError() {
setFieldError(inputPassword, getString(R.string.too_short_password));
}
@Override
public void showLoading() {
LoginViewState vs = (LoginViewState) viewState;
vs.setShowLoading();
}
@Override
public void loginSuccessful() {
Intent intent = new Intent(RegistrationActivity.this, DecksActivity.class);
startActivity(intent);
finish();
}
@Override
public Context getContext() {
return RegistrationActivity.this;
}
@NonNull
@Override
public ViewState<LoginView> createViewState() {
return new LoginViewState();
}
private void setFieldError(TextInputEditText field, String message) {
LoginViewState vs = (LoginViewState) viewState;
vs.setShowLoginForm();
field.setError(message);
field.requestFocus();
}
/**
* Applies custom font to every activity that overrides this method
*/
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
}
| Network error handling
| app/src/main/java/com/blstream/studybox/activities/RegistrationActivity.java | Network error handling |
|
Java | apache-2.0 | 1f0edab0d1022c1a0ab43aa73c112ad49e1c3b28 | 0 | rjenkinsjr/smart-reactor-maven-extension | package util;
import info.ronjenkins.maven.rtr.RTR;
import info.ronjenkins.maven.rtr.steps.SmartReactorStep;
import info.ronjenkins.maven.rtr.steps.release.AbstractSmartReactorReleaseStep;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import mockit.Deencapsulation;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.Validate;
import org.apache.maven.shared.release.config.ReleaseDescriptor;
import org.apache.maven.shared.release.env.ReleaseEnvironment;
import org.apache.maven.shared.release.phase.ReleasePhase;
/**
* Utility functions to facilitate testing.
*
* @author Ronald Jack Jenkins Jr.
*/
public final class TestUtils {
/**
* Adds a test logger to a smart reactor step for testing.
*
* @param step
* not null.
* @return never null.
*/
public static TestLogger addLogger(final SmartReactorStep step) {
Validate.notNull(step, "step is null");
final TestLogger logger = new TestLogger();
Deencapsulation.setField(step, "logger", logger);
return logger;
}
/**
* Adds a test logger and other dependencies to a smart reactor release step
* for testing.
*
* @param step
* not null.
* @param rtr
* not null.
* @param releasePhases
* can be null, which is coerced to an empty list.
* @param rollbackPhases
* can be null, which is coerced to an empty list.
* @param availablePhases
* can be null.
* @param releaseDescriptor
* can be null.
* @param releaseEnvironment
* can be null.
* @return never null.
*/
public static TestLogger addLoggerAndReleaseDependencies(
final AbstractSmartReactorReleaseStep step, final RTR rtr,
final List<String> releasePhases,
final List<String> rollbackPhases,
final Map<String, ReleasePhase> availablePhases,
final ReleaseDescriptor releaseDescriptor,
final ReleaseEnvironment releaseEnvironment) {
Validate.notNull(step, "step is null");
Validate.notNull(rtr, "rtr is null");
final TestLogger logger = addLogger(step);
Deencapsulation.setField(step, "rtr", rtr);
Deencapsulation.setField(
step,
"releasePhases",
ObjectUtils.defaultIfNull(releasePhases,
Collections.emptyList()));
Deencapsulation.setField(
step,
"rollbackPhases",
ObjectUtils.defaultIfNull(rollbackPhases,
Collections.emptyList()));
Deencapsulation.setField(step, "availablePhases", availablePhases);
Deencapsulation.setField(step, "releaseDescriptor", releaseDescriptor);
Deencapsulation
.setField(step, "releaseEnvironment", releaseEnvironment);
return logger;
}
/** Uninstantiable. */
private TestUtils() {
}
}
| src/test/java/util/TestUtils.java | package util;
import info.ronjenkins.maven.rtr.RTR;
import info.ronjenkins.maven.rtr.steps.SmartReactorStep;
import info.ronjenkins.maven.rtr.steps.release.AbstractSmartReactorReleaseStep;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import mockit.Deencapsulation;
import mockit.Mock;
import mockit.MockUp;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.Validate;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
import org.apache.maven.artifact.handler.ArtifactHandler;
import org.apache.maven.model.Model;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.release.config.ReleaseDescriptor;
import org.apache.maven.shared.release.env.ReleaseEnvironment;
import org.apache.maven.shared.release.phase.ReleasePhase;
/**
* Utility functions to facilitate testing.
*
* @author Ronald Jack Jenkins Jr.
*/
public final class TestUtils {
/**
* Adds a test logger to a smart reactor step for testing.
*
* @param step
* not null.
* @return never null.
*/
public static TestLogger addLogger(final SmartReactorStep step) {
Validate.notNull(step, "step is null");
final TestLogger logger = new TestLogger();
Deencapsulation.setField(step, "logger", logger);
return logger;
}
/**
* Adds a test logger and other dependencies to a smart reactor release step
* for testing.
*
* @param step
* not null.
* @param rtr
* not null.
* @param releasePhases
* can be null, which is coerced to an empty list.
* @param rollbackPhases
* can be null, which is coerced to an empty list.
* @param availablePhases
* can be null.
* @param releaseDescriptor
* can be null.
* @param releaseEnvironment
* can be null.
* @return never null.
*/
public static TestLogger addLoggerAndReleaseDependencies(
final AbstractSmartReactorReleaseStep step, final RTR rtr,
final List<String> releasePhases,
final List<String> rollbackPhases,
final Map<String, ReleasePhase> availablePhases,
final ReleaseDescriptor releaseDescriptor,
final ReleaseEnvironment releaseEnvironment) {
Validate.notNull(step, "step is null");
Validate.notNull(rtr, "rtr is null");
final TestLogger logger = addLogger(step);
Deencapsulation.setField(step, "rtr", rtr);
Deencapsulation.setField(
step,
"releasePhases",
ObjectUtils.defaultIfNull(releasePhases,
Collections.emptyList()));
Deencapsulation.setField(
step,
"rollbackPhases",
ObjectUtils.defaultIfNull(rollbackPhases,
Collections.emptyList()));
Deencapsulation.setField(step, "availablePhases", availablePhases);
Deencapsulation.setField(step, "releaseDescriptor", releaseDescriptor);
Deencapsulation
.setField(step, "releaseEnvironment", releaseEnvironment);
return logger;
}
/**
* Returns a new MavenProject object whose GAV matches the given parameters.
* The scope is "compile", the type/packaging is "jar" and the classifier is
* blank.
*
* <p>
* The underlying {@link Model} and {@link ArtifactHandler} are mocked, but
* the underlying {@link Artifact} is not.
*
* @param groupId
* not null.
* @param artifactId
* not null.
* @param version
* not null.
* @return never null.
*/
public static MavenProject mockMavenProject(final String groupId,
final String artifactId, final String version) {
return mockMavenProject(groupId, artifactId, version, "compile", "jar",
"");
}
/**
* Returns a new MavenProject object whose scope and coordinate matches the
* given parameters.
*
* <p>
* The underlying {@link Model} and {@link ArtifactHandler} are mocked, but
* the underlying {@link Artifact} is not.
*
* @param groupId
* not null.
* @param artifactId
* not null.
* @param version
* not null.
* @param scope
* not null.
* @param type
* not null.
* @param classifier
* not null.
* @return never null.
*/
public static MavenProject mockMavenProject(final String groupId,
final String artifactId, final String version, final String scope,
final String type, final String classifier) {
Validate.notNull(groupId, "groupId is null");
Validate.notNull(artifactId, "artifactId is null");
Validate.notNull(version, "version is null");
Validate.notNull(scope, "scope is null");
Validate.notNull(type, "type is null");
Validate.notNull(classifier, "classifier is null");
final Model model = new MockUp<Model>() {
@Mock
String getGroupId() {
return groupId;
}
@Mock
String getArtifactId() {
return artifactId;
}
@Mock
String getVersion() {
return version;
}
@Mock
String getPackaging() {
return type;
}
@Mock
public Model clone() {
return this.getMockInstance();
}
}.getMockInstance();
final ArtifactHandler ah = new MockUp<ArtifactHandler>() {
@Mock
String getExtension() {
return type;
}
@Mock
String getDirectory() {
return "";
}
@Mock
String getClassifier() {
return classifier;
}
@Mock
String getPackaging() {
return type;
}
}.getMockInstance();
final Artifact artifact = new DefaultArtifact(groupId, artifactId,
version, scope, type, classifier, ah);
final MavenProject project = new MavenProject(model);
project.setArtifact(artifact);
return project;
}
/** Uninstantiable. */
private TestUtils() {
}
}
| Remove unused testing utility methods.
| src/test/java/util/TestUtils.java | Remove unused testing utility methods. |
|
Java | apache-2.0 | 4a34ff3e6833dee27b05938ee2431771af3c455f | 0 | tmpgit/intellij-community,ernestp/consulo,ibinti/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,da1z/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,holmes/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,kool79/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,jagguli/intellij-community,jagguli/intellij-community,FHannes/intellij-community,signed/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,nicolargo/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,amith01994/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,holmes/intellij-community,xfournet/intellij-community,joewalnes/idea-community,adedayo/intellij-community,diorcety/intellij-community,apixandru/intellij-community,supersven/intellij-community,izonder/intellij-community,signed/intellij-community,amith01994/intellij-community,izonder/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,signed/intellij-community,samthor/intellij-community,ibinti/intellij-community,fnouama/intellij-community,FHannes/intellij-community,slisson/intellij-community,da1z/intellij-community,fitermay/intellij-community,fitermay/intellij-community,kool79/intellij-community,caot/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,clumsy/intellij-community,caot/intellij-community,slisson/intellij-community,samthor/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,consulo/consulo,slisson/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,consulo/consulo,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,signed/intellij-community,semonte/intellij-community,akosyakov/intellij-community,signed/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,jexp/idea2,samthor/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,apixandru/intellij-community,consulo/consulo,jagguli/intellij-community,ryano144/intellij-community,asedunov/intellij-community,blademainer/intellij-community,semonte/intellij-community,vladmm/intellij-community,holmes/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,amith01994/intellij-community,clumsy/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,joewalnes/idea-community,retomerz/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,jexp/idea2,dslomov/intellij-community,robovm/robovm-studio,kdwink/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,robovm/robovm-studio,apixandru/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,jexp/idea2,signed/intellij-community,ryano144/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,adedayo/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,dslomov/intellij-community,joewalnes/idea-community,ahb0327/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,FHannes/intellij-community,jagguli/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,slisson/intellij-community,consulo/consulo,samthor/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,jexp/idea2,wreckJ/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,robovm/robovm-studio,FHannes/intellij-community,robovm/robovm-studio,holmes/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,joewalnes/idea-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,allotria/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,blademainer/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,semonte/intellij-community,dslomov/intellij-community,kdwink/intellij-community,asedunov/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,signed/intellij-community,fitermay/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,samthor/intellij-community,supersven/intellij-community,retomerz/intellij-community,clumsy/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,retomerz/intellij-community,fitermay/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,samthor/intellij-community,youdonghai/intellij-community,semonte/intellij-community,joewalnes/idea-community,allotria/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,hurricup/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,supersven/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,kdwink/intellij-community,slisson/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,fnouama/intellij-community,holmes/intellij-community,ahb0327/intellij-community,semonte/intellij-community,clumsy/intellij-community,caot/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,semonte/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,da1z/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,ernestp/consulo,tmpgit/intellij-community,signed/intellij-community,FHannes/intellij-community,amith01994/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,blademainer/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,joewalnes/idea-community,salguarnieri/intellij-community,hurricup/intellij-community,clumsy/intellij-community,signed/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,ibinti/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,signed/intellij-community,salguarnieri/intellij-community,ernestp/consulo,akosyakov/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,dslomov/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,akosyakov/intellij-community,jexp/idea2,retomerz/intellij-community,ernestp/consulo,suncycheng/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,fnouama/intellij-community,asedunov/intellij-community,adedayo/intellij-community,signed/intellij-community,consulo/consulo,MER-GROUP/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,kool79/intellij-community,jexp/idea2,supersven/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,petteyg/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,amith01994/intellij-community,signed/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,slisson/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,caot/intellij-community,fitermay/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,joewalnes/idea-community,ftomassetti/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,petteyg/intellij-community,robovm/robovm-studio,FHannes/intellij-community,adedayo/intellij-community,xfournet/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,asedunov/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,caot/intellij-community,tmpgit/intellij-community,signed/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,hurricup/intellij-community,apixandru/intellij-community,izonder/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,ernestp/consulo,adedayo/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,jagguli/intellij-community,blademainer/intellij-community,xfournet/intellij-community,asedunov/intellij-community,da1z/intellij-community,retomerz/intellij-community,samthor/intellij-community,holmes/intellij-community,joewalnes/idea-community,diorcety/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,blademainer/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,allotria/intellij-community,supersven/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,blademainer/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,orekyuu/intellij-community,blademainer/intellij-community,kdwink/intellij-community,supersven/intellij-community,joewalnes/idea-community,allotria/intellij-community,jexp/idea2,salguarnieri/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,ibinti/intellij-community,blademainer/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,caot/intellij-community,retomerz/intellij-community,holmes/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,allotria/intellij-community,jexp/idea2,MER-GROUP/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,dslomov/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,izonder/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,slisson/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,da1z/intellij-community,semonte/intellij-community,diorcety/intellij-community,vladmm/intellij-community,supersven/intellij-community,youdonghai/intellij-community,ernestp/consulo,blademainer/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,kdwink/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,da1z/intellij-community,ahb0327/intellij-community,izonder/intellij-community,caot/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,semonte/intellij-community,amith01994/intellij-community,apixandru/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,hurricup/intellij-community,consulo/consulo,vladmm/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,izonder/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,vladmm/intellij-community,petteyg/intellij-community,amith01994/intellij-community | /*
* Copyright 2000-2005 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* Service for validating and parsing Java identifiers.
*
* @see com.intellij.psi.PsiManager#getNameHelper()
*/
public abstract class PsiNameHelper {
@NonNls private static final Pattern WHITESPACE_PATTERN = Pattern.compile("(?:\\s)|(?:/\\*.*\\*/)|(?://[^\\n]*)");
/**
* Checks if the specified text is a Java identifier, using the language level of the project
* with which the name helper is associated to filter out keywords.
*
* @param text the text to check.
* @return true if the text is an identifier, false otherwise
*/
public abstract boolean isIdentifier(String text);
/**
* Checks if the specified text is a Java identifier, using the specified language level
* with which the name helper is associated to filter out keywords.
*
* @param text the text to check.
* @return true if the text is an identifier, false otherwise
*/
public abstract boolean isIdentifier(String text, LanguageLevel languageLevel);
/**
* Checks if the specified text is a Java keyword, using the language level of the project
* with which the name helper is associated.
*
* @param text the text to check.
* @return true if the text is a keyword, false otherwise
*/
public abstract boolean isKeyword(String text);
/**
* Checks if the specified string is a qualified name (sequence of identifiers separated by
* periods).
*
* @param text the text to check.
* @return true if the text is a qualified name, false otherwise.
*/
public abstract boolean isQualifiedName(String text);
public static String getShortClassName(@NotNull String referenceText) {
return getShortClassName(referenceText, true);
}
private static String getShortClassName(String referenceText, boolean flag) {
final char[] chars = referenceText.toCharArray();
int lessPos = chars.length;
int count = 0;
for (int i = chars.length - 1; i >= 0; i--) {
final char aChar = chars[i];
switch (aChar) {
case ')':
case '>':
count++;
break;
case '(':
case '<':
count--;
lessPos = i;
break;
case '@':
case '.':
if (count == 0) return new String(chars, i + 1, lessPos - (i + 1)).trim();
break;
default:
if (count == 0) {
if (Character.isWhitespace(aChar)) {
break;
}
else if (flag && !Character.isJavaIdentifierPart(aChar)) {
return getShortClassName(
removeWhitespace(referenceText), false);
}
}
}
}
return new String(chars, 0, lessPos).trim();
}
public static String getPresentableText(PsiJavaCodeReferenceElement ref) {
StringBuffer buffer = new StringBuffer();
buffer.append(ref.getReferenceName());
PsiType[] typeParameters = ref.getTypeParameters();
if (typeParameters.length > 0) {
buffer.append("<");
for (int i = 0; i < typeParameters.length; i++) {
buffer.append(typeParameters[i].getPresentableText());
if (i < typeParameters.length - 1) buffer.append(", ");
}
buffer.append(">");
}
return buffer.toString();
}
public static String getQualifiedClassName(String referenceText, boolean removeWhitespace) {
if (removeWhitespace) {
referenceText = removeWhitespace(referenceText);
}
if (referenceText.indexOf('<') < 0) return referenceText;
final StringBuffer buffer = new StringBuffer(referenceText.length());
final char[] chars = referenceText.toCharArray();
int gtPos = 0;
int count = 0;
for (int i = 0; i < chars.length; i++) {
final char aChar = chars[i];
switch (aChar) {
case '<':
count++;
if (count == 1) buffer.append(new String(chars, gtPos, i - gtPos));
break;
case '>':
count--;
gtPos = i + 1;
break;
}
}
if (count == 0) {
buffer.append(new String(chars, gtPos, chars.length - gtPos));
}
return buffer.toString();
}
private static String removeWhitespace(String referenceText) {
return WHITESPACE_PATTERN.matcher(referenceText).replaceAll("");
}
/**
* Obtains text of all type parameter values in a reference.
* They go in left-to-right order: <code>A<List<String>>.B<Integer></code> yields
* <code>["List<String>","Integer"]</code>
*
* @param referenceText the text of the reference to calculate type parameters for.
* @return the calculated array of type parameters.
*/
public static String[] getClassParametersText(String referenceText) {
if (referenceText.indexOf('<') < 0) return ArrayUtil.EMPTY_STRING_ARRAY;
referenceText = removeWhitespace(referenceText);
final char[] chars = referenceText.toCharArray();
int count = 0;
int dim = 0;
for(final char aChar : chars) {
switch (aChar) {
case '<':
count++;
if (count == 1) dim++;
break;
case ',':
if (count == 1) dim++;
break;
case '>':
count--;
break;
}
}
if (count != 0 || dim == 0) return ArrayUtil.EMPTY_STRING_ARRAY;
final String[] result = new String[dim];
dim = 0;
int ltPos = 0;
for (int i = 0; i < chars.length; i++) {
final char aChar = chars[i];
switch (aChar) {
case '<':
count++;
if (count == 1) ltPos = i;
break;
case ',':
if (count == 1) {
result[dim++] = new String(chars, ltPos + 1, i - ltPos - 1);
ltPos = i;
}
break;
case '>':
count--;
if (count == 0) result[dim++] = new String(chars, ltPos + 1, i - ltPos - 1);
break;
}
}
return result;
}
/**
* Splits an identifier into words, separated with underscores or upper-case characters
* (camel-case).
*
* @param name the identifier to split.
* @return the array of strings into which the identifier has been split.
*/
public static String[] splitNameIntoWords(@NotNull String name) {
final String[] underlineDelimited = name.split("_");
List<String> result = new ArrayList<String>();
for (String word : underlineDelimited) {
addAllWords(word, result);
}
return result.toArray(new String[result.size()]);
}
private static final int NO_WORD = 0;
private static final int PREV_UC = 1;
private static final int WORD = 2;
private static void addAllWords(String word, List<String> result) {
CharacterIterator it = new StringCharacterIterator(word);
StringBuffer b = new StringBuffer();
int state = NO_WORD;
char curPrevUC = '\0';
for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
switch (state) {
case NO_WORD:
if (!Character.isUpperCase(c)) {
b.append(c);
state = WORD;
}
else {
state = PREV_UC;
curPrevUC = c;
}
break;
case PREV_UC:
if (!Character.isUpperCase(c)) {
b = startNewWord(result, b, curPrevUC);
b.append(c);
state = WORD;
}
else {
b.append(curPrevUC);
state = PREV_UC;
curPrevUC = c;
}
break;
case WORD:
if (Character.isUpperCase(c)) {
startNewWord(result, b, c);
b.setLength(0);
state = PREV_UC;
curPrevUC = c;
}
else {
b.append(c);
}
break;
}
}
if (state == PREV_UC) {
b.append(curPrevUC);
}
result.add(b.toString());
}
private static StringBuffer startNewWord(List<String> result, StringBuffer b, char c) {
if (b.length() > 0) {
result.add(b.toString());
}
b = new StringBuffer();
b.append(c);
return b;
}
}
| openapi/src/com/intellij/psi/PsiNameHelper.java | /*
* Copyright 2000-2005 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* Service for validating and parsing Java identifiers.
*
* @see com.intellij.psi.PsiManager#getNameHelper()
*/
public abstract class PsiNameHelper {
@NonNls private static final Pattern WHITESPACE_PATTERN = Pattern.compile("(?:\\s)|(?:/\\*.*\\*/)|(?://[^\\n]*)");
/**
* Checks if the specified text is a Java identifier, using the language level of the project
* with which the name helper is associated to filter out keywords.
*
* @param text the text to check.
* @return true if the text is an identifier, false otherwise
*/
public abstract boolean isIdentifier(String text);
/**
* Checks if the specified text is a Java identifier, using the specified language level
* with which the name helper is associated to filter out keywords.
*
* @param text the text to check.
* @return true if the text is an identifier, false otherwise
*/
public abstract boolean isIdentifier(String text, LanguageLevel languageLevel);
/**
* Checks if the specified text is a Java keyword, using the language level of the project
* with which the name helper is associated.
*
* @param text the text to check.
* @return true if the text is a keyword, false otherwise
*/
public abstract boolean isKeyword(String text);
/**
* Checks if the specified string is a qualified name (sequence of identifiers separated by
* periods).
*
* @param text the text to check.
* @return true if the text is a qualified name, false otherwise.
*/
public abstract boolean isQualifiedName(String text);
public static String getShortClassName(String referenceText) {
return getShortClassName(referenceText, true);
}
private static String getShortClassName(String referenceText, boolean flag) {
final char[] chars = referenceText.toCharArray();
int lessPos = chars.length;
int count = 0;
for (int i = chars.length - 1; i >= 0; i--) {
final char aChar = chars[i];
switch (aChar) {
case ')':
case '>':
count++;
break;
case '(':
case '<':
count--;
lessPos = i;
break;
case '@':
case '.':
if (count == 0) return new String(chars, i + 1, lessPos - (i + 1)).trim();
break;
default:
if (count == 0) {
if (Character.isWhitespace(aChar)) {
break;
}
else if (flag && !Character.isJavaIdentifierPart(aChar)) {
return getShortClassName(
removeWhitespace(referenceText), false);
}
}
}
}
return new String(chars, 0, lessPos).trim();
}
public static String getPresentableText(PsiJavaCodeReferenceElement ref) {
StringBuffer buffer = new StringBuffer();
buffer.append(ref.getReferenceName());
PsiType[] typeParameters = ref.getTypeParameters();
if (typeParameters.length > 0) {
buffer.append("<");
for (int i = 0; i < typeParameters.length; i++) {
buffer.append(typeParameters[i].getPresentableText());
if (i < typeParameters.length - 1) buffer.append(", ");
}
buffer.append(">");
}
return buffer.toString();
}
public static String getQualifiedClassName(String referenceText, boolean removeWhitespace) {
if (removeWhitespace) {
referenceText = removeWhitespace(referenceText);
}
if (referenceText.indexOf('<') < 0) return referenceText;
final StringBuffer buffer = new StringBuffer(referenceText.length());
final char[] chars = referenceText.toCharArray();
int gtPos = 0;
int count = 0;
for (int i = 0; i < chars.length; i++) {
final char aChar = chars[i];
switch (aChar) {
case '<':
count++;
if (count == 1) buffer.append(new String(chars, gtPos, i - gtPos));
break;
case '>':
count--;
gtPos = i + 1;
break;
}
}
if (count == 0) {
buffer.append(new String(chars, gtPos, chars.length - gtPos));
}
return buffer.toString();
}
private static String removeWhitespace(String referenceText) {
return WHITESPACE_PATTERN.matcher(referenceText).replaceAll("");
}
/**
* Obtains text of all type parameter values in a reference.
* They go in left-to-right order: <code>A<List<String>>.B<Integer></code> yields
* <code>["List<String>","Integer"]</code>
*
* @param referenceText the text of the reference to calculate type parameters for.
* @return the calculated array of type parameters.
*/
public static String[] getClassParametersText(String referenceText) {
if (referenceText.indexOf('<') < 0) return ArrayUtil.EMPTY_STRING_ARRAY;
referenceText = removeWhitespace(referenceText);
final char[] chars = referenceText.toCharArray();
int count = 0;
int dim = 0;
for(final char aChar : chars) {
switch (aChar) {
case '<':
count++;
if (count == 1) dim++;
break;
case ',':
if (count == 1) dim++;
break;
case '>':
count--;
break;
}
}
if (count != 0 || dim == 0) return ArrayUtil.EMPTY_STRING_ARRAY;
final String[] result = new String[dim];
dim = 0;
int ltPos = 0;
for (int i = 0; i < chars.length; i++) {
final char aChar = chars[i];
switch (aChar) {
case '<':
count++;
if (count == 1) ltPos = i;
break;
case ',':
if (count == 1) {
result[dim++] = new String(chars, ltPos + 1, i - ltPos - 1);
ltPos = i;
}
break;
case '>':
count--;
if (count == 0) result[dim++] = new String(chars, ltPos + 1, i - ltPos - 1);
break;
}
}
return result;
}
/**
* Splits an identifier into words, separated with underscores or upper-case characters
* (camel-case).
*
* @param name the identifier to split.
* @return the array of strings into which the identifier has been split.
*/
public static String[] splitNameIntoWords(@NotNull String name) {
final String[] underlineDelimited = name.split("_");
List<String> result = new ArrayList<String>();
for (String word : underlineDelimited) {
addAllWords(word, result);
}
return result.toArray(new String[result.size()]);
}
private static final int NO_WORD = 0;
private static final int PREV_UC = 1;
private static final int WORD = 2;
private static void addAllWords(String word, List<String> result) {
CharacterIterator it = new StringCharacterIterator(word);
StringBuffer b = new StringBuffer();
int state = NO_WORD;
char curPrevUC = '\0';
for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
switch (state) {
case NO_WORD:
if (!Character.isUpperCase(c)) {
b.append(c);
state = WORD;
}
else {
state = PREV_UC;
curPrevUC = c;
}
break;
case PREV_UC:
if (!Character.isUpperCase(c)) {
b = startNewWord(result, b, curPrevUC);
b.append(c);
state = WORD;
}
else {
b.append(curPrevUC);
state = PREV_UC;
curPrevUC = c;
}
break;
case WORD:
if (Character.isUpperCase(c)) {
startNewWord(result, b, c);
b.setLength(0);
state = PREV_UC;
curPrevUC = c;
}
else {
b.append(c);
}
break;
}
}
if (state == PREV_UC) {
b.append(curPrevUC);
}
result.add(b.toString());
}
private static StringBuffer startNewWord(List<String> result, StringBuffer b, char c) {
if (b.length() > 0) {
result.add(b.toString());
}
b = new StringBuffer();
b.append(c);
return b;
}
}
| (no message) | openapi/src/com/intellij/psi/PsiNameHelper.java | (no message) |
|
Java | apache-2.0 | 5ed2b83b27dedc099908ec330b84428c7a20a820 | 0 | MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim | package sbmleditor;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.regex.*;
import javax.swing.*;
import org.sbml.libsbml.*;
import biomodelsim.*;
import reb2sac.*;
import buttons.*;
/**
* This is the SBML_Editor class. It takes in an sbml file and allows the user
* to edit it by changing different fields displayed in a frame. It also
* implements the ActionListener class, the MouseListener class, and the
* KeyListener class which allows it to perform certain actions when buttons are
* clicked on the frame, when one of the JList's items is double clicked, or
* when text is entered into the model's ID.
*
* @author Curtis Madsen
*/
public class SBML_Editor extends JPanel implements ActionListener, MouseListener {
private static final long serialVersionUID = 8236967001410906807L;
private SBMLDocument document; // sbml document
private String file; // SBML file
/*
* compartment buttons
*/
private JButton addCompart, removeCompart, editCompart;
private JButton addFunction, removeFunction, editFunction;
private JButton addUnit, removeUnit, editUnit;
private JButton addList, removeList, editList;
private JButton addCompType, removeCompType, editCompType;
private JButton addSpecType, removeSpecType, editSpecType;
private JButton addInit, removeInit, editInit;
private JButton addRule, removeRule, editRule;
private JButton addEvent, removeEvent, editEvent;
private JButton addAssignment, removeAssignment, editAssignment;
private JButton addConstraint, removeConstraint, editConstraint;
private String[] comps; // array of compartments
private String[] funcs; // array of functions
private String[] units; // array of units
private String[] uList; // unit list array
private String[] cpTyp; // array of compartment types
private String[] spTyp; // array of species types
private String[] inits; // array of initial assignments
private String[] rul; // array of rules
private String[] ev; // array of events
private String[] assign; // array of event assignments
private String[] origAssign; // array of original event assignments
private String[] cons; // array of constraints
private JList compartments; // JList of compartments
private JList functions; // JList of functions
private JList unitDefs; // JList of units
private JList unitList; // unit JList
private JList compTypes; // JList of compartment types
private JList specTypes; // JList of species types
private JList initAssigns; // JList of initial assignments
private JList rules; // JList of rules
private JList events; // JList of events
private JList eventAssign; // JList of event assignments
private JList constraints; // JList of constraints
private JTextField compID, compSize, compName; // compartment fields;
private JTextField funcID, funcName, eqn, args; // function fields;
private JTextField unitID, unitName; // unit defn fields;
private JTextField exp, scale, mult; // unit list fields;
private JTextField compTypeID, compTypeName; // compartment type fields;
private JTextField specTypeID, specTypeName; // species type fields;
private JComboBox initVar; // init fields;
private JTextField initMath; // init fields;
private JComboBox ruleType, ruleVar; // rule fields;
private JTextField ruleMath; // rule fields;
private JTextField eventID, eventName, eventTrigger, eventDelay; // event
// fields;
private JComboBox eaID; // event assignment fields;
private JTextField consID, consMath, consMessage; // constraints fields;
private JButton addSpec, removeSpec, editSpec; // species buttons
private String[] specs; // array of species
private JList species; // JList of species
private JTextField ID, init, Name; // species text fields
private JComboBox compUnits, compOutside, compConstant; // compartment units
// combo box
private JComboBox compTypeBox, dimBox; // compartment type combo box
private JComboBox specTypeBox, specBoundary, specConstant; // species combo
// boxes
private JComboBox specUnits, initLabel, stoiciLabel;
private JComboBox comp; // compartment combo box
private boolean change; // determines if any changes were made
private JTextField modelID; // the model's ID
private JTextField modelName; // the model's Name
private JList reactions; // JList of reactions
private String[] reacts; // array of reactions
/*
* reactions buttons
*/
private JButton addReac, removeReac, editReac, copyReac;
private JList parameters; // JList of parameters
private String[] params; // array of parameters
private JButton addParam, removeParam, editParam; // parameters buttons
/*
* parameters text fields
*/
private JTextField paramID, paramName, paramValue;
private JComboBox paramUnits;
private JComboBox paramConst;
private JList reacParameters; // JList of reaction parameters
private String[] reacParams; // array of reaction parameters
/*
* reaction parameters buttons
*/
private JButton reacAddParam, reacRemoveParam, reacEditParam;
/*
* reaction parameters text fields
*/
private JTextField reacParamID, reacParamValue, reacParamName;
private JComboBox reacParamUnits;
private ArrayList<Parameter> changedParameters; // ArrayList of parameters
private JTextField reacID, reacName; // reaction name and id text
// fields
private JComboBox reacReverse, reacFast; // reaction reversible, fast combo
// boxes
/*
* reactant buttons
*/
private JButton addReactant, removeReactant, editReactant;
private JList reactants; // JList for reactants
private String[] reacta; // array for reactants
/*
* ArrayList of reactants
*/
private ArrayList<SpeciesReference> changedReactants;
/*
* product buttons
*/
private JButton addProduct, removeProduct, editProduct;
private JList products; // JList for products
private String[] product; // array for products
/*
* ArrayList of products
*/
private ArrayList<SpeciesReference> changedProducts;
/*
* modifier buttons
*/
private JButton addModifier, removeModifier, editModifier;
private JList modifiers; // JList for modifiers
private String[] modifier; // array for modifiers
/*
* ArrayList of modifiers
*/
private ArrayList<ModifierSpeciesReference> changedModifiers;
private JComboBox productSpecies; // ComboBox for product editing
private JComboBox modifierSpecies; // ComboBox for modifier editing
private JTextField productStoiciometry; // text field for editing products
private JComboBox reactantSpecies; // ComboBox for reactant editing
/*
* text field for editing reactants
*/
private JTextField reactantStoiciometry;
private JTextArea kineticLaw; // text area for editing kinetic law
private Reb2Sac reb2sac; // reb2sac options
private JButton saveNoRun, run, saveAs, check; // save and run buttons
private Log log;
private ArrayList<String> usedIDs;
private ArrayList<String> thisReactionParams;
private BioSim biosim;
private JButton useMassAction, clearKineticLaw;
private String separator;
private boolean paramsOnly;
private String simDir;
private String paramFile;
private ArrayList<String> parameterChanges;
private Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*");
private boolean editComp = false;
private String refFile;
/**
* Creates a new SBML_Editor and sets up the frame where the user can edit a
* new sbml file.
*/
public SBML_Editor(Reb2Sac reb2sac, Log log, BioSim biosim, String simDir, String paramFile) {
this.reb2sac = reb2sac;
paramsOnly = (reb2sac != null);
this.log = log;
this.biosim = biosim;
this.simDir = simDir;
this.paramFile = paramFile;
if (paramFile != null) {
try {
Scanner scan = new Scanner(new File(paramFile));
if (scan.hasNextLine()) {
refFile = scan.nextLine();
}
scan.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to read parameter file.", "Error",
JOptionPane.ERROR_MESSAGE);
refFile = "";
}
}
createSbmlFrame("");
}
/**
* Creates a new SBML_Editor and sets up the frame where the user can edit the
* sbml file given to this constructor.
*/
public SBML_Editor(String file, Reb2Sac reb2sac, Log log, BioSim biosim, String simDir,
String paramFile) {
this.reb2sac = reb2sac;
paramsOnly = (reb2sac != null);
this.log = log;
this.biosim = biosim;
this.simDir = simDir;
this.paramFile = paramFile;
if (paramFile != null) {
try {
Scanner scan = new Scanner(new File(paramFile));
if (scan.hasNextLine()) {
refFile = scan.nextLine();
}
scan.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to read parameter file.", "Error",
JOptionPane.ERROR_MESSAGE);
refFile = file;
}
}
createSbmlFrame(file);
}
/**
* Private helper method that helps create the sbml frame.
*/
private void createSbmlFrame(String file) {
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
// intitializes the member variables
if (!file.equals("")) {
this.file = file;
}
else {
this.file = null;
}
// creates the sbml reader and reads the sbml file
Model model;
if (!file.equals("")) {
SBMLReader reader = new SBMLReader();
document = reader.readSBML(file);
model = document.getModel();
modelName = new JTextField(model.getName(), 50);
if (model.getId().equals("")) {
String modelID = file.split(separator)[file.split(separator).length - 1];
if (modelID.indexOf('.') >= 0) {
modelID = modelID.substring(0, modelID.indexOf('.'));
}
model.setId(modelID);
save(false);
}
}
else {
document = new SBMLDocument();
model = document.createModel();
}
document.setLevelAndVersion(2, 3);
usedIDs = new ArrayList<String>();
if (model.isSetId()) {
usedIDs.add(model.getId());
}
ListOf ids = model.getListOfFunctionDefinitions();
for (int i = 0; i < model.getNumFunctionDefinitions(); i++) {
usedIDs.add(((FunctionDefinition) ids.get(i)).getId());
}
ids = model.getListOfUnitDefinitions();
for (int i = 0; i < model.getNumUnitDefinitions(); i++) {
usedIDs.add(((UnitDefinition) ids.get(i)).getId());
}
ids = model.getListOfCompartmentTypes();
for (int i = 0; i < model.getNumCompartmentTypes(); i++) {
usedIDs.add(((CompartmentType) ids.get(i)).getId());
}
ids = model.getListOfSpeciesTypes();
for (int i = 0; i < model.getNumSpeciesTypes(); i++) {
usedIDs.add(((SpeciesType) ids.get(i)).getId());
}
ids = model.getListOfCompartments();
for (int i = 0; i < model.getNumCompartments(); i++) {
usedIDs.add(((Compartment) ids.get(i)).getId());
}
ids = model.getListOfParameters();
for (int i = 0; i < model.getNumParameters(); i++) {
usedIDs.add(((Parameter) ids.get(i)).getId());
}
ids = model.getListOfReactions();
for (int i = 0; i < model.getNumReactions(); i++) {
usedIDs.add(((Reaction) ids.get(i)).getId());
}
ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
usedIDs.add(((Species) ids.get(i)).getId());
}
ids = model.getListOfConstraints();
for (int i = 0; i < model.getNumConstraints(); i++) {
usedIDs.add(((Constraint) ids.get(i)).getMetaId());
}
// sets up the compartments editor
JPanel comp = new JPanel(new BorderLayout());
JPanel addRemComp = new JPanel();
addCompart = new JButton("Add Compartment");
removeCompart = new JButton("Remove Compartment");
editCompart = new JButton("Edit Compartment");
addRemComp.add(addCompart);
addRemComp.add(removeCompart);
addRemComp.add(editCompart);
addCompart.addActionListener(this);
removeCompart.addActionListener(this);
editCompart.addActionListener(this);
if (paramsOnly) {
parameterChanges = new ArrayList<String>();
try {
Scanner scan = new Scanner(new File(paramFile));
if (scan.hasNextLine()) {
scan.nextLine();
}
while (scan.hasNextLine()) {
parameterChanges.add(scan.nextLine());
}
scan.close();
}
catch (Exception e) {
}
addCompart.setEnabled(false);
removeCompart.setEnabled(false);
}
JLabel compartmentsLabel = new JLabel("List of Compartments:");
compartments = new JList();
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(260, 220));
scroll.setPreferredSize(new Dimension(276, 152));
scroll.setViewportView(compartments);
ListOf listOfCompartments = model.getListOfCompartments();
comps = new String[(int) model.getNumCompartments()];
for (int i = 0; i < model.getNumCompartments(); i++) {
Compartment compartment = (Compartment) listOfCompartments.get(i);
if (compartment.isSetCompartmentType()) {
comps[i] = compartment.getId() + " " + compartment.getCompartmentType();
}
else {
comps[i] = compartment.getId();
}
if (compartment.isSetSize()) {
comps[i] += " " + compartment.getSize();
}
if (compartment.isSetUnits()) {
comps[i] += " " + compartment.getUnits();
}
if (paramsOnly) {
for (int j = 0; j < parameterChanges.size(); j++) {
if (parameterChanges.get(j).split(" ")[0].equals(compartment.getId())) {
String[] splits = parameterChanges.get(j).split(" ");
if (splits[splits.length - 2].equals("Custom")) {
String value = splits[splits.length - 1];
compartment.setSize(Double.parseDouble(value));
comps[i] += " " + splits[splits.length - 2] + " " + splits[splits.length - 1];
}
else if (splits[splits.length - 2].equals("Sweep")) {
String value = splits[splits.length - 1];
compartment.setSize(Double.parseDouble(value.split(",")[0].substring(1).trim()));
comps[i] += " " + splits[splits.length - 2] + " " + splits[splits.length - 1];
}
}
}
}
}
sort(comps);
compartments.setListData(comps);
compartments.addMouseListener(this);
comp.add(compartmentsLabel, "North");
comp.add(scroll, "Center");
comp.add(addRemComp, "South");
// sets up the species editor
JPanel spec = new JPanel(new BorderLayout());
JPanel addSpecs = new JPanel();
addSpec = new JButton("Add Species");
removeSpec = new JButton("Remove Species");
editSpec = new JButton("Edit Species");
addSpecs.add(addSpec);
addSpecs.add(removeSpec);
addSpecs.add(editSpec);
addSpec.addActionListener(this);
removeSpec.addActionListener(this);
editSpec.addActionListener(this);
if (paramsOnly) {
addSpec.setEnabled(false);
removeSpec.setEnabled(false);
}
JLabel speciesLabel = new JLabel("List of Species:");
species = new JList();
species.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll1 = new JScrollPane();
scroll1.setMinimumSize(new Dimension(260, 220));
scroll1.setPreferredSize(new Dimension(276, 152));
scroll1.setViewportView(species);
ListOf listOfSpecies = model.getListOfSpecies();
specs = new String[(int) model.getNumSpecies()];
for (int i = 0; i < model.getNumSpecies(); i++) {
Species species = (Species) listOfSpecies.get(i);
if (species.isSetSpeciesType()) {
specs[i] = species.getId() + " " + species.getSpeciesType() + " "
+ species.getCompartment();
}
else {
specs[i] = species.getId() + " " + species.getCompartment();
}
if (species.isSetInitialAmount()) {
specs[i] += " " + species.getInitialAmount();
}
else {
specs[i] += " " + species.getInitialConcentration();
}
if (species.isSetUnits()) {
specs[i] += " " + species.getUnits();
}
if (paramsOnly) {
for (int j = 0; j < parameterChanges.size(); j++) {
if (parameterChanges.get(j).split(" ")[0].equals(species.getId())) {
String[] splits = parameterChanges.get(j).split(" ");
if (splits[splits.length - 2].equals("Custom")) {
String value = splits[splits.length - 1];
if (species.isSetInitialAmount()) {
species.setInitialAmount(Double.parseDouble(value));
}
else {
species.setInitialConcentration(Double.parseDouble(value));
}
specs[i] += " " + splits[splits.length - 2] + " " + splits[splits.length - 1];
}
else if (splits[splits.length - 2].equals("Sweep")) {
String value = splits[splits.length - 1];
if (species.isSetInitialAmount()) {
species.setInitialAmount(Double
.parseDouble(value.split(",")[0].substring(1).trim()));
}
else {
species.setInitialConcentration(Double.parseDouble(value.split(",")[0].substring(1)
.trim()));
}
specs[i] += " " + splits[splits.length - 2] + " " + splits[splits.length - 1];
}
}
}
}
}
sort(specs);
species.setListData(specs);
species.setSelectedIndex(0);
species.addMouseListener(this);
spec.add(speciesLabel, "North");
spec.add(scroll1, "Center");
spec.add(addSpecs, "South");
// sets up the reactions editor
JPanel reac = new JPanel(new BorderLayout());
JPanel addReacs = new JPanel();
addReac = new JButton("Add Reaction");
removeReac = new JButton("Remove Reaction");
editReac = new JButton("Edit Reaction");
copyReac = new JButton("Copy Reaction");
addReacs.add(addReac);
addReacs.add(removeReac);
addReacs.add(editReac);
addReacs.add(copyReac);
addReac.addActionListener(this);
removeReac.addActionListener(this);
editReac.addActionListener(this);
copyReac.addActionListener(this);
if (paramsOnly) {
addReac.setEnabled(false);
removeReac.setEnabled(false);
copyReac.setEnabled(false);
}
JLabel reactionsLabel = new JLabel("List of Reactions:");
reactions = new JList();
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll2 = new JScrollPane();
scroll2.setMinimumSize(new Dimension(400, 220));
scroll2.setPreferredSize(new Dimension(436, 152));
scroll2.setViewportView(reactions);
ListOf listOfReactions = model.getListOfReactions();
reacts = new String[(int) model.getNumReactions()];
for (int i = 0; i < model.getNumReactions(); i++) {
Reaction reaction = (Reaction) listOfReactions.get(i);
reacts[i] = reaction.getId();
if (paramsOnly) {
ListOf params = reaction.getKineticLaw().getListOfParameters();
for (int j = 0; j < reaction.getKineticLaw().getNumParameters(); j++) {
Parameter paramet = ((Parameter) (params.get(j)));
for (int k = 0; k < parameterChanges.size(); k++) {
if (parameterChanges.get(k).split(" ")[0].equals(reaction.getId() + "/"
+ paramet.getId())) {
String[] splits = parameterChanges.get(k).split(" ");
if (splits[splits.length - 2].equals("Custom")) {
String value = splits[splits.length - 1];
paramet.setValue(Double.parseDouble(value));
}
else if (splits[splits.length - 2].equals("Sweep")) {
String value = splits[splits.length - 1];
paramet.setValue(Double.parseDouble(value.split(",")[0].substring(1).trim()));
}
if (!reacts[i].contains("Modified")) {
reacts[i] += " Modified";
}
}
}
}
}
}
sort(reacts);
reactions.setListData(reacts);
reactions.setSelectedIndex(0);
reactions.addMouseListener(this);
reac.add(reactionsLabel, "North");
reac.add(scroll2, "Center");
reac.add(addReacs, "South");
// sets up the parameters editor
JPanel param = new JPanel(new BorderLayout());
JPanel addParams = new JPanel();
addParam = new JButton("Add Parameter");
removeParam = new JButton("Remove Parameter");
editParam = new JButton("Edit Parameter");
addParams.add(addParam);
addParams.add(removeParam);
addParams.add(editParam);
addParam.addActionListener(this);
removeParam.addActionListener(this);
editParam.addActionListener(this);
if (paramsOnly) {
addParam.setEnabled(false);
removeParam.setEnabled(false);
}
JLabel parametersLabel = new JLabel("List of Global Parameters:");
parameters = new JList();
parameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll3 = new JScrollPane();
scroll3.setMinimumSize(new Dimension(260, 220));
scroll3.setPreferredSize(new Dimension(276, 152));
scroll3.setViewportView(parameters);
ListOf listOfParameters = model.getListOfParameters();
params = new String[(int) model.getNumParameters()];
for (int i = 0; i < model.getNumParameters(); i++) {
Parameter parameter = (Parameter) listOfParameters.get(i);
if (parameter.isSetUnits()) {
params[i] = parameter.getId() + " " + parameter.getValue() + " " + parameter.getUnits();
}
else {
params[i] = parameter.getId() + " " + parameter.getValue();
}
if (paramsOnly) {
for (int j = 0; j < parameterChanges.size(); j++) {
if (parameterChanges.get(j).split(" ")[0].equals(parameter.getId())) {
String[] splits = parameterChanges.get(j).split(" ");
if (splits[splits.length - 2].equals("Custom")) {
String value = splits[splits.length - 1];
parameter.setValue(Double.parseDouble(value));
params[i] += " " + splits[splits.length - 2] + " " + splits[splits.length - 1];
}
else if (splits[splits.length - 2].equals("Sweep")) {
String value = splits[splits.length - 1];
parameter.setValue(Double.parseDouble(value.split(",")[0].substring(1).trim()));
params[i] += " " + splits[splits.length - 2] + " " + splits[splits.length - 1];
}
}
}
}
}
sort(params);
parameters.setListData(params);
parameters.setSelectedIndex(0);
parameters.addMouseListener(this);
param.add(parametersLabel, "North");
param.add(scroll3, "Center");
param.add(addParams, "South");
// adds the main panel to the frame and displays it
JPanel mainPanelNorth = new JPanel();
JPanel mainPanelCenter = new JPanel(new BorderLayout());
JPanel mainPanelCenterUp = new JPanel();
JPanel mainPanelCenterDown = new JPanel();
mainPanelCenterUp.add(comp);
mainPanelCenterUp.add(spec);
mainPanelCenterDown.add(reac);
mainPanelCenterDown.add(param);
mainPanelCenter.add(mainPanelCenterUp, "North");
mainPanelCenter.add(mainPanelCenterDown, "South");
modelID = new JTextField(model.getId(), 16);
modelName = new JTextField(model.getName(), 50);
JLabel modelIDLabel = new JLabel("Model ID:");
JLabel modelNameLabel = new JLabel("Model Name:");
modelID.setEditable(false);
mainPanelNorth.add(modelIDLabel);
mainPanelNorth.add(modelID);
mainPanelNorth.add(modelNameLabel);
mainPanelNorth.add(modelName);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setLayout(new BorderLayout());
mainPanel.add(mainPanelNorth, "North");
mainPanel.add(mainPanelCenter, "Center");
JPanel defnPanel = createDefnFrame(model);
JPanel rulesPanel = createRuleFrame(model);
if (!paramsOnly) {
JTabbedPane tab = new JTabbedPane();
tab.addTab("Main Elements", mainPanel);
tab.addTab("Definitions/Types", defnPanel);
tab.addTab("Initial Assignments/Rules/Constraints/Events", rulesPanel);
this.add(tab, "Center");
}
else {
this.add(mainPanel, "Center");
}
change = false;
if (paramsOnly) {
saveNoRun = new JButton("Save Parameters");
run = new JButton("Save And Run");
saveNoRun.setMnemonic(KeyEvent.VK_S);
run.setMnemonic(KeyEvent.VK_R);
saveNoRun.addActionListener(this);
run.addActionListener(this);
JPanel saveRun = new JPanel();
saveRun.add(saveNoRun);
saveRun.add(run);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, saveRun, null);
splitPane.setDividerSize(0);
this.add(splitPane, "South");
}
else {
check = new JButton("Save and Check SBML");
check.setMnemonic(KeyEvent.VK_C);
check.addActionListener(this);
saveNoRun = new JButton("Save SBML");
saveAs = new JButton("Save As");
saveNoRun.setMnemonic(KeyEvent.VK_S);
saveAs.setMnemonic(KeyEvent.VK_A);
saveNoRun.addActionListener(this);
saveAs.addActionListener(this);
JPanel saveRun = new JPanel();
saveRun.add(saveNoRun);
saveRun.add(check);
saveRun.add(saveAs);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, saveRun, null);
splitPane.setDividerSize(0);
this.add(splitPane, "South");
}
}
/**
* Private helper method to create definitions/types frame.
*/
private JPanel createDefnFrame(Model model) {
/* Create function definition panel */
addFunction = new JButton("Add Function");
removeFunction = new JButton("Remove Function");
editFunction = new JButton("Edit Function");
functions = new JList();
ListOf listOfFunctions = model.getListOfFunctionDefinitions();
funcs = new String[(int) model.getNumFunctionDefinitions()];
for (int i = 0; i < model.getNumFunctionDefinitions(); i++) {
FunctionDefinition function = (FunctionDefinition) listOfFunctions.get(i);
funcs[i] = function.getId() + " ( ";
for (long j = 0; j < function.getNumArguments(); j++) {
if (j != 0) {
funcs[i] += ", ";
}
funcs[i] += myFormulaToString(function.getArgument(j));
}
if (function.isSetMath()) {
funcs[i] += " ) = " + myFormulaToString(function.getBody());
}
}
String[] oldFuncs = funcs;
try {
funcs = sortFunctions(funcs);
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in function definitions.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
funcs = oldFuncs;
}
JPanel funcdefnPanel = createPanel(model, "Function Definitions", functions, funcs,
addFunction, removeFunction, editFunction);
/* Create unit definition panel */
addUnit = new JButton("Add Unit");
removeUnit = new JButton("Remove Unit");
editUnit = new JButton("Edit Unit");
unitDefs = new JList();
ListOf listOfUnits = model.getListOfUnitDefinitions();
units = new String[(int) model.getNumUnitDefinitions()];
for (int i = 0; i < model.getNumUnitDefinitions(); i++) {
UnitDefinition unit = (UnitDefinition) listOfUnits.get(i);
units[i] = unit.getId();
// GET OTHER THINGS
}
JPanel unitdefnPanel = createPanel(model, "Unit Definitions", unitDefs, units, addUnit,
removeUnit, editUnit);
/* Create compartment type panel */
addCompType = new JButton("Add Type");
removeCompType = new JButton("Remove Type");
editCompType = new JButton("Edit Type");
compTypes = new JList();
ListOf listOfCompartmentTypes = model.getListOfCompartmentTypes();
cpTyp = new String[(int) model.getNumCompartmentTypes()];
for (int i = 0; i < model.getNumCompartmentTypes(); i++) {
CompartmentType compType = (CompartmentType) listOfCompartmentTypes.get(i);
cpTyp[i] = compType.getId();
}
JPanel compTypePanel = createPanel(model, "Compartment Types", compTypes, cpTyp, addCompType,
removeCompType, editCompType);
/* Create species type panel */
addSpecType = new JButton("Add Type");
removeSpecType = new JButton("Remove Type");
editSpecType = new JButton("Edit Type");
specTypes = new JList();
ListOf listOfSpeciesTypes = model.getListOfSpeciesTypes();
spTyp = new String[(int) model.getNumSpeciesTypes()];
for (int i = 0; i < model.getNumSpeciesTypes(); i++) {
SpeciesType specType = (SpeciesType) listOfSpeciesTypes.get(i);
spTyp[i] = specType.getId();
}
JPanel specTypePanel = createPanel(model, "Species Types", specTypes, spTyp, addSpecType,
removeSpecType, editSpecType);
JPanel defnPanelNorth = new JPanel();
JPanel defnPanelSouth = new JPanel();
JPanel defnPanel = new JPanel(new BorderLayout());
defnPanelNorth.add(funcdefnPanel);
defnPanelNorth.add(unitdefnPanel);
defnPanelSouth.add(compTypePanel);
defnPanelSouth.add(specTypePanel);
defnPanel.add(defnPanelNorth, "North");
defnPanel.add(defnPanelSouth, "South");
return defnPanel;
}
/**
* Private helper method to create rules/events/constraints frame.
*/
private JPanel createRuleFrame(Model model) {
/* Create initial assignment panel */
addInit = new JButton("Add Initial");
removeInit = new JButton("Remove Initial");
editInit = new JButton("Edit Initial");
initAssigns = new JList();
ListOf listOfInits = model.getListOfInitialAssignments();
inits = new String[(int) model.getNumInitialAssignments()];
for (int i = 0; i < model.getNumInitialAssignments(); i++) {
InitialAssignment init = (InitialAssignment) listOfInits.get(i);
inits[i] = init.getSymbol() + " = " + myFormulaToString(init.getMath());
}
String[] oldInits = inits;
boolean cycle = false;
try {
inits = sortInitRules(inits);
}
catch (Exception e) {
cycle = true;
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in initial assignments.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
inits = oldInits;
}
JPanel initPanel = createPanel(model, "Initial Assignments", initAssigns, inits, addInit,
removeInit, editInit);
/* Create rule panel */
addRule = new JButton("Add Rule");
removeRule = new JButton("Remove Rule");
editRule = new JButton("Edit Rule");
rules = new JList();
ListOf listOfRules = model.getListOfRules();
rul = new String[(int) model.getNumRules()];
for (int i = 0; i < model.getNumRules(); i++) {
Rule rule = (Rule) listOfRules.get(i);
if (rule.isAlgebraic()) {
rul[i] = "0 = " + myFormulaToString(rule.getMath());
}
else if (rule.isAssignment()) {
rul[i] = rule.getVariable() + " = " + myFormulaToString(rule.getMath());
}
else {
rul[i] = "d( " + rule.getVariable() + " )/dt = " + myFormulaToString(rule.getMath());
}
}
String[] oldRul = rul;
try {
rul = sortRules(rul);
}
catch (Exception e) {
cycle = true;
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in assignments.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
rul = oldRul;
}
if (!cycle && checkCycles(inits, rul)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected within initial assignments and assignment rules.", "Cycle Detected",
JOptionPane.ERROR_MESSAGE);
}
JPanel rulePanel = createPanel(model, "Rules", rules, rul, addRule, removeRule, editRule);
/* Create constraint panel */
addConstraint = new JButton("Add Constraint");
removeConstraint = new JButton("Remove Constraint");
editConstraint = new JButton("Edit Constraint");
constraints = new JList();
ListOf listOfConstraints = model.getListOfConstraints();
cons = new String[(int) model.getNumConstraints()];
for (int i = 0; i < model.getNumConstraints(); i++) {
Constraint constraint = (Constraint) listOfConstraints.get(i);
cons[i] = myFormulaToString(constraint.getMath());
}
JPanel constraintPanel = createPanel(model, "Constraints", constraints, cons, addConstraint,
removeConstraint, editConstraint);
/* Create event panel */
addEvent = new JButton("Add Event");
removeEvent = new JButton("Remove Event");
editEvent = new JButton("Edit Event");
events = new JList();
ListOf listOfEvents = model.getListOfEvents();
ev = new String[(int) model.getNumEvents()];
for (int i = 0; i < model.getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) listOfEvents.get(i);
ev[i] = myFormulaToString(event.getTrigger().getMath());
}
JPanel eventPanel = createPanel(model, "Events", events, ev, addEvent, removeEvent, editEvent);
JPanel recPanelNorth = new JPanel();
JPanel recPanelSouth = new JPanel();
JPanel recPanel = new JPanel(new BorderLayout());
recPanelNorth.add(initPanel);
recPanelNorth.add(rulePanel);
recPanelSouth.add(constraintPanel);
recPanelSouth.add(eventPanel);
recPanel.add(recPanelNorth, "North");
recPanel.add(recPanelSouth, "South");
return recPanel;
}
/* Create add/remove/edit panel */
private JPanel createPanel(Model model, String panelName, JList panelJList, String[] panelList,
JButton addButton, JButton removeButton, JButton editButton) {
JPanel Panel = new JPanel(new BorderLayout());
JPanel addRem = new JPanel();
addRem.add(addButton);
addRem.add(removeButton);
addRem.add(editButton);
addButton.addActionListener(this);
removeButton.addActionListener(this);
editButton.addActionListener(this);
JLabel panelLabel = new JLabel("List of " + panelName + ":");
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(260, 220));
scroll.setPreferredSize(new Dimension(276, 152));
scroll.setViewportView(panelJList);
if (!panelName.equals("Rules") && !panelName.equals("Function Definitions")
&& !panelName.equals("Initial Assignments")) {
sort(panelList);
}
panelJList.setListData(panelList);
panelJList.addMouseListener(this);
Panel.add(panelLabel, "North");
Panel.add(scroll, "Center");
Panel.add(addRem, "South");
return Panel;
}
/**
* This method performs different functions depending on what buttons are
* pushed and what input fields contain data.
*/
public void actionPerformed(ActionEvent e) {
// if the run button is clicked
if (e.getSource() == run) {
reb2sac.getRunButton().doClick();
}
// if the check button is clicked
else if (e.getSource() == check) {
save(false);
check();
}
// if the save button is clicked
else if (e.getSource() == saveNoRun) {
if (paramsOnly) {
reb2sac.getSaveButton().doClick();
}
else {
save(false);
}
}
// if the save as button is clicked
else if (e.getSource() == saveAs) {
saveAs();
}
// if the add function button is clicked
else if (e.getSource() == addFunction) {
functionEditor("Add");
}
// if the edit function button is clicked
else if (e.getSource() == editFunction) {
functionEditor("OK");
}
// if the remove function button is clicked
else if (e.getSource() == removeFunction) {
removeFunction();
}
// if the add unit button is clicked
else if (e.getSource() == addUnit) {
unitEditor("Add");
}
// if the edit unit button is clicked
else if (e.getSource() == editUnit) {
unitEditor("OK");
}
// if the remove unit button is clicked
else if (e.getSource() == removeUnit) {
removeUnit();
}
// if the add to unit list button is clicked
else if (e.getSource() == addList) {
unitListEditor("Add");
}
// if the edit unit list button is clicked
else if (e.getSource() == editList) {
unitListEditor("OK");
}
// if the remove from unit list button is clicked
else if (e.getSource() == removeList) {
removeList();
}
// if the add compartment type button is clicked
else if (e.getSource() == addCompType) {
compTypeEditor("Add");
}
// if the edit compartment type button is clicked
else if (e.getSource() == editCompType) {
compTypeEditor("OK");
}
// if the remove compartment type button is clicked
else if (e.getSource() == removeCompType) {
removeCompType();
}
// if the add species type button is clicked
else if (e.getSource() == addSpecType) {
specTypeEditor("Add");
}
// if the edit species type button is clicked
else if (e.getSource() == editSpecType) {
specTypeEditor("OK");
}
// if the remove species type button is clicked
else if (e.getSource() == removeSpecType) {
removeSpecType();
}
// if the add init button is clicked
else if (e.getSource() == addInit) {
initEditor("Add");
}
// if the edit init button is clicked
else if (e.getSource() == editInit) {
initEditor("OK");
}
// if the remove rule button is clicked
else if (e.getSource() == removeInit) {
removeInit();
}
// if the add rule button is clicked
else if (e.getSource() == addRule) {
ruleEditor("Add");
}
// if the edit rule button is clicked
else if (e.getSource() == editRule) {
ruleEditor("OK");
}
// if the remove rule button is clicked
else if (e.getSource() == removeRule) {
removeRule();
}
// if the add event button is clicked
else if (e.getSource() == addEvent) {
eventEditor("Add");
}
// if the edit event button is clicked
else if (e.getSource() == editEvent) {
eventEditor("OK");
}
// if the remove event button is clicked
else if (e.getSource() == removeEvent) {
removeEvent();
}
// if the add event assignment button is clicked
else if (e.getSource() == addAssignment) {
eventAssignEditor("Add");
}
// if the edit event assignment button is clicked
else if (e.getSource() == editAssignment) {
eventAssignEditor("OK");
}
// if the remove event assignment button is clicked
else if (e.getSource() == removeAssignment) {
removeAssignment();
}
// if the add constraint button is clicked
else if (e.getSource() == addConstraint) {
constraintEditor("Add");
}
// if the edit constraint button is clicked
else if (e.getSource() == editConstraint) {
constraintEditor("OK");
}
// if the remove constraint button is clicked
else if (e.getSource() == removeConstraint) {
removeConstraint();
}
// if the add comparment button is clicked
else if (e.getSource() == addCompart) {
compartEditor("Add");
}
// if the edit comparment button is clicked
else if (e.getSource() == editCompart) {
compartEditor("OK");
}
// if the remove compartment button is clicked
else if (e.getSource() == removeCompart) {
removeCompartment();
}
// if the add species button is clicked
else if (e.getSource() == addSpec) {
speciesEditor("Add");
}
// if the edit species button is clicked
else if (e.getSource() == editSpec) {
speciesEditor("OK");
}
// if the remove species button is clicked
else if (e.getSource() == removeSpec) {
removeSpecies();
}
// if the add reactions button is clicked
else if (e.getSource() == addReac) {
reactionsEditor("Add");
}
// if the edit reactions button is clicked
else if (e.getSource() == editReac) {
reactionsEditor("OK");
}
// if the copy reactions button is clicked
else if (e.getSource() == copyReac) {
copyReaction();
}
// if the remove reactions button is clicked
else if (e.getSource() == removeReac) {
removeReaction();
}
// if the add parameters button is clicked
else if (e.getSource() == addParam) {
parametersEditor("Add");
}
// if the edit parameters button is clicked
else if (e.getSource() == editParam) {
parametersEditor("OK");
}
// if the remove parameters button is clicked
else if (e.getSource() == removeParam) {
removeParameter();
}
// if the add reactions parameters button is clicked
else if (e.getSource() == reacAddParam) {
reacParametersEditor("Add");
}
// if the edit reactions parameters button is clicked
else if (e.getSource() == reacEditParam) {
reacParametersEditor("OK");
}
// if the remove reactions parameters button is clicked
else if (e.getSource() == reacRemoveParam) {
reacRemoveParam();
}
// if the add reactants button is clicked
else if (e.getSource() == addReactant) {
reactantsEditor("Add");
}
// if the edit reactants button is clicked
else if (e.getSource() == editReactant) {
reactantsEditor("OK");
}
// if the remove reactants button is clicked
else if (e.getSource() == removeReactant) {
removeReactant();
}
// if the add products button is clicked
else if (e.getSource() == addProduct) {
productsEditor("Add");
}
// if the edit products button is clicked
else if (e.getSource() == editProduct) {
productsEditor("OK");
}
// if the remove products button is clicked
else if (e.getSource() == removeProduct) {
removeProduct();
}
// if the add modifiers button is clicked
else if (e.getSource() == addModifier) {
modifiersEditor("Add");
}
// if the edit modifiers button is clicked
else if (e.getSource() == editModifier) {
modifiersEditor("OK");
}
// if the remove modifiers button is clicked
else if (e.getSource() == removeModifier) {
removeModifier();
}
// if the clear button is clicked
else if (e.getSource() == clearKineticLaw) {
kineticLaw.setText("");
change = true;
}
// if the use mass action button is clicked
else if (e.getSource() == useMassAction) {
useMassAction();
}
}
/**
* Remove a unit from list
*/
private void removeList() {
if (unitDefs.getSelectedIndex() != -1) {
UnitDefinition tempUnit = document.getModel().getUnitDefinition(
((String) unitDefs.getSelectedValue()).split(" ")[0]);
if (unitList.getSelectedIndex() != -1) {
String selected = (String) unitList.getSelectedValue();
ListOf u = tempUnit.getListOfUnits();
for (int i = 0; i < tempUnit.getNumUnits(); i++) {
if (selected.contains(unitToString(tempUnit.getUnit(i)))) {
u.remove(i);
}
}
}
unitList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
uList = (String[]) Buttons.remove(unitList, uList);
unitList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
unitList.setSelectedIndex(0);
change = true;
}
}
/**
* Remove a unit
*/
private void removeUnit() {
if (unitDefs.getSelectedIndex() != -1) {
if (!unitsInUse(((String) unitDefs.getSelectedValue()).split(" ")[0])) {
UnitDefinition tempUnit = document.getModel().getUnitDefinition(
((String) unitDefs.getSelectedValue()).split(" ")[0]);
ListOf u = document.getModel().getListOfUnitDefinitions();
for (int i = 0; i < document.getModel().getNumUnitDefinitions(); i++) {
if (((UnitDefinition) u.get(i)).getId().equals(tempUnit.getId())) {
u.remove(i);
}
}
usedIDs.remove(((String) unitDefs.getSelectedValue()).split(" ")[0]);
unitDefs.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
units = (String[]) Buttons.remove(unitDefs, units);
unitDefs.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
unitDefs.setSelectedIndex(0);
change = true;
}
}
}
/**
* Remove a compartment type
*/
private void removeCompType() {
if (compTypes.getSelectedIndex() != -1) {
boolean remove = true;
ArrayList<String> compartmentUsing = new ArrayList<String>();
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = (Compartment) document.getModel().getListOfCompartments().get(i);
if (compartment.isSetCompartmentType()) {
if (compartment.getCompartmentType().equals(
((String) compTypes.getSelectedValue()).split(" ")[0])) {
remove = false;
compartmentUsing.add(compartment.getId());
}
}
}
if (remove) {
CompartmentType tempCompType = document.getModel().getCompartmentType(
((String) compTypes.getSelectedValue()).split(" ")[0]);
ListOf c = document.getModel().getListOfCompartmentTypes();
for (int i = 0; i < document.getModel().getNumCompartmentTypes(); i++) {
if (((CompartmentType) c.get(i)).getId().equals(tempCompType.getId())) {
c.remove(i);
}
}
usedIDs.remove(((String) compTypes.getSelectedValue()).split(" ")[0]);
compTypes.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
cpTyp = (String[]) Buttons.remove(compTypes, cpTyp);
compTypes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
compTypes.setSelectedIndex(0);
change = true;
}
else {
String compartment = "";
String[] comps = compartmentUsing.toArray(new String[0]);
sort(comps);
for (int i = 0; i < comps.length; i++) {
if (i == comps.length - 1) {
compartment += comps[i];
}
else {
compartment += comps[i] + "\n";
}
}
String message = "Unable to remove the selected compartment type.";
if (compartmentUsing.size() != 0) {
message += "\n\nIt is used by the following compartments:\n" + compartment;
}
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(300, 300));
scroll.setPreferredSize(new Dimension(300, 300));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scroll, "Unable To Remove Compartment Type",
JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Remove an initial assignment
*/
private void removeInit() {
if (initAssigns.getSelectedIndex() != -1) {
String selected = ((String) initAssigns.getSelectedValue());
String tempVar = selected.split(" ")[0];
String tempMath = selected.substring(selected.indexOf('=') + 2);
ListOf r = document.getModel().getListOfInitialAssignments();
for (int i = 0; i < document.getModel().getNumInitialAssignments(); i++) {
if (myFormulaToString(((InitialAssignment) r.get(i)).getMath()).equals(tempMath)
&& ((InitialAssignment) r.get(i)).getSymbol().equals(tempVar)) {
r.remove(i);
}
}
initAssigns.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
inits = (String[]) Buttons.remove(initAssigns, inits);
initAssigns.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
initAssigns.setSelectedIndex(0);
change = true;
}
}
/**
* Remove a species type
*/
private void removeSpecType() {
if (specTypes.getSelectedIndex() != -1) {
boolean remove = true;
ArrayList<String> speciesUsing = new ArrayList<String>();
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
Species species = (Species) document.getModel().getListOfSpecies().get(i);
if (species.isSetSpeciesType()) {
if (species.getSpeciesType()
.equals(((String) specTypes.getSelectedValue()).split(" ")[0])) {
remove = false;
speciesUsing.add(species.getId());
}
}
}
if (remove) {
SpeciesType tempSpecType = document.getModel().getSpeciesType(
((String) specTypes.getSelectedValue()).split(" ")[0]);
ListOf s = document.getModel().getListOfSpeciesTypes();
for (int i = 0; i < document.getModel().getNumSpeciesTypes(); i++) {
if (((SpeciesType) s.get(i)).getId().equals(tempSpecType.getId())) {
s.remove(i);
}
}
usedIDs.remove(((String) specTypes.getSelectedValue()).split(" ")[0]);
specTypes.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
spTyp = (String[]) Buttons.remove(specTypes, spTyp);
specTypes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
specTypes.setSelectedIndex(0);
change = true;
}
else {
String species = "";
String[] specs = speciesUsing.toArray(new String[0]);
sort(specs);
for (int i = 0; i < specs.length; i++) {
if (i == specs.length - 1) {
species += specs[i];
}
else {
species += specs[i] + "\n";
}
}
String message = "Unable to remove the selected species type.";
if (speciesUsing.size() != 0) {
message += "\n\nIt is used by the following species:\n" + species;
}
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(300, 300));
scroll.setPreferredSize(new Dimension(300, 300));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scroll, "Unable To Remove Species Type",
JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Remove a rule
*/
private void removeRule() {
if (rules.getSelectedIndex() != -1) {
String selected = ((String) rules.getSelectedValue());
removeTheRule(selected);
rules.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
rul = (String[]) Buttons.remove(rules, rul);
rules.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
rules.setSelectedIndex(0);
change = true;
}
}
/**
* Remove the rule
*/
private void removeTheRule(String selected) {
// algebraic rule
if ((selected.split(" ")[0]).equals("0")) {
String tempMath = selected.substring(4);
ListOf r = document.getModel().getListOfRules();
for (int i = 0; i < document.getModel().getNumRules(); i++) {
if ((((Rule) r.get(i)).isAlgebraic()) && ((Rule) r.get(i)).getFormula().equals(tempMath)) {
r.remove(i);
}
}
}
// rate rule
else if ((selected.split(" ")[0]).equals("d(")) {
String tempVar = selected.split(" ")[1];
String tempMath = selected.substring(selected.indexOf('=') + 2);
ListOf r = document.getModel().getListOfRules();
for (int i = 0; i < document.getModel().getNumRules(); i++) {
if ((((Rule) r.get(i)).isRate()) && ((Rule) r.get(i)).getFormula().equals(tempMath)
&& ((Rule) r.get(i)).getVariable().equals(tempVar)) {
r.remove(i);
}
}
}
// assignment rule
else {
String tempVar = selected.split(" ")[0];
String tempMath = selected.substring(selected.indexOf('=') + 2);
ListOf r = document.getModel().getListOfRules();
for (int i = 0; i < document.getModel().getNumRules(); i++) {
if ((((Rule) r.get(i)).isAssignment()) && ((Rule) r.get(i)).getFormula().equals(tempMath)
&& ((Rule) r.get(i)).getVariable().equals(tempVar)) {
r.remove(i);
}
}
}
}
/**
* Remove an event
*/
private void removeEvent() {
if (events.getSelectedIndex() != -1) {
String selected = ((String) events.getSelectedValue());
removeTheEvent(selected);
events.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
ev = (String[]) Buttons.remove(events, ev);
events.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
events.setSelectedIndex(0);
change = true;
}
}
/**
* Remove the event
*/
private void removeTheEvent(String selected) {
ListOf EL = document.getModel().getListOfEvents();
for (int i = 0; i < document.getModel().getNumEvents(); i++) {
org.sbml.libsbml.Event E = (org.sbml.libsbml.Event) EL.get(i);
if (myFormulaToString(E.getTrigger().getMath()).equals(selected)) {
EL.remove(i);
}
}
}
/**
* Remove an assignment
*/
private void removeAssignment() {
if (eventAssign.getSelectedIndex() != -1) {
eventAssign.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
assign = (String[]) Buttons.remove(eventAssign, assign);
eventAssign.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
eventAssign.setSelectedIndex(0);
change = true;
}
}
/**
* Remove a constraint
*/
private void removeConstraint() {
if (constraints.getSelectedIndex() != -1) {
String selected = ((String) constraints.getSelectedValue());
ListOf c = document.getModel().getListOfConstraints();
for (int i = 0; i < document.getModel().getNumConstraints(); i++) {
if (myFormulaToString(((Constraint) c.get(i)).getMath()).equals(selected)) {
usedIDs.remove(((Constraint) c.get(i)).getMetaId());
c.remove(i);
}
}
constraints.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
cons = (String[]) Buttons.remove(constraints, cons);
constraints.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
constraints.setSelectedIndex(0);
change = true;
}
}
/**
* Remove a compartment
*/
private void removeCompartment() {
if (compartments.getSelectedIndex() != -1) {
if (document.getModel().getNumCompartments() != 1) {
boolean remove = true;
ArrayList<String> speciesUsing = new ArrayList<String>();
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
Species species = (Species) document.getModel().getListOfSpecies().get(i);
if (species.isSetCompartment()) {
if (species.getCompartment().equals(
((String) compartments.getSelectedValue()).split(" ")[0])) {
remove = false;
speciesUsing.add(species.getId());
}
}
}
ArrayList<String> outsideUsing = new ArrayList<String>();
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = document.getModel().getCompartment(i);
if (compartment.isSetOutside()) {
if (compartment.getOutside().equals(
((String) compartments.getSelectedValue()).split(" ")[0])) {
remove = false;
outsideUsing.add(compartment.getId());
}
}
}
if (!remove) {
String message = "Unable to remove the selected compartment.";
if (speciesUsing.size() != 0) {
message += "\n\nIt contains the following species:\n";
String[] vars = speciesUsing.toArray(new String[0]);
sort(vars);
for (int i = 0; i < vars.length; i++) {
if (i == vars.length - 1) {
message += vars[i];
}
else {
message += vars[i] + "\n";
}
}
}
if (outsideUsing.size() != 0) {
message += "\n\nIt outside the following compartments:\n";
String[] vars = outsideUsing.toArray(new String[0]);
sort(vars);
for (int i = 0; i < vars.length; i++) {
if (i == vars.length - 1) {
message += vars[i];
}
else {
message += vars[i] + "\n";
}
}
}
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(300, 300));
scroll.setPreferredSize(new Dimension(300, 300));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scroll, "Unable To Remove Compartment",
JOptionPane.ERROR_MESSAGE);
}
else if (!variableInUse(((String) compartments.getSelectedValue()).split(" ")[0], false)) {
Compartment tempComp = document.getModel().getCompartment(
((String) compartments.getSelectedValue()).split(" ")[0]);
ListOf c = document.getModel().getListOfCompartments();
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
if (((Compartment) c.get(i)).getId().equals(tempComp.getId())) {
c.remove(i);
}
}
usedIDs.remove(((String) compartments.getSelectedValue()).split(" ")[0]);
compartments.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
comps = (String[]) Buttons.remove(compartments, comps);
compartments.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
compartments.setSelectedIndex(0);
change = true;
}
}
else {
JOptionPane.showMessageDialog(biosim.frame(),
"Each model must contain at least one compartment.", "Unable To Remove Compartment",
JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Remove a species
*/
private void removeSpecies() {
if (species.getSelectedIndex() != -1) {
if (!variableInUse(((String) species.getSelectedValue()).split(" ")[0], false)) {
Species tempSpecies = document.getModel().getSpecies(
((String) species.getSelectedValue()).split(" ")[0]);
ListOf s = document.getModel().getListOfSpecies();
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
if (((Species) s.get(i)).getId().equals(tempSpecies.getId())) {
s.remove(i);
}
}
usedIDs.remove(tempSpecies.getId());
species.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
specs = (String[]) Buttons.remove(species, specs);
species.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
species.setSelectedIndex(0);
change = true;
}
}
}
/**
* Copy a reaction
*/
private void copyReaction() {
String reacID = JOptionPane.showInputDialog(biosim.frame(), "Enter New Reaction ID:",
"Reaction ID", JOptionPane.PLAIN_MESSAGE);
if (reacID == null) {
return;
}
if (!usedIDs.contains(reacID.trim()) && !reacID.trim().equals("")) {
Reaction react = document.getModel().createReaction();
react.setKineticLaw(new KineticLaw());
int index = reactions.getSelectedIndex();
Reaction r = document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]);
for (int i = 0; i < r.getKineticLaw().getNumParameters(); i++) {
react.getKineticLaw().addParameter(
(Parameter) r.getKineticLaw().getListOfParameters().get(i));
}
for (int i = 0; i < r.getNumProducts(); i++) {
react.addProduct(r.getProduct(i));
}
for (int i = 0; i < r.getNumModifiers(); i++) {
react.addModifier(r.getModifier(i));
}
for (int i = 0; i < r.getNumReactants(); i++) {
react.addReactant(r.getReactant(i));
}
react.setReversible(r.getReversible());
react.setId(reacID.trim());
usedIDs.add(reacID.trim());
react.getKineticLaw().setFormula(r.getKineticLaw().getFormula());
JList add = new JList();
Object[] adding = { reacID.trim() };
add.setListData(adding);
add.setSelectedIndex(0);
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(reacts, reactions, add, false, null, null, null, null, null, null,
biosim.frame());
reacts = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
reacts[i] = (String) adding[i];
}
sort(reacts);
reactions.setListData(reacts);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumReactions() == 1) {
reactions.setSelectedIndex(0);
}
else {
reactions.setSelectedIndex(index);
}
change = true;
}
else {
JOptionPane.showMessageDialog(biosim.frame(), "ID is not unique.", "Enter A Unique ID",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* Remove a reaction
*/
private void removeReaction() {
if (reactions.getSelectedIndex() != -1) {
String selected = ((String) reactions.getSelectedValue()).split(" ")[0];
removeTheReaction(selected);
usedIDs.remove(selected);
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacts = (String[]) Buttons.remove(reactions, reacts);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reactions.setSelectedIndex(0);
change = true;
}
}
/**
* Remove the reaction
*/
private void removeTheReaction(String selected) {
Reaction tempReaction = document.getModel().getReaction(selected);
ListOf r = document.getModel().getListOfReactions();
for (int i = 0; i < document.getModel().getNumReactions(); i++) {
if (((Reaction) r.get(i)).getId().equals(tempReaction.getId())) {
r.remove(i);
}
}
usedIDs.remove(selected);
}
/**
* Remove a global parameter
*/
private void removeParameter() {
if (parameters.getSelectedIndex() != -1) {
if (!variableInUse(((String) parameters.getSelectedValue()).split(" ")[0], false)) {
Parameter tempParameter = document.getModel().getParameter(
((String) parameters.getSelectedValue()).split(" ")[0]);
ListOf p = document.getModel().getListOfParameters();
for (int i = 0; i < document.getModel().getNumParameters(); i++) {
if (((Parameter) p.get(i)).getId().equals(tempParameter.getId())) {
p.remove(i);
}
}
usedIDs.remove(tempParameter.getId());
parameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
params = (String[]) Buttons.remove(parameters, params);
parameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
parameters.setSelectedIndex(0);
change = true;
}
}
}
/**
* Remove a reactant from a reaction
*/
private void removeReactant() {
if (reactants.getSelectedIndex() != -1) {
String v = ((String) reactants.getSelectedValue()).split(" ")[0];
for (int i = 0; i < changedReactants.size(); i++) {
if (changedReactants.get(i).getSpecies().equals(v)) {
changedReactants.remove(i);
}
}
reactants.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacta = (String[]) Buttons.remove(reactants, reacta);
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reactants.setSelectedIndex(0);
change = true;
}
}
/**
* Remove a product from a reaction
*/
private void removeProduct() {
if (products.getSelectedIndex() != -1) {
String v = ((String) products.getSelectedValue()).split(" ")[0];
for (int i = 0; i < changedProducts.size(); i++) {
if (changedProducts.get(i).getSpecies().equals(v)) {
changedProducts.remove(i);
}
}
products.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
product = (String[]) Buttons.remove(products, product);
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
products.setSelectedIndex(0);
change = true;
}
}
/**
* Remove a modifier from a reaction
*/
private void removeModifier() {
if (modifiers.getSelectedIndex() != -1) {
String v = ((String) modifiers.getSelectedValue()).split(" ")[0];
for (int i = 0; i < changedModifiers.size(); i++) {
if (changedModifiers.get(i).getSpecies().equals(v)) {
changedModifiers.remove(i);
}
}
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modifier = (String[]) Buttons.remove(modifiers, modifier);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
modifiers.setSelectedIndex(0);
change = true;
}
}
/**
* Remove a function if not in use
*/
private void useMassAction() {
String kf;
String kr;
if (changedParameters.size() == 0) {
kf = "kf";
kr = "kr";
}
else if (changedParameters.size() == 1) {
kf = changedParameters.get(0).getId();
kr = changedParameters.get(0).getId();
}
else {
kf = changedParameters.get(0).getId();
kr = changedParameters.get(1).getId();
}
String kinetic = kf;
for (SpeciesReference s : changedReactants) {
if (s.isSetStoichiometryMath()) {
kinetic += " * pow(" + s.getSpecies() + ", "
+ myFormulaToString(s.getStoichiometryMath().getMath()) + ")";
}
else {
if (s.getStoichiometry() == 1) {
kinetic += " * " + s.getSpecies();
}
else {
kinetic += " * pow(" + s.getSpecies() + ", " + s.getStoichiometry() + ")";
}
}
}
for (ModifierSpeciesReference s : changedModifiers) {
kinetic += " * " + s.getSpecies();
}
if (reacReverse.getSelectedItem().equals("true")) {
kinetic += " - " + kr;
for (SpeciesReference s : changedProducts) {
if (s.isSetStoichiometryMath()) {
kinetic += " * pow(" + s.getSpecies() + ", "
+ myFormulaToString(s.getStoichiometryMath().getMath()) + ")";
}
else {
if (s.getStoichiometry() == 1) {
kinetic += " * " + s.getSpecies();
}
else {
kinetic += " * pow(" + s.getSpecies() + ", " + s.getStoichiometry() + ")";
}
}
}
for (ModifierSpeciesReference s : changedModifiers) {
kinetic += " * " + s.getSpecies();
}
}
kineticLaw.setText(kinetic);
change = true;
}
/**
* Remove a function if not in use
*/
private void removeFunction() {
if (functions.getSelectedIndex() != -1) {
if (!variableInUse(((String) functions.getSelectedValue()).split(" ")[0], false)) {
FunctionDefinition tempFunc = document.getModel().getFunctionDefinition(
((String) functions.getSelectedValue()).split(" ")[0]);
ListOf f = document.getModel().getListOfFunctionDefinitions();
for (int i = 0; i < document.getModel().getNumFunctionDefinitions(); i++) {
if (((FunctionDefinition) f.get(i)).getId().equals(tempFunc.getId())) {
f.remove(i);
}
}
usedIDs.remove(((String) functions.getSelectedValue()).split(" ")[0]);
functions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
funcs = (String[]) Buttons.remove(functions, funcs);
functions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
functions.setSelectedIndex(0);
change = true;
}
}
}
/**
* Save SBML file with a new name
*/
private void saveAs() {
String simName = JOptionPane.showInputDialog(biosim.frame(), "Enter Model ID:", "Model ID",
JOptionPane.PLAIN_MESSAGE);
if (simName != null && !simName.equals("")) {
if (simName.length() > 4) {
if (!simName.substring(simName.length() - 5).equals(".sbml")
&& !simName.substring(simName.length() - 4).equals(".xml")) {
simName += ".sbml";
}
}
else {
simName += ".sbml";
}
String modelID = "";
if (simName.length() > 4) {
if (simName.substring(simName.length() - 5).equals(".sbml")) {
modelID = simName.substring(0, simName.length() - 5);
}
else {
modelID = simName.substring(0, simName.length() - 4);
}
}
String oldId = document.getModel().getId();
document.getModel().setId(modelID);
document.getModel().setName(modelName.getText().trim());
String newFile = file;
newFile = newFile.substring(0, newFile.length()
- newFile.split(separator)[newFile.split(separator).length - 1].length())
+ simName;
try {
log.addText("Saving sbml file as:\n" + newFile + "\n");
FileOutputStream out = new FileOutputStream(new File(newFile));
SBMLWriter writer = new SBMLWriter();
String doc = writer.writeToString(document);
byte[] output = doc.getBytes();
out.write(output);
out.close();
JTabbedPane tab = biosim.getTab();
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(file.split(separator)[file.split(separator).length - 1])) {
tab.setTitleAt(i, simName);
tab
.setComponentAt(i,
new SBML_Editor(newFile, reb2sac, log, biosim, simDir, paramFile));
tab.getComponentAt(i).setName("SBML Editor");
}
}
biosim.refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to save sbml file.",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
finally {
document.getModel().setId(oldId);
}
}
}
/**
* Remove a reaction parameter, if allowed
*/
private void reacRemoveParam() {
if (reacParameters.getSelectedIndex() != -1) {
String v = ((String) reacParameters.getSelectedValue()).split(" ")[0];
Reaction reaction = document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]);
String[] vars = reaction.getKineticLaw().getFormula().split(" |\\(|\\)|\\,");
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(v)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cannot remove reaction parameter because it is used in the kinetic law.",
"Cannot Remove Parameter", JOptionPane.ERROR_MESSAGE);
return;
}
}
for (int j = 0; j < reaction.getNumProducts(); j++) {
if (reaction.getProduct(j).isSetSpecies()) {
String specRef = reaction.getProduct(j).getSpecies();
if (reaction.getProduct(j).isSetStoichiometryMath()) {
vars = myFormulaToString(reaction.getProduct(j).getStoichiometryMath().getMath())
.split(" |\\(|\\)|\\,");
for (int k = 0; k < vars.length; k++) {
if (vars[k].equals(v)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cannot remove reaction parameter because it is used in the stoichiometry math for product "
+ specRef + ".", "Cannot Remove Parameter", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
}
}
for (int j = 0; j < reaction.getNumReactants(); j++) {
if (reaction.getReactant(j).isSetSpecies()) {
String specRef = reaction.getReactant(j).getSpecies();
if (reaction.getReactant(j).isSetStoichiometryMath()) {
vars = myFormulaToString(reaction.getReactant(j).getStoichiometryMath().getMath())
.split(" |\\(|\\)|\\,");
for (int k = 0; k < vars.length; k++) {
if (vars[k].equals(v)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cannot remove reaction parameter because it is used in the stoichiometry math for reactant "
+ specRef + ".", "Cannot Remove Parameter", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
}
}
for (int i = 0; i < changedParameters.size(); i++) {
if (changedParameters.get(i).getId().equals(v)) {
changedParameters.remove(i);
}
}
thisReactionParams.remove(v);
reacParameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacParams = (String[]) Buttons.remove(reacParameters, reacParams);
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reacParameters.setSelectedIndex(0);
change = true;
}
}
/**
* Check if a unit is in use.
*/
private boolean unitsInUse(String unit) {
Model model = document.getModel();
boolean inUse = false;
ArrayList<String> compartmentsUsing = new ArrayList<String>();
for (int i = 0; i < model.getNumCompartments(); i++) {
Compartment compartment = (Compartment) model.getListOfCompartments().get(i);
if (compartment.getUnits().equals(unit)) {
inUse = true;
compartmentsUsing.add(compartment.getId());
}
}
ArrayList<String> speciesUsing = new ArrayList<String>();
for (int i = 0; i < model.getNumSpecies(); i++) {
Species species = (Species) model.getListOfSpecies().get(i);
if (species.getUnits().equals(unit)) {
inUse = true;
speciesUsing.add(species.getId());
}
}
ArrayList<String> parametersUsing = new ArrayList<String>();
for (int i = 0; i < model.getNumParameters(); i++) {
Parameter parameters = (Parameter) model.getListOfParameters().get(i);
if (parameters.getUnits().equals(unit)) {
inUse = true;
parametersUsing.add(parameters.getId());
}
}
ArrayList<String> reacParametersUsing = new ArrayList<String>();
for (int i = 0; i < model.getNumReactions(); i++) {
for (int j = 0; j < model.getReaction(i).getKineticLaw().getNumParameters(); j++) {
Parameter parameters = (Parameter) model.getReaction(i).getKineticLaw()
.getListOfParameters().get(j);
if (parameters.getUnits().equals(unit)) {
inUse = true;
reacParametersUsing.add(model.getReaction(i).getId() + "/" + parameters.getId());
}
}
}
if (inUse) {
String message = "Unable to remove the selected unit.";
String[] ids;
if (compartmentsUsing.size() != 0) {
ids = compartmentsUsing.toArray(new String[0]);
sort(ids);
message += "\n\nIt is used by the following compartments:\n";
for (int i = 0; i < ids.length; i++) {
if (i == ids.length - 1) {
message += ids[i];
}
else {
message += ids[i] + "\n";
}
}
}
if (speciesUsing.size() != 0) {
ids = speciesUsing.toArray(new String[0]);
sort(ids);
message += "\n\nIt is used by the following species:\n";
for (int i = 0; i < ids.length; i++) {
if (i == ids.length - 1) {
message += ids[i];
}
else {
message += ids[i] + "\n";
}
}
}
if (parametersUsing.size() != 0) {
ids = parametersUsing.toArray(new String[0]);
sort(ids);
message += "\n\nIt is used by the following parameters:\n";
for (int i = 0; i < ids.length; i++) {
if (i == ids.length - 1) {
message += ids[i];
}
else {
message += ids[i] + "\n";
}
}
}
if (reacParametersUsing.size() != 0) {
ids = reacParametersUsing.toArray(new String[0]);
sort(ids);
message += "\n\nIt is used by the following reaction/parameters:\n";
for (int i = 0; i < ids.length; i++) {
if (i == ids.length - 1) {
message += ids[i];
}
else {
message += ids[i] + "\n";
}
}
}
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(350, 350));
scroll.setPreferredSize(new Dimension(350, 350));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scroll, "Unable To Remove Variable",
JOptionPane.ERROR_MESSAGE);
}
return inUse;
}
/**
* Check if a variable is in use.
*/
private boolean variableInUse(String species, boolean zeroDim) {
Model model = document.getModel();
boolean inUse = false;
ArrayList<String> stoicMathUsing = new ArrayList<String>();
ArrayList<String> reactantsUsing = new ArrayList<String>();
ArrayList<String> productsUsing = new ArrayList<String>();
ArrayList<String> modifiersUsing = new ArrayList<String>();
ArrayList<String> kineticLawsUsing = new ArrayList<String>();
ArrayList<String> initsUsing = new ArrayList<String>();
ArrayList<String> rulesUsing = new ArrayList<String>();
ArrayList<String> constraintsUsing = new ArrayList<String>();
ArrayList<String> eventsUsing = new ArrayList<String>();
for (int i = 0; i < model.getNumReactions(); i++) {
Reaction reaction = (Reaction) model.getListOfReactions().get(i);
for (int j = 0; j < reaction.getNumProducts(); j++) {
if (reaction.getProduct(j).isSetSpecies()) {
String specRef = reaction.getProduct(j).getSpecies();
if (species.equals(specRef)) {
inUse = true;
productsUsing.add(reaction.getId());
}
else if (reaction.getProduct(j).isSetStoichiometryMath()) {
String[] vars = myFormulaToString(
reaction.getProduct(j).getStoichiometryMath().getMath()).split(" |\\(|\\)|\\,");
for (int k = 0; k < vars.length; k++) {
if (vars[k].equals(species)) {
stoicMathUsing.add(reaction.getId() + "/" + specRef);
inUse = true;
break;
}
}
}
}
}
for (int j = 0; j < reaction.getNumReactants(); j++) {
if (reaction.getReactant(j).isSetSpecies()) {
String specRef = reaction.getReactant(j).getSpecies();
if (species.equals(specRef)) {
inUse = true;
reactantsUsing.add(reaction.getId());
}
else if (reaction.getReactant(j).isSetStoichiometryMath()) {
String[] vars = myFormulaToString(
reaction.getReactant(j).getStoichiometryMath().getMath()).split(" |\\(|\\)|\\,");
for (int k = 0; k < vars.length; k++) {
if (vars[k].equals(species)) {
stoicMathUsing.add(reaction.getId() + "/" + specRef);
inUse = true;
break;
}
}
}
}
}
for (int j = 0; j < reaction.getNumModifiers(); j++) {
if (reaction.getModifier(j).isSetSpecies()) {
String specRef = reaction.getModifier(j).getSpecies();
if (species.equals(specRef)) {
inUse = true;
modifiersUsing.add(reaction.getId());
}
}
}
String[] vars = reaction.getKineticLaw().getFormula().split(" |\\(|\\)|\\,");
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(species)) {
kineticLawsUsing.add(reaction.getId());
inUse = true;
break;
}
}
}
for (int i = 0; i < inits.length; i++) {
String[] vars = inits[i].split(" |\\(|\\)|\\,");
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(species)) {
initsUsing.add(inits[i]);
inUse = true;
break;
}
}
}
for (int i = 0; i < rul.length; i++) {
String[] vars = rul[i].split(" |\\(|\\)|\\,");
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(species)) {
rulesUsing.add(rul[i]);
inUse = true;
break;
}
}
}
for (int i = 0; i < cons.length; i++) {
String[] vars = cons[i].split(" |\\(|\\)|\\,");
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(species)) {
constraintsUsing.add(cons[i]);
inUse = true;
break;
}
}
}
ListOf e = model.getListOfEvents();
for (int i = 0; i < model.getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) e.get(i);
String trigger = myFormulaToString(event.getTrigger().getMath());
String eventStr = trigger;
if (event.isSetDelay()) {
eventStr += " " + myFormulaToString(event.getDelay().getMath());
}
for (int j = 0; j < event.getNumEventAssignments(); j++) {
eventStr += " " + (event.getEventAssignment(j).getVariable()) + " = "
+ myFormulaToString(event.getEventAssignment(j).getMath());
}
String[] vars = eventStr.split(" |\\(|\\)|\\,");
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(species)) {
eventsUsing.add(trigger);
inUse = true;
break;
}
}
}
if (inUse) {
String reactants = "";
String products = "";
String modifiers = "";
String kineticLaws = "";
String stoicMath = "";
String initAssigns = "";
String rules = "";
String constraints = "";
String events = "";
String[] reacts = reactantsUsing.toArray(new String[0]);
sort(reacts);
String[] prods = productsUsing.toArray(new String[0]);
sort(prods);
String[] mods = modifiersUsing.toArray(new String[0]);
sort(mods);
String[] kls = kineticLawsUsing.toArray(new String[0]);
sort(kls);
String[] sm = stoicMathUsing.toArray(new String[0]);
sort(sm);
String[] inAs = initsUsing.toArray(new String[0]);
sort(inAs);
String[] ruls = rulesUsing.toArray(new String[0]);
sort(ruls);
String[] consts = constraintsUsing.toArray(new String[0]);
sort(consts);
String[] evs = eventsUsing.toArray(new String[0]);
sort(evs);
for (int i = 0; i < reacts.length; i++) {
if (i == reacts.length - 1) {
reactants += reacts[i];
}
else {
reactants += reacts[i] + "\n";
}
}
for (int i = 0; i < prods.length; i++) {
if (i == prods.length - 1) {
products += prods[i];
}
else {
products += prods[i] + "\n";
}
}
for (int i = 0; i < mods.length; i++) {
if (i == mods.length - 1) {
modifiers += mods[i];
}
else {
modifiers += mods[i] + "\n";
}
}
for (int i = 0; i < kls.length; i++) {
if (i == kls.length - 1) {
kineticLaws += kls[i];
}
else {
kineticLaws += kls[i] + "\n";
}
}
for (int i = 0; i < sm.length; i++) {
if (i == sm.length - 1) {
stoicMath += sm[i];
}
else {
stoicMath += sm[i] + "\n";
}
}
for (int i = 0; i < inAs.length; i++) {
if (i == inAs.length - 1) {
initAssigns += inAs[i];
}
else {
initAssigns += inAs[i] + "\n";
}
}
for (int i = 0; i < ruls.length; i++) {
if (i == ruls.length - 1) {
rules += ruls[i];
}
else {
rules += ruls[i] + "\n";
}
}
for (int i = 0; i < consts.length; i++) {
if (i == consts.length - 1) {
constraints += consts[i];
}
else {
constraints += consts[i] + "\n";
}
}
for (int i = 0; i < evs.length; i++) {
if (i == evs.length - 1) {
events += evs[i];
}
else {
events += evs[i] + "\n";
}
}
String message;
if (zeroDim) {
message = "Unable to change compartment to 0-dimensions.";
}
else {
message = "Unable to remove the selected species.";
}
if (reactantsUsing.size() != 0) {
message += "\n\nIt is used as a reactant in the following reactions:\n" + reactants;
}
if (productsUsing.size() != 0) {
message += "\n\nIt is used as a product in the following reactions:\n" + products;
}
if (modifiersUsing.size() != 0) {
message += "\n\nIt is used as a modifier in the following reactions:\n" + modifiers;
}
if (kineticLawsUsing.size() != 0) {
message += "\n\nIt is used in the kinetic law in the following reactions:\n" + kineticLaws;
}
if (stoicMathUsing.size() != 0) {
message += "\n\nIt is used in the stoichiometry math for the following reaction/species:\n"
+ stoicMath;
}
if (initsUsing.size() != 0) {
message += "\n\nIt is used in the following initial assignments:\n" + initAssigns;
}
if (rulesUsing.size() != 0) {
message += "\n\nIt is used in the following rules:\n" + rules;
}
if (constraintsUsing.size() != 0) {
message += "\n\nIt is used in the following constraints:\n" + constraints;
}
if (eventsUsing.size() != 0) {
message += "\n\nIt is used in the following events:\n" + events;
}
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(400, 400));
scroll.setPreferredSize(new Dimension(400, 400));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scroll, "Unable To Remove Variable",
JOptionPane.ERROR_MESSAGE);
}
return inUse;
}
/**
* Check that ID is valid and unique
*/
private boolean checkID(String ID, String selectedID, boolean isReacParam) {
if (ID.equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "An ID is required.", "Enter an ID",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (!(IDpat.matcher(ID).matches())) {
JOptionPane.showMessageDialog(biosim.frame(),
"An ID can only contain letters, numbers, and underscores.", "Invalid ID",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (ID.equals("t") || ID.equals("t") || ID.equals("true") || ID.equals("false")
|| ID.equals("notanumber") || ID.equals("pi") || ID.equals("infinity")
|| ID.equals("exponentiale") || ID.equals("abs") || ID.equals("arccos")
|| ID.equals("arccosh") || ID.equals("arcsin") || ID.equals("arcsinh")
|| ID.equals("arctan") || ID.equals("arctanh") || ID.equals("arccot")
|| ID.equals("arccoth") || ID.equals("arccsc") || ID.equals("arccsch")
|| ID.equals("arcsec") || ID.equals("arcsech") || ID.equals("acos") || ID.equals("acosh")
|| ID.equals("asin") || ID.equals("asinh") || ID.equals("atan") || ID.equals("atanh")
|| ID.equals("acot") || ID.equals("acoth") || ID.equals("acsc") || ID.equals("acsch")
|| ID.equals("asec") || ID.equals("asech") || ID.equals("cos") || ID.equals("cosh")
|| ID.equals("cot") || ID.equals("coth") || ID.equals("csc") || ID.equals("csch")
|| ID.equals("ceil") || ID.equals("factorial") || ID.equals("exp") || ID.equals("floor")
|| ID.equals("ln") || ID.equals("log") || ID.equals("sqr") || ID.equals("log10")
|| ID.equals("pow") || ID.equals("sqrt") || ID.equals("root") || ID.equals("piecewise")
|| ID.equals("sec") || ID.equals("sech") || ID.equals("sin") || ID.equals("sinh")
|| ID.equals("tan") || ID.equals("tanh") || ID.equals("and") || ID.equals("or")
|| ID.equals("xor") || ID.equals("not") || ID.equals("eq") || ID.equals("geq")
|| ID.equals("leq") || ID.equals("gt") || ID.equals("neq") || ID.equals("lt")
|| ID.equals("delay")) {
JOptionPane.showMessageDialog(biosim.frame(), "ID cannot be a reserved word.", "Illegal ID",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (usedIDs.contains(ID) && !ID.equals(selectedID)) {
if (isReacParam) {
JOptionPane.showMessageDialog(biosim.frame(), "ID shadows a global ID.", "Not a Unique ID",
JOptionPane.WARNING_MESSAGE);
}
else {
JOptionPane.showMessageDialog(biosim.frame(), "ID is not unique.", "Enter a Unique ID",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
return false;
}
/**
* Creates a frame used to edit functions or create new ones.
*/
private void functionEditor(String option) {
if (option.equals("OK") && functions.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No function selected.",
"Must Select a Function", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel functionPanel = new JPanel();
JPanel funcPanel = new JPanel(new GridLayout(4, 2));
JLabel idLabel = new JLabel("ID:");
JLabel nameLabel = new JLabel("Name:");
JLabel argLabel = new JLabel("Arguments:");
JLabel eqnLabel = new JLabel("Definition:");
funcID = new JTextField(12);
funcName = new JTextField(12);
args = new JTextField(12);
eqn = new JTextField(12);
String selectedID = "";
if (option.equals("OK")) {
try {
FunctionDefinition function = document.getModel().getFunctionDefinition(
(((String) functions.getSelectedValue()).split(" ")[0]));
funcID.setText(function.getId());
selectedID = function.getId();
funcName.setText(function.getName());
String argStr = "";
for (long j = 0; j < function.getNumArguments(); j++) {
if (j != 0) {
argStr += ", ";
}
argStr += myFormulaToString(function.getArgument(j));
}
args.setText(argStr);
if (function.isSetMath()) {
eqn.setText("" + myFormulaToString(function.getBody()));
}
else {
eqn.setText("");
}
}
catch (Exception e) {
}
}
funcPanel.add(idLabel);
funcPanel.add(funcID);
funcPanel.add(nameLabel);
funcPanel.add(funcName);
funcPanel.add(argLabel);
funcPanel.add(args);
funcPanel.add(eqnLabel);
funcPanel.add(eqn);
functionPanel.add(funcPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), functionPanel, "Function Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = checkID(funcID.getText().trim(), selectedID, false);
if (!error) {
String[] vars = eqn.getText().trim().split(" |\\(|\\)|\\,|\\*|\\+|\\/|\\-");
for (int i = 0; i < vars.length; i++) {
if (vars[i].equals(funcID.getText().trim())) {
JOptionPane.showMessageDialog(biosim.frame(), "Recursive functions are not allowed.",
"Recursion Illegal", JOptionPane.ERROR_MESSAGE);
error = true;
break;
}
}
}
if (!error) {
if (eqn.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "Formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (args.getText().trim().equals("")
&& libsbml.parseFormula("lambda(" + eqn.getText().trim() + ")") == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (!args.getText().trim().equals("")
&& libsbml.parseFormula("lambda(" + args.getText().trim() + "," + eqn.getText().trim()
+ ")") == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariables(eqn.getText().trim(), false, args
.getText().trim(), true);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Function can only contain the arguments or other function calls.\n\n"
+ "Illegal variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Illegal Variables",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
if (!error) {
error = checkNumFunctionArguments(myParseFormula(eqn.getText().trim()));
}
if (!error) {
if (option.equals("OK")) {
int index = functions.getSelectedIndex();
String val = ((String) functions.getSelectedValue()).split(" ")[0];
functions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
funcs = Buttons.getList(funcs, functions);
functions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
FunctionDefinition f = document.getModel().getFunctionDefinition(val);
f.setId(funcID.getText().trim());
f.setName(funcName.getText().trim());
if (args.getText().trim().equals("")) {
f.setMath(libsbml.parseFormula("lambda(" + eqn.getText().trim() + ")"));
}
else {
f.setMath(libsbml.parseFormula("lambda(" + args.getText().trim() + ","
+ eqn.getText().trim() + ")"));
}
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(val)) {
usedIDs.set(i, funcID.getText().trim());
}
}
String oldVal = funcs[index];
funcs[index] = funcID.getText().trim() + " ( " + args.getText().trim() + " ) = "
+ eqn.getText().trim();
try {
funcs = sortFunctions(funcs);
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in functions.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
error = true;
funcs[index] = oldVal;
}
functions.setListData(funcs);
functions.setSelectedIndex(index);
updateVarId(false, val, funcID.getText().trim());
}
else {
int index = functions.getSelectedIndex();
JList add = new JList();
String addStr;
addStr = funcID.getText().trim() + " ( " + args.getText().trim() + " ) = "
+ eqn.getText().trim();
Object[] adding = { addStr };
add.setListData(adding);
add.setSelectedIndex(0);
functions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(funcs, functions, add, false, null, null, null, null, null, null,
biosim.frame());
String[] oldVal = funcs;
funcs = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
funcs[i] = (String) adding[i];
}
try {
funcs = sortFunctions(funcs);
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in functions.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
error = true;
funcs = oldVal;
}
if (!error) {
FunctionDefinition f = document.getModel().createFunctionDefinition();
f.setId(funcID.getText().trim());
f.setName(funcName.getText().trim());
if (args.getText().trim().equals("")) {
f.setMath(libsbml.parseFormula("lambda(" + eqn.getText().trim() + ")"));
}
else {
f.setMath(libsbml.parseFormula("lambda(" + args.getText().trim() + ","
+ eqn.getText().trim() + ")"));
}
usedIDs.add(funcID.getText().trim());
}
functions.setListData(funcs);
functions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumFunctionDefinitions() == 1) {
functions.setSelectedIndex(0);
}
else {
functions.setSelectedIndex(index);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), functionPanel, "Function Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Sort functions in order to be evaluated
*/
private String[] sortFunctions(String[] funcs) {
String[] result = new String[funcs.length];
String temp;
String temp2;
int j = 0;
int start = 0;
int end = 0;
for (int i = 0; i < funcs.length; i++) {
String[] func = funcs[i].split(" |\\(|\\)|\\,|\\*|\\+|\\/|\\-");
start = -1;
end = -1;
for (int k = 0; k < j; k++) {
String[] f = result[k].split(" |\\(|\\)|\\,|\\*|\\+|\\/|\\-");
for (int l = 1; l < f.length; l++) {
if (f[l].equals(func[0])) {
end = k;
}
}
for (int l = 1; l < func.length; l++) {
if (func[l].equals(f[0])) {
start = k;
}
}
}
if (end == -1) {
result[j] = funcs[i];
}
else if (start < end) {
temp = result[end];
result[end] = funcs[i];
for (int k = end + 1; k < j; k++) {
temp2 = result[k];
result[k] = temp;
temp = temp2;
}
result[j] = temp;
}
else {
result[j] = funcs[i];
throw new RuntimeException();
}
j++;
}
return result;
}
/**
* Creates a frame used to edit units or create new ones.
*/
private void unitEditor(String option) {
if (option.equals("OK") && unitDefs.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No unit definition selected.",
"Must Select a Unit Definition", JOptionPane.ERROR_MESSAGE);
return;
}
String[] kinds = { "ampere", "becquerel", "candela", "celsius", "coulomb", "dimensionless",
"farad", "gram", "gray", "henry", "hertz", "item", "joule", "katal", "kelvin", "kilogram",
"litre", "lumen", "lux", "metre", "mole", "newton", "ohm", "pascal", "radian", "second",
"siemens", "sievert", "steradian", "tesla", "volt", "watt", "weber" };
JPanel unitDefPanel = new JPanel(new BorderLayout());
JPanel unitPanel = new JPanel(new GridLayout(2, 2));
JLabel idLabel = new JLabel("ID:");
unitID = new JTextField(12);
JLabel nameLabel = new JLabel("Name:");
unitName = new JTextField(12);
JPanel unitListPanel = new JPanel(new BorderLayout());
JPanel addUnitList = new JPanel();
addList = new JButton("Add to List");
removeList = new JButton("Remove from List");
editList = new JButton("Edit List");
addUnitList.add(addList);
addUnitList.add(removeList);
addUnitList.add(editList);
addList.addActionListener(this);
removeList.addActionListener(this);
editList.addActionListener(this);
JLabel unitListLabel = new JLabel("List of Units:");
unitList = new JList();
unitList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(260, 220));
scroll.setPreferredSize(new Dimension(276, 152));
scroll.setViewportView(unitList);
uList = new String[0];
if (option.equals("OK")) {
try {
UnitDefinition unit = document.getModel().getUnitDefinition(
(((String) unitDefs.getSelectedValue()).split(" ")[0]));
unitID.setText(unit.getId());
unitName.setText(unit.getName());
uList = new String[(int) unit.getNumUnits()];
for (int i = 0; i < unit.getNumUnits(); i++) {
uList[i] = "";
if (unit.getUnit(i).getMultiplier() != 1.0) {
uList[i] = unit.getUnit(i).getMultiplier() + " * ";
}
if (unit.getUnit(i).getScale() != 0) {
uList[i] = uList[i] + "10^" + unit.getUnit(i).getScale() + " * ";
}
uList[i] = uList[i] + unitToString(unit.getUnit(i));
if (unit.getUnit(i).getExponent() != 1) {
uList[i] = "( " + uList[i] + " )^" + unit.getUnit(i).getExponent();
}
}
}
catch (Exception e) {
}
}
sort(uList);
unitList.setListData(uList);
unitList.setSelectedIndex(0);
unitList.addMouseListener(this);
unitListPanel.add(unitListLabel, "North");
unitListPanel.add(scroll, "Center");
unitListPanel.add(addUnitList, "South");
unitPanel.add(idLabel);
unitPanel.add(unitID);
unitPanel.add(nameLabel);
unitPanel.add(unitName);
unitDefPanel.add(unitPanel, "North");
unitDefPanel.add(unitListPanel, "South");
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), unitDefPanel,
"Unit Definition Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
if (unitID.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "A unit definition ID is required.",
"Enter an ID", JOptionPane.ERROR_MESSAGE);
error = true;
value = JOptionPane.showOptionDialog(biosim.frame(), unitDefPanel,
"Unit Definition Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
}
else {
String addUnit = "";
addUnit = unitID.getText().trim();
if (!(IDpat.matcher(addUnit).matches())) {
JOptionPane.showMessageDialog(biosim.frame(),
"A unit definition ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
for (int i = 0; i < kinds.length; i++) {
if (kinds[i].equals(addUnit)) {
JOptionPane.showMessageDialog(biosim.frame(), "Unit ID matches a predefined unit.",
"Enter a Unique ID", JOptionPane.ERROR_MESSAGE);
error = true;
break;
}
}
}
if (!error) {
for (int i = 0; i < units.length; i++) {
if (option.equals("OK")) {
if (units[i].equals((String) unitDefs.getSelectedValue()))
continue;
}
if (units[i].equals(addUnit)) {
JOptionPane.showMessageDialog(biosim.frame(), "Unit ID is not unique.",
"Enter a Unique ID", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
if ((!error) && (uList.length == 0)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Unit definition must have at least one unit.", "Unit Needed",
JOptionPane.ERROR_MESSAGE);
error = true;
}
if ((!error)
&& ((addUnit.equals("substance")) || (addUnit.equals("length"))
|| (addUnit.equals("area")) || (addUnit.equals("volume")) || (addUnit
.equals("time")))) {
if (uList.length > 1) {
JOptionPane.showMessageDialog(biosim.frame(),
"Redefinition of built-in unit must have a single unit.", "Single Unit Required",
JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
if (addUnit.equals("substance")) {
if (!(extractUnitKind(uList[0]).equals("dimensionless")
|| (extractUnitKind(uList[0]).equals("mole") && Integer
.valueOf(extractUnitExp(uList[0])) == 1)
|| (extractUnitKind(uList[0]).equals("item") && Integer
.valueOf(extractUnitExp(uList[0])) == 1)
|| (extractUnitKind(uList[0]).equals("gram") && Integer
.valueOf(extractUnitExp(uList[0])) == 1) || (extractUnitKind(uList[0])
.equals("kilogram") && Integer.valueOf(extractUnitExp(uList[0])) == 1))) {
JOptionPane
.showMessageDialog(
biosim.frame(),
"Redefinition of substance must be dimensionless or\n in terms of moles, items, grams, or kilograms.",
"Incorrect Redefinition", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
else if (addUnit.equals("time")) {
if (!(extractUnitKind(uList[0]).equals("dimensionless") || (extractUnitKind(uList[0])
.equals("second") && Integer.valueOf(extractUnitExp(uList[0])) == 1))) {
JOptionPane.showMessageDialog(biosim.frame(),
"Redefinition of time must be dimensionless or in terms of seconds.",
"Incorrect Redefinition", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
else if (addUnit.equals("length")) {
if (!(extractUnitKind(uList[0]).equals("dimensionless") || (extractUnitKind(uList[0])
.equals("metre") && Integer.valueOf(extractUnitExp(uList[0])) == 1))) {
JOptionPane.showMessageDialog(biosim.frame(),
"Redefinition of length must be dimensionless or in terms of metres.",
"Incorrect Redefinition", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
else if (addUnit.equals("area")) {
if (!(extractUnitKind(uList[0]).equals("dimensionless") || (extractUnitKind(uList[0])
.equals("metre") && Integer.valueOf(extractUnitExp(uList[0])) == 2))) {
JOptionPane.showMessageDialog(biosim.frame(),
"Redefinition of area must be dimensionless or in terms of metres^2.",
"Incorrect Redefinition", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
else if (addUnit.equals("volume")) {
if (!(extractUnitKind(uList[0]).equals("dimensionless")
|| (extractUnitKind(uList[0]).equals("litre") && Integer
.valueOf(extractUnitExp(uList[0])) == 1) || (extractUnitKind(uList[0])
.equals("metre") && Integer.valueOf(extractUnitExp(uList[0])) == 3))) {
JOptionPane
.showMessageDialog(
biosim.frame(),
"Redefinition of volume must be dimensionless or in terms of litres or metres^3.",
"Incorrect Redefinition", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
}
if (!error) {
if (option.equals("OK")) {
int index = unitDefs.getSelectedIndex();
String val = ((String) unitDefs.getSelectedValue()).split(" ")[0];
unitDefs.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
units = Buttons.getList(units, unitDefs);
unitDefs.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
UnitDefinition u = document.getModel().getUnitDefinition(val);
u.setId(unitID.getText().trim());
u.setName(unitName.getText().trim());
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(val)) {
usedIDs.set(i, addUnit);
}
}
while (u.getNumUnits() > 0) {
u.getListOfUnits().remove(0);
}
for (int i = 0; i < uList.length; i++) {
Unit unit = new Unit(extractUnitKind(uList[i]), Integer.valueOf(
extractUnitExp(uList[i])).intValue(), Integer.valueOf(extractUnitScale(uList[i]))
.intValue(), Double.valueOf(extractUnitMult(uList[i])).doubleValue());
u.addUnit(unit);
}
units[index] = addUnit;
sort(units);
unitDefs.setListData(units);
unitDefs.setSelectedIndex(index);
updateUnitId(val, unitID.getText().trim());
}
else {
int index = unitDefs.getSelectedIndex();
UnitDefinition u = document.getModel().createUnitDefinition();
u.setId(unitID.getText().trim());
u.setName(unitName.getText().trim());
usedIDs.add(addUnit);
for (int i = 0; i < uList.length; i++) {
Unit unit = new Unit(extractUnitKind(uList[i]), Integer.valueOf(
extractUnitExp(uList[i])).intValue(), Integer.valueOf(extractUnitScale(uList[i]))
.intValue(), Double.valueOf(extractUnitMult(uList[i])).doubleValue());
u.addUnit(unit);
}
JList add = new JList();
Object[] adding = { addUnit };
add.setListData(adding);
add.setSelectedIndex(0);
unitDefs.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(units, unitDefs, add, false, null, null, null, null, null, null,
biosim.frame());
units = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
units[i] = (String) adding[i];
}
sort(units);
unitDefs.setListData(units);
unitDefs.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumUnitDefinitions() == 1) {
unitDefs.setSelectedIndex(0);
}
else {
unitDefs.setSelectedIndex(index);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), unitDefPanel,
"Unit Definition Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
}
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit unit list elements or create new ones.
*/
private void unitListEditor(String option) {
if (option.equals("OK") && unitList.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No unit selected.", "Must Select an Unit",
JOptionPane.ERROR_MESSAGE);
return;
}
JPanel unitListPanel = new JPanel();
JPanel ULPanel = new JPanel(new GridLayout(4, 2));
JLabel kindLabel = new JLabel("Kind:");
JLabel expLabel = new JLabel("Exponent:");
JLabel scaleLabel = new JLabel("Scale:");
JLabel multLabel = new JLabel("Multiplier:");
String[] kinds = { "ampere", "becquerel", "candela", "celsius", "coulomb", "dimensionless",
"farad", "gram", "gray", "henry", "hertz", "item", "joule", "katal", "kelvin", "kilogram",
"litre", "lumen", "lux", "metre", "mole", "newton", "ohm", "pascal", "radian", "second",
"siemens", "sievert", "steradian", "tesla", "volt", "watt", "weber" };
final JComboBox kindBox = new JComboBox(kinds);
exp = new JTextField(12);
exp.setText("1");
scale = new JTextField(12);
scale.setText("0");
mult = new JTextField(12);
mult.setText("1.0");
if (option.equals("OK")) {
String selected = (String) unitList.getSelectedValue();
kindBox.setSelectedItem(extractUnitKind(selected));
exp.setText(extractUnitExp(selected));
scale.setText(extractUnitScale(selected));
mult.setText(extractUnitMult(selected));
}
ULPanel.add(kindLabel);
ULPanel.add(kindBox);
ULPanel.add(expLabel);
ULPanel.add(exp);
ULPanel.add(scaleLabel);
ULPanel.add(scale);
ULPanel.add(multLabel);
ULPanel.add(mult);
unitListPanel.add(ULPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), unitListPanel, "Unit List Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
try {
Integer.valueOf(exp.getText().trim()).intValue();
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Exponent must be an integer.",
"Integer Expected", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
try {
Integer.valueOf(scale.getText().trim()).intValue();
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Scale must be an integer.",
"Integer Expected", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
try {
Double.valueOf(mult.getText().trim()).doubleValue();
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Multiplier must be a double.",
"Double Expected", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
if (option.equals("OK")) {
int index = unitList.getSelectedIndex();
unitList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
uList = Buttons.getList(uList, unitList);
unitList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
uList[index] = "";
if (!mult.getText().trim().equals("1.0")) {
uList[index] = mult.getText().trim() + " * ";
}
if (!scale.getText().trim().equals("0")) {
uList[index] = uList[index] + "10^" + scale.getText().trim() + " * ";
}
uList[index] = uList[index] + kindBox.getSelectedItem();
if (!exp.getText().trim().equals("1")) {
uList[index] = "( " + uList[index] + " )^" + exp.getText().trim();
}
sort(uList);
unitList.setListData(uList);
unitList.setSelectedIndex(index);
}
else {
JList add = new JList();
int index = unitList.getSelectedIndex();
String addStr;
addStr = "";
if (!mult.getText().trim().equals("1.0")) {
addStr = mult.getText().trim() + " * ";
}
if (!scale.getText().trim().equals("0")) {
addStr = addStr + "10^" + scale.getText().trim() + " * ";
}
addStr = addStr + kindBox.getSelectedItem();
if (!exp.getText().trim().equals("1")) {
addStr = "( " + addStr + " )^" + exp.getText().trim();
}
Object[] adding = { addStr };
add.setListData(adding);
add.setSelectedIndex(0);
unitList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(uList, unitList, add, false, null, null, null, null, null, null,
biosim.frame());
uList = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
uList[i] = (String) adding[i];
}
sort(uList);
unitList.setListData(uList);
unitList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (adding.length == 1) {
unitList.setSelectedIndex(0);
}
else {
unitList.setSelectedIndex(index);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), unitListPanel, "Unit List Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Convert unit kind to string
*/
private String unitToString(Unit unit) {
if (unit.isAmpere()) {
return "ampere";
}
else if (unit.isBecquerel()) {
return "becquerel";
}
else if (unit.isCandela()) {
return "candela";
}
else if (unit.isCelsius()) {
return "celsius";
}
else if (unit.isCoulomb()) {
return "coulomb";
}
else if (unit.isDimensionless()) {
return "dimensionless";
}
else if (unit.isFarad()) {
return "farad";
}
else if (unit.isGram()) {
return "gram";
}
else if (unit.isGray()) {
return "gray";
}
else if (unit.isHenry()) {
return "henry";
}
else if (unit.isHertz()) {
return "hertz";
}
else if (unit.isItem()) {
return "item";
}
else if (unit.isJoule()) {
return "joule";
}
else if (unit.isKatal()) {
return "katal";
}
else if (unit.isKelvin()) {
return "kelvin";
}
else if (unit.isKilogram()) {
return "kilogram";
}
else if (unit.isLitre()) {
return "litre";
}
else if (unit.isLumen()) {
return "lumen";
}
else if (unit.isLux()) {
return "lux";
}
else if (unit.isMetre()) {
return "metre";
}
else if (unit.isMole()) {
return "mole";
}
else if (unit.isNewton()) {
return "newton";
}
else if (unit.isOhm()) {
return "ohm";
}
else if (unit.isPascal()) {
return "pascal";
}
else if (unit.isRadian()) {
return "radian";
}
else if (unit.isSecond()) {
return "second";
}
else if (unit.isSiemens()) {
return "siemens";
}
else if (unit.isSievert()) {
return "sievert";
}
else if (unit.isSteradian()) {
return "steradian";
}
else if (unit.isTesla()) {
return "tesla";
}
else if (unit.isVolt()) {
return "volt";
}
else if (unit.isWatt()) {
return "watt";
}
else if (unit.isWeber()) {
return "weber";
}
return "Unknown";
}
/**
* Extract unit kind from string
*/
private String extractUnitKind(String selected) {
if (selected.contains(")^")) {
if (selected.contains("10^")) {
return selected.substring(selected.lastIndexOf("*") + 2, selected.indexOf(")") - 1);
}
else if (selected.contains("*")) {
return selected.substring(selected.lastIndexOf("*") + 2, selected.indexOf(")") - 1);
}
else {
return selected.substring(2, selected.indexOf(")") - 1);
}
}
else if (selected.contains("10^")) {
return selected.substring(selected.lastIndexOf("*") + 2);
}
else if (selected.contains("*")) {
mult.setText(selected.substring(0, selected.indexOf("*") - 1));
return selected.substring(selected.indexOf("*") + 2);
}
else {
return selected;
}
}
/**
* Extract unit exponent from string
*/
private String extractUnitExp(String selected) {
if (selected.contains(")^")) {
return selected.substring(selected.indexOf(")^") + 2);
}
return "1";
}
/**
* Extract unit scale from string
*/
private String extractUnitScale(String selected) {
if (selected.contains(")^")) {
if (selected.contains("10^")) {
return selected.substring(selected.indexOf("10^") + 3, selected.lastIndexOf("*") - 1);
}
}
else if (selected.contains("10^")) {
return selected.substring(selected.indexOf("10^") + 3, selected.lastIndexOf("*") - 1);
}
return "0";
}
/**
* Extract unit multiplier from string
*/
private String extractUnitMult(String selected) {
if (selected.contains(")^")) {
if (selected.contains("10^")) {
String multStr = selected.substring(2, selected.indexOf("*") - 1);
if (!multStr.contains("10^")) {
return multStr;
}
}
else if (selected.contains("*")) {
return selected.substring(2, selected.indexOf("*") - 1);
}
else if (selected.contains("10^")) {
String multStr = selected.substring(0, selected.indexOf("*") - 1);
if (!multStr.contains("10^")) {
return multStr;
}
}
else if (selected.contains("*")) {
return selected.substring(0, selected.indexOf("*") - 1);
}
}
return "1.0";
}
/**
* Creates a frame used to edit compartment types or create new ones.
*/
private void compTypeEditor(String option) {
if (option.equals("OK") && compTypes.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No compartment type selected.",
"Must Select a Compartment Type", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel compTypePanel = new JPanel();
JPanel cpTypPanel = new JPanel(new GridLayout(2, 2));
JLabel idLabel = new JLabel("ID:");
JLabel nameLabel = new JLabel("Name:");
compTypeID = new JTextField(12);
compTypeName = new JTextField(12);
String selectedID = "";
if (option.equals("OK")) {
try {
CompartmentType compType = document.getModel().getCompartmentType(
(((String) compTypes.getSelectedValue()).split(" ")[0]));
compTypeID.setText(compType.getId());
selectedID = compType.getId();
compTypeName.setText(compType.getName());
}
catch (Exception e) {
}
}
cpTypPanel.add(idLabel);
cpTypPanel.add(compTypeID);
cpTypPanel.add(nameLabel);
cpTypPanel.add(compTypeName);
compTypePanel.add(cpTypPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), compTypePanel,
"Compartment Type Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = checkID(compTypeID.getText().trim(), selectedID, false);
if (!error) {
if (option.equals("OK")) {
int index = compTypes.getSelectedIndex();
String val = ((String) compTypes.getSelectedValue()).split(" ")[0];
compTypes.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
cpTyp = Buttons.getList(cpTyp, compTypes);
compTypes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
CompartmentType c = document.getModel().getCompartmentType(val);
c.setId(compTypeID.getText().trim());
c.setName(compTypeName.getText().trim());
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(val)) {
usedIDs.set(i, compTypeID.getText().trim());
}
}
cpTyp[index] = compTypeID.getText().trim();
sort(cpTyp);
compTypes.setListData(cpTyp);
compTypes.setSelectedIndex(index);
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = document.getModel().getCompartment(i);
if (compartment.getCompartmentType().equals(val)) {
compartment.setCompartmentType(compTypeID.getText().trim());
}
}
int index1 = compartments.getSelectedIndex();
compartments.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
comps = Buttons.getList(comps, compartments);
compartments.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
for (int i = 0; i < comps.length; i++) {
if (comps[i].split(" ")[1].equals(val)) {
comps[i] = comps[i].split(" ")[0] + " " + compTypeID.getText().trim() + " "
+ comps[i].split(" ")[2];
}
}
sort(comps);
compartments.setListData(comps);
compartments.setSelectedIndex(index1);
}
else {
int index = compTypes.getSelectedIndex();
CompartmentType c = document.getModel().createCompartmentType();
c.setId(compTypeID.getText().trim());
c.setName(compTypeName.getText().trim());
usedIDs.add(compTypeID.getText().trim());
JList add = new JList();
Object[] adding = { compTypeID.getText().trim() };
add.setListData(adding);
add.setSelectedIndex(0);
compTypes.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(cpTyp, compTypes, add, false, null, null, null, null, null, null,
biosim.frame());
cpTyp = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
cpTyp[i] = (String) adding[i];
}
sort(cpTyp);
compTypes.setListData(cpTyp);
compTypes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumCompartmentTypes() == 1) {
compTypes.setSelectedIndex(0);
}
else {
compTypes.setSelectedIndex(index);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), compTypePanel,
"Compartment Type Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit species types or create new ones.
*/
private void specTypeEditor(String option) {
if (option.equals("OK") && specTypes.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No species type selected.",
"Must Select a Species Type", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel specTypePanel = new JPanel();
JPanel spTypPanel = new JPanel(new GridLayout(2, 2));
JLabel idLabel = new JLabel("ID:");
JLabel nameLabel = new JLabel("Name:");
specTypeID = new JTextField(12);
specTypeName = new JTextField(12);
String selectedID = "";
if (option.equals("OK")) {
try {
SpeciesType specType = document.getModel().getSpeciesType(
(((String) specTypes.getSelectedValue()).split(" ")[0]));
specTypeID.setText(specType.getId());
selectedID = specType.getId();
specTypeName.setText(specType.getName());
}
catch (Exception e) {
}
}
spTypPanel.add(idLabel);
spTypPanel.add(specTypeID);
spTypPanel.add(nameLabel);
spTypPanel.add(specTypeName);
specTypePanel.add(spTypPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), specTypePanel, "Species Type Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = checkID(specTypeID.getText().trim(), selectedID, false);
if (!error) {
if (option.equals("OK")) {
int index = specTypes.getSelectedIndex();
String val = ((String) specTypes.getSelectedValue()).split(" ")[0];
specTypes.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
spTyp = Buttons.getList(spTyp, specTypes);
specTypes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
SpeciesType s = document.getModel().getSpeciesType(val);
s.setId(specTypeID.getText().trim());
s.setName(specTypeName.getText().trim());
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(val)) {
usedIDs.set(i, specTypeID.getText().trim());
}
}
spTyp[index] = specTypeID.getText().trim();
sort(spTyp);
specTypes.setListData(spTyp);
specTypes.setSelectedIndex(index);
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
Species species = document.getModel().getSpecies(i);
if (species.getSpeciesType().equals(val)) {
species.setSpeciesType(specTypeID.getText().trim());
}
}
int index1 = species.getSelectedIndex();
species.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
specs = Buttons.getList(specs, species);
species.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
for (int i = 0; i < specs.length; i++) {
if (specs[i].split(" ")[1].equals(val)) {
specs[i] = specs[i].split(" ")[0] + " " + specTypeID.getText().trim() + " "
+ specs[i].split(" ")[2] + " " + specs[i].split(" ")[3];
}
}
sort(specs);
species.setListData(specs);
species.setSelectedIndex(index1);
}
else {
int index = specTypes.getSelectedIndex();
SpeciesType s = document.getModel().createSpeciesType();
s.setId(specTypeID.getText().trim());
s.setName(specTypeName.getText().trim());
usedIDs.add(specTypeID.getText().trim());
JList add = new JList();
Object[] adding = { specTypeID.getText().trim() };
add.setListData(adding);
add.setSelectedIndex(0);
specTypes.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(spTyp, specTypes, add, false, null, null, null, null, null, null,
biosim.frame());
spTyp = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
spTyp[i] = (String) adding[i];
}
sort(spTyp);
specTypes.setListData(spTyp);
specTypes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumSpeciesTypes() == 1) {
specTypes.setSelectedIndex(0);
}
else {
specTypes.setSelectedIndex(index);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), specTypePanel, "Species Type Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit initial assignments or create new ones.
*/
private void initEditor(String option) {
if (option.equals("OK") && initAssigns.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No initial assignment selected.",
"Must Select an Initial Assignment", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel initAssignPanel = new JPanel();
JPanel initPanel = new JPanel(new GridLayout(2, 2));
JLabel varLabel = new JLabel("Symbol:");
JLabel assignLabel = new JLabel("Assignment:");
initVar = new JComboBox();
String selected;
if (option.equals("OK")) {
selected = ((String) initAssigns.getSelectedValue());
}
else {
selected = new String("");
}
Model model = document.getModel();
ListOf ids = model.getListOfCompartments();
for (int i = 0; i < model.getNumCompartments(); i++) {
String id = ((Compartment) ids.get(i)).getId();
if (keepVar(selected.split(" ")[0], id, true, false, false, false)
&& ((Compartment) ids.get(i)).getSpatialDimensions() != 0) {
initVar.addItem(id);
}
}
ids = model.getListOfParameters();
for (int i = 0; i < model.getNumParameters(); i++) {
String id = ((Parameter) ids.get(i)).getId();
if (keepVar(selected.split(" ")[0], id, true, false, false, false)) {
initVar.addItem(id);
}
}
ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
String id = ((Species) ids.get(i)).getId();
if (keepVar(selected.split(" ")[0], id, true, false, false, false)) {
initVar.addItem(id);
}
}
initMath = new JTextField(12);
int Rindex = -1;
if (option.equals("OK")) {
initVar.setSelectedItem(selected.split(" ")[0]);
initMath.setText(selected.substring(selected.indexOf('=') + 2));
ListOf r = document.getModel().getListOfInitialAssignments();
for (int i = 0; i < document.getModel().getNumInitialAssignments(); i++) {
if (myFormulaToString(((InitialAssignment) r.get(i)).getMath()).equals(initMath.getText())
&& ((InitialAssignment) r.get(i)).getSymbol().equals(initVar.getSelectedItem())) {
Rindex = i;
}
}
}
initPanel.add(varLabel);
initPanel.add(initVar);
initPanel.add(assignLabel);
initPanel.add(initMath);
initAssignPanel.add(initPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), initAssignPanel,
"Initial Assignment Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
String addVar = "";
addVar = (String) initVar.getSelectedItem();
if (initMath.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "Initial assignment is missing.",
"Enter Assignment", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (myParseFormula(initMath.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Initial assignment is not valid.",
"Enter Valid Assignment", JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariables(initMath.getText().trim(), false, "",
false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Rule contains unknown variables.\n\n" + "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Unknown Variables",
JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = checkNumFunctionArguments(myParseFormula(initMath.getText().trim()));
}
if (!error) {
if (myParseFormula(initMath.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Initial assignment must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
if (!error) {
if (option.equals("OK")) {
int index = initAssigns.getSelectedIndex();
initAssigns.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
inits = Buttons.getList(inits, initAssigns);
initAssigns.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
InitialAssignment r = (InitialAssignment) (document.getModel()
.getListOfInitialAssignments()).get(Rindex);
String oldSymbol = r.getSymbol();
String oldInit = myFormulaToString(r.getMath());
String oldVal = inits[index];
r.setSymbol(addVar);
r.setMath(myParseFormula(initMath.getText().trim()));
inits[index] = addVar + " = " + myFormulaToString(r.getMath());
error = checkInitialAssignmentUnits(r);
if (!error) {
try {
inits = sortInitRules(inits);
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected in initial assignments.", "Cycle Detected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error && checkCycles(inits, rul)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected within initial assignments and assignment rules.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (error) {
r.setSymbol(oldSymbol);
r.setMath(myParseFormula(oldInit));
inits[index] = oldVal;
}
initAssigns.setListData(inits);
initAssigns.setSelectedIndex(index);
}
else {
JList add = new JList();
int index = rules.getSelectedIndex();
String addStr;
InitialAssignment r = document.getModel().createInitialAssignment();
r.setSymbol(addVar);
r.setMath(myParseFormula(initMath.getText().trim()));
addStr = addVar + " = " + myFormulaToString(r.getMath());
Object[] adding = { addStr };
add.setListData(adding);
add.setSelectedIndex(0);
initAssigns.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(inits, initAssigns, add, false, null, null, null, null, null, null,
biosim.frame());
String[] oldInits = inits;
inits = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
inits[i] = (String) adding[i];
}
error = checkInitialAssignmentUnits(r);
if (!error) {
try {
inits = sortInitRules(inits);
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected in initial assignments.", "Cycle Detected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error && checkCycles(inits, rul)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected within initial assignments and assignment rules.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (error) {
inits = oldInits;
ListOf ia = document.getModel().getListOfInitialAssignments();
for (int i = 0; i < document.getModel().getNumInitialAssignments(); i++) {
if (myFormulaToString(((InitialAssignment) ia.get(i)).getMath()).equals(
myFormulaToString(r.getMath()))
&& ((InitialAssignment) ia.get(i)).getSymbol().equals(r.getSymbol())) {
ia.remove(i);
}
}
}
initAssigns.setListData(inits);
initAssigns.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumInitialAssignments() == 1) {
initAssigns.setSelectedIndex(0);
}
else {
initAssigns.setSelectedIndex(index);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), initAssignPanel,
"Initial Assignment Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Determines if a variable is already in an initial or assignment rule
*/
private boolean keepVar(String selected, String id, boolean checkInit, boolean checkRate,
boolean checkEventAssign, boolean checkOnlyCurEvent) {
if (!selected.equals(id)) {
if (checkInit) {
for (int j = 0; j < inits.length; j++) {
if (id.equals(inits[j].split(" ")[0])) {
return false;
}
}
}
if (checkOnlyCurEvent) {
for (int j = 0; j < assign.length; j++) {
if (id.equals(assign[j].split(" ")[0])) {
return false;
}
}
}
if (checkEventAssign) {
ListOf e = document.getModel().getListOfEvents();
for (int i = 0; i < document.getModel().getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) e.get(i);
for (int j = 0; j < event.getNumEventAssignments(); j++) {
if (id.equals(event.getEventAssignment(j).getVariable())) {
return false;
}
}
}
}
for (int j = 0; j < rul.length; j++) {
if (id.equals(rul[j].split(" ")[0])) {
return false;
}
if (checkRate && id.equals(rul[j].split(" ")[1])) {
return false;
}
}
}
return true;
}
/**
* Creates a frame used to edit rules or create new ones.
*/
private void ruleEditor(String option) {
if (option.equals("OK") && rules.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No rule selected.", "Must Select a Rule",
JOptionPane.ERROR_MESSAGE);
return;
}
JPanel rulePanel = new JPanel();
JPanel rulPanel = new JPanel(new GridLayout(3, 2));
JLabel typeLabel = new JLabel("Type:");
JLabel varLabel = new JLabel("Variable:");
JLabel ruleLabel = new JLabel("Rule:");
String[] list = { "Algebraic", "Assignment", "Rate" };
ruleType = new JComboBox(list);
ruleVar = new JComboBox();
ruleMath = new JTextField(12);
ruleVar.setEnabled(false);
ruleType.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((String) ruleType.getSelectedItem()).equals("Assignment")) {
assignRuleVar("");
ruleVar.setEnabled(true);
}
else if (((String) ruleType.getSelectedItem()).equals("Rate")) {
rateRuleVar("");
ruleVar.setEnabled(true);
}
else {
ruleVar.removeAllItems();
ruleVar.setEnabled(false);
}
}
});
int Rindex = -1;
if (option.equals("OK")) {
ruleType.setEnabled(false);
String selected = ((String) rules.getSelectedValue());
// algebraic rule
if ((selected.split(" ")[0]).equals("0")) {
ruleType.setSelectedItem("Algebraic");
ruleVar.setEnabled(false);
ruleMath.setText(selected.substring(4));
ListOf r = document.getModel().getListOfRules();
for (int i = 0; i < document.getModel().getNumRules(); i++) {
if ((((Rule) r.get(i)).isAlgebraic())
&& (myFormulaToString(((Rule) r.get(i)).getMath()).equals(ruleMath.getText()))) {
Rindex = i;
}
}
}
else if ((selected.split(" ")[0]).equals("d(")) {
ruleType.setSelectedItem("Rate");
rateRuleVar(selected.split(" ")[1]);
ruleVar.setEnabled(true);
ruleVar.setSelectedItem(selected.split(" ")[1]);
ruleMath.setText(selected.substring(selected.indexOf('=') + 2));
ListOf r = document.getModel().getListOfRules();
for (int i = 0; i < document.getModel().getNumRules(); i++) {
if ((((Rule) r.get(i)).isRate())
&& ((Rule) r.get(i)).getVariable().equals(ruleVar.getSelectedItem())) {
Rindex = i;
}
}
}
else {
ruleType.setSelectedItem("Assignment");
assignRuleVar(selected.split(" ")[0]);
ruleVar.setEnabled(true);
ruleVar.setSelectedItem(selected.split(" ")[0]);
ruleMath.setText(selected.substring(selected.indexOf('=') + 2));
ListOf r = document.getModel().getListOfRules();
for (int i = 0; i < document.getModel().getNumRules(); i++) {
if ((((Rule) r.get(i)).isAssignment())
&& ((Rule) r.get(i)).getVariable().equals(ruleVar.getSelectedItem())) {
Rindex = i;
}
}
}
}
else {
if (!assignRuleVar("") && !rateRuleVar("")) {
String[] list1 = { "Algebraic" };
ruleType = new JComboBox(list1);
}
else if (!assignRuleVar("")) {
String[] list1 = { "Algebraic", "Rate" };
ruleType = new JComboBox(list1);
}
else if (!rateRuleVar("")) {
String[] list1 = { "Algebraic", "Assignment" };
ruleType = new JComboBox(list1);
}
}
rulPanel.add(typeLabel);
rulPanel.add(ruleType);
rulPanel.add(varLabel);
rulPanel.add(ruleVar);
rulPanel.add(ruleLabel);
rulPanel.add(ruleMath);
rulePanel.add(rulPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), rulePanel, "Rule Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
String addVar = "";
addVar = (String) ruleVar.getSelectedItem();
if (ruleMath.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "Rule must have formula.",
"Enter Rule Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (myParseFormula(ruleMath.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Rule formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariables(ruleMath.getText().trim(), false, "",
false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Rule contains unknown variables.\n\n" + "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Unknown Variables",
JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = checkNumFunctionArguments(myParseFormula(ruleMath.getText().trim()));
}
if (!error) {
if (myParseFormula(ruleMath.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(), "Rule must evaluate to a number.",
"Number Expected", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
if (!error) {
if (option.equals("OK")) {
int index = rules.getSelectedIndex();
rules.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
rul = Buttons.getList(rul, rules);
rules.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Rule r = (Rule) (document.getModel().getListOfRules()).get(Rindex);
String addStr;
String oldVar = "";
String oldMath = myFormulaToString(r.getMath());
if (ruleType.getSelectedItem().equals("Algebraic")) {
r.setMath(myParseFormula(ruleMath.getText().trim()));
addStr = "0 = " + myFormulaToString(r.getMath());
// checkOverDetermined();
}
else if (ruleType.getSelectedItem().equals("Rate")) {
oldVar = r.getVariable();
r.setVariable(addVar);
r.setMath(myParseFormula(ruleMath.getText().trim()));
error = checkRateRuleUnits(r);
addStr = "d( " + addVar + " )/dt = " + myFormulaToString(r.getMath());
}
else {
oldVar = r.getVariable();
r.setVariable(addVar);
r.setMath(myParseFormula(ruleMath.getText().trim()));
error = checkAssignmentRuleUnits(r);
addStr = addVar + " = " + myFormulaToString(r.getMath());
}
String oldVal = rul[index];
rul[index] = addStr;
if (!error) {
try {
rul = sortRules(rul);
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in assignments.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error && checkCycles(inits, rul)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected within initial assignments and assignment rules.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (error) {
if (!oldVar.equals("")) {
r.setVariable(oldVar);
}
r.setMath(myParseFormula(oldMath));
rul[index] = oldVal;
}
updateRules();
rules.setListData(rul);
rules.setSelectedIndex(index);
}
else {
JList add = new JList();
int index = rules.getSelectedIndex();
String addStr;
if (ruleType.getSelectedItem().equals("Algebraic")) {
addStr = "0 = " + myFormulaToString(myParseFormula(ruleMath.getText().trim()));
}
else if (ruleType.getSelectedItem().equals("Rate")) {
addStr = "d( " + addVar + " )/dt = "
+ myFormulaToString(myParseFormula(ruleMath.getText().trim()));
}
else {
addStr = addVar + " = " + myFormulaToString(myParseFormula(ruleMath.getText().trim()));
}
Object[] adding = { addStr };
add.setListData(adding);
add.setSelectedIndex(0);
rules.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(rul, rules, add, false, null, null, null, null, null, null, biosim
.frame());
String[] oldRul = rul;
rul = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
rul[i] = (String) adding[i];
}
try {
rul = sortRules(rul);
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in assignments.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
error = true;
rul = oldRul;
}
if (!error && checkCycles(inits, rul)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected within initial assignments and assignment rules.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
error = true;
rul = oldRul;
}
if (!error) {
if (ruleType.getSelectedItem().equals("Algebraic")) {
AlgebraicRule r = document.getModel().createAlgebraicRule();
r.setMath(myParseFormula(ruleMath.getText().trim()));
// checkOverDetermined();
}
else if (ruleType.getSelectedItem().equals("Rate")) {
RateRule r = document.getModel().createRateRule();
r.setVariable(addVar);
r.setMath(myParseFormula(ruleMath.getText().trim()));
error = checkRateRuleUnits(r);
}
else {
AssignmentRule r = document.getModel().createAssignmentRule();
r.setVariable(addVar);
r.setMath(myParseFormula(ruleMath.getText().trim()));
error = checkAssignmentRuleUnits(r);
}
}
if (error) {
rul = oldRul;
removeTheRule(addStr);
}
updateRules();
rules.setListData(rul);
rules.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumRules() == 1) {
rules.setSelectedIndex(0);
}
else {
rules.setSelectedIndex(index);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), rulePanel, "Rule Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Update rules
*/
private void updateRules() {
ListOf r = document.getModel().getListOfRules();
while (document.getModel().getNumRules() > 0) {
r.remove(0);
}
for (int i = 0; i < rul.length; i++) {
if (rul[i].split(" ")[0].equals("0")) {
AlgebraicRule rule = document.getModel().createAlgebraicRule();
rule.setMath(myParseFormula(rul[i].substring(rul[i].indexOf("=") + 1)));
}
else if (rul[i].split(" ")[0].equals("d(")) {
RateRule rule = document.getModel().createRateRule();
rule.setVariable(rul[i].split(" ")[1]);
rule.setMath(myParseFormula(rul[i].substring(rul[i].indexOf("=") + 1)));
}
else {
AssignmentRule rule = document.getModel().createAssignmentRule();
rule.setVariable(rul[i].split(" ")[0]);
rule.setMath(myParseFormula(rul[i].substring(rul[i].indexOf("=") + 1)));
}
}
}
/**
* Sort rules in order to be evaluated
*/
private String[] sortRules(String[] rules) {
String[] result = new String[rules.length];
int j = 0;
boolean[] used = new boolean[rules.length];
for (int i = 0; i < rules.length; i++) {
used[i] = false;
}
for (int i = 0; i < rules.length; i++) {
if (rules[i].split(" ")[0].equals("0")) {
result[j] = rules[i];
used[i] = true;
j++;
}
}
boolean progress;
do {
progress = false;
for (int i = 0; i < rules.length; i++) {
if (used[i] || (rules[i].split(" ")[0].equals("0"))
|| (rules[i].split(" ")[0].equals("d(")))
continue;
String[] rule = rules[i].split(" ");
boolean insert = true;
for (int k = 1; k < rule.length; k++) {
for (int l = 0; l < rules.length; l++) {
if (used[l] || (rules[l].split(" ")[0].equals("0"))
|| (rules[l].split(" ")[0].equals("d(")))
continue;
String[] rule2 = rules[l].split(" ");
if (rule[k].equals(rule2[0])) {
insert = false;
break;
}
}
if (!insert)
break;
}
if (insert) {
result[j] = rules[i];
j++;
progress = true;
used[i] = true;
}
}
}
while ((progress) && (j < rules.length));
for (int i = 0; i < rules.length; i++) {
if (rules[i].split(" ")[0].equals("d(")) {
result[j] = rules[i];
j++;
}
}
if (j != rules.length) {
throw new RuntimeException();
}
return result;
}
/**
* Sort initial rules in order to be evaluated
*/
private String[] sortInitRules(String[] initRules) {
String[] result = new String[initRules.length];
int j = 0;
boolean[] used = new boolean[initRules.length];
for (int i = 0; i < initRules.length; i++) {
used[i] = false;
}
boolean progress;
do {
progress = false;
for (int i = 0; i < initRules.length; i++) {
if (used[i])
continue;
String[] initRule = initRules[i].split(" ");
boolean insert = true;
for (int k = 1; k < initRule.length; k++) {
for (int l = 0; l < initRules.length; l++) {
if (used[l])
continue;
String[] initRule2 = initRules[l].split(" ");
if (initRule[k].equals(initRule2[0])) {
insert = false;
break;
}
}
if (!insert)
break;
}
if (insert) {
result[j] = initRules[i];
j++;
progress = true;
used[i] = true;
}
}
}
while ((progress) && (j < initRules.length));
if (j != initRules.length) {
throw new RuntimeException();
}
return result;
}
/**
* Check for cycles in initialAssignments and assignmentRules
*/
private boolean checkCycles(String[] initRules, String[] rules) {
String[] result = new String[rules.length + initRules.length];
int j = 0;
boolean[] used = new boolean[rules.length + initRules.length];
for (int i = 0; i < rules.length + initRules.length; i++) {
used[i] = false;
}
for (int i = 0; i < rules.length; i++) {
if (rules[i].split(" ")[0].equals("0")) {
result[j] = rules[i];
used[i] = true;
j++;
}
}
boolean progress;
do {
progress = false;
for (int i = 0; i < rules.length + initRules.length; i++) {
String[] rule;
if (i < rules.length) {
if (used[i] || (rules[i].split(" ")[0].equals("0"))
|| (rules[i].split(" ")[0].equals("d(")))
continue;
rule = rules[i].split(" ");
}
else {
if (used[i])
continue;
rule = initRules[i - rules.length].split(" ");
}
boolean insert = true;
for (int k = 1; k < rule.length; k++) {
for (int l = 0; l < rules.length + initRules.length; l++) {
String rule2;
if (l < rules.length) {
if (used[l] || (rules[l].split(" ")[0].equals("0"))
|| (rules[l].split(" ")[0].equals("d(")))
continue;
rule2 = rules[l].split(" ")[0];
}
else {
if (used[l])
continue;
rule2 = initRules[l - rules.length].split(" ")[0];
}
if (rule[k].equals(rule2)) {
insert = false;
break;
}
}
if (!insert)
break;
}
if (insert) {
if (i < rules.length) {
result[j] = rules[i];
}
else {
result[j] = initRules[i - rules.length];
}
j++;
progress = true;
used[i] = true;
}
}
}
while ((progress) && (j < rules.length + initRules.length));
for (int i = 0; i < rules.length; i++) {
if (rules[i].split(" ")[0].equals("d(")) {
result[j] = rules[i];
j++;
}
}
if (j != rules.length + initRules.length) {
return true;
}
return false;
}
/**
* Create check if species used in reaction
*/
private boolean usedInReaction(String id) {
for (int i = 0; i < document.getModel().getNumReactions(); i++) {
for (int j = 0; j < document.getModel().getReaction(i).getNumReactants(); j++) {
if (document.getModel().getReaction(i).getReactant(j).getSpecies().equals(id)) {
return true;
}
}
for (int j = 0; j < document.getModel().getReaction(i).getNumProducts(); j++) {
if (document.getModel().getReaction(i).getProduct(j).getSpecies().equals(id)) {
return true;
}
}
}
return false;
}
/**
* Create comboBox for assignments rules
*/
private boolean assignRuleVar(String selected) {
boolean assignOK = false;
ruleVar.removeAllItems();
Model model = document.getModel();
ListOf ids = model.getListOfCompartments();
for (int i = 0; i < model.getNumCompartments(); i++) {
String id = ((Compartment) ids.get(i)).getId();
if (!((Compartment) ids.get(i)).getConstant()) {
if (keepVar(selected, id, true, true, true, false)) {
ruleVar.addItem(((Compartment) ids.get(i)).getId());
assignOK = true;
}
}
}
ids = model.getListOfParameters();
for (int i = 0; i < model.getNumParameters(); i++) {
String id = ((Parameter) ids.get(i)).getId();
if (!((Parameter) ids.get(i)).getConstant()) {
if (keepVar(selected, id, true, true, true, false)) {
ruleVar.addItem(((Parameter) ids.get(i)).getId());
assignOK = true;
}
}
}
ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
String id = ((Species) ids.get(i)).getId();
if (!((Species) ids.get(i)).getConstant()) {
if (keepVar(selected, id, true, true, true, false))
if (((Species) ids.get(i)).getBoundaryCondition() || !usedInReaction(id)) {
ruleVar.addItem(((Species) ids.get(i)).getId());
assignOK = true;
}
}
}
return assignOK;
}
/**
* Create comboBox for rate rules
*/
private boolean rateRuleVar(String selected) {
boolean rateOK = false;
ruleVar.removeAllItems();
Model model = document.getModel();
ListOf ids = model.getListOfCompartments();
for (int i = 0; i < model.getNumCompartments(); i++) {
String id = ((Compartment) ids.get(i)).getId();
if (!((Compartment) ids.get(i)).getConstant()) {
if (keepVar(selected, id, false, true, false, false)) {
ruleVar.addItem(((Compartment) ids.get(i)).getId());
rateOK = true;
}
}
}
ids = model.getListOfParameters();
for (int i = 0; i < model.getNumParameters(); i++) {
String id = ((Parameter) ids.get(i)).getId();
if (!((Parameter) ids.get(i)).getConstant()) {
if (keepVar(selected, id, false, true, false, false)) {
ruleVar.addItem(((Parameter) ids.get(i)).getId());
rateOK = true;
}
}
}
ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
String id = ((Species) ids.get(i)).getId();
if (!((Species) ids.get(i)).getConstant()) {
if (keepVar(selected, id, false, true, false, false))
if (((Species) ids.get(i)).getBoundaryCondition() || !usedInReaction(id)) {
ruleVar.addItem(((Species) ids.get(i)).getId());
rateOK = true;
}
}
}
return rateOK;
}
/**
* Creates a frame used to edit events or create new ones.
*/
private void eventEditor(String option) {
if (option.equals("OK") && events.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No event selected.", "Must Select an Event",
JOptionPane.ERROR_MESSAGE);
return;
}
JPanel eventPanel = new JPanel(new BorderLayout());
// JPanel evPanel = new JPanel(new GridLayout(2, 2));
JPanel evPanel = new JPanel(new GridLayout(4, 2));
JLabel IDLabel = new JLabel("ID:");
JLabel NameLabel = new JLabel("Name:");
JLabel triggerLabel = new JLabel("Trigger:");
JLabel delayLabel = new JLabel("Delay:");
eventID = new JTextField(12);
eventName = new JTextField(12);
eventTrigger = new JTextField(12);
eventDelay = new JTextField(12);
JPanel eventAssignPanel = new JPanel(new BorderLayout());
JPanel addEventAssign = new JPanel();
addAssignment = new JButton("Add Assignment");
removeAssignment = new JButton("Remove Assignment");
editAssignment = new JButton("Edit Assignment");
addEventAssign.add(addAssignment);
addEventAssign.add(removeAssignment);
addEventAssign.add(editAssignment);
addAssignment.addActionListener(this);
removeAssignment.addActionListener(this);
editAssignment.addActionListener(this);
JLabel eventAssignLabel = new JLabel("List of Event Assignments:");
eventAssign = new JList();
eventAssign.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(260, 220));
scroll.setPreferredSize(new Dimension(276, 152));
scroll.setViewportView(eventAssign);
assign = new String[0];
int Eindex = -1;
if (option.equals("OK")) {
String selected = ((String) events.getSelectedValue());
eventTrigger.setText(selected);
ListOf e = document.getModel().getListOfEvents();
for (int i = 0; i < document.getModel().getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) e.get(i);
if (myFormulaToString(event.getTrigger().getMath()).equals(selected)) {
Eindex = i;
eventID.setText(event.getId());
eventName.setText(event.getName());
if (event.isSetDelay()) {
eventDelay.setText(myFormulaToString(event.getDelay().getMath()));
}
assign = new String[(int) event.getNumEventAssignments()];
origAssign = new String[(int) event.getNumEventAssignments()];
for (int j = 0; j < event.getNumEventAssignments(); j++) {
assign[j] = event.getEventAssignment(j).getVariable() + " = "
+ myFormulaToString(event.getEventAssignment(j).getMath());
origAssign[j] = event.getEventAssignment(j).getVariable() + " = "
+ myFormulaToString(event.getEventAssignment(j).getMath());
}
}
}
}
sort(assign);
eventAssign.setListData(assign);
eventAssign.setSelectedIndex(0);
eventAssign.addMouseListener(this);
eventAssignPanel.add(eventAssignLabel, "North");
eventAssignPanel.add(scroll, "Center");
eventAssignPanel.add(addEventAssign, "South");
evPanel.add(IDLabel);
evPanel.add(eventID);
evPanel.add(NameLabel);
evPanel.add(eventName);
evPanel.add(triggerLabel);
evPanel.add(eventTrigger);
evPanel.add(delayLabel);
evPanel.add(eventDelay);
eventPanel.add(evPanel, "North");
eventPanel.add(eventAssignPanel, "South");
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), eventPanel, "Event Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
if (eventTrigger.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "Event must have a trigger formula.",
"Enter Trigger Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (myParseFormula(eventTrigger.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Trigger formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (!myParseFormula(eventTrigger.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(), "Trigger formula must be of type Boolean.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (!eventDelay.getText().trim().equals("")
&& myParseFormula(eventDelay.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Delay formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (assign.length == 0) {
JOptionPane.showMessageDialog(biosim.frame(),
"Event must have at least one event assignment.", "Event Assignment Needed",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariables(eventTrigger.getText().trim(), false,
"", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Event trigger contains unknown variables.\n\n" + "Unknown variables:\n"
+ invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Unknown Variables",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
invalidVars = getInvalidVariables(eventDelay.getText().trim(), false, "", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Event delay contains unknown variables.\n\n" + "Unknown variables:\n"
+ invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Unknown Variables",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
error = checkNumFunctionArguments(myParseFormula(eventTrigger.getText().trim()));
}
if ((!error) && (!eventDelay.getText().trim().equals(""))) {
error = checkNumFunctionArguments(myParseFormula(eventDelay.getText().trim()));
if (!error) {
if (myParseFormula(eventDelay.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Event delay must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
}
if (!error) {
if (option.equals("OK")) {
int index = events.getSelectedIndex();
events.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
ev = Buttons.getList(ev, events);
events.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
org.sbml.libsbml.Event e = (org.sbml.libsbml.Event) (document.getModel()
.getListOfEvents()).get(Eindex);
while (e.getNumEventAssignments() > 0) {
e.getListOfEventAssignments().remove(0);
}
for (int i = 0; i < assign.length; i++) {
EventAssignment ea = e.createEventAssignment();
ea.setVariable(assign[i].split(" ")[0]);
ea.setMath(myParseFormula(assign[i].split("=")[1].trim()));
error = checkEventAssignmentUnits(ea);
if (error)
break;
}
if (!error) {
if (eventDelay.getText().trim().equals("")) {
e.unsetDelay();
}
else {
String oldDelayStr = "";
if (e.isSetDelay()) {
oldDelayStr = myFormulaToString(e.getDelay().getMath());
}
Delay delay = new Delay(myParseFormula(eventDelay.getText().trim()));
e.setDelay(delay);
error = checkEventDelayUnits(delay);
if (error) {
if (oldDelayStr.equals("")) {
e.unsetDelay();
}
else {
Delay oldDelay = new Delay(myParseFormula(oldDelayStr));
e.setDelay(oldDelay);
}
}
}
}
if (!error) {
Trigger trigger = new Trigger(myParseFormula(eventTrigger.getText().trim()));
e.setTrigger(trigger);
if (eventID.getText().trim().equals("")) {
e.unsetId();
}
else {
e.setId(eventID.getText().trim());
}
if (eventName.getText().trim().equals("")) {
e.unsetName();
}
else {
e.setName(eventName.getText().trim());
}
ev[index] = myFormulaToString(e.getTrigger().getMath());
sort(ev);
events.setListData(ev);
events.setSelectedIndex(index);
}
else {
while (e.getNumEventAssignments() > 0) {
e.getListOfEventAssignments().remove(0);
}
for (int i = 0; i < origAssign.length; i++) {
EventAssignment ea = e.createEventAssignment();
ea.setVariable(origAssign[i].split(" ")[0]);
ea.setMath(myParseFormula(origAssign[i].split("=")[1].trim()));
}
}
}
else {
JList add = new JList();
int index = events.getSelectedIndex();
org.sbml.libsbml.Event e = document.getModel().createEvent();
Trigger trigger = new Trigger(myParseFormula(eventTrigger.getText().trim()));
e.setTrigger(trigger);
if (!eventDelay.getText().trim().equals("")) {
Delay delay = new Delay(myParseFormula(eventDelay.getText().trim()));
e.setDelay(delay);
error = checkEventDelayUnits(delay);
}
if (!error) {
for (int i = 0; i < assign.length; i++) {
EventAssignment ea = e.createEventAssignment();
ea.setVariable(assign[i].split(" ")[0]);
ea.setMath(myParseFormula(assign[i].split("=")[1].trim()));
error = checkEventAssignmentUnits(ea);
if (error)
break;
}
}
if (!eventID.getText().trim().equals("")) {
e.setId(eventID.getText().trim());
}
if (!eventName.getText().trim().equals("")) {
e.setName(eventName.getText().trim());
}
Object[] adding = { myFormulaToString(e.getTrigger().getMath()) };
add.setListData(adding);
add.setSelectedIndex(0);
events.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(ev, events, add, false, null, null, null, null, null, null, biosim
.frame());
ev = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
ev[i] = (String) adding[i];
}
sort(ev);
events.setListData(ev);
events.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumEvents() == 1) {
events.setSelectedIndex(0);
}
else {
events.setSelectedIndex(index);
}
if (error) {
removeTheEvent(myFormulaToString(e.getTrigger().getMath()));
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), eventPanel, "Event Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit event assignments or create new ones.
*/
private void eventAssignEditor(String option) {
if (option.equals("OK") && eventAssign.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No event assignment selected.",
"Must Select an Event Assignment", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel eventAssignPanel = new JPanel();
JPanel EAPanel = new JPanel(new GridLayout(2, 2));
JLabel idLabel = new JLabel("Variable:");
JLabel eqnLabel = new JLabel("Assignment:");
eaID = new JComboBox();
String selected;
if (option.equals("OK")) {
selected = ((String) eventAssign.getSelectedValue()).split(" ")[0];
}
else {
selected = "";
}
Model model = document.getModel();
ListOf ids = model.getListOfCompartments();
for (int i = 0; i < model.getNumCompartments(); i++) {
String id = ((Compartment) ids.get(i)).getId();
if (!((Compartment) ids.get(i)).getConstant()) {
if (keepVar(selected, id, false, false, false, true)) {
eaID.addItem(id);
}
}
}
ids = model.getListOfParameters();
for (int i = 0; i < model.getNumParameters(); i++) {
String id = ((Parameter) ids.get(i)).getId();
if (!((Parameter) ids.get(i)).getConstant()) {
if (keepVar(selected, id, false, false, false, true)) {
eaID.addItem(id);
}
}
}
ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
String id = ((Species) ids.get(i)).getId();
if (!((Species) ids.get(i)).getConstant()) {
if (keepVar(selected, id, false, false, false, true)) {
eaID.addItem(id);
}
}
}
eqn = new JTextField(12);
if (option.equals("OK")) {
String selectAssign = ((String) eventAssign.getSelectedValue());
eaID.setSelectedItem(selectAssign.split(" ")[0]);
eqn.setText(selectAssign.split("=")[1].trim());
}
EAPanel.add(idLabel);
EAPanel.add(eaID);
EAPanel.add(eqnLabel);
EAPanel.add(eqn);
eventAssignPanel.add(EAPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), eventAssignPanel,
"Event Asssignment Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
if (eqn.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "Event assignment is missing.",
"Enter Assignment", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (myParseFormula(eqn.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Event assignment is not valid.",
"Enter Valid Assignment", JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariables(eqn.getText().trim(), false, "", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Event assignment contains unknown variables.\n\n" + "Unknown variables:\n"
+ invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Unknown Variables",
JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = checkNumFunctionArguments(myParseFormula(eqn.getText().trim()));
}
if (!error) {
if (myParseFormula(eqn.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Event assignment must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
if (!error) {
if (option.equals("OK")) {
int index = eventAssign.getSelectedIndex();
eventAssign.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
assign = Buttons.getList(assign, eventAssign);
eventAssign.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
assign[index] = eaID.getSelectedItem() + " = " + eqn.getText().trim();
sort(assign);
eventAssign.setListData(assign);
eventAssign.setSelectedIndex(index);
}
else {
JList add = new JList();
int index = eventAssign.getSelectedIndex();
Object[] adding = { eaID.getSelectedItem() + " = " + eqn.getText().trim() };
add.setListData(adding);
add.setSelectedIndex(0);
eventAssign.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(assign, eventAssign, add, false, null, null, null, null, null, null,
biosim.frame());
assign = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
assign[i] = (String) adding[i];
}
sort(assign);
eventAssign.setListData(assign);
eventAssign.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (adding.length == 1) {
eventAssign.setSelectedIndex(0);
}
else {
eventAssign.setSelectedIndex(index);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), eventAssignPanel,
"Event Assignment Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit constraints or create new ones.
*/
private void constraintEditor(String option) {
if (option.equals("OK") && constraints.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No constraint selected.",
"Must Select a Constraint", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel constraintPanel = new JPanel();
JPanel consPanel = new JPanel(new GridLayout(3, 2));
JLabel IDLabel = new JLabel("ID:");
JLabel mathLabel = new JLabel("Constraint:");
JLabel messageLabel = new JLabel("Messsage:");
consID = new JTextField(20);
consMath = new JTextField(20);
consMessage = new JTextField(20);
String selectedID = "";
int Cindex = -1;
if (option.equals("OK")) {
String selected = ((String) constraints.getSelectedValue());
consMath.setText(selected);
ListOf c = document.getModel().getListOfConstraints();
for (int i = 0; i < document.getModel().getNumConstraints(); i++) {
if (myFormulaToString(((Constraint) c.get(i)).getMath()).equals(selected)) {
Cindex = i;
if (((Constraint) c.get(i)).isSetMetaId()) {
selectedID = ((Constraint) c.get(i)).getMetaId();
consID.setText(selectedID);
}
if (((Constraint) c.get(i)).isSetMessage()) {
String message = XMLNode.convertXMLNodeToString(((Constraint) c.get(i)).getMessage());
message = message.substring(message.indexOf("xhtml\">") + 7, message.indexOf("</p>"));
consMessage.setText(message);
}
}
}
}
consPanel.add(IDLabel);
consPanel.add(consID);
consPanel.add(mathLabel);
consPanel.add(consMath);
consPanel.add(messageLabel);
consPanel.add(consMessage);
constraintPanel.add(consPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), constraintPanel, "Constraint Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = checkID(consID.getText().trim(), selectedID, false);
if (!error) {
if (consMath.getText().trim().equals("")
|| myParseFormula(consMath.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (!myParseFormula(consMath.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Constraint formula must be of type Boolean.", "Enter Valid Formula",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariables(consMath.getText().trim(), false, "",
false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Constraint contains unknown variables.\n\n" + "Unknown variables:\n"
+ invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Unknown Variables",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
if (option.equals("OK")) {
int index = constraints.getSelectedIndex();
constraints.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
cons = Buttons.getList(cons, constraints);
constraints.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Constraint c = (Constraint) (document.getModel().getListOfConstraints()).get(Cindex);
c.setMath(myParseFormula(consMath.getText().trim()));
c.setMetaId(consID.getText().trim());
if (!consMessage.getText().trim().equals("")) {
XMLNode xmlNode = XMLNode
.convertStringToXMLNode("<message><p xmlns=\"http://www.w3.org/1999/xhtml\">"
+ consMessage.getText().trim() + "</p></message>");
c.setMessage(xmlNode);
}
else {
c.unsetMessage();
}
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(selectedID)) {
usedIDs.set(i, consID.getText().trim());
}
}
cons[index] = myFormulaToString(c.getMath());
sort(cons);
constraints.setListData(cons);
constraints.setSelectedIndex(index);
}
else {
JList add = new JList();
int index = rules.getSelectedIndex();
Constraint c = document.getModel().createConstraint();
c.setMath(myParseFormula(consMath.getText().trim()));
c.setMetaId(consID.getText().trim());
if (!consMessage.getText().trim().equals("")) {
XMLNode xmlNode = XMLNode
.convertStringToXMLNode("<message><p xmlns=\"http://www.w3.org/1999/xhtml\">"
+ consMessage.getText().trim() + "</p></message>");
c.setMessage(xmlNode);
}
usedIDs.add(consID.getText().trim());
Object[] adding = { myFormulaToString(c.getMath()) };
add.setListData(adding);
add.setSelectedIndex(0);
constraints.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(cons, constraints, add, false, null, null, null, null, null, null,
biosim.frame());
cons = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
cons[i] = (String) adding[i];
}
sort(cons);
constraints.setListData(cons);
constraints.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumConstraints() == 1) {
constraints.setSelectedIndex(0);
}
else {
constraints.setSelectedIndex(index);
}
}
change = true;
}
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), constraintPanel, "Constraint Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit compartments or create new ones.
*/
private void compartEditor(String option) {
if (option.equals("OK") && compartments.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No compartment selected.",
"Must Select a Compartment", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel compartPanel = new JPanel();
JPanel compPanel;
if (paramsOnly) {
compPanel = new JPanel(new GridLayout(13, 2));
}
else {
compPanel = new JPanel(new GridLayout(8, 2));
}
JLabel idLabel = new JLabel("ID:");
JLabel nameLabel = new JLabel("Name:");
JLabel compTypeLabel = new JLabel("Type:");
JLabel dimLabel = new JLabel("Dimensions:");
JLabel outsideLabel = new JLabel("Outside:");
JLabel constLabel = new JLabel("Constant:");
JLabel sizeLabel = new JLabel("Size:");
JLabel compUnitsLabel = new JLabel("Units:");
JLabel startLabel = new JLabel("Start:");
JLabel stopLabel = new JLabel("Stop:");
JLabel stepLabel = new JLabel("Step:");
JLabel levelLabel = new JLabel("Level:");
compID = new JTextField(12);
compName = new JTextField(12);
ListOf listOfCompTypes = document.getModel().getListOfCompartmentTypes();
String[] compTypeList = new String[(int) document.getModel().getNumCompartmentTypes() + 1];
compTypeList[0] = "( none )";
for (int i = 0; i < document.getModel().getNumCompartmentTypes(); i++) {
compTypeList[i + 1] = ((CompartmentType) listOfCompTypes.get(i)).getId();
}
sort(compTypeList);
Object[] choices = compTypeList;
compTypeBox = new JComboBox(choices);
Object[] dims = { "0", "1", "2", "3" };
dimBox = new JComboBox(dims);
dimBox.setSelectedItem("3");
compSize = new JTextField(12);
compSize.setText("1.0");
compUnits = new JComboBox();
compOutside = new JComboBox();
String[] optionsTF = { "true", "false" };
compConstant = new JComboBox(optionsTF);
compConstant.setSelectedItem("true");
String selected = "";
editComp = false;
String selectedID = "";
if (option.equals("OK")) {
selected = ((String) compartments.getSelectedValue()).split(" ")[0];
editComp = true;
}
setCompartOptions(selected, "3");
dimBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (editComp) {
setCompartOptions(((String) compartments.getSelectedValue()).split(" ")[0],
(String) dimBox.getSelectedItem());
}
else {
setCompartOptions("", (String) dimBox.getSelectedItem());
}
}
});
String[] list = { "Original", "Custom", "Sweep" };
String[] list1 = { "1", "2" };
final JComboBox type = new JComboBox(list);
final JTextField start = new JTextField();
final JTextField stop = new JTextField();
final JTextField step = new JTextField();
final JComboBox level = new JComboBox(list1);
if (paramsOnly) {
compID.setEnabled(false);
compName.setEnabled(false);
compTypeBox.setEnabled(false);
dimBox.setEnabled(false);
compUnits.setEnabled(false);
compOutside.setEnabled(false);
compConstant.setEnabled(false);
compSize.setEnabled(false);
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
}
if (option.equals("OK")) {
try {
Compartment compartment = document.getModel().getCompartment(
(((String) compartments.getSelectedValue()).split(" ")[0]));
compID.setText(compartment.getId());
selectedID = compartment.getId();
compName.setText(compartment.getName());
if (compartment.isSetCompartmentType()) {
compTypeBox.setSelectedItem(compartment.getCompartmentType());
}
dimBox.setSelectedItem(String.valueOf(compartment.getSpatialDimensions()));
setCompartOptions(((String) compartments.getSelectedValue()).split(" ")[0], String
.valueOf(compartment.getSpatialDimensions()));
if (compartment.isSetSize()) {
compSize.setText("" + compartment.getSize());
}
if (compartment.isSetUnits()) {
compUnits.setSelectedItem(compartment.getUnits());
}
else {
compUnits.setSelectedItem("( none )");
}
if (compartment.isSetOutside()) {
compOutside.setSelectedItem(compartment.getOutside());
}
else {
compOutside.setSelectedItem("( none )");
}
if (compartment.getConstant()) {
compConstant.setSelectedItem("true");
}
else {
compConstant.setSelectedItem("false");
}
if (paramsOnly
&& (((String) compartments.getSelectedValue()).contains("Custom") || ((String) compartments
.getSelectedValue()).contains("Sweep"))) {
if (((String) compartments.getSelectedValue()).contains("Custom")) {
type.setSelectedItem("Custom");
}
else {
type.setSelectedItem("Sweep");
}
if (((String) type.getSelectedItem()).equals("Sweep")) {
String[] splits = ((String) compartments.getSelectedValue()).split(" ");
String sweepVal = splits[splits.length - 1];
start.setText((sweepVal).split(",")[0].substring(1).trim());
stop.setText((sweepVal).split(",")[1].trim());
step.setText((sweepVal).split(",")[2].trim());
level.setSelectedItem((sweepVal).split(",")[3].replace(")", "").trim());
start.setEnabled(true);
stop.setEnabled(true);
step.setEnabled(true);
level.setEnabled(true);
compSize.setEnabled(false);
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
compSize.setEnabled(true);
}
}
}
catch (Exception e) {
}
}
compPanel.add(idLabel);
compPanel.add(compID);
compPanel.add(nameLabel);
compPanel.add(compName);
compPanel.add(compTypeLabel);
compPanel.add(compTypeBox);
compPanel.add(dimLabel);
compPanel.add(dimBox);
compPanel.add(outsideLabel);
compPanel.add(compOutside);
compPanel.add(constLabel);
compPanel.add(compConstant);
if (paramsOnly) {
JLabel typeLabel = new JLabel("Value Type:");
type.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!((String) type.getSelectedItem()).equals("Original")) {
if (((String) type.getSelectedItem()).equals("Sweep")) {
start.setEnabled(true);
stop.setEnabled(true);
step.setEnabled(true);
level.setEnabled(true);
compSize.setEnabled(false);
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
compSize.setEnabled(true);
}
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
compSize.setEnabled(false);
SBMLReader reader = new SBMLReader();
SBMLDocument d = reader.readSBML(file);
if (d.getModel().getCompartment(
((String) compartments.getSelectedValue()).split(" ")[0]).isSetSize()) {
compSize.setText(d.getModel().getCompartment(
((String) compartments.getSelectedValue()).split(" ")[0]).getSize()
+ "");
}
}
}
});
compPanel.add(typeLabel);
compPanel.add(type);
}
compPanel.add(sizeLabel);
compPanel.add(compSize);
compPanel.add(compUnitsLabel);
compPanel.add(compUnits);
if (paramsOnly) {
compPanel.add(startLabel);
compPanel.add(start);
compPanel.add(stopLabel);
compPanel.add(stop);
compPanel.add(stepLabel);
compPanel.add(step);
compPanel.add(levelLabel);
compPanel.add(level);
}
compartPanel.add(compPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), compartPanel, "Compartment Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = checkID(compID.getText().trim(), selectedID, false);
if (!error && option.equals("OK") && compConstant.getSelectedItem().equals("true")) {
String val = ((String) compartments.getSelectedValue()).split(" ")[0];
error = checkConstant("Compartment", val);
}
if (!error && option.equals("OK") && dimBox.getSelectedItem().equals("0")) {
String val = ((String) compartments.getSelectedValue()).split(" ")[0];
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
Species species = document.getModel().getSpecies(i);
if ((species.getCompartment().equals(val)) && (species.isSetInitialConcentration())) {
JOptionPane
.showMessageDialog(
biosim.frame(),
"Compartment with 0-dimensions cannot contain species with an initial concentration.",
"Cannot be 0 Dimensions", JOptionPane.ERROR_MESSAGE);
error = true;
break;
}
}
if (!error) {
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = document.getModel().getCompartment(i);
if (compartment.getOutside().equals(val)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Compartment with 0-dimensions cannot be outside another compartment.",
"Cannot be 0 Dimensions", JOptionPane.ERROR_MESSAGE);
error = true;
break;
}
}
}
}
Double addCompSize = 1.0;
if ((!error) && (Integer.parseInt((String) dimBox.getSelectedItem()) != 0)) {
try {
addCompSize = Double.parseDouble(compSize.getText().trim());
}
catch (Exception e1) {
error = true;
JOptionPane.showMessageDialog(biosim.frame(),
"The compartment size must be a real number.", "Enter a Valid Size",
JOptionPane.ERROR_MESSAGE);
}
}
if (!error) {
if (!compOutside.getSelectedItem().equals("( none )")) {
if (checkOutsideCycle(compID.getText().trim(), (String) compOutside.getSelectedItem(), 0)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Compartment contains itself through outside references.",
"Cycle in Outside References", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
if (!error) {
if (((String) dimBox.getSelectedItem()).equals("0") && (variableInUse(selected, true))) {
error = true;
}
}
if (!error) {
String addComp = "";
String selCompType = (String) compTypeBox.getSelectedItem();
String unit = (String) compUnits.getSelectedItem();
if (paramsOnly && !((String) type.getSelectedItem()).equals("Original")) {
int index = compartments.getSelectedIndex();
String[] splits = comps[index].split(" ");
for (int i = 0; i < splits.length - 2; i++) {
addComp += splits[i] + " ";
}
if (!splits[splits.length - 2].equals("Custom")
&& !splits[splits.length - 2].equals("Sweep")) {
addComp += splits[splits.length - 2] + " " + splits[splits.length - 1] + " ";
}
if (((String) type.getSelectedItem()).equals("Sweep")) {
try {
double startVal = Double.parseDouble(start.getText().trim());
double stopVal = Double.parseDouble(stop.getText().trim());
double stepVal = Double.parseDouble(step.getText().trim());
addComp += "Sweep (" + startVal + "," + stopVal + "," + stepVal + ","
+ level.getSelectedItem() + ")";
}
catch (Exception e1) {
error = true;
JOptionPane.showMessageDialog(biosim.frame(),
"The start, stop, and step fields must be real numbers.", "Enter a Valid Sweep",
JOptionPane.ERROR_MESSAGE);
}
}
else {
addComp += "Custom " + addCompSize;
}
}
else {
addComp = compID.getText().trim();
if (!selCompType.equals("( none )")) {
addComp += " " + selCompType;
}
if (!unit.equals("( none )")) {
addComp += " " + addCompSize + " " + unit;
}
else {
addComp += " " + addCompSize;
}
}
if (!error) {
if (option.equals("OK")) {
int index = compartments.getSelectedIndex();
String val = ((String) compartments.getSelectedValue()).split(" ")[0];
compartments.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
comps = Buttons.getList(comps, compartments);
compartments.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Compartment c = document.getModel().getCompartment(val);
c.setId(compID.getText().trim());
c.setName(compName.getText().trim());
if (!selCompType.equals("( none )")) {
c.setCompartmentType(selCompType);
}
else {
c.unsetCompartmentType();
}
c.setSpatialDimensions(Integer.parseInt((String) dimBox.getSelectedItem()));
if (compSize.getText().trim().equals("")) {
c.unsetSize();
}
else {
c.setSize(Double.parseDouble(compSize.getText().trim()));
}
if (compUnits.getSelectedItem().equals("( none )")) {
c.unsetUnits();
}
else {
c.setUnits((String) compUnits.getSelectedItem());
}
if (compOutside.getSelectedItem().equals("( none )")) {
c.unsetOutside();
}
else {
c.setOutside((String) compOutside.getSelectedItem());
}
if (compConstant.getSelectedItem().equals("true")) {
c.setConstant(true);
}
else {
c.setConstant(false);
}
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(val)) {
usedIDs.set(i, compID.getText().trim());
}
}
comps[index] = addComp;
sort(comps);
compartments.setListData(comps);
compartments.setSelectedIndex(index);
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
Species species = document.getModel().getSpecies(i);
if (species.getCompartment().equals(val)) {
species.setCompartment(compID.getText().trim());
}
}
int index1 = species.getSelectedIndex();
species.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
specs = Buttons.getList(specs, species);
species.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
for (int i = 0; i < specs.length; i++) {
if (specs[i].split(" ")[1].equals(val)) {
specs[i] = specs[i].split(" ")[0] + " " + compID.getText().trim() + " "
+ specs[i].split(" ")[2];
}
else if (specs[i].split(" ")[2].equals(val)) {
specs[i] = specs[i].split(" ")[0] + " " + specs[i].split(" ")[1] + " "
+ compID.getText().trim() + " " + specs[i].split(" ")[3];
}
}
sort(specs);
species.setListData(specs);
species.setSelectedIndex(index1);
if (paramsOnly) {
int remove = -1;
for (int i = 0; i < parameterChanges.size(); i++) {
if (parameterChanges.get(i).split(" ")[0].equals(compID.getText().trim())) {
remove = i;
}
}
if (remove != -1) {
parameterChanges.remove(remove);
}
if (!((String) type.getSelectedItem()).equals("Original")) {
parameterChanges.add(comps[index]);
}
}
else {
updateVarId(false, val, compID.getText().trim());
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = document.getModel().getCompartment(i);
if (compartment.getOutside().equals(val)) {
compartment.setOutside(compID.getText().trim());
}
}
}
}
else {
int index = compartments.getSelectedIndex();
Compartment c = document.getModel().createCompartment();
c.setId(compID.getText().trim());
c.setName(compName.getText().trim());
if (!selCompType.equals("( none )")) {
c.setCompartmentType(selCompType);
}
c.setSpatialDimensions(Integer.parseInt((String) dimBox.getSelectedItem()));
if (!compSize.getText().trim().equals("")) {
c.setSize(Double.parseDouble(compSize.getText().trim()));
}
if (!compUnits.getSelectedItem().equals("( none )")) {
c.setUnits((String) compUnits.getSelectedItem());
}
if (!compOutside.getSelectedItem().equals("( none )")) {
c.setOutside((String) compOutside.getSelectedItem());
}
if (compConstant.getSelectedItem().equals("true")) {
c.setConstant(true);
}
else {
c.setConstant(false);
}
usedIDs.add(compID.getText().trim());
JList add = new JList();
String addStr;
if (!selCompType.equals("( none )")) {
addStr = compID.getText().trim() + " " + selCompType + " "
+ compSize.getText().trim();
}
else {
addStr = compID.getText().trim() + " " + compSize.getText().trim();
}
if (!compUnits.getSelectedItem().equals("( none )")) {
addStr += " " + compUnits.getSelectedItem();
}
Object[] adding = { addStr };
add.setListData(adding);
add.setSelectedIndex(0);
compartments.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(comps, compartments, add, false, null, null, null, null, null,
null, biosim.frame());
comps = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
comps[i] = (String) adding[i];
}
sort(comps);
compartments.setListData(comps);
compartments.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumCompartments() == 1) {
compartments.setSelectedIndex(0);
}
else {
compartments.setSelectedIndex(index);
}
}
change = true;
}
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), compartPanel, "Compartment Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Variable that is updated by a rule or event cannot be constant
*/
private boolean checkOutsideCycle(String compID, String outside, int depth) {
depth++;
if (depth > document.getModel().getNumCompartments())
return true;
Compartment compartment = document.getModel().getCompartment(outside);
if (compartment.isSetOutside()) {
if (compartment.getOutside().equals(compID)) {
return true;
}
return checkOutsideCycle(compID, compartment.getOutside(), depth);
}
return false;
}
/**
* Variable that is updated by a rule or event cannot be constant
*/
private boolean checkConstant(String varType, String val) {
for (int i = 0; i < document.getModel().getNumRules(); i++) {
Rule rule = document.getModel().getRule(i);
if (rule.getVariable().equals(val)) {
JOptionPane.showMessageDialog(biosim.frame(), varType
+ " cannot be constant if updated by a rule.", varType + " Cannot Be Constant",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
for (int i = 0; i < document.getModel().getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) document.getModel().getListOfEvents()
.get(i);
for (int j = 0; j < event.getNumEventAssignments(); j++) {
EventAssignment ea = (EventAssignment) event.getListOfEventAssignments().get(j);
if (ea.getVariable().equals(val)) {
JOptionPane.showMessageDialog(biosim.frame(), varType
+ " cannot be constant if updated by an event.", varType + " Cannot Be Constant",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
}
return false;
}
/**
* Species that is a reactant or product cannot be constant unless it is a
* boundary condition
*/
private boolean checkBoundary(String val, boolean checkRule) {
Model model = document.getModel();
boolean inRule = false;
if (checkRule) {
if (model.getNumRules() > 0) {
for (int i = 0; i < model.getNumRules(); i++) {
Rule rule = (Rule) model.getListOfRules().get(i);
if (rule.isSetVariable() && val.equals(rule.getVariable())) {
inRule = true;
break;
}
}
}
if (!inRule)
return false;
}
for (int i = 0; i < model.getNumReactions(); i++) {
Reaction reaction = (Reaction) model.getListOfReactions().get(i);
for (int j = 0; j < reaction.getNumProducts(); j++) {
if (reaction.getProduct(j).isSetSpecies()) {
SpeciesReference specRef = reaction.getProduct(j);
if (val.equals(specRef.getSpecies())) {
if (checkRule) {
JOptionPane.showMessageDialog(biosim.frame(),
"Boundary condition cannot be false if a species is used\n"
+ "in a rule and as a reactant or product in a reaction.",
"Boundary Condition Cannot be False", JOptionPane.ERROR_MESSAGE);
}
else {
JOptionPane.showMessageDialog(biosim.frame(),
"Species cannot be reactant if constant and not a boundary condition.",
"Invalid Species Attributes", JOptionPane.ERROR_MESSAGE);
}
return true;
}
}
}
for (int j = 0; j < reaction.getNumReactants(); j++) {
if (reaction.getReactant(j).isSetSpecies()) {
SpeciesReference specRef = reaction.getReactant(j);
if (val.equals(specRef.getSpecies())) {
if (checkRule) {
JOptionPane.showMessageDialog(biosim.frame(),
"Boundary condition cannot be false if a species is used\n"
+ "in a rule and as a reactant or product in a reaction.",
"Boundary Condition Cannot be False", JOptionPane.ERROR_MESSAGE);
}
else {
JOptionPane.showMessageDialog(biosim.frame(),
"Species cannot be product if constant and not a boundary condition.",
"Invalid Species Attributes", JOptionPane.ERROR_MESSAGE);
}
return true;
}
}
}
}
return false;
}
/**
* Set compartment options based on number of dimensions
*/
private void setCompartOptions(String selected, String dim) {
if (dim.equals("3")) {
compUnits.removeAllItems();
compUnits.addItem("( none )");
ListOf listOfUnits = document.getModel().getListOfUnitDefinitions();
for (int i = 0; i < document.getModel().getNumUnitDefinitions(); i++) {
UnitDefinition unit = (UnitDefinition) listOfUnits.get(i);
if ((unit.getNumUnits() == 1)
&& (unit.getUnit(0).isLitre() && unit.getUnit(0).getExponent() == 1)
|| (unit.getUnit(0).isMetre() && unit.getUnit(0).getExponent() == 3)) {
if (!unit.getId().equals("volume")) {
compUnits.addItem(unit.getId());
}
}
}
String[] unitIds = { "volume", "litre", "dimensionless" };
for (int i = 0; i < unitIds.length; i++) {
compUnits.addItem(unitIds[i]);
}
compOutside.removeAllItems();
compOutside.addItem("( none )");
ListOf listOfComps = document.getModel().getListOfCompartments();
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = (Compartment) listOfComps.get(i);
if (!compartment.getId().equals(selected) && compartment.getSpatialDimensions() != 0) {
compOutside.addItem(compartment.getId());
}
}
if (!paramsOnly) {
compConstant.setEnabled(true);
compSize.setEnabled(true);
}
}
else if (dim.equals("2")) {
compUnits.removeAllItems();
compUnits.addItem("( none )");
ListOf listOfUnits = document.getModel().getListOfUnitDefinitions();
for (int i = 0; i < document.getModel().getNumUnitDefinitions(); i++) {
UnitDefinition unit = (UnitDefinition) listOfUnits.get(i);
if ((unit.getNumUnits() == 1)
&& (unit.getUnit(0).isMetre() && unit.getUnit(0).getExponent() == 2)) {
if (!unit.getId().equals("area")) {
compUnits.addItem(unit.getId());
}
}
}
String[] unitIds = { "area", "dimensionless" };
for (int i = 0; i < unitIds.length; i++) {
compUnits.addItem(unitIds[i]);
}
compOutside.removeAllItems();
compOutside.addItem("( none )");
ListOf listOfComps = document.getModel().getListOfCompartments();
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = (Compartment) listOfComps.get(i);
if (!compartment.getId().equals(selected) && compartment.getSpatialDimensions() != 0) {
compOutside.addItem(compartment.getId());
}
}
if (!paramsOnly) {
compConstant.setEnabled(true);
compSize.setEnabled(true);
}
}
else if (dim.equals("1")) {
compUnits.removeAllItems();
compUnits.addItem("( none )");
ListOf listOfUnits = document.getModel().getListOfUnitDefinitions();
for (int i = 0; i < document.getModel().getNumUnitDefinitions(); i++) {
UnitDefinition unit = (UnitDefinition) listOfUnits.get(i);
if ((unit.getNumUnits() == 1)
&& (unit.getUnit(0).isMetre() && unit.getUnit(0).getExponent() == 1)) {
if (!unit.getId().equals("length")) {
compUnits.addItem(unit.getId());
}
}
}
String[] unitIds = { "length", "metre", "dimensionless" };
for (int i = 0; i < unitIds.length; i++) {
compUnits.addItem(unitIds[i]);
}
compOutside.removeAllItems();
compOutside.addItem("( none )");
ListOf listOfComps = document.getModel().getListOfCompartments();
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = (Compartment) listOfComps.get(i);
if (!compartment.getId().equals(selected) && compartment.getSpatialDimensions() != 0) {
compOutside.addItem(compartment.getId());
}
}
if (!paramsOnly) {
compConstant.setEnabled(true);
compSize.setEnabled(true);
}
}
else if (dim.equals("0")) {
compSize.setText("");
compUnits.removeAllItems();
compUnits.addItem("( none )");
compOutside.removeAllItems();
compOutside.addItem("( none )");
ListOf listOfComps = document.getModel().getListOfCompartments();
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = (Compartment) listOfComps.get(i);
if (!compartment.getId().equals(selected)) {
compOutside.addItem(compartment.getId());
}
}
compConstant.setEnabled(false);
compSize.setEnabled(false);
}
if (!selected.equals("")) {
Compartment compartment = document.getModel().getCompartment(selected);
if (compartment.isSetOutside()) {
compOutside.setSelectedItem(compartment.getOutside());
}
if (compartment.isSetUnits()) {
compUnits.setSelectedItem(compartment.getUnits());
}
}
}
/**
* Creates a frame used to edit species or create new ones.
*/
private void speciesEditor(String option) {
if (option.equals("OK") && species.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No species selected.",
"Must Select A Species", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel speciesPanel;
if (paramsOnly) {
speciesPanel = new JPanel(new GridLayout(13, 2));
}
else {
speciesPanel = new JPanel(new GridLayout(8, 2));
}
JLabel idLabel = new JLabel("ID:");
JLabel nameLabel = new JLabel("Name:");
JLabel specTypeLabel = new JLabel("Type:");
JLabel compLabel = new JLabel("Compartment:");
String[] initLabels = { "Initial Amount", "Initial Concentration" };
initLabel = new JComboBox(initLabels);
JLabel unitLabel = new JLabel("Units:");
JLabel boundLabel = new JLabel("Boundary Condition:");
JLabel constLabel = new JLabel("Constant:");
ID = new JTextField();
String selectedID = "";
Name = new JTextField();
init = new JTextField("0.0");
specUnits = new JComboBox();
specUnits.addItem("( none )");
ListOf listOfUnits = document.getModel().getListOfUnitDefinitions();
for (int i = 0; i < document.getModel().getNumUnitDefinitions(); i++) {
UnitDefinition unit = (UnitDefinition) listOfUnits.get(i);
if ((unit.getNumUnits() == 1)
&& (unit.getUnit(0).isMole() || unit.getUnit(0).isItem() || unit.getUnit(0).isGram() || unit
.getUnit(0).isKilogram()) && (unit.getUnit(0).getExponent() == 1)) {
if (!unit.getId().equals("substance")) {
specUnits.addItem(unit.getId());
}
}
}
String[] unitIds = { "substance", "dimensionless", "gram", "item", "kilogram", "mole" };
for (int i = 0; i < unitIds.length; i++) {
specUnits.addItem(unitIds[i]);
}
String[] optionsTF = { "true", "false" };
specBoundary = new JComboBox(optionsTF);
specBoundary.setSelectedItem("false");
specConstant = new JComboBox(optionsTF);
specConstant.setSelectedItem("false");
JLabel startLabel = new JLabel("Start:");
JLabel stopLabel = new JLabel("Stop:");
JLabel stepLabel = new JLabel("Step:");
JLabel levelLabel = new JLabel("Level:");
ListOf listOfSpecTypes = document.getModel().getListOfSpeciesTypes();
String[] specTypeList = new String[(int) document.getModel().getNumSpeciesTypes() + 1];
specTypeList[0] = "( none )";
for (int i = 0; i < document.getModel().getNumSpeciesTypes(); i++) {
specTypeList[i + 1] = ((SpeciesType) listOfSpecTypes.get(i)).getId();
}
sort(specTypeList);
Object[] choices = specTypeList;
specTypeBox = new JComboBox(choices);
ListOf listOfCompartments = document.getModel().getListOfCompartments();
String[] add = new String[(int) document.getModel().getNumCompartments()];
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
add[i] = ((Compartment) listOfCompartments.get(i)).getId();
}
try {
add[0].getBytes();
}
catch (Exception e) {
add = new String[1];
add[0] = "default";
}
comp = new JComboBox(add);
String[] list = { "Original", "Custom", "Sweep" };
String[] list1 = { "1", "2" };
final JComboBox type = new JComboBox(list);
final JTextField start = new JTextField();
final JTextField stop = new JTextField();
final JTextField step = new JTextField();
final JComboBox level = new JComboBox(list1);
if (paramsOnly) {
ID.setEditable(false);
Name.setEditable(false);
specTypeBox.setEnabled(false);
specBoundary.setEnabled(false);
specConstant.setEnabled(false);
comp.setEnabled(false);
init.setEnabled(false);
initLabel.setEnabled(false);
specUnits.setEnabled(false);
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
}
if (option.equals("OK")) {
try {
Species specie = document.getModel().getSpecies(
((String) species.getSelectedValue()).split(" ")[0]);
ID.setText(specie.getId());
selectedID = specie.getId();
Name.setText(specie.getName());
specTypeBox.setSelectedItem(specie.getSpeciesType());
if (specie.getBoundaryCondition()) {
specBoundary.setSelectedItem("true");
}
else {
specBoundary.setSelectedItem("false");
}
if (specie.getConstant()) {
specConstant.setSelectedItem("true");
}
else {
specConstant.setSelectedItem("false");
}
if (specie.isSetInitialAmount()) {
init.setText("" + specie.getInitialAmount());
initLabel.setSelectedItem("Initial Amount");
}
else {
init.setText("" + specie.getInitialConcentration());
initLabel.setSelectedItem("Initial Concentration");
}
specUnits.setSelectedItem(specie.getUnits());
comp.setSelectedItem(specie.getCompartment());
if (paramsOnly
&& (((String) species.getSelectedValue()).contains("Custom") || ((String) species
.getSelectedValue()).contains("Sweep"))) {
if (((String) species.getSelectedValue()).contains("Custom")) {
type.setSelectedItem("Custom");
}
else {
type.setSelectedItem("Sweep");
}
if (((String) type.getSelectedItem()).equals("Sweep")) {
String[] splits = ((String) compartments.getSelectedValue()).split(" ");
String sweepVal = splits[splits.length - 1];
start.setText((sweepVal).split(",")[0].substring(1).trim());
stop.setText((sweepVal).split(",")[1].trim());
step.setText((sweepVal).split(",")[2].trim());
level.setSelectedItem((sweepVal).split(",")[3].replace(")", "").trim());
start.setEnabled(true);
stop.setEnabled(true);
step.setEnabled(true);
level.setEnabled(true);
init.setEnabled(false);
initLabel.setEnabled(false);
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
init.setEnabled(true);
initLabel.setEnabled(false);
}
}
}
catch (Exception e) {
}
}
speciesPanel.add(idLabel);
speciesPanel.add(ID);
speciesPanel.add(nameLabel);
speciesPanel.add(Name);
speciesPanel.add(specTypeLabel);
speciesPanel.add(specTypeBox);
speciesPanel.add(compLabel);
speciesPanel.add(comp);
speciesPanel.add(boundLabel);
speciesPanel.add(specBoundary);
speciesPanel.add(constLabel);
speciesPanel.add(specConstant);
if (paramsOnly) {
JLabel typeLabel = new JLabel("Value Type:");
type.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!((String) type.getSelectedItem()).equals("Original")) {
if (((String) type.getSelectedItem()).equals("Sweep")) {
start.setEnabled(true);
stop.setEnabled(true);
step.setEnabled(true);
level.setEnabled(true);
init.setEnabled(false);
initLabel.setEnabled(false);
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
init.setEnabled(true);
initLabel.setEnabled(false);
}
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
init.setEnabled(false);
initLabel.setEnabled(false);
SBMLReader reader = new SBMLReader();
SBMLDocument d = reader.readSBML(file);
if (d.getModel().getSpecies(((String) species.getSelectedValue()).split(" ")[0])
.isSetInitialAmount()) {
init.setText(d.getModel().getSpecies(
((String) species.getSelectedValue()).split(" ")[0]).getInitialAmount()
+ "");
initLabel.setSelectedItem("Initial Amount");
}
else {
init.setText(d.getModel().getSpecies(
((String) species.getSelectedValue()).split(" ")[0]).getInitialConcentration()
+ "");
initLabel.setSelectedItem("Initial Concentration");
}
}
}
});
speciesPanel.add(typeLabel);
speciesPanel.add(type);
}
speciesPanel.add(initLabel);
speciesPanel.add(init);
speciesPanel.add(unitLabel);
speciesPanel.add(specUnits);
if (paramsOnly) {
speciesPanel.add(startLabel);
speciesPanel.add(start);
speciesPanel.add(stopLabel);
speciesPanel.add(stop);
speciesPanel.add(stepLabel);
speciesPanel.add(step);
speciesPanel.add(levelLabel);
speciesPanel.add(level);
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), speciesPanel, "Species Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = checkID(ID.getText().trim(), selectedID, false);
double initial = 0;
if (!error) {
try {
initial = Double.parseDouble(init.getText().trim());
}
catch (Exception e1) {
error = true;
JOptionPane.showMessageDialog(biosim.frame(),
"The initial value field must be a real number.", "Enter a Valid Initial Value",
JOptionPane.ERROR_MESSAGE);
}
String unit = (String) specUnits.getSelectedItem();
String addSpec = "";
String selSpecType = (String) specTypeBox.getSelectedItem();
if (paramsOnly && !((String) type.getSelectedItem()).equals("Original")) {
int index = species.getSelectedIndex();
String[] splits = specs[index].split(" ");
for (int i = 0; i < splits.length - 2; i++) {
addSpec += splits[i] + " ";
}
if (!splits[splits.length - 2].equals("Custom")
&& !splits[splits.length - 2].equals("Sweep")) {
addSpec += splits[splits.length - 2] + " " + splits[splits.length - 1] + " ";
}
if (((String) type.getSelectedItem()).equals("Sweep")) {
double startVal = Double.parseDouble(start.getText().trim());
double stopVal = Double.parseDouble(stop.getText().trim());
double stepVal = Double.parseDouble(step.getText().trim());
addSpec += "Sweep (" + startVal + "," + stopVal + "," + stepVal + ","
+ level.getSelectedItem() + ")";
}
else {
addSpec += "Custom " + initial;
}
}
else {
addSpec = ID.getText().trim();
if (!selSpecType.equals("( none )")) {
addSpec += " " + selSpecType;
}
addSpec += " " + comp.getSelectedItem() + " " + initial;
if (!unit.equals("( none )")) {
addSpec += " " + unit;
}
}
if (!error) {
ListOf listOfSpecies = document.getModel().getListOfSpecies();
String selected = "";
if (option.equals("OK")) {
selected = ((String) species.getSelectedValue()).split(" ")[0];
}
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
if (!listOfSpecies.get(i).getId().equals(selected)) {
if (((Species) listOfSpecies.get(i)).getCompartment().equals(
(String) comp.getSelectedItem())
&& ((Species) listOfSpecies.get(i)).getSpeciesType().equals(selSpecType)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Compartment already contains another species of this type.",
"Species Type Not Unique", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
}
if (!error) {
Compartment compartment = document.getModel().getCompartment(
(String) comp.getSelectedItem());
if (initLabel.getSelectedItem().equals("Initial Concentration")
&& compartment.getSpatialDimensions() == 0) {
JOptionPane.showMessageDialog(biosim.frame(),
"Species in a 0 dimensional compartment cannot have an initial concentration.",
"Concentration Not Possible", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error && option.equals("OK") && specConstant.getSelectedItem().equals("true")) {
String val = ((String) species.getSelectedValue()).split(" ")[0];
error = checkConstant("Species", val);
}
if (!error && option.equals("OK") && specBoundary.getSelectedItem().equals("false")) {
String val = ((String) species.getSelectedValue()).split(" ")[0];
error = checkBoundary(val, specConstant.getSelectedItem().equals("false"));
}
if (!error) {
if (option.equals("OK")) {
int index1 = species.getSelectedIndex();
String val = ((String) species.getSelectedValue()).split(" ")[0];
species.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
specs = Buttons.getList(specs, species);
species.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Species specie = document.getModel().getSpecies(val);
String speciesName = specie.getId();
specie.setCompartment((String) comp.getSelectedItem());
specie.setId(ID.getText().trim());
specie.setName(Name.getText().trim());
if (specBoundary.getSelectedItem().equals("true")) {
specie.setBoundaryCondition(true);
}
else {
specie.setBoundaryCondition(false);
}
if (specConstant.getSelectedItem().equals("true")) {
specie.setConstant(true);
}
else {
specie.setConstant(false);
}
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(val)) {
usedIDs.set(i, ID.getText().trim());
}
}
if (!selSpecType.equals("( none )")) {
specie.setSpeciesType(selSpecType);
}
else {
specie.unsetSpeciesType();
}
if (initLabel.getSelectedItem().equals("Initial Amount")) {
specie.setInitialAmount(initial);
specie.unsetInitialConcentration();
specie.setHasOnlySubstanceUnits(true);
}
else {
specie.unsetInitialAmount();
specie.setInitialConcentration(initial);
specie.setHasOnlySubstanceUnits(false);
}
if (unit.equals("( none )")) {
specie.unsetUnits();
}
else {
specie.setUnits(unit);
}
specs[index1] = addSpec;
sort(specs);
species.setListData(specs);
species.setSelectedIndex(index1);
if (paramsOnly) {
int remove = -1;
for (int i = 0; i < parameterChanges.size(); i++) {
if (parameterChanges.get(i).split(" ")[0].equals(ID.getText().trim())) {
remove = i;
}
}
if (remove != -1) {
parameterChanges.remove(remove);
}
if (!((String) type.getSelectedItem()).equals("Original")) {
parameterChanges.add(addSpec);
}
}
else {
updateVarId(true, speciesName, specie.getId());
}
}
else {
int index1 = species.getSelectedIndex();
Species specie = document.getModel().createSpecies();
specie.setCompartment((String) comp.getSelectedItem());
specie.setId(ID.getText().trim());
specie.setName(Name.getText().trim());
if (specBoundary.getSelectedItem().equals("true")) {
specie.setBoundaryCondition(true);
}
else {
specie.setBoundaryCondition(false);
}
if (specConstant.getSelectedItem().equals("true")) {
specie.setConstant(true);
}
else {
specie.setConstant(false);
}
usedIDs.add(ID.getText().trim());
if (!selSpecType.equals("( none )")) {
specie.setSpeciesType(selSpecType);
}
if (initLabel.getSelectedItem().equals("Initial Amount")) {
specie.setInitialAmount(initial);
specie.setHasOnlySubstanceUnits(true);
}
else {
specie.setInitialConcentration(initial);
specie.setHasOnlySubstanceUnits(false);
}
if (!unit.equals("( none )")) {
specie.setUnits(unit);
}
JList addIt = new JList();
Object[] adding = { addSpec };
addIt.setListData(adding);
addIt.setSelectedIndex(0);
species.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(specs, species, addIt, false, null, null, null, null, null, null,
biosim.frame());
specs = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
specs[i] = (String) adding[i];
}
sort(specs);
species.setListData(specs);
species.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumSpecies() == 1) {
species.setSelectedIndex(0);
}
else {
species.setSelectedIndex(index1);
}
}
change = true;
}
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), speciesPanel, "Species Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Update variable Id
*/
private void updateVarId(boolean isSpecies, String origId, String newId) {
if (origId.equals(newId))
return;
Model model = document.getModel();
for (int i = 0; i < model.getNumReactions(); i++) {
Reaction reaction = (Reaction) model.getListOfReactions().get(i);
for (int j = 0; j < reaction.getNumProducts(); j++) {
if (reaction.getProduct(j).isSetSpecies()) {
SpeciesReference specRef = reaction.getProduct(j);
if (isSpecies && origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
if (specRef.isSetStoichiometryMath()) {
StoichiometryMath sm = new StoichiometryMath(updateMathVar(specRef
.getStoichiometryMath().getMath(), origId, newId));
specRef.setStoichiometryMath(sm);
}
}
}
if (isSpecies) {
for (int j = 0; j < reaction.getNumModifiers(); j++) {
if (reaction.getModifier(j).isSetSpecies()) {
ModifierSpeciesReference specRef = reaction.getModifier(j);
if (origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
}
}
}
for (int j = 0; j < reaction.getNumReactants(); j++) {
if (reaction.getReactant(j).isSetSpecies()) {
SpeciesReference specRef = reaction.getReactant(j);
if (isSpecies && origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
if (specRef.isSetStoichiometryMath()) {
StoichiometryMath sm = new StoichiometryMath(updateMathVar(specRef
.getStoichiometryMath().getMath(), origId, newId));
specRef.setStoichiometryMath(sm);
}
}
}
reaction.getKineticLaw().setMath(
updateMathVar(reaction.getKineticLaw().getMath(), origId, newId));
}
if (model.getNumInitialAssignments() > 0) {
for (int i = 0; i < model.getNumInitialAssignments(); i++) {
InitialAssignment init = (InitialAssignment) model.getListOfInitialAssignments().get(i);
if (origId.equals(init.getSymbol())) {
init.setSymbol(newId);
}
init.setMath(updateMathVar(init.getMath(), origId, newId));
inits[i] = init.getSymbol() + " = " + myFormulaToString(init.getMath());
}
String[] oldInits = inits;
try {
inits = sortInitRules(inits);
if (checkCycles(inits, rul)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected within initial assignments and assignment rules.", "Cycle Detected",
JOptionPane.ERROR_MESSAGE);
inits = oldInits;
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in assignments.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
inits = oldInits;
}
initAssigns.setListData(inits);
initAssigns.setSelectedIndex(0);
}
if (model.getNumRules() > 0) {
for (int i = 0; i < model.getNumRules(); i++) {
Rule rule = (Rule) model.getListOfRules().get(i);
if (rule.isSetVariable() && origId.equals(rule.getVariable())) {
rule.setVariable(newId);
}
rule.setMath(updateMathVar(rule.getMath(), origId, newId));
if (rule.isAlgebraic()) {
rul[i] = "0 = " + myFormulaToString(rule.getMath());
}
else if (rule.isAssignment()) {
rul[i] = rule.getVariable() + " = " + myFormulaToString(rule.getMath());
}
else {
rul[i] = "d( " + rule.getVariable() + " )/dt = " + myFormulaToString(rule.getMath());
}
}
String[] oldRul = rul;
try {
rul = sortRules(rul);
if (checkCycles(inits, rul)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected within initial assignments and assignment rules.", "Cycle Detected",
JOptionPane.ERROR_MESSAGE);
rul = oldRul;
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in assignments.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
rul = oldRul;
}
rules.setListData(rul);
rules.setSelectedIndex(0);
}
if (model.getNumConstraints() > 0) {
for (int i = 0; i < model.getNumConstraints(); i++) {
Constraint constraint = (Constraint) model.getListOfConstraints().get(i);
constraint.setMath(updateMathVar(constraint.getMath(), origId, newId));
cons[i] = myFormulaToString(constraint.getMath());
}
sort(cons);
constraints.setListData(cons);
constraints.setSelectedIndex(0);
}
if (model.getNumEvents() > 0) {
for (int i = 0; i < model.getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) model.getListOfEvents().get(i);
if (event.isSetTrigger()) {
Trigger trigger = new Trigger(updateMathVar(event.getTrigger().getMath(), origId, newId));
event.setTrigger(trigger);
}
if (event.isSetDelay()) {
Delay delay = new Delay(updateMathVar(event.getDelay().getMath(), origId, newId));
event.setDelay(delay);
}
ev[i] = myFormulaToString(event.getTrigger().getMath());
for (int j = 0; j < event.getNumEventAssignments(); j++) {
EventAssignment ea = (EventAssignment) event.getListOfEventAssignments().get(j);
if (ea.getVariable().equals(origId)) {
ea.setVariable(newId);
}
if (ea.isSetMath()) {
ea.setMath(updateMathVar(ea.getMath(), origId, newId));
}
}
}
sort(ev);
events.setListData(ev);
events.setSelectedIndex(0);
}
}
/**
* Update variable in math formula using String
*/
private String updateFormulaVar(String s, String origVar, String newVar) {
s = " " + s + " ";
s = s.replace(" " + origVar + " ", " " + newVar + " ");
s = s.replace(" " + origVar + "(", " " + newVar + "(");
s = s.replace("(" + origVar + ")", "(" + newVar + ")");
s = s.replace("(" + origVar + " ", "(" + newVar + " ");
s = s.replace("(" + origVar + ",", "(" + newVar + ",");
s = s.replace(" " + origVar + ")", " " + newVar + ")");
return s.trim();
}
/**
* Update variable in math formula using ASTNode
*/
private ASTNode updateMathVar(ASTNode math, String origVar, String newVar) {
String s = updateFormulaVar(myFormulaToString(math), origVar, newVar);
return myParseFormula(s);
}
/**
* Update unit Id
*/
private void updateUnitId(String origId, String newId) {
if (origId.equals(newId))
return;
Model model = document.getModel();
if (model.getNumCompartments() > 0) {
for (int i = 0; i < model.getNumCompartments(); i++) {
Compartment compartment = (Compartment) model.getListOfCompartments().get(i);
if (compartment.getUnits().equals(origId)) {
compartment.setUnits(newId);
}
comps[i] = compartment.getId();
if (compartment.isSetCompartmentType()) {
comps[i] += " " + compartment.getCompartmentType();
}
if (compartment.isSetSize()) {
comps[i] += " " + compartment.getSize();
}
if (compartment.isSetUnits()) {
comps[i] += " " + compartment.getUnits();
}
}
sort(comps);
compartments.setListData(comps);
compartments.setSelectedIndex(0);
}
if (model.getNumSpecies() > 0) {
for (int i = 0; i < model.getNumSpecies(); i++) {
Species species = (Species) model.getListOfSpecies().get(i);
if (species.getUnits().equals(origId)) {
species.setUnits(newId);
}
if (species.isSetSpeciesType()) {
specs[i] = species.getId() + " " + species.getSpeciesType() + " "
+ species.getCompartment();
}
else {
specs[i] = species.getId() + " " + species.getCompartment();
}
if (species.isSetInitialAmount()) {
specs[i] += " " + species.getInitialAmount();
}
else {
specs[i] += " " + species.getInitialConcentration();
}
if (species.isSetUnits()) {
specs[i] += " " + species.getUnits();
}
}
sort(specs);
species.setListData(specs);
species.setSelectedIndex(0);
}
if (model.getNumParameters() > 0) {
for (int i = 0; i < model.getNumParameters(); i++) {
Parameter parameter = (Parameter) model.getListOfParameters().get(i);
if (parameter.getUnits().equals(origId)) {
parameter.setUnits(newId);
}
if (parameter.isSetUnits()) {
params[i] = parameter.getId() + " " + parameter.getValue() + " " + parameter.getUnits();
}
else {
params[i] = parameter.getId() + " " + parameter.getValue();
}
}
sort(params);
parameters.setListData(params);
parameters.setSelectedIndex(0);
}
for (int i = 0; i < model.getNumReactions(); i++) {
KineticLaw kineticLaw = (KineticLaw) model.getReaction(i).getKineticLaw();
for (int j = 0; j < kineticLaw.getNumParameters(); j++) {
if (kineticLaw.getParameter(j).getUnits().equals(origId)) {
kineticLaw.getParameter(j).setUnits(newId);
}
}
}
}
/**
* Creates a frame used to edit reactions or create new ones.
*/
private void reactionsEditor(String option) {
if (option.equals("OK") && reactions.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No reaction selected.",
"Must Select A Reaction", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel reactionPanelNorth = new JPanel();
JPanel reactionPanelNorth1 = new JPanel();
JPanel reactionPanelNorth1b = new JPanel();
JPanel reactionPanelNorth2 = new JPanel();
JPanel reactionPanelCentral = new JPanel(new GridLayout(1, 3));
JPanel reactionPanelSouth = new JPanel(new GridLayout(1, 2));
JPanel reactionPanel = new JPanel(new BorderLayout());
JLabel id = new JLabel("ID:");
reacID = new JTextField(15);
JLabel name = new JLabel("Name:");
reacName = new JTextField(50);
JLabel reverse = new JLabel("Reversible:");
String[] options = { "true", "false" };
reacReverse = new JComboBox(options);
reacReverse.setSelectedItem("false");
JLabel fast = new JLabel("Fast:");
reacFast = new JComboBox(options);
reacFast.setSelectedItem("false");
String selectedID = "";
if (option.equals("OK")) {
Reaction reac = document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]);
reacID.setText(reac.getId());
selectedID = reac.getId();
reacName.setText(reac.getName());
if (reac.getReversible()) {
reacReverse.setSelectedItem("true");
}
else {
reacReverse.setSelectedItem("false");
}
if (reac.getFast()) {
reacFast.setSelectedItem("true");
}
else {
reacFast.setSelectedItem("false");
}
}
JPanel param = new JPanel(new BorderLayout());
JPanel addParams = new JPanel();
reacAddParam = new JButton("Add Parameter");
reacRemoveParam = new JButton("Remove Parameter");
reacEditParam = new JButton("Edit Parameter");
addParams.add(reacAddParam);
addParams.add(reacRemoveParam);
addParams.add(reacEditParam);
reacAddParam.addActionListener(this);
reacRemoveParam.addActionListener(this);
reacEditParam.addActionListener(this);
JLabel parametersLabel = new JLabel("List Of Local Parameters:");
reacParameters = new JList();
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(260, 220));
scroll.setPreferredSize(new Dimension(276, 152));
scroll.setViewportView(reacParameters);
reacParams = new String[0];
changedParameters = new ArrayList<Parameter>();
thisReactionParams = new ArrayList<String>();
if (option.equals("OK")) {
Reaction reac = document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]);
ListOf listOfParameters = reac.getKineticLaw().getListOfParameters();
reacParams = new String[(int) reac.getKineticLaw().getNumParameters()];
for (int i = 0; i < reac.getKineticLaw().getNumParameters(); i++) {
Parameter parameter = (Parameter) listOfParameters.get(i);
changedParameters.add(parameter);
thisReactionParams.add(parameter.getId());
String p;
if (parameter.isSetUnits()) {
p = parameter.getId() + " " + parameter.getValue() + " " + parameter.getUnits();
}
else {
p = parameter.getId() + " " + parameter.getValue();
}
if (paramsOnly) {
for (int j = 0; j < parameterChanges.size(); j++) {
if (parameterChanges.get(j).split(" ")[0]
.equals(((String) reactions.getSelectedValue()).split(" ")[0] + "/"
+ parameter.getId())) {
p = parameterChanges.get(j).split("/")[1];
}
}
}
reacParams[i] = p;
}
}
else {
Parameter p = new Parameter();
p.setId("kf");
p.setValue(0.1);
changedParameters.add(p);
p = new Parameter();
p.setId("kr");
p.setValue(0.1);
changedParameters.add(p);
reacParams = new String[2];
reacParams[0] = "kf 0.1";
reacParams[1] = "kr 0.1";
thisReactionParams.add("kf");
thisReactionParams.add("kr");
}
sort(reacParams);
reacParameters.setListData(reacParams);
reacParameters.setSelectedIndex(0);
reacParameters.addMouseListener(this);
param.add(parametersLabel, "North");
param.add(scroll, "Center");
param.add(addParams, "South");
JPanel reactantsPanel = new JPanel(new BorderLayout());
JPanel addReactants = new JPanel();
addReactant = new JButton("Add Reactant");
removeReactant = new JButton("Remove Reactant");
editReactant = new JButton("Edit Reactant");
addReactants.add(addReactant);
addReactants.add(removeReactant);
addReactants.add(editReactant);
addReactant.addActionListener(this);
removeReactant.addActionListener(this);
editReactant.addActionListener(this);
JLabel reactantsLabel = new JLabel("List Of Reactants:");
reactants = new JList();
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll2 = new JScrollPane();
scroll2.setMinimumSize(new Dimension(260, 220));
scroll2.setPreferredSize(new Dimension(276, 152));
scroll2.setViewportView(reactants);
reacta = new String[0];
changedReactants = new ArrayList<SpeciesReference>();
if (option.equals("OK")) {
Reaction reac = document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]);
ListOf listOfReactants = reac.getListOfReactants();
reacta = new String[(int) reac.getNumReactants()];
for (int i = 0; i < reac.getNumReactants(); i++) {
SpeciesReference reactant = (SpeciesReference) listOfReactants.get(i);
changedReactants.add(reactant);
if (reactant.isSetStoichiometryMath()) {
reacta[i] = reactant.getSpecies() + " "
+ myFormulaToString(reactant.getStoichiometryMath().getMath());
}
else {
reacta[i] = reactant.getSpecies() + " " + reactant.getStoichiometry();
}
}
}
sort(reacta);
reactants.setListData(reacta);
reactants.setSelectedIndex(0);
reactants.addMouseListener(this);
reactantsPanel.add(reactantsLabel, "North");
reactantsPanel.add(scroll2, "Center");
reactantsPanel.add(addReactants, "South");
JPanel productsPanel = new JPanel(new BorderLayout());
JPanel addProducts = new JPanel();
addProduct = new JButton("Add Product");
removeProduct = new JButton("Remove Product");
editProduct = new JButton("Edit Product");
addProducts.add(addProduct);
addProducts.add(removeProduct);
addProducts.add(editProduct);
addProduct.addActionListener(this);
removeProduct.addActionListener(this);
editProduct.addActionListener(this);
JLabel productsLabel = new JLabel("List Of Products:");
products = new JList();
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll3 = new JScrollPane();
scroll3.setMinimumSize(new Dimension(260, 220));
scroll3.setPreferredSize(new Dimension(276, 152));
scroll3.setViewportView(products);
product = new String[0];
changedProducts = new ArrayList<SpeciesReference>();
if (option.equals("OK")) {
Reaction reac = document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]);
ListOf listOfProducts = reac.getListOfProducts();
product = new String[(int) reac.getNumProducts()];
for (int i = 0; i < reac.getNumProducts(); i++) {
SpeciesReference product = (SpeciesReference) listOfProducts.get(i);
changedProducts.add(product);
if (product.isSetStoichiometryMath()) {
this.product[i] = product.getSpecies() + " "
+ myFormulaToString(product.getStoichiometryMath().getMath());
}
else {
this.product[i] = product.getSpecies() + " " + product.getStoichiometry();
}
}
}
sort(product);
products.setListData(product);
products.setSelectedIndex(0);
products.addMouseListener(this);
productsPanel.add(productsLabel, "North");
productsPanel.add(scroll3, "Center");
productsPanel.add(addProducts, "South");
JPanel modifierPanel = new JPanel(new BorderLayout());
JPanel addModifiers = new JPanel();
addModifier = new JButton("Add Modifier");
removeModifier = new JButton("Remove Modifier");
editModifier = new JButton("Edit Modifier");
addModifiers.add(addModifier);
addModifiers.add(removeModifier);
addModifiers.add(editModifier);
addModifier.addActionListener(this);
removeModifier.addActionListener(this);
editModifier.addActionListener(this);
JLabel modifiersLabel = new JLabel("List Of Modifiers:");
modifiers = new JList();
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll5 = new JScrollPane();
scroll5.setMinimumSize(new Dimension(260, 220));
scroll5.setPreferredSize(new Dimension(276, 152));
scroll5.setViewportView(modifiers);
modifier = new String[0];
changedModifiers = new ArrayList<ModifierSpeciesReference>();
if (option.equals("OK")) {
Reaction reac = document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]);
ListOf listOfModifiers = reac.getListOfModifiers();
modifier = new String[(int) reac.getNumModifiers()];
for (int i = 0; i < reac.getNumModifiers(); i++) {
ModifierSpeciesReference modifier = (ModifierSpeciesReference) listOfModifiers.get(i);
changedModifiers.add(modifier);
this.modifier[i] = modifier.getSpecies();
}
}
sort(modifier);
modifiers.setListData(modifier);
modifiers.setSelectedIndex(0);
modifiers.addMouseListener(this);
modifierPanel.add(modifiersLabel, "North");
modifierPanel.add(scroll5, "Center");
modifierPanel.add(addModifiers, "South");
JLabel kineticLabel = new JLabel("Kinetic Law:");
kineticLaw = new JTextArea();
kineticLaw.setLineWrap(true);
kineticLaw.setWrapStyleWord(true);
useMassAction = new JButton("Use Mass Action");
clearKineticLaw = new JButton("Clear");
useMassAction.addActionListener(this);
clearKineticLaw.addActionListener(this);
JPanel kineticButtons = new JPanel();
kineticButtons.add(useMassAction);
kineticButtons.add(clearKineticLaw);
JScrollPane scroll4 = new JScrollPane();
scroll4.setMinimumSize(new Dimension(100, 100));
scroll4.setPreferredSize(new Dimension(100, 100));
scroll4.setViewportView(kineticLaw);
if (option.equals("OK")) {
kineticLaw.setText(document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]).getKineticLaw().getFormula());
}
JPanel kineticPanel = new JPanel(new BorderLayout());
kineticPanel.add(kineticLabel, "North");
kineticPanel.add(scroll4, "Center");
kineticPanel.add(kineticButtons, "South");
reactionPanelNorth1.add(id);
reactionPanelNorth1.add(reacID);
reactionPanelNorth1.add(name);
reactionPanelNorth1.add(reacName);
reactionPanelNorth1b.add(reverse);
reactionPanelNorth1b.add(reacReverse);
reactionPanelNorth1b.add(fast);
reactionPanelNorth1b.add(reacFast);
reactionPanelNorth2.add(reactionPanelNorth1);
reactionPanelNorth2.add(reactionPanelNorth1b);
reactionPanelNorth.add(reactionPanelNorth2);
reactionPanelCentral.add(reactantsPanel);
reactionPanelCentral.add(productsPanel);
reactionPanelCentral.add(modifierPanel);
reactionPanelSouth.add(param);
reactionPanelSouth.add(kineticPanel);
reactionPanel.add(reactionPanelNorth, "North");
reactionPanel.add(reactionPanelCentral, "Center");
reactionPanel.add(reactionPanelSouth, "South");
if (paramsOnly) {
reacID.setEditable(false);
reacName.setEditable(false);
reacReverse.setEnabled(false);
reacFast.setEnabled(false);
reacAddParam.setEnabled(false);
reacRemoveParam.setEnabled(false);
addReactant.setEnabled(false);
removeReactant.setEnabled(false);
editReactant.setEnabled(false);
addProduct.setEnabled(false);
removeProduct.setEnabled(false);
editProduct.setEnabled(false);
addModifier.setEnabled(false);
removeModifier.setEnabled(false);
editModifier.setEnabled(false);
kineticLaw.setEditable(false);
useMassAction.setEnabled(false);
clearKineticLaw.setEnabled(false);
}
Object[] options1 = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), reactionPanel, "Reaction Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options1, options1[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
String reac = reacID.getText().trim();
error = checkID(reac, selectedID, false);
if (!error) {
if (kineticLaw.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "A reaction must have a kinetic law.",
"Enter A Kinetic Law", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if ((changedReactants.size() == 0) && (changedProducts.size() == 0)) {
JOptionPane.showMessageDialog(biosim.frame(),
"A reaction must have at least one reactant or product.", "No Reactants or Products",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (myParseFormula(kineticLaw.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to parse kinetic law.",
"Kinetic Law Error", JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidKineticVars = getInvalidVariables(kineticLaw.getText().trim(),
true, "", false);
if (invalidKineticVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidKineticVars.size(); i++) {
if (i == invalidKineticVars.size() - 1) {
invalid += invalidKineticVars.get(i);
}
else {
invalid += invalidKineticVars.get(i) + "\n";
}
}
String message;
message = "Kinetic law contains unknown variables.\n\n" + "Unknown variables:\n"
+ invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Kinetic Law Error",
JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = checkNumFunctionArguments(myParseFormula(kineticLaw.getText().trim()));
}
}
}
if (!error) {
if (myParseFormula(kineticLaw.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(), "Kinetic law must evaluate to a number.",
"Number Expected", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
if (option.equals("OK")) {
int index = reactions.getSelectedIndex();
String val = ((String) reactions.getSelectedValue()).split(" ")[0];
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacts = Buttons.getList(reacts, reactions);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Reaction react = document.getModel().getReaction(val);
Reaction copyReact = (Reaction) react.cloneObject();
ListOf remove;
long size;
remove = react.getKineticLaw().getListOfParameters();
size = react.getKineticLaw().getNumParameters();
for (int i = 0; i < size; i++) {
remove.remove(0);
}
for (int i = 0; i < changedParameters.size(); i++) {
react.getKineticLaw().addParameter(changedParameters.get(i));
}
remove = react.getListOfProducts();
size = react.getNumProducts();
for (int i = 0; i < size; i++) {
remove.remove(0);
}
for (int i = 0; i < changedProducts.size(); i++) {
react.addProduct(changedProducts.get(i));
}
remove = react.getListOfModifiers();
size = react.getNumModifiers();
for (int i = 0; i < size; i++) {
remove.remove(0);
}
for (int i = 0; i < changedModifiers.size(); i++) {
react.addModifier(changedModifiers.get(i));
}
remove = react.getListOfReactants();
size = react.getNumReactants();
for (int i = 0; i < size; i++) {
remove.remove(0);
}
for (int i = 0; i < changedReactants.size(); i++) {
react.addReactant(changedReactants.get(i));
}
if (reacReverse.getSelectedItem().equals("true")) {
react.setReversible(true);
}
else {
react.setReversible(false);
}
if (reacFast.getSelectedItem().equals("true")) {
react.setFast(true);
}
else {
react.setFast(false);
}
react.setId(reacID.getText().trim());
react.setName(reacName.getText().trim());
react.getKineticLaw().setFormula(kineticLaw.getText().trim());
error = checkKineticLawUnits(react.getKineticLaw());
if (!error) {
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(val)) {
usedIDs.set(i, reacID.getText().trim());
}
}
if (!paramsOnly) {
reacts[index] = reac;
}
sort(reacts);
reactions.setListData(reacts);
reactions.setSelectedIndex(index);
}
else {
removeTheReaction(reac);
document.getModel().addReaction(copyReact);
}
}
else {
Reaction react = document.getModel().createReaction();
react.setKineticLaw(new KineticLaw());
int index = reactions.getSelectedIndex();
for (int i = 0; i < changedParameters.size(); i++) {
react.getKineticLaw().addParameter(changedParameters.get(i));
}
for (int i = 0; i < changedProducts.size(); i++) {
react.addProduct(changedProducts.get(i));
}
for (int i = 0; i < changedModifiers.size(); i++) {
react.addModifier(changedModifiers.get(i));
}
for (int i = 0; i < changedReactants.size(); i++) {
react.addReactant(changedReactants.get(i));
}
if (reacReverse.getSelectedItem().equals("true")) {
react.setReversible(true);
}
else {
react.setReversible(false);
}
if (reacFast.getSelectedItem().equals("true")) {
react.setFast(true);
}
else {
react.setFast(false);
}
react.setId(reacID.getText().trim());
react.setName(reacName.getText().trim());
react.getKineticLaw().setFormula(kineticLaw.getText().trim());
error = checkKineticLawUnits(react.getKineticLaw());
if (!error) {
usedIDs.add(reacID.getText().trim());
JList add = new JList();
Object[] adding = { reac };
add.setListData(adding);
add.setSelectedIndex(0);
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(reacts, reactions, add, false, null, null, null, null, null, null,
biosim.frame());
reacts = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
reacts[i] = (String) adding[i];
}
sort(reacts);
reactions.setListData(reacts);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumReactions() == 1) {
reactions.setSelectedIndex(0);
}
else {
reactions.setSelectedIndex(index);
}
}
else {
removeTheReaction(reac);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), reactionPanel, "Reaction Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options1, options1[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Find invalid reaction variables in a formula
*/
private ArrayList<String> getInvalidVariables(String formula, boolean isReaction,
String arguments, boolean isFunction) {
ArrayList<String> validVars = new ArrayList<String>();
ArrayList<String> invalidVars = new ArrayList<String>();
ListOf sbml = document.getModel().getListOfFunctionDefinitions();
for (int i = 0; i < document.getModel().getNumFunctionDefinitions(); i++) {
validVars.add(((FunctionDefinition) sbml.get(i)).getId());
}
if (isReaction) {
for (int i = 0; i < changedParameters.size(); i++) {
validVars.add(((Parameter) changedParameters.get(i)).getId());
}
for (int i = 0; i < changedReactants.size(); i++) {
validVars.add(((SpeciesReference) changedReactants.get(i)).getSpecies());
}
for (int i = 0; i < changedProducts.size(); i++) {
validVars.add(((SpeciesReference) changedProducts.get(i)).getSpecies());
}
for (int i = 0; i < changedModifiers.size(); i++) {
validVars.add(((ModifierSpeciesReference) changedModifiers.get(i)).getSpecies());
}
}
else if (!isFunction) {
sbml = document.getModel().getListOfSpecies();
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
validVars.add(((Species) sbml.get(i)).getId());
}
}
if (isFunction) {
String[] args = arguments.split(" |\\,");
for (int i = 0; i < args.length; i++) {
validVars.add(args[i]);
}
}
else {
sbml = document.getModel().getListOfCompartments();
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
if (((Compartment) sbml.get(i)).getSpatialDimensions() != 0) {
validVars.add(((Compartment) sbml.get(i)).getId());
}
}
sbml = document.getModel().getListOfParameters();
for (int i = 0; i < document.getModel().getNumParameters(); i++) {
validVars.add(((Parameter) sbml.get(i)).getId());
}
sbml = document.getModel().getListOfReactions();
for (int i = 0; i < document.getModel().getNumReactions(); i++) {
validVars.add(((Reaction) sbml.get(i)).getId());
}
}
String[] splitLaw = formula.split(" |\\(|\\)|\\,|\\*|\\+|\\/|\\-");
for (int i = 0; i < splitLaw.length; i++) {
if (splitLaw[i].equals("abs") || splitLaw[i].equals("arccos")
|| splitLaw[i].equals("arccosh") || splitLaw[i].equals("arcsin")
|| splitLaw[i].equals("arcsinh") || splitLaw[i].equals("arctan")
|| splitLaw[i].equals("arctanh") || splitLaw[i].equals("arccot")
|| splitLaw[i].equals("arccoth") || splitLaw[i].equals("arccsc")
|| splitLaw[i].equals("arccsch") || splitLaw[i].equals("arcsec")
|| splitLaw[i].equals("arcsech") || splitLaw[i].equals("acos")
|| splitLaw[i].equals("acosh") || splitLaw[i].equals("asin")
|| splitLaw[i].equals("asinh") || splitLaw[i].equals("atan")
|| splitLaw[i].equals("atanh") || splitLaw[i].equals("acot")
|| splitLaw[i].equals("acoth") || splitLaw[i].equals("acsc")
|| splitLaw[i].equals("acsch") || splitLaw[i].equals("asec")
|| splitLaw[i].equals("asech") || splitLaw[i].equals("cos") || splitLaw[i].equals("cosh")
|| splitLaw[i].equals("cot") || splitLaw[i].equals("coth") || splitLaw[i].equals("csc")
|| splitLaw[i].equals("csch") || splitLaw[i].equals("ceil")
|| splitLaw[i].equals("factorial") || splitLaw[i].equals("exp")
|| splitLaw[i].equals("floor") || splitLaw[i].equals("ln") || splitLaw[i].equals("log")
|| splitLaw[i].equals("sqr") || splitLaw[i].equals("log10") || splitLaw[i].equals("pow")
|| splitLaw[i].equals("sqrt") || splitLaw[i].equals("root")
|| splitLaw[i].equals("piecewise") || splitLaw[i].equals("sec")
|| splitLaw[i].equals("sech") || splitLaw[i].equals("sin") || splitLaw[i].equals("sinh")
|| splitLaw[i].equals("tan") || splitLaw[i].equals("tanh") || splitLaw[i].equals("")
|| splitLaw[i].equals("and") || splitLaw[i].equals("or") || splitLaw[i].equals("xor")
|| splitLaw[i].equals("not") || splitLaw[i].equals("eq") || splitLaw[i].equals("geq")
|| splitLaw[i].equals("leq") || splitLaw[i].equals("gt") || splitLaw[i].equals("neq")
|| splitLaw[i].equals("lt") || splitLaw[i].equals("delay") || splitLaw[i].equals("t")
|| splitLaw[i].equals("true") || splitLaw[i].equals("false") || splitLaw[i].equals("pi")
|| splitLaw[i].equals("exponentiale")) {
}
else {
String temp = splitLaw[i];
if (splitLaw[i].substring(splitLaw[i].length() - 1, splitLaw[i].length()).equals("e")) {
temp = splitLaw[i].substring(0, splitLaw[i].length() - 1);
}
try {
Double.parseDouble(temp);
}
catch (Exception e1) {
if (!validVars.contains(splitLaw[i])) {
invalidVars.add(splitLaw[i]);
}
}
}
}
return invalidVars;
}
/**
* Creates a frame used to edit parameters or create new ones.
*/
private void parametersEditor(String option) {
if (option.equals("OK") && parameters.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No parameter selected.",
"Must Select A Parameter", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel parametersPanel;
if (paramsOnly) {
parametersPanel = new JPanel(new GridLayout(10, 2));
}
else {
parametersPanel = new JPanel(new GridLayout(5, 2));
}
JLabel idLabel = new JLabel("ID:");
JLabel nameLabel = new JLabel("Name:");
JLabel valueLabel = new JLabel("Value:");
JLabel unitLabel = new JLabel("Units:");
JLabel constLabel = new JLabel("Constant:");
JLabel startLabel = new JLabel("Start:");
JLabel stopLabel = new JLabel("Stop:");
JLabel stepLabel = new JLabel("Step:");
JLabel levelLabel = new JLabel("Level:");
paramID = new JTextField();
paramName = new JTextField();
paramValue = new JTextField();
paramUnits = new JComboBox();
paramUnits.addItem("( none )");
for (int i = 0; i < units.length; i++) {
if (!units[i].equals("substance") && !units[i].equals("volume") && !units[i].equals("area")
&& !units[i].equals("length") && !units[i].equals("time")) {
paramUnits.addItem(units[i]);
}
}
String[] unitIds = { "substance", "volume", "area", "length", "time", "ampere", "becquerel",
"candela", "celsius", "coulomb", "dimensionless", "farad", "gram", "gray", "henry",
"hertz", "item", "joule", "katal", "kelvin", "kilogram", "litre", "lumen", "lux", "metre",
"mole", "newton", "ohm", "pascal", "radian", "second", "siemens", "sievert", "steradian",
"tesla", "volt", "watt", "weber" };
for (int i = 0; i < unitIds.length; i++) {
paramUnits.addItem(unitIds[i]);
}
paramConst = new JComboBox();
paramConst.addItem("true");
paramConst.addItem("false");
String[] list = { "Original", "Custom", "Sweep" };
String[] list1 = { "1", "2" };
final JComboBox type = new JComboBox(list);
final JTextField start = new JTextField();
final JTextField stop = new JTextField();
final JTextField step = new JTextField();
final JComboBox level = new JComboBox(list1);
if (paramsOnly) {
paramID.setEditable(false);
paramName.setEditable(false);
paramValue.setEnabled(false);
paramUnits.setEnabled(false);
paramConst.setEnabled(false);
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
}
String selectedID = "";
if (option.equals("OK")) {
try {
Parameter paramet = document.getModel().getParameter(
((String) parameters.getSelectedValue()).split(" ")[0]);
paramID.setText(paramet.getId());
selectedID = paramet.getId();
paramName.setText(paramet.getName());
if (paramet.getConstant()) {
paramConst.setSelectedItem("true");
}
else {
paramConst.setSelectedItem("false");
}
if (paramet.isSetValue()) {
paramValue.setText("" + paramet.getValue());
}
if (paramet.isSetUnits()) {
paramUnits.setSelectedItem(paramet.getUnits());
}
if (paramsOnly && (((String) parameters.getSelectedValue()).contains("Custom"))
|| (((String) parameters.getSelectedValue()).contains("Sweep"))) {
if (((String) parameters.getSelectedValue()).contains("Custom")) {
type.setSelectedItem("Custom");
}
else {
type.setSelectedItem("Sweep");
}
if (((String) type.getSelectedItem()).equals("Sweep")) {
String[] splits = ((String) parameters.getSelectedValue()).split(" ");
String sweepVal = splits[splits.length - 1];
start.setText((sweepVal).split(",")[0].substring(1).trim());
stop.setText((sweepVal).split(",")[1].trim());
step.setText((sweepVal).split(",")[2].trim());
level.setSelectedItem((sweepVal).split(",")[3].replace(")", "").trim());
start.setEnabled(true);
stop.setEnabled(true);
step.setEnabled(true);
level.setEnabled(true);
paramValue.setEnabled(false);
paramUnits.setEnabled(false);
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
paramValue.setEnabled(true);
paramUnits.setEnabled(false);
}
}
}
catch (Exception e) {
}
}
parametersPanel.add(idLabel);
parametersPanel.add(paramID);
parametersPanel.add(nameLabel);
parametersPanel.add(paramName);
if (paramsOnly) {
JLabel typeLabel = new JLabel("Type:");
type.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!((String) type.getSelectedItem()).equals("Original")) {
if (((String) type.getSelectedItem()).equals("Sweep")) {
start.setEnabled(true);
stop.setEnabled(true);
step.setEnabled(true);
level.setEnabled(true);
paramValue.setEnabled(false);
paramUnits.setEnabled(false);
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
paramValue.setEnabled(true);
paramUnits.setEnabled(false);
}
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
paramValue.setEnabled(false);
paramUnits.setEnabled(false);
SBMLReader reader = new SBMLReader();
SBMLDocument d = reader.readSBML(file);
if (d.getModel().getParameter(((String) parameters.getSelectedValue()).split(" ")[0])
.isSetValue()) {
paramValue.setText(d.getModel().getParameter(
((String) parameters.getSelectedValue()).split(" ")[0]).getValue()
+ "");
}
else {
paramValue.setText("");
}
if (d.getModel().getParameter(((String) parameters.getSelectedValue()).split(" ")[0])
.isSetUnits()) {
paramUnits.setSelectedItem(d.getModel().getParameter(
((String) parameters.getSelectedValue()).split(" ")[0]).getUnits()
+ "");
}
}
}
});
parametersPanel.add(typeLabel);
parametersPanel.add(type);
}
parametersPanel.add(valueLabel);
parametersPanel.add(paramValue);
parametersPanel.add(unitLabel);
parametersPanel.add(paramUnits);
parametersPanel.add(constLabel);
parametersPanel.add(paramConst);
if (paramsOnly) {
parametersPanel.add(startLabel);
parametersPanel.add(start);
parametersPanel.add(stopLabel);
parametersPanel.add(stop);
parametersPanel.add(stepLabel);
parametersPanel.add(step);
parametersPanel.add(levelLabel);
parametersPanel.add(level);
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), parametersPanel, "Parameter Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = checkID(paramID.getText().trim(), selectedID, false);
if (!error) {
double val = 0.0;
try {
val = Double.parseDouble(paramValue.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "The value must be a real number.",
"Enter A Valid Value", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
String unit = (String) paramUnits.getSelectedItem();
String param = "";
if (paramsOnly && !((String) type.getSelectedItem()).equals("Original")) {
int index = parameters.getSelectedIndex();
String[] splits = params[index].split(" ");
for (int i = 0; i < splits.length - 2; i++) {
param += splits[i] + " ";
}
if (!splits[splits.length - 2].equals("Custom")
&& !splits[splits.length - 2].equals("Sweep")) {
param += splits[splits.length - 2] + " " + splits[splits.length - 1] + " ";
}
if (((String) type.getSelectedItem()).equals("Sweep")) {
double startVal = Double.parseDouble(start.getText().trim());
double stopVal = Double.parseDouble(stop.getText().trim());
double stepVal = Double.parseDouble(step.getText().trim());
param += "Sweep (" + startVal + "," + stopVal + "," + stepVal + ","
+ level.getSelectedItem() + ")";
}
else {
param += "Custom " + val;
}
}
else {
param = paramID.getText().trim() + " " + val;
if (!unit.equals("( none )")) {
param = paramID.getText().trim() + " " + val + " " + unit;
}
}
if (!error && option.equals("OK") && paramConst.getSelectedItem().equals("true")) {
String v = ((String) parameters.getSelectedValue()).split(" ")[0];
error = checkConstant("Parameters", v);
}
if (!error) {
if (option.equals("OK")) {
int index = parameters.getSelectedIndex();
String v = ((String) parameters.getSelectedValue()).split(" ")[0];
Parameter paramet = document.getModel().getParameter(v);
parameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
params = Buttons.getList(params, parameters);
parameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
paramet.setId(paramID.getText().trim());
paramet.setName(paramName.getText().trim());
if (paramConst.getSelectedItem().equals("true")) {
paramet.setConstant(true);
}
else {
paramet.setConstant(false);
}
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(v)) {
usedIDs.set(i, paramID.getText().trim());
}
}
paramet.setValue(val);
if (unit.equals("( none )")) {
paramet.unsetUnits();
}
else {
paramet.setUnits(unit);
}
params[index] = param;
sort(params);
parameters.setListData(params);
parameters.setSelectedIndex(index);
if (paramsOnly) {
int remove = -1;
for (int i = 0; i < parameterChanges.size(); i++) {
if (parameterChanges.get(i).split(" ")[0].equals(paramID.getText().trim())) {
remove = i;
}
}
if (remove != -1) {
parameterChanges.remove(remove);
}
if (!((String) type.getSelectedItem()).equals("Original")) {
parameterChanges.add(param);
}
}
else {
updateVarId(false, v, paramID.getText().trim());
}
}
else {
int index = parameters.getSelectedIndex();
Parameter paramet = document.getModel().createParameter();
paramet.setId(paramID.getText().trim());
paramet.setName(paramName.getText().trim());
usedIDs.add(paramID.getText().trim());
if (paramConst.getSelectedItem().equals("true")) {
paramet.setConstant(true);
}
else {
paramet.setConstant(false);
}
paramet.setValue(val);
if (!unit.equals("( none )")) {
paramet.setUnits(unit);
}
JList add = new JList();
Object[] adding = { param };
add.setListData(adding);
add.setSelectedIndex(0);
parameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(params, parameters, add, false, null, null, null, null, null,
null, biosim.frame());
params = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
params[i] = (String) adding[i];
}
sort(params);
parameters.setListData(params);
parameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumParameters() == 1) {
parameters.setSelectedIndex(0);
}
else {
parameters.setSelectedIndex(index);
}
}
change = true;
}
}
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), parametersPanel, "Parameter Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit reactions parameters or create new ones.
*/
private void reacParametersEditor(String option) {
if (option.equals("OK") && reacParameters.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No parameter selected.",
"Must Select A Parameter", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel parametersPanel;
if (paramsOnly) {
parametersPanel = new JPanel(new GridLayout(9, 2));
}
else {
parametersPanel = new JPanel(new GridLayout(4, 2));
}
JLabel idLabel = new JLabel("ID:");
JLabel nameLabel = new JLabel("Name:");
JLabel valueLabel = new JLabel("Value:");
JLabel unitsLabel = new JLabel("Units:");
JLabel startLabel = new JLabel("Start:");
JLabel stopLabel = new JLabel("Stop:");
JLabel stepLabel = new JLabel("Step:");
JLabel levelLabel = new JLabel("Level:");
reacParamID = new JTextField();
reacParamName = new JTextField();
reacParamValue = new JTextField();
reacParamUnits = new JComboBox();
reacParamUnits.addItem("( none )");
for (int i = 0; i < units.length; i++) {
if (!units[i].equals("substance") && !units[i].equals("volume") && !units[i].equals("area")
&& !units[i].equals("length") && !units[i].equals("time")) {
reacParamUnits.addItem(units[i]);
}
}
String[] unitIds = { "substance", "volume", "area", "length", "time", "ampere", "becquerel",
"candela", "celsius", "coulomb", "dimensionless", "farad", "gram", "gray", "henry",
"hertz", "item", "joule", "katal", "kelvin", "kilogram", "litre", "lumen", "lux", "metre",
"mole", "newton", "ohm", "pascal", "radian", "second", "siemens", "sievert", "steradian",
"tesla", "volt", "watt", "weber" };
for (int i = 0; i < unitIds.length; i++) {
reacParamUnits.addItem(unitIds[i]);
}
String[] list = { "Original", "Custom", "Sweep" };
String[] list1 = { "1", "2" };
final JComboBox type = new JComboBox(list);
final JTextField start = new JTextField();
final JTextField stop = new JTextField();
final JTextField step = new JTextField();
final JComboBox level = new JComboBox(list1);
if (paramsOnly) {
reacParamID.setEditable(false);
reacParamName.setEditable(false);
reacParamValue.setEnabled(false);
reacParamUnits.setEnabled(false);
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
}
String selectedID = "";
if (option.equals("OK")) {
String v = ((String) reacParameters.getSelectedValue()).split(" ")[0];
Parameter paramet = null;
for (Parameter p : changedParameters) {
if (p.getId().equals(v)) {
paramet = p;
}
}
reacParamID.setText(paramet.getId());
selectedID = paramet.getId();
reacParamName.setText(paramet.getName());
reacParamValue.setText("" + paramet.getValue());
if (paramet.isSetUnits()) {
reacParamUnits.setSelectedItem(paramet.getUnits());
}
if (paramsOnly && (((String) reacParameters.getSelectedValue()).contains("Custom"))
|| (((String) reacParameters.getSelectedValue()).contains("Sweep"))) {
if (((String) reacParameters.getSelectedValue()).contains("Custom")) {
type.setSelectedItem("Custom");
}
else {
type.setSelectedItem("Sweep");
}
if (((String) type.getSelectedItem()).equals("Sweep")) {
String[] splits = ((String) reacParameters.getSelectedValue()).split(" ");
String sweepVal = splits[splits.length - 1];
start.setText((sweepVal).split(",")[0].substring(1).trim());
stop.setText((sweepVal).split(",")[1].trim());
step.setText((sweepVal).split(",")[2].trim());
level.setSelectedItem((sweepVal).split(",")[3].replace(")", "").trim());
start.setEnabled(true);
stop.setEnabled(true);
step.setEnabled(true);
level.setEnabled(true);
reacParamValue.setEnabled(false);
reacParamUnits.setEnabled(false);
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
reacParamValue.setEnabled(true);
reacParamUnits.setEnabled(false);
}
}
}
parametersPanel.add(idLabel);
parametersPanel.add(reacParamID);
parametersPanel.add(nameLabel);
parametersPanel.add(reacParamName);
if (paramsOnly) {
JLabel typeLabel = new JLabel("Type:");
type.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!((String) type.getSelectedItem()).equals("Original")) {
if (((String) type.getSelectedItem()).equals("Sweep")) {
start.setEnabled(true);
stop.setEnabled(true);
step.setEnabled(true);
level.setEnabled(true);
reacParamValue.setEnabled(false);
reacParamUnits.setEnabled(false);
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
reacParamValue.setEnabled(true);
reacParamUnits.setEnabled(false);
}
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
reacParamValue.setEnabled(false);
reacParamUnits.setEnabled(false);
SBMLReader reader = new SBMLReader();
SBMLDocument d = reader.readSBML(file);
KineticLaw KL = d.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]).getKineticLaw();
ListOf list = KL.getListOfParameters();
int number = -1;
for (int i = 0; i < KL.getNumParameters(); i++) {
if (((Parameter) list.get(i)).getId().equals(
((String) reacParameters.getSelectedValue()).split(" ")[0])) {
number = i;
}
}
reacParamValue.setText(d.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]).getKineticLaw()
.getParameter(number).getValue()
+ "");
if (d.getModel().getReaction(((String) reactions.getSelectedValue()).split(" ")[0])
.getKineticLaw().getParameter(number).isSetUnits()) {
reacParamUnits.setSelectedItem(d.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]).getKineticLaw()
.getParameter(number).getUnits());
}
reacParamValue.setText(d.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]).getKineticLaw()
.getParameter(number).getValue()
+ "");
}
}
});
parametersPanel.add(typeLabel);
parametersPanel.add(type);
}
parametersPanel.add(valueLabel);
parametersPanel.add(reacParamValue);
parametersPanel.add(unitsLabel);
parametersPanel.add(reacParamUnits);
if (paramsOnly) {
parametersPanel.add(startLabel);
parametersPanel.add(start);
parametersPanel.add(stopLabel);
parametersPanel.add(stop);
parametersPanel.add(stepLabel);
parametersPanel.add(step);
parametersPanel.add(levelLabel);
parametersPanel.add(level);
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), parametersPanel, "Parameter Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = checkID(reacParamID.getText().trim(), selectedID, true);
if (!error) {
if (thisReactionParams.contains(reacParamID.getText().trim())
&& (!reacParamID.getText().trim().equals(selectedID))) {
JOptionPane.showMessageDialog(biosim.frame(), "ID is not unique.", "ID Not Unique",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
double val = 0;
try {
val = Double.parseDouble(reacParamValue.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "The value must be a real number.",
"Enter A Valid Value", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
String unit = (String) reacParamUnits.getSelectedItem();
String param = "";
if (paramsOnly && !((String) type.getSelectedItem()).equals("Original")) {
int index = reacParameters.getSelectedIndex();
String[] splits = reacParams[index].split(" ");
for (int i = 0; i < splits.length - 2; i++) {
param += splits[i] + " ";
}
if (!splits[splits.length - 2].equals("Custom")
&& !splits[splits.length - 2].equals("Sweep")) {
param += splits[splits.length - 2] + " " + splits[splits.length - 1] + " ";
}
if (((String) type.getSelectedItem()).equals("Sweep")) {
double startVal = Double.parseDouble(start.getText().trim());
double stopVal = Double.parseDouble(stop.getText().trim());
double stepVal = Double.parseDouble(step.getText().trim());
param += "Sweep (" + startVal + "," + stopVal + "," + stepVal + ","
+ level.getSelectedItem() + ")";
}
else {
param += "Custom " + val;
}
}
else {
if (unit.equals("( none )")) {
param = reacParamID.getText().trim() + " " + val;
}
else {
param = reacParamID.getText().trim() + " " + val + " " + unit;
}
}
if (option.equals("OK")) {
int index = reacParameters.getSelectedIndex();
String v = ((String) reacParameters.getSelectedValue()).split(" ")[0];
Parameter paramet = null;
for (Parameter p : changedParameters) {
if (p.getId().equals(v)) {
paramet = p;
}
}
reacParameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacParams = Buttons.getList(reacParams, reacParameters);
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
paramet.setId(reacParamID.getText().trim());
paramet.setName(reacParamName.getText().trim());
for (int i = 0; i < thisReactionParams.size(); i++) {
if (thisReactionParams.get(i).equals(v)) {
thisReactionParams.set(i, reacParamID.getText().trim());
}
}
paramet.setValue(val);
if (unit.equals("( none )")) {
paramet.unsetUnits();
}
else {
paramet.setUnits(unit);
}
reacParams[index] = param;
sort(reacParams);
reacParameters.setListData(reacParams);
reacParameters.setSelectedIndex(index);
if (paramsOnly) {
int remove = -1;
for (int i = 0; i < parameterChanges.size(); i++) {
if (parameterChanges.get(i).split(" ")[0].equals(((String) reactions
.getSelectedValue()).split(" ")[0]
+ "/" + reacParamID.getText().trim())) {
remove = i;
}
}
if (remove != -1) {
parameterChanges.remove(remove);
int index1 = reactions.getSelectedIndex();
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacts = Buttons.getList(reacts, reactions);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reacts[index1] = ((String) reactions.getSelectedValue()).split(" ")[0];
sort(reacts);
reactions.setListData(reacts);
reactions.setSelectedIndex(index1);
}
if (!((String) type.getSelectedItem()).equals("Original")) {
String reacValue = ((String) reactions.getSelectedValue()).split(" ")[0];
parameterChanges.add(reacValue + "/" + param);
int index1 = reactions.getSelectedIndex();
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacts = Buttons.getList(reacts, reactions);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reacts[index1] = reacValue + " Modified";
sort(reacts);
reactions.setListData(reacts);
reactions.setSelectedIndex(index1);
}
}
else {
kineticLaw.setText(updateFormulaVar(kineticLaw.getText().trim(), v, reacParamID
.getText().trim()));
}
}
else {
int index = reacParameters.getSelectedIndex();
Parameter paramet = new Parameter();
changedParameters.add(paramet);
paramet.setId(reacParamID.getText().trim());
paramet.setName(reacParamName.getText().trim());
thisReactionParams.add(reacParamID.getText().trim());
paramet.setValue(val);
if (!unit.equals("( none )")) {
paramet.setUnits(unit);
}
JList add = new JList();
Object[] adding = { param };
add.setListData(adding);
add.setSelectedIndex(0);
reacParameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(reacParams, reacParameters, add, false, null, null, null, null,
null, null, biosim.frame());
reacParams = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
reacParams[i] = (String) adding[i];
}
sort(reacParams);
reacParameters.setListData(reacParams);
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
try {
if (document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]).getKineticLaw()
.getNumParameters() == 1) {
reacParameters.setSelectedIndex(0);
}
else {
reacParameters.setSelectedIndex(index);
}
}
catch (Exception e2) {
reacParameters.setSelectedIndex(0);
}
}
change = true;
}
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), parametersPanel, "Parameter Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit products or create new ones.
*/
public void productsEditor(String option) {
if (option.equals("OK") && products.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No product selected.",
"Must Select A Product", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel productsPanel = new JPanel(new GridLayout(2, 2));
JLabel speciesLabel = new JLabel("Species:");
Object[] stoiciOptions = { "Stoichiometry", "Stoichiometry Math" };
stoiciLabel = new JComboBox(stoiciOptions);
ListOf listOfSpecies = document.getModel().getListOfSpecies();
String[] speciesList = new String[(int) document.getModel().getNumSpecies()];
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
speciesList[i] = ((Species) listOfSpecies.get(i)).getId();
}
sort(speciesList);
productSpecies = new JComboBox();
for (int i = 0; i < speciesList.length; i++) {
Species species = document.getModel().getSpecies(speciesList[i]);
if (species.getBoundaryCondition()
|| (!species.getConstant() && keepVar("", speciesList[i], false, true, false, false))) {
productSpecies.addItem(speciesList[i]);
}
}
productStoiciometry = new JTextField("1");
if (option.equals("OK")) {
String v = ((String) products.getSelectedValue()).split(" ")[0];
SpeciesReference product = null;
for (SpeciesReference p : changedProducts) {
if (p.getSpecies().equals(v)) {
product = p;
}
}
productSpecies.setSelectedItem(product.getSpecies());
if (product.isSetStoichiometryMath()) {
stoiciLabel.setSelectedItem("Stoichiometry Math");
productStoiciometry.setText(""
+ myFormulaToString(product.getStoichiometryMath().getMath()));
}
else {
productStoiciometry.setText("" + product.getStoichiometry());
}
}
productsPanel.add(speciesLabel);
productsPanel.add(productSpecies);
productsPanel.add(stoiciLabel);
productsPanel.add(productStoiciometry);
if (speciesList.length == 0) {
JOptionPane.showMessageDialog(biosim.frame(),
"There are no species availiable to be products."
+ "\nAdd species to this sbml file first.", "No Species", JOptionPane.ERROR_MESSAGE);
return;
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), productsPanel, "Products Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
String prod;
double val = 1.0;
if (stoiciLabel.getSelectedItem().equals("Stoichiometry")) {
try {
val = Double.parseDouble(productStoiciometry.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "The stoichiometry must be a real number.",
"Enter A Valid Value", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (val <= 0) {
JOptionPane.showMessageDialog(biosim.frame(),
"The stoichiometry value must be greater than 0.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
}
prod = productSpecies.getSelectedItem() + " " + val;
}
else {
prod = productSpecies.getSelectedItem() + " " + productStoiciometry.getText().trim();
}
int index = -1;
if (!error) {
if (option.equals("OK")) {
index = products.getSelectedIndex();
}
products.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
product = Buttons.getList(product, products);
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index >= 0) {
products.setSelectedIndex(index);
}
for (int i = 0; i < product.length; i++) {
if (i != index) {
if (product[i].split(" ")[0].equals(productSpecies.getSelectedItem())) {
error = true;
JOptionPane.showMessageDialog(biosim.frame(), "Unable to add species as a product.\n"
+ "Each species can only be used as a product once.",
"Species Can Only Be Used Once", JOptionPane.ERROR_MESSAGE);
}
}
}
}
if (!error) {
if (stoiciLabel.getSelectedItem().equals("Stoichiometry Math")) {
if (productStoiciometry.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "Stoichiometry math must have formula.",
"Enter Stoichiometry Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (myParseFormula(productStoiciometry.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Stoichiometry formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariables(productStoiciometry.getText()
.trim(), true, "", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Stoiciometry math contains unknown variables.\n\n"
+ "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Stoiciometry Math Error",
JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = checkNumFunctionArguments(myParseFormula(productStoiciometry.getText().trim()));
}
if (!error) {
if (myParseFormula(productStoiciometry.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Stoichiometry math must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
}
}
if (!error) {
if (option.equals("OK")) {
String v = ((String) products.getSelectedValue()).split(" ")[0];
SpeciesReference produ = null;
for (SpeciesReference p : changedProducts) {
if (p.getSpecies().equals(v)) {
produ = p;
}
}
products.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
product = Buttons.getList(product, products);
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
produ.setSpecies((String) productSpecies.getSelectedItem());
if (stoiciLabel.getSelectedItem().equals("Stoichiometry")) {
produ.setStoichiometry(val);
produ.unsetStoichiometryMath();
}
else {
StoichiometryMath sm = new StoichiometryMath(myParseFormula(productStoiciometry
.getText().trim()));
produ.setStoichiometryMath(sm);
produ.setStoichiometry(1);
}
product[index] = prod;
sort(product);
products.setListData(product);
products.setSelectedIndex(index);
}
else {
SpeciesReference produ = new SpeciesReference();
changedProducts.add(produ);
produ.setSpecies((String) productSpecies.getSelectedItem());
if (stoiciLabel.getSelectedItem().equals("Stoichiometry")) {
produ.setStoichiometry(val);
}
else {
StoichiometryMath sm = new StoichiometryMath(myParseFormula(productStoiciometry
.getText().trim()));
produ.setStoichiometryMath(sm);
}
JList add = new JList();
Object[] adding = { prod };
add.setListData(adding);
add.setSelectedIndex(0);
products.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(product, products, add, false, null, null, null, null, null, null,
biosim.frame());
product = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
product[i] = (String) adding[i];
}
sort(product);
products.setListData(product);
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
products.setSelectedIndex(0);
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), productsPanel, "Products Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit modifiers or create new ones.
*/
public void modifiersEditor(String option) {
if (option.equals("OK") && modifiers.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No modifier selected.",
"Must Select A Modifier", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel modifiersPanel = new JPanel(new GridLayout(1, 2));
JLabel speciesLabel = new JLabel("Species:");
ListOf listOfSpecies = document.getModel().getListOfSpecies();
String[] speciesList = new String[(int) document.getModel().getNumSpecies()];
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
speciesList[i] = ((Species) listOfSpecies.get(i)).getId();
}
sort(speciesList);
Object[] choices = speciesList;
modifierSpecies = new JComboBox(choices);
if (option.equals("OK")) {
String v = ((String) modifiers.getSelectedValue()).split(" ")[0];
ModifierSpeciesReference modifier = null;
for (ModifierSpeciesReference p : changedModifiers) {
if (p.getSpecies().equals(v)) {
modifier = p;
}
}
modifierSpecies.setSelectedItem(modifier.getSpecies());
}
modifiersPanel.add(speciesLabel);
modifiersPanel.add(modifierSpecies);
if (choices.length == 0) {
JOptionPane.showMessageDialog(biosim.frame(),
"There are no species availiable to be modifiers."
+ "\nAdd species to this sbml file first.", "No Species", JOptionPane.ERROR_MESSAGE);
return;
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), modifiersPanel, "Modifiers Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
String mod = (String) modifierSpecies.getSelectedItem();
if (option.equals("OK")) {
int index = modifiers.getSelectedIndex();
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modifier = Buttons.getList(modifier, modifiers);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
modifiers.setSelectedIndex(index);
for (int i = 0; i < modifier.length; i++) {
if (i != index) {
if (modifier[i].equals(modifierSpecies.getSelectedItem())) {
error = true;
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to add species as a modifier.\n"
+ "Each species can only be used as a modifier once.",
"Species Can Only Be Used Once", JOptionPane.ERROR_MESSAGE);
}
}
}
if (!error) {
String v = ((String) modifiers.getSelectedValue());
ModifierSpeciesReference modi = null;
for (ModifierSpeciesReference p : changedModifiers) {
if (p.getSpecies().equals(v)) {
modi = p;
}
}
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modifier = Buttons.getList(modifier, modifiers);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
modi.setSpecies((String) modifierSpecies.getSelectedItem());
modifier[index] = mod;
sort(modifier);
modifiers.setListData(modifier);
modifiers.setSelectedIndex(index);
}
}
else {
int index = modifiers.getSelectedIndex();
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modifier = Buttons.getList(modifier, modifiers);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
modifiers.setSelectedIndex(index);
for (int i = 0; i < modifier.length; i++) {
if (modifier[i].equals(modifierSpecies.getSelectedItem())) {
error = true;
JOptionPane.showMessageDialog(biosim.frame(), "Unable to add species as a modifier.\n"
+ "Each species can only be used as a modifier once.",
"Species Can Only Be Used Once", JOptionPane.ERROR_MESSAGE);
}
}
if (!error) {
ModifierSpeciesReference modi = new ModifierSpeciesReference();
changedModifiers.add(modi);
modi.setSpecies((String) modifierSpecies.getSelectedItem());
JList add = new JList();
Object[] adding = { mod };
add.setListData(adding);
add.setSelectedIndex(0);
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(modifier, modifiers, add, false, null, null, null, null, null, null,
biosim.frame());
modifier = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
modifier[i] = (String) adding[i];
}
sort(modifier);
modifiers.setListData(modifier);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
try {
if (document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]).getNumModifiers() == 1) {
modifiers.setSelectedIndex(0);
}
else {
modifiers.setSelectedIndex(index);
}
}
catch (Exception e2) {
modifiers.setSelectedIndex(0);
}
}
}
change = true;
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), modifiersPanel, "Modifiers Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit reactants or create new ones.
*/
public void reactantsEditor(String option) {
if (option.equals("OK") && reactants.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No reactant selected.",
"Must Select A Reactant", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel reactantsPanel = new JPanel(new GridLayout(2, 2));
JLabel speciesLabel = new JLabel("Species:");
Object[] stoiciOptions = { "Stoichiometry", "Stoichiometry Math" };
stoiciLabel = new JComboBox(stoiciOptions);
ListOf listOfSpecies = document.getModel().getListOfSpecies();
String[] speciesList = new String[(int) document.getModel().getNumSpecies()];
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
speciesList[i] = ((Species) listOfSpecies.get(i)).getId();
}
sort(speciesList);
reactantSpecies = new JComboBox();
for (int i = 0; i < speciesList.length; i++) {
Species species = document.getModel().getSpecies(speciesList[i]);
if (species.getBoundaryCondition()
|| (!species.getConstant() && keepVar("", speciesList[i], false, true, false, false))) {
reactantSpecies.addItem(speciesList[i]);
}
}
reactantStoiciometry = new JTextField("1");
if (option.equals("OK")) {
String v = ((String) reactants.getSelectedValue()).split(" ")[0];
SpeciesReference reactant = null;
for (SpeciesReference r : changedReactants) {
if (r.getSpecies().equals(v)) {
reactant = r;
}
}
reactantSpecies.setSelectedItem(reactant.getSpecies());
if (reactant.isSetStoichiometryMath()) {
stoiciLabel.setSelectedItem("Stoichiometry Math");
reactantStoiciometry.setText(""
+ myFormulaToString(reactant.getStoichiometryMath().getMath()));
}
else {
reactantStoiciometry.setText("" + reactant.getStoichiometry());
}
}
reactantsPanel.add(speciesLabel);
reactantsPanel.add(reactantSpecies);
reactantsPanel.add(stoiciLabel);
reactantsPanel.add(reactantStoiciometry);
if (speciesList.length == 0) {
JOptionPane.showMessageDialog(biosim.frame(),
"There are no species availiable to be reactants."
+ "\nAdd species to this sbml file first.", "No Species", JOptionPane.ERROR_MESSAGE);
return;
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), reactantsPanel, "Reactants Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
String react;
double val = 1.0;
if (stoiciLabel.getSelectedItem().equals("Stoichiometry")) {
try {
val = Double.parseDouble(reactantStoiciometry.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "The stoichiometry must be a real number.",
"Enter A Valid Value", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (val <= 0) {
JOptionPane.showMessageDialog(biosim.frame(),
"The stoichiometry value must be greater than 0.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
}
react = reactantSpecies.getSelectedItem() + " " + val;
}
else {
react = reactantSpecies.getSelectedItem() + " " + reactantStoiciometry.getText().trim();
}
int index = -1;
if (!error) {
if (option.equals("OK")) {
index = reactants.getSelectedIndex();
}
reactants.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacta = Buttons.getList(reacta, reactants);
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index >= 0) {
reactants.setSelectedIndex(index);
}
for (int i = 0; i < reacta.length; i++) {
if (i != index) {
if (reacta[i].split(" ")[0].equals(reactantSpecies.getSelectedItem())) {
error = true;
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to add species as a reactant.\n"
+ "Each species can only be used as a reactant once.",
"Species Can Only Be Used Once", JOptionPane.ERROR_MESSAGE);
}
}
}
}
if (!error) {
if (stoiciLabel.getSelectedItem().equals("Stoichiometry Math")) {
if (reactantStoiciometry.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "Stoichiometry math must have formula.",
"Enter Stoichiometry Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (myParseFormula(reactantStoiciometry.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Stoichiometry formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariables(reactantStoiciometry.getText()
.trim(), true, "", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Stoiciometry math contains unknown variables.\n\n"
+ "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Stoiciometry Math Error",
JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = checkNumFunctionArguments(myParseFormula(reactantStoiciometry.getText()
.trim()));
}
if (!error) {
if (myParseFormula(reactantStoiciometry.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Stoichiometry math must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
}
}
if (!error) {
if (option.equals("OK")) {
String v = ((String) reactants.getSelectedValue()).split(" ")[0];
SpeciesReference reactan = null;
for (SpeciesReference r : changedReactants) {
if (r.getSpecies().equals(v)) {
reactan = r;
}
}
reactants.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacta = Buttons.getList(reacta, reactants);
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reactan.setSpecies((String) reactantSpecies.getSelectedItem());
if (stoiciLabel.getSelectedItem().equals("Stoichiometry")) {
reactan.setStoichiometry(val);
reactan.unsetStoichiometryMath();
}
else {
StoichiometryMath sm = new StoichiometryMath(myParseFormula(reactantStoiciometry
.getText().trim()));
reactan.setStoichiometryMath(sm);
reactan.setStoichiometry(1);
}
reacta[index] = react;
sort(reacta);
reactants.setListData(reacta);
reactants.setSelectedIndex(index);
}
else {
SpeciesReference reactan = new SpeciesReference();
changedReactants.add(reactan);
reactan.setSpecies((String) reactantSpecies.getSelectedItem());
if (stoiciLabel.getSelectedItem().equals("Stoichiometry")) {
reactan.setStoichiometry(val);
}
else {
StoichiometryMath sm = new StoichiometryMath(myParseFormula(reactantStoiciometry
.getText().trim()));
reactan.setStoichiometryMath(sm);
}
JList add = new JList();
Object[] adding = { react };
add.setListData(adding);
add.setSelectedIndex(0);
reactants.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(reacta, reactants, add, false, null, null, null, null, null, null,
biosim.frame());
reacta = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
reacta[i] = (String) adding[i];
}
sort(reacta);
reactants.setListData(reacta);
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reactants.setSelectedIndex(0);
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), reactantsPanel, "Reactants Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Invoked when the mouse is double clicked in one of the JLists. Opens the
* editor for the selected item.
*/
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
if (e.getSource() == compartments) {
if (!paramsOnly) {
compartEditor("OK");
}
}
else if (e.getSource() == functions) {
functionEditor("OK");
}
else if (e.getSource() == unitDefs) {
unitEditor("OK");
}
else if (e.getSource() == compTypes) {
compTypeEditor("OK");
}
else if (e.getSource() == specTypes) {
specTypeEditor("OK");
}
else if (e.getSource() == initAssigns) {
initEditor("OK");
}
else if (e.getSource() == rules) {
ruleEditor("OK");
}
else if (e.getSource() == events) {
eventEditor("OK");
}
else if (e.getSource() == constraints) {
constraintEditor("OK");
}
else if (e.getSource() == species) {
speciesEditor("OK");
}
else if (e.getSource() == reactions) {
reactionsEditor("OK");
}
else if (e.getSource() == parameters) {
parametersEditor("OK");
}
else if (e.getSource() == reacParameters) {
reacParametersEditor("OK");
}
else if (e.getSource() == reactants) {
if (!paramsOnly) {
reactantsEditor("OK");
}
}
else if (e.getSource() == products) {
if (!paramsOnly) {
productsEditor("OK");
}
}
else if (e.getSource() == modifiers) {
if (!paramsOnly) {
modifiersEditor("OK");
}
}
}
}
/**
* This method currently does nothing.
*/
public void mousePressed(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseReleased(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseExited(MouseEvent e) {
}
public boolean hasChanged() {
return change;
}
public void setChanged(boolean change) {
this.change = change;
}
/**
* Sorting function
*/
private void sort(String[] sort) {
int i, j;
String index;
for (i = 1; i < sort.length; i++) {
index = sort[i];
j = i;
while ((j > 0) && sort[j - 1].compareToIgnoreCase(index) > 0) {
sort[j] = sort[j - 1];
j = j - 1;
}
sort[j] = index;
}
}
/**
* Create the SBML file
*/
public void createSBML(String direct) {
try {
FileOutputStream out = new FileOutputStream(new File(paramFile));
out.write((refFile + "\n").getBytes());
for (String s : parameterChanges) {
out.write((s + "\n").getBytes());
}
out.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to save parameter file.",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
try {
if (!direct.equals(".")) {
String[] d = direct.split("_");
ArrayList<String> dd = new ArrayList<String>();
for (int i = 0; i < d.length; i++) {
if (!d[i].contains("=")) {
String di = d[i];
while (!d[i].contains("=")) {
i++;
di += "_" + d[i];
}
dd.add(di);
}
else {
dd.add(d[i]);
}
}
for (String di : dd) {
if (di.contains("/")) {
KineticLaw KL = document.getModel().getReaction(di.split("=")[0].split("/")[0])
.getKineticLaw();
ListOf p = KL.getListOfParameters();
for (int i = 0; i < KL.getNumParameters(); i++) {
Parameter param = ((Parameter) p.get(i));
if (param.getId().equals(di.split("=")[0].split("/")[1])) {
param.setValue(Double.parseDouble(di.split("=")[1]));
}
}
}
else {
if (document.getModel().getParameter(di.split("=")[0]) != null) {
document.getModel().getParameter(di.split("=")[0]).setValue(
Double.parseDouble(di.split("=")[1]));
}
else {
if (document.getModel().getSpecies(di.split("=")[0]).isSetInitialAmount()) {
document.getModel().getSpecies(di.split("=")[0]).setInitialAmount(
Double.parseDouble(di.split("=")[1]));
}
else {
document.getModel().getSpecies(di.split("=")[0]).setInitialConcentration(
Double.parseDouble(di.split("=")[1]));
}
}
}
}
}
direct = direct.replace("/", "-");
FileOutputStream out = new FileOutputStream(new File(simDir + separator + direct + separator
+ file.split(separator)[file.split(separator).length - 1]));
document.getModel().setName(modelName.getText().trim());
SBMLWriter writer = new SBMLWriter();
String doc = writer.writeToString(document);
byte[] output = doc.getBytes();
out.write(output);
out.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to create sbml file.",
"Error Creating File", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Checks consistency of the sbml file.
*/
public void checkOverDetermined() {
document.setConsistencyChecks(libsbml.LIBSBML_CAT_GENERAL_CONSISTENCY, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_IDENTIFIER_CONSISTENCY, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_UNITS_CONSISTENCY, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_MATHML_CONSISTENCY, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_SBO_CONSISTENCY, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_MODELING_PRACTICE, false);
long numErrors = document.checkConsistency();
String message = "";
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage(); // .replace(". ",".\n");
message += i + ":" + error + "\n";
}
if (numErrors > 0) {
JOptionPane.showMessageDialog(biosim.frame(), "Algebraic rules make model overdetermined.",
"Model is Overdetermined", JOptionPane.WARNING_MESSAGE);
}
}
/**
* Checks consistency of the sbml file.
*/
public void check() {
// Hack to avoid wierd bug.
// By reloading the file before consistency checks, it seems to avoid a
// crash when attempting to save a newly added parameter with no units
SBMLReader reader = new SBMLReader();
document = reader.readSBML(file);
long numErrors = document.checkConsistency();
String message = "";
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage(); // .replace(". ",".\n");
message += i + ":" + error + "\n";
}
if (numErrors > 0) {
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scroll, "SBML Errors and Warnings",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* Saves the sbml file.
*/
public void save(boolean run) {
if (paramsOnly) {
if (run) {
ArrayList<String> sweepThese1 = new ArrayList<String>();
ArrayList<ArrayList<Double>> sweep1 = new ArrayList<ArrayList<Double>>();
ArrayList<String> sweepThese2 = new ArrayList<String>();
ArrayList<ArrayList<Double>> sweep2 = new ArrayList<ArrayList<Double>>();
for (String s : parameterChanges) {
if (s.split(" ")[s.split(" ").length - 2].equals("Sweep")) {
if ((s.split(" ")[s.split(" ").length - 1]).split(",")[3].replace(")", "").trim()
.equals("1")) {
sweepThese1.add(s.split(" ")[0]);
double start = Double
.parseDouble((s.split(" ")[s.split(" ").length - 1]).split(",")[0].substring(1)
.trim());
double stop = Double
.parseDouble((s.split(" ")[s.split(" ").length - 1]).split(",")[1].trim());
double step = Double
.parseDouble((s.split(" ")[s.split(" ").length - 1]).split(",")[2].trim());
ArrayList<Double> add = new ArrayList<Double>();
for (double i = start; i <= stop; i += step) {
add.add(i);
}
sweep1.add(add);
}
else {
sweepThese2.add(s.split(" ")[0]);
double start = Double
.parseDouble((s.split(" ")[s.split(" ").length - 1]).split(",")[0].substring(1)
.trim());
double stop = Double
.parseDouble((s.split(" ")[s.split(" ").length - 1]).split(",")[1].trim());
double step = Double
.parseDouble((s.split(" ")[s.split(" ").length - 1]).split(",")[2].trim());
ArrayList<Double> add = new ArrayList<Double>();
for (double i = start; i <= stop; i += step) {
add.add(i);
}
sweep2.add(add);
}
}
}
if (sweepThese1.size() > 0) {
int max = 0;
for (ArrayList<Double> d : sweep1) {
max = Math.max(max, d.size());
}
for (int j = 0; j < max; j++) {
String sweep = "";
for (int i = 0; i < sweepThese1.size(); i++) {
int k = j;
if (k >= sweep1.get(i).size()) {
k = sweep1.get(i).size() - 1;
}
if (sweep.equals("")) {
sweep += sweepThese1.get(i) + "=" + sweep1.get(i).get(k);
}
else {
sweep += "_" + sweepThese1.get(i) + "=" + sweep1.get(i).get(k);
}
}
if (sweepThese2.size() > 0) {
int max2 = 0;
for (ArrayList<Double> d : sweep2) {
max2 = Math.max(max2, d.size());
}
for (int l = 0; l < max2; l++) {
String sweepTwo = sweep;
for (int i = 0; i < sweepThese2.size(); i++) {
int k = l;
if (k >= sweep2.get(i).size()) {
k = sweep2.get(i).size() - 1;
}
if (sweepTwo.equals("")) {
sweepTwo += sweepThese2.get(i) + "=" + sweep2.get(i).get(k);
}
else {
sweepTwo += "_" + sweepThese2.get(i) + "=" + sweep2.get(i).get(k);
}
}
new File(simDir + separator + sweepTwo.replace("/", "-")).mkdir();
createSBML(sweepTwo);
new Reb2SacThread(reb2sac).start(sweepTwo.replace("/", "-"));
reb2sac.emptyFrames();
}
}
else {
new File(simDir + separator + sweep.replace("/", "-")).mkdir();
createSBML(sweep);
new Reb2SacThread(reb2sac).start(sweep.replace("/", "-"));
reb2sac.emptyFrames();
}
}
}
else {
createSBML(".");
new Reb2SacThread(reb2sac).start(".");
reb2sac.emptyFrames();
}
}
else {
createSBML(".");
}
change = false;
}
else {
try {
log.addText("Saving sbml file:\n" + file + "\n");
FileOutputStream out = new FileOutputStream(new File(file));
document.getModel().setName(modelName.getText().trim());
SBMLWriter writer = new SBMLWriter();
String doc = writer.writeToString(document);
byte[] output = doc.getBytes();
out.write(output);
out.close();
change = false;
if (paramsOnly) {
reb2sac.updateSpeciesList();
}
biosim.updateViews(file.split(separator)[file.split(separator).length - 1]);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to save sbml file.",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
}
}
public void updateSBML(int tab, int tab2) {
SBML_Editor sbml = new SBML_Editor(file, reb2sac, log, biosim, simDir, paramFile);
((JTabbedPane) (biosim.getTab().getComponentAt(tab))).setComponentAt(tab2, sbml);
reb2sac.setSbml(sbml);
((JTabbedPane) (biosim.getTab().getComponentAt(tab))).getComponentAt(tab2).setName(
"SBML Editor");
}
/**
* Set the file name
*/
public void setFile(String newFile) {
file = newFile;
}
/**
* Set the model ID
*/
public void setModelID(String modelID) {
this.modelID.setText(modelID);
document.getModel().setId(modelID);
}
/**
* Convert ASTNodes into a string
*/
public String myFormulaToString(ASTNode mathFormula) {
String formula = libsbml.formulaToString(mathFormula);
formula = formula.replaceAll("arccot", "acot");
formula = formula.replaceAll("arccoth", "acoth");
formula = formula.replaceAll("arccsc", "acsc");
formula = formula.replaceAll("arccsch", "acsch");
formula = formula.replaceAll("arcsec", "asec");
formula = formula.replaceAll("arcsech", "asech");
formula = formula.replaceAll("arccosh", "acosh");
formula = formula.replaceAll("arcsinh", "asinh");
formula = formula.replaceAll("arctanh", "atanh");
String newformula = formula.replaceFirst("00e", "0e");
while (!(newformula.equals(formula))) {
formula = newformula;
newformula = formula.replaceFirst("0e\\+", "e+");
newformula = newformula.replaceFirst("0e-", "e-");
}
formula = formula.replaceFirst("\\.e\\+", ".0e+");
formula = formula.replaceFirst("\\.e-", ".0e-");
return formula;
}
/**
* Convert String into ASTNodes
*/
public ASTNode myParseFormula(String formula) {
ASTNode mathFormula = libsbml.parseFormula(formula);
if (mathFormula == null)
return null;
setTimeAndTrigVar(mathFormula);
return mathFormula;
}
/**
* Recursive function to set time and trig functions
*/
public void setTimeAndTrigVar(ASTNode node) {
if (node.getType() == libsbml.AST_NAME) {
if (node.getName().equals("t")) {
node.setType(libsbml.AST_NAME_TIME);
}
}
if (node.getType() == libsbml.AST_FUNCTION) {
if (node.getName().equals("acot")) {
node.setType(libsbml.AST_FUNCTION_ARCCOT);
}
else if (node.getName().equals("acoth")) {
node.setType(libsbml.AST_FUNCTION_ARCCOTH);
}
else if (node.getName().equals("acsc")) {
node.setType(libsbml.AST_FUNCTION_ARCCSC);
}
else if (node.getName().equals("acsch")) {
node.setType(libsbml.AST_FUNCTION_ARCCSCH);
}
else if (node.getName().equals("asec")) {
node.setType(libsbml.AST_FUNCTION_ARCSEC);
}
else if (node.getName().equals("asech")) {
node.setType(libsbml.AST_FUNCTION_ARCSECH);
}
else if (node.getName().equals("acosh")) {
node.setType(libsbml.AST_FUNCTION_ARCCOSH);
}
else if (node.getName().equals("asinh")) {
node.setType(libsbml.AST_FUNCTION_ARCSINH);
}
else if (node.getName().equals("atanh")) {
node.setType(libsbml.AST_FUNCTION_ARCTANH);
}
}
for (int c = 0; c < node.getNumChildren(); c++)
setTimeAndTrigVar(node.getChild(c));
}
/**
* Check the number of arguments to a function
*/
public boolean checkNumFunctionArguments(ASTNode node) {
ListOf sbml = document.getModel().getListOfFunctionDefinitions();
switch (node.getType()) {
case libsbml.AST_FUNCTION_ABS:
case libsbml.AST_FUNCTION_ARCCOS:
case libsbml.AST_FUNCTION_ARCCOSH:
case libsbml.AST_FUNCTION_ARCSIN:
case libsbml.AST_FUNCTION_ARCSINH:
case libsbml.AST_FUNCTION_ARCTAN:
case libsbml.AST_FUNCTION_ARCTANH:
case libsbml.AST_FUNCTION_ARCCOT:
case libsbml.AST_FUNCTION_ARCCOTH:
case libsbml.AST_FUNCTION_ARCCSC:
case libsbml.AST_FUNCTION_ARCCSCH:
case libsbml.AST_FUNCTION_ARCSEC:
case libsbml.AST_FUNCTION_ARCSECH:
case libsbml.AST_FUNCTION_COS:
case libsbml.AST_FUNCTION_COSH:
case libsbml.AST_FUNCTION_SIN:
case libsbml.AST_FUNCTION_SINH:
case libsbml.AST_FUNCTION_TAN:
case libsbml.AST_FUNCTION_TANH:
case libsbml.AST_FUNCTION_COT:
case libsbml.AST_FUNCTION_COTH:
case libsbml.AST_FUNCTION_CSC:
case libsbml.AST_FUNCTION_CSCH:
case libsbml.AST_FUNCTION_SEC:
case libsbml.AST_FUNCTION_SECH:
case libsbml.AST_FUNCTION_CEILING:
case libsbml.AST_FUNCTION_FACTORIAL:
case libsbml.AST_FUNCTION_EXP:
case libsbml.AST_FUNCTION_FLOOR:
case libsbml.AST_FUNCTION_LN:
case libsbml.AST_FUNCTION_LOG:
if (node.getNumChildren() != 1) {
JOptionPane.showMessageDialog(biosim.frame(), "Expected 1 argument for " + node.getName()
+ " but found " + node.getNumChildren() + ".", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(), "Argument for " + node.getName()
+ " function must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_LOGICAL_NOT:
if (node.getNumChildren() != 1) {
JOptionPane.showMessageDialog(biosim.frame(), "Expected 1 argument for " + node.getName()
+ " but found " + node.getNumChildren() + ".", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (!node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument for not function must be of type Boolean.", "Boolean Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_LOGICAL_AND:
case libsbml.AST_LOGICAL_OR:
case libsbml.AST_LOGICAL_XOR:
if (node.getNumChildren() != 2) {
JOptionPane.showMessageDialog(biosim.frame(), "Expected 2 arguments for " + node.getName()
+ " but found " + node.getNumChildren() + ".", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (!node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(), "Argument 1 for " + node.getName()
+ " function is not of type Boolean.", "Boolean Expected", JOptionPane.ERROR_MESSAGE);
return true;
}
if (!node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(), "Argument 2 for " + node.getName()
+ " function is not of type Boolean.", "Boolean Expected", JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_PLUS:
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 1 for + operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 2 for + operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_MINUS:
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 1 for - operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 2 for - operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_TIMES:
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 1 for * operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 2 for * operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_DIVIDE:
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 1 for / operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 2 for / operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_POWER:
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 1 for ^ operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 2 for ^ operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_FUNCTION_DELAY:
case libsbml.AST_FUNCTION_POWER:
case libsbml.AST_FUNCTION_ROOT:
case libsbml.AST_RELATIONAL_GEQ:
case libsbml.AST_RELATIONAL_LEQ:
case libsbml.AST_RELATIONAL_LT:
case libsbml.AST_RELATIONAL_GT:
if (node.getNumChildren() != 2) {
JOptionPane.showMessageDialog(biosim.frame(), "Expected 2 arguments for " + node.getName()
+ " but found " + node.getNumChildren() + ".", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(), "Argument 1 for " + node.getName()
+ " function must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(), "Argument 2 for " + node.getName()
+ " function must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_RELATIONAL_EQ:
case libsbml.AST_RELATIONAL_NEQ:
if (node.getNumChildren() != 2) {
JOptionPane.showMessageDialog(biosim.frame(), "Expected 2 arguments for " + node.getName()
+ " but found " + node.getNumChildren() + ".", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
if ((node.getChild(0).isBoolean() && !node.getChild(1).isBoolean())
|| (!node.getChild(0).isBoolean() && node.getChild(1).isBoolean())) {
JOptionPane.showMessageDialog(biosim.frame(), "Arguments for " + node.getName()
+ " function must either both be numbers or Booleans.", "Argument Mismatch",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_FUNCTION_PIECEWISE:
if (node.getNumChildren() < 1) {
JOptionPane.showMessageDialog(biosim.frame(),
"Piecewise function requires at least 1 argument.", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
for (int i = 1; i < node.getNumChildren(); i += 2) {
if (!node.getChild(i).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Even arguments of piecewise function must be of type Boolean.", "Boolean Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
int pieceType = -1;
for (int i = 0; i < node.getNumChildren(); i += 2) {
if (node.getChild(i).isBoolean()) {
if (pieceType == 2) {
JOptionPane.showMessageDialog(biosim.frame(),
"All odd arguments of a piecewise function must agree.", "Type Mismatch",
JOptionPane.ERROR_MESSAGE);
return true;
}
pieceType = 1;
}
else {
if (pieceType == 1) {
JOptionPane.showMessageDialog(biosim.frame(),
"All odd arguments of a piecewise function must agree.", "Type Mismatch",
JOptionPane.ERROR_MESSAGE);
return true;
}
pieceType = 2;
}
}
case libsbml.AST_FUNCTION:
for (int i = 0; i < document.getModel().getNumFunctionDefinitions(); i++) {
if (((FunctionDefinition) sbml.get(i)).getId().equals(node.getName())) {
long numArgs = ((FunctionDefinition) sbml.get(i)).getNumArguments();
if (numArgs != node.getNumChildren()) {
JOptionPane.showMessageDialog(biosim.frame(), "Expected " + numArgs
+ " argument(s) for " + node.getName() + " but found " + node.getNumChildren()
+ ".", "Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE);
return true;
}
break;
}
}
break;
case libsbml.AST_NAME:
if (node.getName().equals("abs") || node.getName().equals("arccos")
|| node.getName().equals("arccosh") || node.getName().equals("arcsin")
|| node.getName().equals("arcsinh") || node.getName().equals("arctan")
|| node.getName().equals("arctanh") || node.getName().equals("arccot")
|| node.getName().equals("arccoth") || node.getName().equals("arccsc")
|| node.getName().equals("arccsch") || node.getName().equals("arcsec")
|| node.getName().equals("arcsech") || node.getName().equals("acos")
|| node.getName().equals("acosh") || node.getName().equals("asin")
|| node.getName().equals("asinh") || node.getName().equals("atan")
|| node.getName().equals("atanh") || node.getName().equals("acot")
|| node.getName().equals("acoth") || node.getName().equals("acsc")
|| node.getName().equals("acsch") || node.getName().equals("asec")
|| node.getName().equals("asech") || node.getName().equals("cos")
|| node.getName().equals("cosh") || node.getName().equals("cot")
|| node.getName().equals("coth") || node.getName().equals("csc")
|| node.getName().equals("csch") || node.getName().equals("ceil")
|| node.getName().equals("factorial") || node.getName().equals("exp")
|| node.getName().equals("floor") || node.getName().equals("ln")
|| node.getName().equals("log") || node.getName().equals("sqr")
|| node.getName().equals("log10") || node.getName().equals("sqrt")
|| node.getName().equals("sec") || node.getName().equals("sech")
|| node.getName().equals("sin") || node.getName().equals("sinh")
|| node.getName().equals("tan") || node.getName().equals("tanh")
|| node.getName().equals("not")) {
JOptionPane.showMessageDialog(biosim.frame(), "Expected 1 argument for " + node.getName()
+ " but found 0.", "Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getName().equals("and") || node.getName().equals("or")
|| node.getName().equals("xor") || node.getName().equals("pow")
|| node.getName().equals("eq") || node.getName().equals("geq")
|| node.getName().equals("leq") || node.getName().equals("gt")
|| node.getName().equals("neq") || node.getName().equals("lt")
|| node.getName().equals("delay") || node.getName().equals("root")) {
JOptionPane.showMessageDialog(biosim.frame(), "Expected 2 arguments for " + node.getName()
+ " but found 0.", "Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getName().equals("piecewise")) {
JOptionPane.showMessageDialog(biosim.frame(),
"Piecewise function requires at least 1 argument.", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
for (int i = 0; i < document.getModel().getNumFunctionDefinitions(); i++) {
if (((FunctionDefinition) sbml.get(i)).getId().equals(node.getName())) {
long numArgs = ((FunctionDefinition) sbml.get(i)).getNumArguments();
JOptionPane.showMessageDialog(biosim.frame(), "Expected " + numArgs + " argument(s) for "
+ node.getName() + " but found 0.", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
break;
}
for (int c = 0; c < node.getNumChildren(); c++) {
if (checkNumFunctionArguments(node.getChild(c))) {
return true;
}
}
return false;
}
/**
* Check the units of a rate rule
*/
public boolean checkRateRuleUnits(Rule rule) {
document.getModel().populateListFormulaUnitsData();
if (rule.containsUndeclaredUnits()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Rate rule contains literals numbers or parameters with undeclared units.\n"
+ "Therefore, it is not possible to completely verify the consistency of the units.",
"Contains Undeclared Units", JOptionPane.WARNING_MESSAGE);
return false;
}
else {
UnitDefinition unitDef = rule.getDerivedUnitDefinition();
UnitDefinition unitDefVar;
Species species = document.getModel().getSpecies(rule.getVariable());
Compartment compartment = document.getModel().getCompartment(rule.getVariable());
Parameter parameter = document.getModel().getParameter(rule.getVariable());
if (species != null) {
unitDefVar = species.getDerivedUnitDefinition();
}
else if (compartment != null) {
unitDefVar = compartment.getDerivedUnitDefinition();
}
else {
unitDefVar = parameter.getDerivedUnitDefinition();
}
if (document.getModel().getUnitDefinition("time") != null) {
UnitDefinition timeUnitDef = document.getModel().getUnitDefinition("time");
for (int i = 0; i < timeUnitDef.getNumUnits(); i++) {
Unit timeUnit = timeUnitDef.getUnit(i);
Unit recTimeUnit = new Unit(timeUnit.getKind(), timeUnit.getExponent() * (-1), timeUnit
.getScale(), timeUnit.getMultiplier());
unitDefVar.addUnit(recTimeUnit);
}
}
else {
Unit unit = new Unit("second", -1, 0, 1.0);
unitDefVar.addUnit(unit);
}
if (!UnitDefinition.areEquivalent(unitDef, unitDefVar)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Units on the left and right-hand side of the rate rule do not agree.",
"Units Do Not Match", JOptionPane.ERROR_MESSAGE);
return true;
}
}
return false;
}
/**
* Check the units of an assignment rule
*/
public boolean checkAssignmentRuleUnits(Rule rule) {
document.getModel().populateListFormulaUnitsData();
if (rule.containsUndeclaredUnits()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Assignment rule contains literals numbers or parameters with undeclared units.\n"
+ "Therefore, it is not possible to completely verify the consistency of the units.",
"Contains Undeclared Units", JOptionPane.WARNING_MESSAGE);
return false;
}
else {
UnitDefinition unitDef = rule.getDerivedUnitDefinition();
UnitDefinition unitDefVar;
Species species = document.getModel().getSpecies(rule.getVariable());
Compartment compartment = document.getModel().getCompartment(rule.getVariable());
Parameter parameter = document.getModel().getParameter(rule.getVariable());
if (species != null) {
unitDefVar = species.getDerivedUnitDefinition();
}
else if (compartment != null) {
unitDefVar = compartment.getDerivedUnitDefinition();
}
else {
unitDefVar = parameter.getDerivedUnitDefinition();
}
if (!UnitDefinition.areEquivalent(unitDef, unitDefVar)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Units on the left and right-hand side of the assignment rule do not agree.",
"Units Do Not Match", JOptionPane.ERROR_MESSAGE);
return true;
}
}
return false;
}
/**
* Check the units of an initial assignment
*/
public boolean checkInitialAssignmentUnits(InitialAssignment init) {
document.getModel().populateListFormulaUnitsData();
if (init.containsUndeclaredUnits()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Initial assignment contains literals numbers or parameters with undeclared units.\n"
+ "Therefore, it is not possible to completely verify the consistency of the units.",
"Contains Undeclared Units", JOptionPane.WARNING_MESSAGE);
return false;
}
else {
UnitDefinition unitDef = init.getDerivedUnitDefinition();
UnitDefinition unitDefVar;
Species species = document.getModel().getSpecies(init.getSymbol());
Compartment compartment = document.getModel().getCompartment(init.getSymbol());
Parameter parameter = document.getModel().getParameter(init.getSymbol());
if (species != null) {
unitDefVar = species.getDerivedUnitDefinition();
}
else if (compartment != null) {
unitDefVar = compartment.getDerivedUnitDefinition();
}
else {
unitDefVar = parameter.getDerivedUnitDefinition();
}
if (!UnitDefinition.areEquivalent(unitDef, unitDefVar)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Units on the left and right-hand side of the initial assignment do not agree.",
"Units Do Not Match", JOptionPane.ERROR_MESSAGE);
return true;
}
// for (int i = 0; i < unitDef.getNumUnits(); i++) {
// Unit unit = unitDef.getUnit(i);
// System.out.println(unit.getKind() + " Exp = " + unit.getExponent() + "
// Mult = " + unit.getMultiplier() + " Scale = " + unit.getScale());
// }
// for (int i = 0; i < unitDefVar.getNumUnits(); i++) {
// Unit unit = unitDefVar.getUnit(i);
// System.out.println(unit.getKind() + " Exp = " + unit.getExponent() + "
// Mult = " + unit.getMultiplier() + " Scale = " + unit.getScale());
// }
}
return false;
}
/**
* Check the units of an event assignment
*/
public boolean checkEventAssignmentUnits(EventAssignment assign) {
document.getModel().populateListFormulaUnitsData();
if (assign.containsUndeclaredUnits()) {
JOptionPane.showMessageDialog(biosim.frame(), "Event assignment to " + assign.getVariable()
+ " contains literals numbers or parameters with undeclared units.\n"
+ "Therefore, it is not possible to completely verify the consistency of the units.",
"Contains Undeclared Units", JOptionPane.WARNING_MESSAGE);
return false;
}
else {
UnitDefinition unitDef = assign.getDerivedUnitDefinition();
UnitDefinition unitDefVar;
Species species = document.getModel().getSpecies(assign.getVariable());
Compartment compartment = document.getModel().getCompartment(assign.getVariable());
Parameter parameter = document.getModel().getParameter(assign.getVariable());
if (species != null) {
unitDefVar = species.getDerivedUnitDefinition();
}
else if (compartment != null) {
unitDefVar = compartment.getDerivedUnitDefinition();
}
else {
unitDefVar = parameter.getDerivedUnitDefinition();
}
if (!UnitDefinition.areEquivalent(unitDef, unitDefVar)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Units on the left and right-hand side for the event assignment "
+ assign.getVariable() + " do not agree.", "Units Do Not Match",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
return false;
}
/**
* Check the units of an event delay
*/
public boolean checkEventDelayUnits(Delay delay) {
// document.getModel().populateListFormulaUnitsData();
// System.out.println(myFormulaToString(delay.getMath()));
// if (delay.containsUndeclaredUnits()) {
// JOptionPane.showMessageDialog(biosim.frame(), "Event assignment delay contains literals numbers or parameters with undeclared units.\n" +
// "Therefore, it is not possible to completely verify the consistency of the units.",
// "Contains Undeclared Units", JOptionPane.WARNING_MESSAGE);
// return false;
// } else {
// UnitDefinition unitDef = delay.getDerivedUnitDefinition();
// /* NEED TO CHECK IT AGAINST TIME HERE */
// }
return false;
}
/**
* Check the units of a kinetic law
*/
public boolean checkKineticLawUnits(KineticLaw law) {
document.getModel().populateListFormulaUnitsData();
if (law.containsUndeclaredUnits()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Kinetic law contains literals numbers or parameters with undeclared units.\n"
+ "Therefore, it is not possible to completely verify the consistency of the units.",
"Contains Undeclared Units", JOptionPane.WARNING_MESSAGE);
return false;
}
else {
UnitDefinition unitDef = law.getDerivedUnitDefinition();
UnitDefinition unitDefLaw = new UnitDefinition();
if (document.getModel().getUnitDefinition("substance") != null) {
UnitDefinition subUnitDef = document.getModel().getUnitDefinition("substance");
for (int i = 0; i < subUnitDef.getNumUnits(); i++) {
Unit subUnit = subUnitDef.getUnit(i);
unitDefLaw.addUnit(subUnit);
}
}
else {
Unit unit = new Unit("mole", 1, 0, 1.0);
unitDefLaw.addUnit(unit);
}
if (document.getModel().getUnitDefinition("time") != null) {
UnitDefinition timeUnitDef = document.getModel().getUnitDefinition("time");
for (int i = 0; i < timeUnitDef.getNumUnits(); i++) {
Unit timeUnit = timeUnitDef.getUnit(i);
Unit recTimeUnit = new Unit(timeUnit.getKind(), timeUnit.getExponent() * (-1), timeUnit
.getScale(), timeUnit.getMultiplier());
unitDefLaw.addUnit(recTimeUnit);
}
}
else {
Unit unit = new Unit("second", -1, 0, 1.0);
unitDefLaw.addUnit(unit);
}
if (!UnitDefinition.areEquivalent(unitDef, unitDefLaw)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Kinetic law units should be substance / time.", "Units Do Not Match",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
return false;
}
}
| gui/src/sbmleditor/SBML_Editor.java | package sbmleditor;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.regex.*;
import javax.swing.*;
import org.sbml.libsbml.*;
import biomodelsim.*;
import reb2sac.*;
import buttons.*;
/**
* This is the SBML_Editor class. It takes in an sbml file and allows the user
* to edit it by changing different fields displayed in a frame. It also
* implements the ActionListener class, the MouseListener class, and the
* KeyListener class which allows it to perform certain actions when buttons are
* clicked on the frame, when one of the JList's items is double clicked, or
* when text is entered into the model's ID.
*
* @author Curtis Madsen
*/
public class SBML_Editor extends JPanel implements ActionListener, MouseListener {
private static final long serialVersionUID = 8236967001410906807L;
private SBMLDocument document; // sbml document
private String file; // SBML file
/*
* compartment buttons
*/
private JButton addCompart, removeCompart, editCompart;
private JButton addFunction, removeFunction, editFunction;
private JButton addUnit, removeUnit, editUnit;
private JButton addList, removeList, editList;
private JButton addCompType, removeCompType, editCompType;
private JButton addSpecType, removeSpecType, editSpecType;
private JButton addInit, removeInit, editInit;
private JButton addRule, removeRule, editRule;
private JButton addEvent, removeEvent, editEvent;
private JButton addAssignment, removeAssignment, editAssignment;
private JButton addConstraint, removeConstraint, editConstraint;
private String[] comps; // array of compartments
private String[] funcs; // array of functions
private String[] units; // array of units
private String[] uList; // unit list array
private String[] cpTyp; // array of compartment types
private String[] spTyp; // array of species types
private String[] inits; // array of initial assignments
private String[] rul; // array of rules
private String[] ev; // array of events
private String[] assign; // array of event assignments
private String[] origAssign; // array of original event assignments
private String[] cons; // array of constraints
private JList compartments; // JList of compartments
private JList functions; // JList of functions
private JList unitDefs; // JList of units
private JList unitList; // unit JList
private JList compTypes; // JList of compartment types
private JList specTypes; // JList of species types
private JList initAssigns; // JList of initial assignments
private JList rules; // JList of rules
private JList events; // JList of events
private JList eventAssign; // JList of event assignments
private JList constraints; // JList of constraints
private JTextField compID, compSize, compName; // compartment fields;
private JTextField funcID, funcName, eqn, args; // function fields;
private JTextField unitID, unitName; // unit defn fields;
private JTextField exp, scale, mult; // unit list fields;
private JTextField compTypeID, compTypeName; // compartment type fields;
private JTextField specTypeID, specTypeName; // species type fields;
private JComboBox initVar; // init fields;
private JTextField initMath; // init fields;
private JComboBox ruleType, ruleVar; // rule fields;
private JTextField ruleMath; // rule fields;
private JTextField eventID, eventName, eventTrigger, eventDelay; // event
// fields;
private JComboBox eaID; // event assignment fields;
private JTextField consID, consMath, consMessage; // constraints fields;
private JButton addSpec, removeSpec, editSpec; // species buttons
private String[] specs; // array of species
private JList species; // JList of species
private JTextField ID, init, Name; // species text fields
private JComboBox compUnits, compOutside, compConstant; // compartment units
// combo box
private JComboBox compTypeBox, dimBox; // compartment type combo box
private JComboBox specTypeBox, specBoundary, specConstant; // species combo
// boxes
private JComboBox specUnits, initLabel, stoiciLabel;
private JComboBox comp; // compartment combo box
private boolean change; // determines if any changes were made
private JTextField modelID; // the model's ID
private JTextField modelName; // the model's Name
private JList reactions; // JList of reactions
private String[] reacts; // array of reactions
/*
* reactions buttons
*/
private JButton addReac, removeReac, editReac, copyReac;
private JList parameters; // JList of parameters
private String[] params; // array of parameters
private JButton addParam, removeParam, editParam; // parameters buttons
/*
* parameters text fields
*/
private JTextField paramID, paramName, paramValue;
private JComboBox paramUnits;
private JComboBox paramConst;
private JList reacParameters; // JList of reaction parameters
private String[] reacParams; // array of reaction parameters
/*
* reaction parameters buttons
*/
private JButton reacAddParam, reacRemoveParam, reacEditParam;
/*
* reaction parameters text fields
*/
private JTextField reacParamID, reacParamValue, reacParamName;
private JComboBox reacParamUnits;
private ArrayList<Parameter> changedParameters; // ArrayList of parameters
private JTextField reacID, reacName; // reaction name and id text
// fields
private JComboBox reacReverse, reacFast; // reaction reversible, fast combo
// boxes
/*
* reactant buttons
*/
private JButton addReactant, removeReactant, editReactant;
private JList reactants; // JList for reactants
private String[] reacta; // array for reactants
/*
* ArrayList of reactants
*/
private ArrayList<SpeciesReference> changedReactants;
/*
* product buttons
*/
private JButton addProduct, removeProduct, editProduct;
private JList products; // JList for products
private String[] product; // array for products
/*
* ArrayList of products
*/
private ArrayList<SpeciesReference> changedProducts;
/*
* modifier buttons
*/
private JButton addModifier, removeModifier, editModifier;
private JList modifiers; // JList for modifiers
private String[] modifier; // array for modifiers
/*
* ArrayList of modifiers
*/
private ArrayList<ModifierSpeciesReference> changedModifiers;
private JComboBox productSpecies; // ComboBox for product editing
private JComboBox modifierSpecies; // ComboBox for modifier editing
private JTextField productStoiciometry; // text field for editing products
private JComboBox reactantSpecies; // ComboBox for reactant editing
/*
* text field for editing reactants
*/
private JTextField reactantStoiciometry;
private JTextArea kineticLaw; // text area for editing kinetic law
private Reb2Sac reb2sac; // reb2sac options
private JButton saveNoRun, run, saveAs, check; // save and run buttons
private Log log;
private ArrayList<String> usedIDs;
private ArrayList<String> thisReactionParams;
private BioSim biosim;
private JButton useMassAction, clearKineticLaw;
private String separator;
private boolean paramsOnly;
private String simDir;
private String paramFile;
private ArrayList<String> parameterChanges;
private Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*");
private boolean editComp = false;
private String refFile;
/**
* Creates a new SBML_Editor and sets up the frame where the user can edit a
* new sbml file.
*/
public SBML_Editor(Reb2Sac reb2sac, Log log, BioSim biosim, String simDir, String paramFile) {
this.reb2sac = reb2sac;
paramsOnly = (reb2sac != null);
this.log = log;
this.biosim = biosim;
this.simDir = simDir;
this.paramFile = paramFile;
if (paramFile != null) {
try {
Scanner scan = new Scanner(new File(paramFile));
if (scan.hasNextLine()) {
refFile = scan.nextLine();
}
scan.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to read parameter file.", "Error",
JOptionPane.ERROR_MESSAGE);
refFile = "";
}
}
createSbmlFrame("");
}
/**
* Creates a new SBML_Editor and sets up the frame where the user can edit the
* sbml file given to this constructor.
*/
public SBML_Editor(String file, Reb2Sac reb2sac, Log log, BioSim biosim, String simDir,
String paramFile) {
this.reb2sac = reb2sac;
paramsOnly = (reb2sac != null);
this.log = log;
this.biosim = biosim;
this.simDir = simDir;
this.paramFile = paramFile;
if (paramFile != null) {
try {
Scanner scan = new Scanner(new File(paramFile));
if (scan.hasNextLine()) {
refFile = scan.nextLine();
}
scan.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to read parameter file.", "Error",
JOptionPane.ERROR_MESSAGE);
refFile = file;
}
}
createSbmlFrame(file);
}
/**
* Private helper method that helps create the sbml frame.
*/
private void createSbmlFrame(String file) {
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
// intitializes the member variables
if (!file.equals("")) {
this.file = file;
}
else {
this.file = null;
}
// creates the sbml reader and reads the sbml file
Model model;
if (!file.equals("")) {
SBMLReader reader = new SBMLReader();
document = reader.readSBML(file);
model = document.getModel();
modelName = new JTextField(model.getName(), 50);
if (model.getId().equals("")) {
String modelID = file.split(separator)[file.split(separator).length - 1];
if (modelID.indexOf('.') >= 0) {
modelID = modelID.substring(0, modelID.indexOf('.'));
}
model.setId(modelID);
save(false);
}
}
else {
document = new SBMLDocument();
model = document.createModel();
}
document.setLevelAndVersion(2, 3);
usedIDs = new ArrayList<String>();
if (model.isSetId()) {
usedIDs.add(model.getId());
}
ListOf ids = model.getListOfFunctionDefinitions();
for (int i = 0; i < model.getNumFunctionDefinitions(); i++) {
usedIDs.add(((FunctionDefinition) ids.get(i)).getId());
}
ids = model.getListOfUnitDefinitions();
for (int i = 0; i < model.getNumUnitDefinitions(); i++) {
usedIDs.add(((UnitDefinition) ids.get(i)).getId());
}
ids = model.getListOfCompartmentTypes();
for (int i = 0; i < model.getNumCompartmentTypes(); i++) {
usedIDs.add(((CompartmentType) ids.get(i)).getId());
}
ids = model.getListOfSpeciesTypes();
for (int i = 0; i < model.getNumSpeciesTypes(); i++) {
usedIDs.add(((SpeciesType) ids.get(i)).getId());
}
ids = model.getListOfCompartments();
for (int i = 0; i < model.getNumCompartments(); i++) {
usedIDs.add(((Compartment) ids.get(i)).getId());
}
ids = model.getListOfParameters();
for (int i = 0; i < model.getNumParameters(); i++) {
usedIDs.add(((Parameter) ids.get(i)).getId());
}
ids = model.getListOfReactions();
for (int i = 0; i < model.getNumReactions(); i++) {
usedIDs.add(((Reaction) ids.get(i)).getId());
}
ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
usedIDs.add(((Species) ids.get(i)).getId());
}
ids = model.getListOfConstraints();
for (int i = 0; i < model.getNumConstraints(); i++) {
usedIDs.add(((Constraint) ids.get(i)).getMetaId());
}
// sets up the compartments editor
JPanel comp = new JPanel(new BorderLayout());
JPanel addRemComp = new JPanel();
addCompart = new JButton("Add Compartment");
removeCompart = new JButton("Remove Compartment");
editCompart = new JButton("Edit Compartment");
addRemComp.add(addCompart);
addRemComp.add(removeCompart);
addRemComp.add(editCompart);
addCompart.addActionListener(this);
removeCompart.addActionListener(this);
editCompart.addActionListener(this);
if (paramsOnly) {
parameterChanges = new ArrayList<String>();
try {
Scanner scan = new Scanner(new File(paramFile));
if (scan.hasNextLine()) {
scan.nextLine();
}
while (scan.hasNextLine()) {
parameterChanges.add(scan.nextLine());
}
scan.close();
}
catch (Exception e) {
}
addCompart.setEnabled(false);
removeCompart.setEnabled(false);
}
JLabel compartmentsLabel = new JLabel("List of Compartments:");
compartments = new JList();
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(260, 220));
scroll.setPreferredSize(new Dimension(276, 152));
scroll.setViewportView(compartments);
ListOf listOfCompartments = model.getListOfCompartments();
comps = new String[(int) model.getNumCompartments()];
for (int i = 0; i < model.getNumCompartments(); i++) {
Compartment compartment = (Compartment) listOfCompartments.get(i);
if (compartment.isSetCompartmentType()) {
comps[i] = compartment.getId() + " " + compartment.getCompartmentType();
}
else {
comps[i] = compartment.getId();
}
if (compartment.isSetSize()) {
comps[i] += " " + compartment.getSize();
}
if (compartment.isSetUnits()) {
comps[i] += " " + compartment.getUnits();
}
if (paramsOnly) {
for (int j = 0; j < parameterChanges.size(); j++) {
if (parameterChanges.get(j).split(" ")[0].equals(compartment.getId())) {
String[] splits = parameterChanges.get(j).split(" ");
if (splits[splits.length - 2].equals("Custom")) {
String value = splits[splits.length - 1];
compartment.setSize(Double.parseDouble(value));
comps[i] += " " + splits[splits.length - 2] + " " + splits[splits.length - 1];
}
else if (splits[splits.length - 2].equals("Sweep")) {
String value = splits[splits.length - 1];
compartment.setSize(Double.parseDouble(value.split(",")[0].substring(1).trim()));
comps[i] += " " + splits[splits.length - 2] + " " + splits[splits.length - 1];
}
}
}
}
}
sort(comps);
compartments.setListData(comps);
compartments.addMouseListener(this);
comp.add(compartmentsLabel, "North");
comp.add(scroll, "Center");
comp.add(addRemComp, "South");
// sets up the species editor
JPanel spec = new JPanel(new BorderLayout());
JPanel addSpecs = new JPanel();
addSpec = new JButton("Add Species");
removeSpec = new JButton("Remove Species");
editSpec = new JButton("Edit Species");
addSpecs.add(addSpec);
addSpecs.add(removeSpec);
addSpecs.add(editSpec);
addSpec.addActionListener(this);
removeSpec.addActionListener(this);
editSpec.addActionListener(this);
if (paramsOnly) {
addSpec.setEnabled(false);
removeSpec.setEnabled(false);
}
JLabel speciesLabel = new JLabel("List of Species:");
species = new JList();
species.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll1 = new JScrollPane();
scroll1.setMinimumSize(new Dimension(260, 220));
scroll1.setPreferredSize(new Dimension(276, 152));
scroll1.setViewportView(species);
ListOf listOfSpecies = model.getListOfSpecies();
specs = new String[(int) model.getNumSpecies()];
for (int i = 0; i < model.getNumSpecies(); i++) {
Species species = (Species) listOfSpecies.get(i);
if (species.isSetSpeciesType()) {
specs[i] = species.getId() + " " + species.getSpeciesType() + " "
+ species.getCompartment();
}
else {
specs[i] = species.getId() + " " + species.getCompartment();
}
if (species.isSetInitialAmount()) {
specs[i] += " " + species.getInitialAmount();
}
else {
specs[i] += " " + species.getInitialConcentration();
}
if (species.isSetUnits()) {
specs[i] += " " + species.getUnits();
}
if (paramsOnly) {
for (int j = 0; j < parameterChanges.size(); j++) {
if (parameterChanges.get(j).split(" ")[0].equals(species.getId())) {
String[] splits = parameterChanges.get(j).split(" ");
if (splits[splits.length - 2].equals("Custom")) {
String value = splits[splits.length - 1];
if (species.isSetInitialAmount()) {
species.setInitialAmount(Double.parseDouble(value));
}
else {
species.setInitialConcentration(Double.parseDouble(value));
}
specs[i] += " " + splits[splits.length - 2] + " " + splits[splits.length - 1];
}
else if (splits[splits.length - 2].equals("Sweep")) {
String value = splits[splits.length - 1];
if (species.isSetInitialAmount()) {
species.setInitialAmount(Double
.parseDouble(value.split(",")[0].substring(1).trim()));
}
else {
species.setInitialConcentration(Double.parseDouble(value.split(",")[0].substring(1)
.trim()));
}
specs[i] += " " + splits[splits.length - 2] + " " + splits[splits.length - 1];
}
}
}
}
}
sort(specs);
species.setListData(specs);
species.setSelectedIndex(0);
species.addMouseListener(this);
spec.add(speciesLabel, "North");
spec.add(scroll1, "Center");
spec.add(addSpecs, "South");
// sets up the reactions editor
JPanel reac = new JPanel(new BorderLayout());
JPanel addReacs = new JPanel();
addReac = new JButton("Add Reaction");
removeReac = new JButton("Remove Reaction");
editReac = new JButton("Edit Reaction");
copyReac = new JButton("Copy Reaction");
addReacs.add(addReac);
addReacs.add(removeReac);
addReacs.add(editReac);
addReacs.add(copyReac);
addReac.addActionListener(this);
removeReac.addActionListener(this);
editReac.addActionListener(this);
copyReac.addActionListener(this);
if (paramsOnly) {
addReac.setEnabled(false);
removeReac.setEnabled(false);
copyReac.setEnabled(false);
}
JLabel reactionsLabel = new JLabel("List of Reactions:");
reactions = new JList();
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll2 = new JScrollPane();
scroll2.setMinimumSize(new Dimension(400, 220));
scroll2.setPreferredSize(new Dimension(436, 152));
scroll2.setViewportView(reactions);
ListOf listOfReactions = model.getListOfReactions();
reacts = new String[(int) model.getNumReactions()];
for (int i = 0; i < model.getNumReactions(); i++) {
Reaction reaction = (Reaction) listOfReactions.get(i);
reacts[i] = reaction.getId();
if (paramsOnly) {
ListOf params = reaction.getKineticLaw().getListOfParameters();
for (int j = 0; j < reaction.getKineticLaw().getNumParameters(); j++) {
Parameter paramet = ((Parameter) (params.get(j)));
for (int k = 0; k < parameterChanges.size(); k++) {
if (parameterChanges.get(k).split(" ")[0].equals(reaction.getId() + "/"
+ paramet.getId())) {
String[] splits = parameterChanges.get(k).split(" ");
if (splits[splits.length - 2].equals("Custom")) {
String value = splits[splits.length - 1];
paramet.setValue(Double.parseDouble(value));
}
else if (splits[splits.length - 2].equals("Sweep")) {
String value = splits[splits.length - 1];
paramet.setValue(Double.parseDouble(value.split(",")[0].substring(1).trim()));
}
if (!reacts[i].contains("Modified")) {
reacts[i] += " Modified";
}
}
}
}
}
}
sort(reacts);
reactions.setListData(reacts);
reactions.setSelectedIndex(0);
reactions.addMouseListener(this);
reac.add(reactionsLabel, "North");
reac.add(scroll2, "Center");
reac.add(addReacs, "South");
// sets up the parameters editor
JPanel param = new JPanel(new BorderLayout());
JPanel addParams = new JPanel();
addParam = new JButton("Add Parameter");
removeParam = new JButton("Remove Parameter");
editParam = new JButton("Edit Parameter");
addParams.add(addParam);
addParams.add(removeParam);
addParams.add(editParam);
addParam.addActionListener(this);
removeParam.addActionListener(this);
editParam.addActionListener(this);
if (paramsOnly) {
addParam.setEnabled(false);
removeParam.setEnabled(false);
}
JLabel parametersLabel = new JLabel("List of Global Parameters:");
parameters = new JList();
parameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll3 = new JScrollPane();
scroll3.setMinimumSize(new Dimension(260, 220));
scroll3.setPreferredSize(new Dimension(276, 152));
scroll3.setViewportView(parameters);
ListOf listOfParameters = model.getListOfParameters();
params = new String[(int) model.getNumParameters()];
for (int i = 0; i < model.getNumParameters(); i++) {
Parameter parameter = (Parameter) listOfParameters.get(i);
if (parameter.isSetUnits()) {
params[i] = parameter.getId() + " " + parameter.getValue() + " " + parameter.getUnits();
}
else {
params[i] = parameter.getId() + " " + parameter.getValue();
}
if (paramsOnly) {
for (int j = 0; j < parameterChanges.size(); j++) {
if (parameterChanges.get(j).split(" ")[0].equals(parameter.getId())) {
String[] splits = parameterChanges.get(j).split(" ");
if (splits[splits.length - 2].equals("Custom")) {
String value = splits[splits.length - 1];
parameter.setValue(Double.parseDouble(value));
params[i] += " " + splits[splits.length - 2] + " " + splits[splits.length - 1];
}
else if (splits[splits.length - 2].equals("Sweep")) {
String value = splits[splits.length - 1];
parameter.setValue(Double.parseDouble(value.split(",")[0].substring(1).trim()));
params[i] += " " + splits[splits.length - 2] + " " + splits[splits.length - 1];
}
}
}
}
}
sort(params);
parameters.setListData(params);
parameters.setSelectedIndex(0);
parameters.addMouseListener(this);
param.add(parametersLabel, "North");
param.add(scroll3, "Center");
param.add(addParams, "South");
// adds the main panel to the frame and displays it
JPanel mainPanelNorth = new JPanel();
JPanel mainPanelCenter = new JPanel(new BorderLayout());
JPanel mainPanelCenterUp = new JPanel();
JPanel mainPanelCenterDown = new JPanel();
mainPanelCenterUp.add(comp);
mainPanelCenterUp.add(spec);
mainPanelCenterDown.add(reac);
mainPanelCenterDown.add(param);
mainPanelCenter.add(mainPanelCenterUp, "North");
mainPanelCenter.add(mainPanelCenterDown, "South");
modelID = new JTextField(model.getId(), 16);
modelName = new JTextField(model.getName(), 50);
JLabel modelIDLabel = new JLabel("Model ID:");
JLabel modelNameLabel = new JLabel("Model Name:");
modelID.setEditable(false);
mainPanelNorth.add(modelIDLabel);
mainPanelNorth.add(modelID);
mainPanelNorth.add(modelNameLabel);
mainPanelNorth.add(modelName);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setLayout(new BorderLayout());
mainPanel.add(mainPanelNorth, "North");
mainPanel.add(mainPanelCenter, "Center");
JPanel defnPanel = createDefnFrame(model);
JPanel rulesPanel = createRuleFrame(model);
if (!paramsOnly) {
JTabbedPane tab = new JTabbedPane();
tab.addTab("Main Elements", mainPanel);
tab.addTab("Definitions/Types", defnPanel);
tab.addTab("Initial Assignments/Rules/Constraints/Events", rulesPanel);
this.add(tab, "Center");
}
else {
this.add(mainPanel, "Center");
}
change = false;
if (paramsOnly) {
saveNoRun = new JButton("Save Parameters");
run = new JButton("Save And Run");
saveNoRun.setMnemonic(KeyEvent.VK_S);
run.setMnemonic(KeyEvent.VK_R);
saveNoRun.addActionListener(this);
run.addActionListener(this);
JPanel saveRun = new JPanel();
saveRun.add(saveNoRun);
saveRun.add(run);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, saveRun, null);
splitPane.setDividerSize(0);
this.add(splitPane, "South");
}
else {
check = new JButton("Save and Check SBML");
check.setMnemonic(KeyEvent.VK_C);
check.addActionListener(this);
saveNoRun = new JButton("Save SBML");
saveAs = new JButton("Save As");
saveNoRun.setMnemonic(KeyEvent.VK_S);
saveAs.setMnemonic(KeyEvent.VK_A);
saveNoRun.addActionListener(this);
saveAs.addActionListener(this);
JPanel saveRun = new JPanel();
saveRun.add(saveNoRun);
saveRun.add(check);
saveRun.add(saveAs);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, saveRun, null);
splitPane.setDividerSize(0);
this.add(splitPane, "South");
}
}
/**
* Private helper method to create definitions/types frame.
*/
private JPanel createDefnFrame(Model model) {
/* Create function definition panel */
addFunction = new JButton("Add Function");
removeFunction = new JButton("Remove Function");
editFunction = new JButton("Edit Function");
functions = new JList();
ListOf listOfFunctions = model.getListOfFunctionDefinitions();
funcs = new String[(int) model.getNumFunctionDefinitions()];
for (int i = 0; i < model.getNumFunctionDefinitions(); i++) {
FunctionDefinition function = (FunctionDefinition) listOfFunctions.get(i);
funcs[i] = function.getId() + " ( ";
for (long j = 0; j < function.getNumArguments(); j++) {
if (j != 0) {
funcs[i] += ", ";
}
funcs[i] += myFormulaToString(function.getArgument(j));
}
if (function.isSetMath()) {
funcs[i] += " ) = " + myFormulaToString(function.getBody());
}
}
String[] oldFuncs = funcs;
try {
funcs = sortFunctions(funcs);
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in function definitions.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
funcs = oldFuncs;
}
JPanel funcdefnPanel = createPanel(model, "Function Definitions", functions, funcs,
addFunction, removeFunction, editFunction);
/* Create unit definition panel */
addUnit = new JButton("Add Unit");
removeUnit = new JButton("Remove Unit");
editUnit = new JButton("Edit Unit");
unitDefs = new JList();
ListOf listOfUnits = model.getListOfUnitDefinitions();
units = new String[(int) model.getNumUnitDefinitions()];
for (int i = 0; i < model.getNumUnitDefinitions(); i++) {
UnitDefinition unit = (UnitDefinition) listOfUnits.get(i);
units[i] = unit.getId();
// GET OTHER THINGS
}
JPanel unitdefnPanel = createPanel(model, "Unit Definitions", unitDefs, units, addUnit,
removeUnit, editUnit);
/* Create compartment type panel */
addCompType = new JButton("Add Type");
removeCompType = new JButton("Remove Type");
editCompType = new JButton("Edit Type");
compTypes = new JList();
ListOf listOfCompartmentTypes = model.getListOfCompartmentTypes();
cpTyp = new String[(int) model.getNumCompartmentTypes()];
for (int i = 0; i < model.getNumCompartmentTypes(); i++) {
CompartmentType compType = (CompartmentType) listOfCompartmentTypes.get(i);
cpTyp[i] = compType.getId();
}
JPanel compTypePanel = createPanel(model, "Compartment Types", compTypes, cpTyp, addCompType,
removeCompType, editCompType);
/* Create species type panel */
addSpecType = new JButton("Add Type");
removeSpecType = new JButton("Remove Type");
editSpecType = new JButton("Edit Type");
specTypes = new JList();
ListOf listOfSpeciesTypes = model.getListOfSpeciesTypes();
spTyp = new String[(int) model.getNumSpeciesTypes()];
for (int i = 0; i < model.getNumSpeciesTypes(); i++) {
SpeciesType specType = (SpeciesType) listOfSpeciesTypes.get(i);
spTyp[i] = specType.getId();
}
JPanel specTypePanel = createPanel(model, "Species Types", specTypes, spTyp, addSpecType,
removeSpecType, editSpecType);
JPanel defnPanelNorth = new JPanel();
JPanel defnPanelSouth = new JPanel();
JPanel defnPanel = new JPanel(new BorderLayout());
defnPanelNorth.add(funcdefnPanel);
defnPanelNorth.add(unitdefnPanel);
defnPanelSouth.add(compTypePanel);
defnPanelSouth.add(specTypePanel);
defnPanel.add(defnPanelNorth, "North");
defnPanel.add(defnPanelSouth, "South");
return defnPanel;
}
/**
* Private helper method to create rules/events/constraints frame.
*/
private JPanel createRuleFrame(Model model) {
/* Create initial assignment panel */
addInit = new JButton("Add Initial");
removeInit = new JButton("Remove Initial");
editInit = new JButton("Edit Initial");
initAssigns = new JList();
ListOf listOfInits = model.getListOfInitialAssignments();
inits = new String[(int) model.getNumInitialAssignments()];
for (int i = 0; i < model.getNumInitialAssignments(); i++) {
InitialAssignment init = (InitialAssignment) listOfInits.get(i);
inits[i] = init.getSymbol() + " = " + myFormulaToString(init.getMath());
}
String[] oldInits = inits;
boolean cycle = false;
try {
inits = sortInitRules(inits);
}
catch (Exception e) {
cycle = true;
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in initial assignments.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
inits = oldInits;
}
JPanel initPanel = createPanel(model, "Initial Assignments", initAssigns, inits, addInit,
removeInit, editInit);
/* Create rule panel */
addRule = new JButton("Add Rule");
removeRule = new JButton("Remove Rule");
editRule = new JButton("Edit Rule");
rules = new JList();
ListOf listOfRules = model.getListOfRules();
rul = new String[(int) model.getNumRules()];
for (int i = 0; i < model.getNumRules(); i++) {
Rule rule = (Rule) listOfRules.get(i);
if (rule.isAlgebraic()) {
rul[i] = "0 = " + myFormulaToString(rule.getMath());
}
else if (rule.isAssignment()) {
rul[i] = rule.getVariable() + " = " + myFormulaToString(rule.getMath());
}
else {
rul[i] = "d( " + rule.getVariable() + " )/dt = " + myFormulaToString(rule.getMath());
}
}
String[] oldRul = rul;
try {
rul = sortRules(rul);
}
catch (Exception e) {
cycle = true;
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in assignments.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
rul = oldRul;
}
if (!cycle && checkCycles(inits, rul)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected within initial assignments and assignment rules.", "Cycle Detected",
JOptionPane.ERROR_MESSAGE);
}
JPanel rulePanel = createPanel(model, "Rules", rules, rul, addRule, removeRule, editRule);
/* Create constraint panel */
addConstraint = new JButton("Add Constraint");
removeConstraint = new JButton("Remove Constraint");
editConstraint = new JButton("Edit Constraint");
constraints = new JList();
ListOf listOfConstraints = model.getListOfConstraints();
cons = new String[(int) model.getNumConstraints()];
for (int i = 0; i < model.getNumConstraints(); i++) {
Constraint constraint = (Constraint) listOfConstraints.get(i);
cons[i] = myFormulaToString(constraint.getMath());
}
JPanel constraintPanel = createPanel(model, "Constraints", constraints, cons, addConstraint,
removeConstraint, editConstraint);
/* Create event panel */
addEvent = new JButton("Add Event");
removeEvent = new JButton("Remove Event");
editEvent = new JButton("Edit Event");
events = new JList();
ListOf listOfEvents = model.getListOfEvents();
ev = new String[(int) model.getNumEvents()];
for (int i = 0; i < model.getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) listOfEvents.get(i);
ev[i] = myFormulaToString(event.getTrigger().getMath());
}
JPanel eventPanel = createPanel(model, "Events", events, ev, addEvent, removeEvent, editEvent);
JPanel recPanelNorth = new JPanel();
JPanel recPanelSouth = new JPanel();
JPanel recPanel = new JPanel(new BorderLayout());
recPanelNorth.add(initPanel);
recPanelNorth.add(rulePanel);
recPanelSouth.add(constraintPanel);
recPanelSouth.add(eventPanel);
recPanel.add(recPanelNorth, "North");
recPanel.add(recPanelSouth, "South");
return recPanel;
}
/* Create add/remove/edit panel */
private JPanel createPanel(Model model, String panelName, JList panelJList, String[] panelList,
JButton addButton, JButton removeButton, JButton editButton) {
JPanel Panel = new JPanel(new BorderLayout());
JPanel addRem = new JPanel();
addRem.add(addButton);
addRem.add(removeButton);
addRem.add(editButton);
addButton.addActionListener(this);
removeButton.addActionListener(this);
editButton.addActionListener(this);
JLabel panelLabel = new JLabel("List of " + panelName + ":");
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(260, 220));
scroll.setPreferredSize(new Dimension(276, 152));
scroll.setViewportView(panelJList);
if (!panelName.equals("Rules") && !panelName.equals("Function Definitions")
&& !panelName.equals("Initial Assignments")) {
sort(panelList);
}
panelJList.setListData(panelList);
panelJList.addMouseListener(this);
Panel.add(panelLabel, "North");
Panel.add(scroll, "Center");
Panel.add(addRem, "South");
return Panel;
}
/**
* This method performs different functions depending on what buttons are
* pushed and what input fields contain data.
*/
public void actionPerformed(ActionEvent e) {
// if the run button is clicked
if (e.getSource() == run) {
reb2sac.getRunButton().doClick();
}
// if the check button is clicked
else if (e.getSource() == check) {
save(false);
check();
}
// if the save button is clicked
else if (e.getSource() == saveNoRun) {
if (paramsOnly) {
reb2sac.getSaveButton().doClick();
}
else {
save(false);
}
}
// if the save as button is clicked
else if (e.getSource() == saveAs) {
saveAs();
}
// if the add function button is clicked
else if (e.getSource() == addFunction) {
functionEditor("Add");
}
// if the edit function button is clicked
else if (e.getSource() == editFunction) {
functionEditor("OK");
}
// if the remove function button is clicked
else if (e.getSource() == removeFunction) {
removeFunction();
}
// if the add unit button is clicked
else if (e.getSource() == addUnit) {
unitEditor("Add");
}
// if the edit unit button is clicked
else if (e.getSource() == editUnit) {
unitEditor("OK");
}
// if the remove unit button is clicked
else if (e.getSource() == removeUnit) {
removeUnit();
}
// if the add to unit list button is clicked
else if (e.getSource() == addList) {
unitListEditor("Add");
}
// if the edit unit list button is clicked
else if (e.getSource() == editList) {
unitListEditor("OK");
}
// if the remove from unit list button is clicked
else if (e.getSource() == removeList) {
removeList();
}
// if the add compartment type button is clicked
else if (e.getSource() == addCompType) {
compTypeEditor("Add");
}
// if the edit compartment type button is clicked
else if (e.getSource() == editCompType) {
compTypeEditor("OK");
}
// if the remove compartment type button is clicked
else if (e.getSource() == removeCompType) {
removeCompType();
}
// if the add species type button is clicked
else if (e.getSource() == addSpecType) {
specTypeEditor("Add");
}
// if the edit species type button is clicked
else if (e.getSource() == editSpecType) {
specTypeEditor("OK");
}
// if the remove species type button is clicked
else if (e.getSource() == removeSpecType) {
removeSpecType();
}
// if the add init button is clicked
else if (e.getSource() == addInit) {
initEditor("Add");
}
// if the edit init button is clicked
else if (e.getSource() == editInit) {
initEditor("OK");
}
// if the remove rule button is clicked
else if (e.getSource() == removeInit) {
removeInit();
}
// if the add rule button is clicked
else if (e.getSource() == addRule) {
ruleEditor("Add");
}
// if the edit rule button is clicked
else if (e.getSource() == editRule) {
ruleEditor("OK");
}
// if the remove rule button is clicked
else if (e.getSource() == removeRule) {
removeRule();
}
// if the add event button is clicked
else if (e.getSource() == addEvent) {
eventEditor("Add");
}
// if the edit event button is clicked
else if (e.getSource() == editEvent) {
eventEditor("OK");
}
// if the remove event button is clicked
else if (e.getSource() == removeEvent) {
removeEvent();
}
// if the add event assignment button is clicked
else if (e.getSource() == addAssignment) {
eventAssignEditor("Add");
}
// if the edit event assignment button is clicked
else if (e.getSource() == editAssignment) {
eventAssignEditor("OK");
}
// if the remove event assignment button is clicked
else if (e.getSource() == removeAssignment) {
removeAssignment();
}
// if the add constraint button is clicked
else if (e.getSource() == addConstraint) {
constraintEditor("Add");
}
// if the edit constraint button is clicked
else if (e.getSource() == editConstraint) {
constraintEditor("OK");
}
// if the remove constraint button is clicked
else if (e.getSource() == removeConstraint) {
removeConstraint();
}
// if the add comparment button is clicked
else if (e.getSource() == addCompart) {
compartEditor("Add");
}
// if the edit comparment button is clicked
else if (e.getSource() == editCompart) {
compartEditor("OK");
}
// if the remove compartment button is clicked
else if (e.getSource() == removeCompart) {
removeCompartment();
}
// if the add species button is clicked
else if (e.getSource() == addSpec) {
speciesEditor("Add");
}
// if the edit species button is clicked
else if (e.getSource() == editSpec) {
speciesEditor("OK");
}
// if the remove species button is clicked
else if (e.getSource() == removeSpec) {
removeSpecies();
}
// if the add reactions button is clicked
else if (e.getSource() == addReac) {
reactionsEditor("Add");
}
// if the edit reactions button is clicked
else if (e.getSource() == editReac) {
reactionsEditor("OK");
}
// if the copy reactions button is clicked
else if (e.getSource() == copyReac) {
copyReaction();
}
// if the remove reactions button is clicked
else if (e.getSource() == removeReac) {
removeReaction();
}
// if the add parameters button is clicked
else if (e.getSource() == addParam) {
parametersEditor("Add");
}
// if the edit parameters button is clicked
else if (e.getSource() == editParam) {
parametersEditor("OK");
}
// if the remove parameters button is clicked
else if (e.getSource() == removeParam) {
removeParameter();
}
// if the add reactions parameters button is clicked
else if (e.getSource() == reacAddParam) {
reacParametersEditor("Add");
}
// if the edit reactions parameters button is clicked
else if (e.getSource() == reacEditParam) {
reacParametersEditor("OK");
}
// if the remove reactions parameters button is clicked
else if (e.getSource() == reacRemoveParam) {
reacRemoveParam();
}
// if the add reactants button is clicked
else if (e.getSource() == addReactant) {
reactantsEditor("Add");
}
// if the edit reactants button is clicked
else if (e.getSource() == editReactant) {
reactantsEditor("OK");
}
// if the remove reactants button is clicked
else if (e.getSource() == removeReactant) {
removeReactant();
}
// if the add products button is clicked
else if (e.getSource() == addProduct) {
productsEditor("Add");
}
// if the edit products button is clicked
else if (e.getSource() == editProduct) {
productsEditor("OK");
}
// if the remove products button is clicked
else if (e.getSource() == removeProduct) {
removeProduct();
}
// if the add modifiers button is clicked
else if (e.getSource() == addModifier) {
modifiersEditor("Add");
}
// if the edit modifiers button is clicked
else if (e.getSource() == editModifier) {
modifiersEditor("OK");
}
// if the remove modifiers button is clicked
else if (e.getSource() == removeModifier) {
removeModifier();
}
// if the clear button is clicked
else if (e.getSource() == clearKineticLaw) {
kineticLaw.setText("");
change = true;
}
// if the use mass action button is clicked
else if (e.getSource() == useMassAction) {
useMassAction();
}
}
/**
* Remove a unit from list
*/
private void removeList() {
if (unitDefs.getSelectedIndex() != -1) {
UnitDefinition tempUnit = document.getModel().getUnitDefinition(
((String) unitDefs.getSelectedValue()).split(" ")[0]);
if (unitList.getSelectedIndex() != -1) {
String selected = (String) unitList.getSelectedValue();
ListOf u = tempUnit.getListOfUnits();
for (int i = 0; i < tempUnit.getNumUnits(); i++) {
if (selected.contains(unitToString(tempUnit.getUnit(i)))) {
u.remove(i);
}
}
}
unitList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
uList = (String[]) Buttons.remove(unitList, uList);
unitList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
unitList.setSelectedIndex(0);
change = true;
}
}
/**
* Remove a unit
*/
private void removeUnit() {
if (unitDefs.getSelectedIndex() != -1) {
if (!unitsInUse(((String) unitDefs.getSelectedValue()).split(" ")[0])) {
UnitDefinition tempUnit = document.getModel().getUnitDefinition(
((String) unitDefs.getSelectedValue()).split(" ")[0]);
ListOf u = document.getModel().getListOfUnitDefinitions();
for (int i = 0; i < document.getModel().getNumUnitDefinitions(); i++) {
if (((UnitDefinition) u.get(i)).getId().equals(tempUnit.getId())) {
u.remove(i);
}
}
usedIDs.remove(((String) unitDefs.getSelectedValue()).split(" ")[0]);
unitDefs.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
units = (String[]) Buttons.remove(unitDefs, units);
unitDefs.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
unitDefs.setSelectedIndex(0);
change = true;
}
}
}
/**
* Remove a compartment type
*/
private void removeCompType() {
if (compTypes.getSelectedIndex() != -1) {
boolean remove = true;
ArrayList<String> compartmentUsing = new ArrayList<String>();
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = (Compartment) document.getModel().getListOfCompartments().get(i);
if (compartment.isSetCompartmentType()) {
if (compartment.getCompartmentType().equals(
((String) compTypes.getSelectedValue()).split(" ")[0])) {
remove = false;
compartmentUsing.add(compartment.getId());
}
}
}
if (remove) {
CompartmentType tempCompType = document.getModel().getCompartmentType(
((String) compTypes.getSelectedValue()).split(" ")[0]);
ListOf c = document.getModel().getListOfCompartmentTypes();
for (int i = 0; i < document.getModel().getNumCompartmentTypes(); i++) {
if (((CompartmentType) c.get(i)).getId().equals(tempCompType.getId())) {
c.remove(i);
}
}
usedIDs.remove(((String) compTypes.getSelectedValue()).split(" ")[0]);
compTypes.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
cpTyp = (String[]) Buttons.remove(compTypes, cpTyp);
compTypes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
compTypes.setSelectedIndex(0);
change = true;
}
else {
String compartment = "";
String[] comps = compartmentUsing.toArray(new String[0]);
sort(comps);
for (int i = 0; i < comps.length; i++) {
if (i == comps.length - 1) {
compartment += comps[i];
}
else {
compartment += comps[i] + "\n";
}
}
String message = "Unable to remove the selected compartment type.";
if (compartmentUsing.size() != 0) {
message += "\n\nIt is used by the following compartments:\n" + compartment;
}
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(300, 300));
scroll.setPreferredSize(new Dimension(300, 300));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scroll, "Unable To Remove Compartment Type",
JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Remove an initial assignment
*/
private void removeInit() {
if (initAssigns.getSelectedIndex() != -1) {
String selected = ((String) initAssigns.getSelectedValue());
String tempVar = selected.split(" ")[0];
String tempMath = selected.substring(selected.indexOf('=') + 2);
ListOf r = document.getModel().getListOfInitialAssignments();
for (int i = 0; i < document.getModel().getNumInitialAssignments(); i++) {
if (myFormulaToString(((InitialAssignment) r.get(i)).getMath()).equals(tempMath)
&& ((InitialAssignment) r.get(i)).getSymbol().equals(tempVar)) {
r.remove(i);
}
}
initAssigns.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
inits = (String[]) Buttons.remove(initAssigns, inits);
initAssigns.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
initAssigns.setSelectedIndex(0);
change = true;
}
}
/**
* Remove a species type
*/
private void removeSpecType() {
if (specTypes.getSelectedIndex() != -1) {
boolean remove = true;
ArrayList<String> speciesUsing = new ArrayList<String>();
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
Species species = (Species) document.getModel().getListOfSpecies().get(i);
if (species.isSetSpeciesType()) {
if (species.getSpeciesType()
.equals(((String) specTypes.getSelectedValue()).split(" ")[0])) {
remove = false;
speciesUsing.add(species.getId());
}
}
}
if (remove) {
SpeciesType tempSpecType = document.getModel().getSpeciesType(
((String) specTypes.getSelectedValue()).split(" ")[0]);
ListOf s = document.getModel().getListOfSpeciesTypes();
for (int i = 0; i < document.getModel().getNumSpeciesTypes(); i++) {
if (((SpeciesType) s.get(i)).getId().equals(tempSpecType.getId())) {
s.remove(i);
}
}
usedIDs.remove(((String) specTypes.getSelectedValue()).split(" ")[0]);
specTypes.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
spTyp = (String[]) Buttons.remove(specTypes, spTyp);
specTypes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
specTypes.setSelectedIndex(0);
change = true;
}
else {
String species = "";
String[] specs = speciesUsing.toArray(new String[0]);
sort(specs);
for (int i = 0; i < specs.length; i++) {
if (i == specs.length - 1) {
species += specs[i];
}
else {
species += specs[i] + "\n";
}
}
String message = "Unable to remove the selected species type.";
if (speciesUsing.size() != 0) {
message += "\n\nIt is used by the following species:\n" + species;
}
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(300, 300));
scroll.setPreferredSize(new Dimension(300, 300));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scroll, "Unable To Remove Species Type",
JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Remove a rule
*/
private void removeRule() {
if (rules.getSelectedIndex() != -1) {
String selected = ((String) rules.getSelectedValue());
removeTheRule(selected);
rules.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
rul = (String[]) Buttons.remove(rules, rul);
rules.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
rules.setSelectedIndex(0);
change = true;
}
}
/**
* Remove the rule
*/
private void removeTheRule(String selected) {
// algebraic rule
if ((selected.split(" ")[0]).equals("0")) {
String tempMath = selected.substring(4);
ListOf r = document.getModel().getListOfRules();
for (int i = 0; i < document.getModel().getNumRules(); i++) {
if ((((Rule) r.get(i)).isAlgebraic()) && ((Rule) r.get(i)).getFormula().equals(tempMath)) {
r.remove(i);
}
}
}
// rate rule
else if ((selected.split(" ")[0]).equals("d(")) {
String tempVar = selected.split(" ")[1];
String tempMath = selected.substring(selected.indexOf('=') + 2);
ListOf r = document.getModel().getListOfRules();
for (int i = 0; i < document.getModel().getNumRules(); i++) {
if ((((Rule) r.get(i)).isRate()) && ((Rule) r.get(i)).getFormula().equals(tempMath)
&& ((Rule) r.get(i)).getVariable().equals(tempVar)) {
r.remove(i);
}
}
}
// assignment rule
else {
String tempVar = selected.split(" ")[0];
String tempMath = selected.substring(selected.indexOf('=') + 2);
ListOf r = document.getModel().getListOfRules();
for (int i = 0; i < document.getModel().getNumRules(); i++) {
if ((((Rule) r.get(i)).isAssignment()) && ((Rule) r.get(i)).getFormula().equals(tempMath)
&& ((Rule) r.get(i)).getVariable().equals(tempVar)) {
r.remove(i);
}
}
}
}
/**
* Remove an event
*/
private void removeEvent() {
if (events.getSelectedIndex() != -1) {
String selected = ((String) events.getSelectedValue());
removeTheEvent(selected);
events.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
ev = (String[]) Buttons.remove(events, ev);
events.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
events.setSelectedIndex(0);
change = true;
}
}
/**
* Remove the event
*/
private void removeTheEvent(String selected) {
ListOf EL = document.getModel().getListOfEvents();
for (int i = 0; i < document.getModel().getNumEvents(); i++) {
org.sbml.libsbml.Event E = (org.sbml.libsbml.Event) EL.get(i);
if (myFormulaToString(E.getTrigger().getMath()).equals(selected)) {
EL.remove(i);
}
}
}
/**
* Remove an assignment
*/
private void removeAssignment() {
if (eventAssign.getSelectedIndex() != -1) {
eventAssign.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
assign = (String[]) Buttons.remove(eventAssign, assign);
eventAssign.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
eventAssign.setSelectedIndex(0);
change = true;
}
}
/**
* Remove a constraint
*/
private void removeConstraint() {
if (constraints.getSelectedIndex() != -1) {
String selected = ((String) constraints.getSelectedValue());
ListOf c = document.getModel().getListOfConstraints();
for (int i = 0; i < document.getModel().getNumConstraints(); i++) {
if (myFormulaToString(((Constraint) c.get(i)).getMath()).equals(selected)) {
usedIDs.remove(((Constraint) c.get(i)).getMetaId());
c.remove(i);
}
}
constraints.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
cons = (String[]) Buttons.remove(constraints, cons);
constraints.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
constraints.setSelectedIndex(0);
change = true;
}
}
/**
* Remove a compartment
*/
private void removeCompartment() {
if (compartments.getSelectedIndex() != -1) {
if (document.getModel().getNumCompartments() != 1) {
boolean remove = true;
ArrayList<String> speciesUsing = new ArrayList<String>();
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
Species species = (Species) document.getModel().getListOfSpecies().get(i);
if (species.isSetCompartment()) {
if (species.getCompartment().equals(
((String) compartments.getSelectedValue()).split(" ")[0])) {
remove = false;
speciesUsing.add(species.getId());
}
}
}
ArrayList<String> outsideUsing = new ArrayList<String>();
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = document.getModel().getCompartment(i);
if (compartment.isSetOutside()) {
if (compartment.getOutside().equals(
((String) compartments.getSelectedValue()).split(" ")[0])) {
remove = false;
outsideUsing.add(compartment.getId());
}
}
}
if (!remove) {
String message = "Unable to remove the selected compartment.";
if (speciesUsing.size() != 0) {
message += "\n\nIt contains the following species:\n";
String[] vars = speciesUsing.toArray(new String[0]);
sort(vars);
for (int i = 0; i < vars.length; i++) {
if (i == vars.length - 1) {
message += vars[i];
}
else {
message += vars[i] + "\n";
}
}
}
if (outsideUsing.size() != 0) {
message += "\n\nIt outside the following compartments:\n";
String[] vars = outsideUsing.toArray(new String[0]);
sort(vars);
for (int i = 0; i < vars.length; i++) {
if (i == vars.length - 1) {
message += vars[i];
}
else {
message += vars[i] + "\n";
}
}
}
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(300, 300));
scroll.setPreferredSize(new Dimension(300, 300));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scroll, "Unable To Remove Compartment",
JOptionPane.ERROR_MESSAGE);
}
else if (!variableInUse(((String) compartments.getSelectedValue()).split(" ")[0], false)) {
Compartment tempComp = document.getModel().getCompartment(
((String) compartments.getSelectedValue()).split(" ")[0]);
ListOf c = document.getModel().getListOfCompartments();
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
if (((Compartment) c.get(i)).getId().equals(tempComp.getId())) {
c.remove(i);
}
}
usedIDs.remove(((String) compartments.getSelectedValue()).split(" ")[0]);
compartments.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
comps = (String[]) Buttons.remove(compartments, comps);
compartments.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
compartments.setSelectedIndex(0);
change = true;
}
}
else {
JOptionPane.showMessageDialog(biosim.frame(),
"Each model must contain at least one compartment.", "Unable To Remove Compartment",
JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Remove a species
*/
private void removeSpecies() {
if (species.getSelectedIndex() != -1) {
if (!variableInUse(((String) species.getSelectedValue()).split(" ")[0], false)) {
Species tempSpecies = document.getModel().getSpecies(
((String) species.getSelectedValue()).split(" ")[0]);
ListOf s = document.getModel().getListOfSpecies();
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
if (((Species) s.get(i)).getId().equals(tempSpecies.getId())) {
s.remove(i);
}
}
usedIDs.remove(tempSpecies.getId());
species.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
specs = (String[]) Buttons.remove(species, specs);
species.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
species.setSelectedIndex(0);
change = true;
}
}
}
/**
* Copy a reaction
*/
private void copyReaction() {
String reacID = JOptionPane.showInputDialog(biosim.frame(), "Enter New Reaction ID:",
"Reaction ID", JOptionPane.PLAIN_MESSAGE);
if (reacID == null) {
return;
}
if (!usedIDs.contains(reacID.trim()) && !reacID.trim().equals("")) {
Reaction react = document.getModel().createReaction();
react.setKineticLaw(new KineticLaw());
int index = reactions.getSelectedIndex();
Reaction r = document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]);
for (int i = 0; i < r.getKineticLaw().getNumParameters(); i++) {
react.getKineticLaw().addParameter(
(Parameter) r.getKineticLaw().getListOfParameters().get(i));
}
for (int i = 0; i < r.getNumProducts(); i++) {
react.addProduct(r.getProduct(i));
}
for (int i = 0; i < r.getNumModifiers(); i++) {
react.addModifier(r.getModifier(i));
}
for (int i = 0; i < r.getNumReactants(); i++) {
react.addReactant(r.getReactant(i));
}
react.setReversible(r.getReversible());
react.setId(reacID.trim());
usedIDs.add(reacID.trim());
react.getKineticLaw().setFormula(r.getKineticLaw().getFormula());
JList add = new JList();
Object[] adding = { reacID.trim() };
add.setListData(adding);
add.setSelectedIndex(0);
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(reacts, reactions, add, false, null, null, null, null, null, null,
biosim.frame());
reacts = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
reacts[i] = (String) adding[i];
}
sort(reacts);
reactions.setListData(reacts);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumReactions() == 1) {
reactions.setSelectedIndex(0);
}
else {
reactions.setSelectedIndex(index);
}
change = true;
}
else {
JOptionPane.showMessageDialog(biosim.frame(), "ID is not unique.", "Enter A Unique ID",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* Remove a reaction
*/
private void removeReaction() {
if (reactions.getSelectedIndex() != -1) {
String selected = ((String) reactions.getSelectedValue()).split(" ")[0];
removeTheReaction(selected);
usedIDs.remove(selected);
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacts = (String[]) Buttons.remove(reactions, reacts);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reactions.setSelectedIndex(0);
change = true;
}
}
/**
* Remove the reaction
*/
private void removeTheReaction(String selected) {
Reaction tempReaction = document.getModel().getReaction(selected);
ListOf r = document.getModel().getListOfReactions();
for (int i = 0; i < document.getModel().getNumReactions(); i++) {
if (((Reaction) r.get(i)).getId().equals(tempReaction.getId())) {
r.remove(i);
}
}
usedIDs.remove(selected);
}
/**
* Remove a global parameter
*/
private void removeParameter() {
if (parameters.getSelectedIndex() != -1) {
if (!variableInUse(((String) parameters.getSelectedValue()).split(" ")[0], false)) {
Parameter tempParameter = document.getModel().getParameter(
((String) parameters.getSelectedValue()).split(" ")[0]);
ListOf p = document.getModel().getListOfParameters();
for (int i = 0; i < document.getModel().getNumParameters(); i++) {
if (((Parameter) p.get(i)).getId().equals(tempParameter.getId())) {
p.remove(i);
}
}
usedIDs.remove(tempParameter.getId());
parameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
params = (String[]) Buttons.remove(parameters, params);
parameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
parameters.setSelectedIndex(0);
change = true;
}
}
}
/**
* Remove a reactant from a reaction
*/
private void removeReactant() {
if (reactants.getSelectedIndex() != -1) {
String v = ((String) reactants.getSelectedValue()).split(" ")[0];
for (int i = 0; i < changedReactants.size(); i++) {
if (changedReactants.get(i).getSpecies().equals(v)) {
changedReactants.remove(i);
}
}
reactants.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacta = (String[]) Buttons.remove(reactants, reacta);
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reactants.setSelectedIndex(0);
change = true;
}
}
/**
* Remove a product from a reaction
*/
private void removeProduct() {
if (products.getSelectedIndex() != -1) {
String v = ((String) products.getSelectedValue()).split(" ")[0];
for (int i = 0; i < changedProducts.size(); i++) {
if (changedProducts.get(i).getSpecies().equals(v)) {
changedProducts.remove(i);
}
}
products.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
product = (String[]) Buttons.remove(products, product);
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
products.setSelectedIndex(0);
change = true;
}
}
/**
* Remove a modifier from a reaction
*/
private void removeModifier() {
if (modifiers.getSelectedIndex() != -1) {
String v = ((String) modifiers.getSelectedValue()).split(" ")[0];
for (int i = 0; i < changedModifiers.size(); i++) {
if (changedModifiers.get(i).getSpecies().equals(v)) {
changedModifiers.remove(i);
}
}
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modifier = (String[]) Buttons.remove(modifiers, modifier);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
modifiers.setSelectedIndex(0);
change = true;
}
}
/**
* Remove a function if not in use
*/
private void useMassAction() {
String kf;
String kr;
if (changedParameters.size() == 0) {
kf = "kf";
kr = "kr";
}
else if (changedParameters.size() == 1) {
kf = changedParameters.get(0).getId();
kr = changedParameters.get(0).getId();
}
else {
kf = changedParameters.get(0).getId();
kr = changedParameters.get(1).getId();
}
String kinetic = kf;
for (SpeciesReference s : changedReactants) {
if (s.isSetStoichiometryMath()) {
kinetic += " * pow(" + s.getSpecies() + ", "
+ myFormulaToString(s.getStoichiometryMath().getMath()) + ")";
}
else {
if (s.getStoichiometry() == 1) {
kinetic += " * " + s.getSpecies();
}
else {
kinetic += " * pow(" + s.getSpecies() + ", " + s.getStoichiometry() + ")";
}
}
}
for (ModifierSpeciesReference s : changedModifiers) {
kinetic += " * " + s.getSpecies();
}
if (reacReverse.getSelectedItem().equals("true")) {
kinetic += " - " + kr;
for (SpeciesReference s : changedProducts) {
if (s.isSetStoichiometryMath()) {
kinetic += " * pow(" + s.getSpecies() + ", "
+ myFormulaToString(s.getStoichiometryMath().getMath()) + ")";
}
else {
if (s.getStoichiometry() == 1) {
kinetic += " * " + s.getSpecies();
}
else {
kinetic += " * pow(" + s.getSpecies() + ", " + s.getStoichiometry() + ")";
}
}
}
for (ModifierSpeciesReference s : changedModifiers) {
kinetic += " * " + s.getSpecies();
}
}
kineticLaw.setText(kinetic);
change = true;
}
/**
* Remove a function if not in use
*/
private void removeFunction() {
if (functions.getSelectedIndex() != -1) {
if (!variableInUse(((String) functions.getSelectedValue()).split(" ")[0], false)) {
FunctionDefinition tempFunc = document.getModel().getFunctionDefinition(
((String) functions.getSelectedValue()).split(" ")[0]);
ListOf f = document.getModel().getListOfFunctionDefinitions();
for (int i = 0; i < document.getModel().getNumFunctionDefinitions(); i++) {
if (((FunctionDefinition) f.get(i)).getId().equals(tempFunc.getId())) {
f.remove(i);
}
}
usedIDs.remove(((String) functions.getSelectedValue()).split(" ")[0]);
functions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
funcs = (String[]) Buttons.remove(functions, funcs);
functions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
functions.setSelectedIndex(0);
change = true;
}
}
}
/**
* Save SBML file with a new name
*/
private void saveAs() {
String simName = JOptionPane.showInputDialog(biosim.frame(), "Enter Model ID:", "Model ID",
JOptionPane.PLAIN_MESSAGE);
if (simName != null && !simName.equals("")) {
if (simName.length() > 4) {
if (!simName.substring(simName.length() - 5).equals(".sbml")
&& !simName.substring(simName.length() - 4).equals(".xml")) {
simName += ".sbml";
}
}
else {
simName += ".sbml";
}
String modelID = "";
if (simName.length() > 4) {
if (simName.substring(simName.length() - 5).equals(".sbml")) {
modelID = simName.substring(0, simName.length() - 5);
}
else {
modelID = simName.substring(0, simName.length() - 4);
}
}
String oldId = document.getModel().getId();
document.getModel().setId(modelID);
document.getModel().setName(modelName.getText().trim());
String newFile = file;
newFile = newFile.substring(0, newFile.length()
- newFile.split(separator)[newFile.split(separator).length - 1].length())
+ simName;
try {
log.addText("Saving sbml file as:\n" + newFile + "\n");
FileOutputStream out = new FileOutputStream(new File(newFile));
SBMLWriter writer = new SBMLWriter();
String doc = writer.writeToString(document);
byte[] output = doc.getBytes();
out.write(output);
out.close();
JTabbedPane tab = biosim.getTab();
for (int i = 0; i < tab.getTabCount(); i++) {
if (tab.getTitleAt(i).equals(file.split(separator)[file.split(separator).length - 1])) {
tab.setTitleAt(i, simName);
tab
.setComponentAt(i,
new SBML_Editor(newFile, reb2sac, log, biosim, simDir, paramFile));
tab.getComponentAt(i).setName("SBML Editor");
}
}
biosim.refreshTree();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to save sbml file.",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
finally {
document.getModel().setId(oldId);
}
}
}
/**
* Remove a reaction parameter, if allowed
*/
private void reacRemoveParam() {
if (reacParameters.getSelectedIndex() != -1) {
String v = ((String) reacParameters.getSelectedValue()).split(" ")[0];
Reaction reaction = document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]);
String[] vars = reaction.getKineticLaw().getFormula().split(" |\\(|\\)|\\,");
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(v)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cannot remove reaction parameter because it is used in the kinetic law.",
"Cannot Remove Parameter", JOptionPane.ERROR_MESSAGE);
return;
}
}
for (int j = 0; j < reaction.getNumProducts(); j++) {
if (reaction.getProduct(j).isSetSpecies()) {
String specRef = reaction.getProduct(j).getSpecies();
if (reaction.getProduct(j).isSetStoichiometryMath()) {
vars = myFormulaToString(reaction.getProduct(j).getStoichiometryMath().getMath())
.split(" |\\(|\\)|\\,");
for (int k = 0; k < vars.length; k++) {
if (vars[k].equals(v)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cannot remove reaction parameter because it is used in the stoichiometry math for product "
+ specRef + ".", "Cannot Remove Parameter", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
}
}
for (int j = 0; j < reaction.getNumReactants(); j++) {
if (reaction.getReactant(j).isSetSpecies()) {
String specRef = reaction.getReactant(j).getSpecies();
if (reaction.getReactant(j).isSetStoichiometryMath()) {
vars = myFormulaToString(reaction.getReactant(j).getStoichiometryMath().getMath())
.split(" |\\(|\\)|\\,");
for (int k = 0; k < vars.length; k++) {
if (vars[k].equals(v)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cannot remove reaction parameter because it is used in the stoichiometry math for reactant "
+ specRef + ".", "Cannot Remove Parameter", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
}
}
for (int i = 0; i < changedParameters.size(); i++) {
if (changedParameters.get(i).getId().equals(v)) {
changedParameters.remove(i);
}
}
thisReactionParams.remove(v);
reacParameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacParams = (String[]) Buttons.remove(reacParameters, reacParams);
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reacParameters.setSelectedIndex(0);
change = true;
}
}
/**
* Check if a unit is in use.
*/
private boolean unitsInUse(String unit) {
Model model = document.getModel();
boolean inUse = false;
ArrayList<String> compartmentsUsing = new ArrayList<String>();
for (int i = 0; i < model.getNumCompartments(); i++) {
Compartment compartment = (Compartment) model.getListOfCompartments().get(i);
if (compartment.getUnits().equals(unit)) {
inUse = true;
compartmentsUsing.add(compartment.getId());
}
}
ArrayList<String> speciesUsing = new ArrayList<String>();
for (int i = 0; i < model.getNumSpecies(); i++) {
Species species = (Species) model.getListOfSpecies().get(i);
if (species.getUnits().equals(unit)) {
inUse = true;
speciesUsing.add(species.getId());
}
}
ArrayList<String> parametersUsing = new ArrayList<String>();
for (int i = 0; i < model.getNumParameters(); i++) {
Parameter parameters = (Parameter) model.getListOfParameters().get(i);
if (parameters.getUnits().equals(unit)) {
inUse = true;
parametersUsing.add(parameters.getId());
}
}
ArrayList<String> reacParametersUsing = new ArrayList<String>();
for (int i = 0; i < model.getNumReactions(); i++) {
for (int j = 0; j < model.getReaction(i).getKineticLaw().getNumParameters(); j++) {
Parameter parameters = (Parameter) model.getReaction(i).getKineticLaw()
.getListOfParameters().get(j);
if (parameters.getUnits().equals(unit)) {
inUse = true;
reacParametersUsing.add(model.getReaction(i).getId() + "/" + parameters.getId());
}
}
}
if (inUse) {
String message = "Unable to remove the selected unit.";
String[] ids;
if (compartmentsUsing.size() != 0) {
ids = compartmentsUsing.toArray(new String[0]);
sort(ids);
message += "\n\nIt is used by the following compartments:\n";
for (int i = 0; i < ids.length; i++) {
if (i == ids.length - 1) {
message += ids[i];
}
else {
message += ids[i] + "\n";
}
}
}
if (speciesUsing.size() != 0) {
ids = speciesUsing.toArray(new String[0]);
sort(ids);
message += "\n\nIt is used by the following species:\n";
for (int i = 0; i < ids.length; i++) {
if (i == ids.length - 1) {
message += ids[i];
}
else {
message += ids[i] + "\n";
}
}
}
if (parametersUsing.size() != 0) {
ids = parametersUsing.toArray(new String[0]);
sort(ids);
message += "\n\nIt is used by the following parameters:\n";
for (int i = 0; i < ids.length; i++) {
if (i == ids.length - 1) {
message += ids[i];
}
else {
message += ids[i] + "\n";
}
}
}
if (reacParametersUsing.size() != 0) {
ids = reacParametersUsing.toArray(new String[0]);
sort(ids);
message += "\n\nIt is used by the following reaction/parameters:\n";
for (int i = 0; i < ids.length; i++) {
if (i == ids.length - 1) {
message += ids[i];
}
else {
message += ids[i] + "\n";
}
}
}
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(350, 350));
scroll.setPreferredSize(new Dimension(350, 350));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scroll, "Unable To Remove Variable",
JOptionPane.ERROR_MESSAGE);
}
return inUse;
}
/**
* Check if a variable is in use.
*/
private boolean variableInUse(String species, boolean zeroDim) {
Model model = document.getModel();
boolean inUse = false;
ArrayList<String> stoicMathUsing = new ArrayList<String>();
ArrayList<String> reactantsUsing = new ArrayList<String>();
ArrayList<String> productsUsing = new ArrayList<String>();
ArrayList<String> modifiersUsing = new ArrayList<String>();
ArrayList<String> kineticLawsUsing = new ArrayList<String>();
ArrayList<String> initsUsing = new ArrayList<String>();
ArrayList<String> rulesUsing = new ArrayList<String>();
ArrayList<String> constraintsUsing = new ArrayList<String>();
ArrayList<String> eventsUsing = new ArrayList<String>();
for (int i = 0; i < model.getNumReactions(); i++) {
Reaction reaction = (Reaction) model.getListOfReactions().get(i);
for (int j = 0; j < reaction.getNumProducts(); j++) {
if (reaction.getProduct(j).isSetSpecies()) {
String specRef = reaction.getProduct(j).getSpecies();
if (species.equals(specRef)) {
inUse = true;
productsUsing.add(reaction.getId());
}
else if (reaction.getProduct(j).isSetStoichiometryMath()) {
String[] vars = myFormulaToString(
reaction.getProduct(j).getStoichiometryMath().getMath()).split(" |\\(|\\)|\\,");
for (int k = 0; k < vars.length; k++) {
if (vars[k].equals(species)) {
stoicMathUsing.add(reaction.getId() + "/" + specRef);
inUse = true;
break;
}
}
}
}
}
for (int j = 0; j < reaction.getNumReactants(); j++) {
if (reaction.getReactant(j).isSetSpecies()) {
String specRef = reaction.getReactant(j).getSpecies();
if (species.equals(specRef)) {
inUse = true;
reactantsUsing.add(reaction.getId());
}
else if (reaction.getReactant(j).isSetStoichiometryMath()) {
String[] vars = myFormulaToString(
reaction.getReactant(j).getStoichiometryMath().getMath()).split(" |\\(|\\)|\\,");
for (int k = 0; k < vars.length; k++) {
if (vars[k].equals(species)) {
stoicMathUsing.add(reaction.getId() + "/" + specRef);
inUse = true;
break;
}
}
}
}
}
for (int j = 0; j < reaction.getNumModifiers(); j++) {
if (reaction.getModifier(j).isSetSpecies()) {
String specRef = reaction.getModifier(j).getSpecies();
if (species.equals(specRef)) {
inUse = true;
modifiersUsing.add(reaction.getId());
}
}
}
String[] vars = reaction.getKineticLaw().getFormula().split(" |\\(|\\)|\\,");
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(species)) {
kineticLawsUsing.add(reaction.getId());
inUse = true;
break;
}
}
}
for (int i = 0; i < inits.length; i++) {
String[] vars = inits[i].split(" |\\(|\\)|\\,");
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(species)) {
initsUsing.add(inits[i]);
inUse = true;
break;
}
}
}
for (int i = 0; i < rul.length; i++) {
String[] vars = rul[i].split(" |\\(|\\)|\\,");
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(species)) {
rulesUsing.add(rul[i]);
inUse = true;
break;
}
}
}
for (int i = 0; i < cons.length; i++) {
String[] vars = cons[i].split(" |\\(|\\)|\\,");
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(species)) {
constraintsUsing.add(cons[i]);
inUse = true;
break;
}
}
}
ListOf e = model.getListOfEvents();
for (int i = 0; i < model.getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) e.get(i);
String trigger = myFormulaToString(event.getTrigger().getMath());
String eventStr = trigger;
if (event.isSetDelay()) {
eventStr += " " + myFormulaToString(event.getDelay().getMath());
}
for (int j = 0; j < event.getNumEventAssignments(); j++) {
eventStr += " " + (event.getEventAssignment(j).getVariable()) + " = "
+ myFormulaToString(event.getEventAssignment(j).getMath());
}
String[] vars = eventStr.split(" |\\(|\\)|\\,");
for (int j = 0; j < vars.length; j++) {
if (vars[j].equals(species)) {
eventsUsing.add(trigger);
inUse = true;
break;
}
}
}
if (inUse) {
String reactants = "";
String products = "";
String modifiers = "";
String kineticLaws = "";
String stoicMath = "";
String initAssigns = "";
String rules = "";
String constraints = "";
String events = "";
String[] reacts = reactantsUsing.toArray(new String[0]);
sort(reacts);
String[] prods = productsUsing.toArray(new String[0]);
sort(prods);
String[] mods = modifiersUsing.toArray(new String[0]);
sort(mods);
String[] kls = kineticLawsUsing.toArray(new String[0]);
sort(kls);
String[] sm = stoicMathUsing.toArray(new String[0]);
sort(sm);
String[] inAs = initsUsing.toArray(new String[0]);
sort(inAs);
String[] ruls = rulesUsing.toArray(new String[0]);
sort(ruls);
String[] consts = constraintsUsing.toArray(new String[0]);
sort(consts);
String[] evs = eventsUsing.toArray(new String[0]);
sort(evs);
for (int i = 0; i < reacts.length; i++) {
if (i == reacts.length - 1) {
reactants += reacts[i];
}
else {
reactants += reacts[i] + "\n";
}
}
for (int i = 0; i < prods.length; i++) {
if (i == prods.length - 1) {
products += prods[i];
}
else {
products += prods[i] + "\n";
}
}
for (int i = 0; i < mods.length; i++) {
if (i == mods.length - 1) {
modifiers += mods[i];
}
else {
modifiers += mods[i] + "\n";
}
}
for (int i = 0; i < kls.length; i++) {
if (i == kls.length - 1) {
kineticLaws += kls[i];
}
else {
kineticLaws += kls[i] + "\n";
}
}
for (int i = 0; i < sm.length; i++) {
if (i == sm.length - 1) {
stoicMath += sm[i];
}
else {
stoicMath += sm[i] + "\n";
}
}
for (int i = 0; i < inAs.length; i++) {
if (i == inAs.length - 1) {
initAssigns += inAs[i];
}
else {
initAssigns += inAs[i] + "\n";
}
}
for (int i = 0; i < ruls.length; i++) {
if (i == ruls.length - 1) {
rules += ruls[i];
}
else {
rules += ruls[i] + "\n";
}
}
for (int i = 0; i < consts.length; i++) {
if (i == consts.length - 1) {
constraints += consts[i];
}
else {
constraints += consts[i] + "\n";
}
}
for (int i = 0; i < evs.length; i++) {
if (i == evs.length - 1) {
events += evs[i];
}
else {
events += evs[i] + "\n";
}
}
String message;
if (zeroDim) {
message = "Unable to change compartment to 0-dimensions.";
}
else {
message = "Unable to remove the selected species.";
}
if (reactantsUsing.size() != 0) {
message += "\n\nIt is used as a reactant in the following reactions:\n" + reactants;
}
if (productsUsing.size() != 0) {
message += "\n\nIt is used as a product in the following reactions:\n" + products;
}
if (modifiersUsing.size() != 0) {
message += "\n\nIt is used as a modifier in the following reactions:\n" + modifiers;
}
if (kineticLawsUsing.size() != 0) {
message += "\n\nIt is used in the kinetic law in the following reactions:\n" + kineticLaws;
}
if (stoicMathUsing.size() != 0) {
message += "\n\nIt is used in the stoichiometry math for the following reaction/species:\n"
+ stoicMath;
}
if (initsUsing.size() != 0) {
message += "\n\nIt is used in the following initial assignments:\n" + initAssigns;
}
if (rulesUsing.size() != 0) {
message += "\n\nIt is used in the following rules:\n" + rules;
}
if (constraintsUsing.size() != 0) {
message += "\n\nIt is used in the following constraints:\n" + constraints;
}
if (eventsUsing.size() != 0) {
message += "\n\nIt is used in the following events:\n" + events;
}
JTextArea messageArea = new JTextArea(message);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(400, 400));
scroll.setPreferredSize(new Dimension(400, 400));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scroll, "Unable To Remove Variable",
JOptionPane.ERROR_MESSAGE);
}
return inUse;
}
/**
* Check that ID is valid and unique
*/
private boolean checkID(String ID, String selectedID, boolean isReacParam) {
if (ID.equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "An ID is required.", "Enter an ID",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (!(IDpat.matcher(ID).matches())) {
JOptionPane.showMessageDialog(biosim.frame(),
"An ID can only contain letters, numbers, and underscores.", "Invalid ID",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (ID.equals("t") || ID.equals("t") || ID.equals("true") || ID.equals("false")
|| ID.equals("notanumber") || ID.equals("pi") || ID.equals("infinity")
|| ID.equals("exponentiale") || ID.equals("abs") || ID.equals("arccos")
|| ID.equals("arccosh") || ID.equals("arcsin") || ID.equals("arcsinh")
|| ID.equals("arctan") || ID.equals("arctanh") || ID.equals("arccot")
|| ID.equals("arccoth") || ID.equals("arccsc") || ID.equals("arccsch")
|| ID.equals("arcsec") || ID.equals("arcsech") || ID.equals("acos") || ID.equals("acosh")
|| ID.equals("asin") || ID.equals("asinh") || ID.equals("atan") || ID.equals("atanh")
|| ID.equals("acot") || ID.equals("acoth") || ID.equals("acsc") || ID.equals("acsch")
|| ID.equals("asec") || ID.equals("asech") || ID.equals("cos") || ID.equals("cosh")
|| ID.equals("cot") || ID.equals("coth") || ID.equals("csc") || ID.equals("csch")
|| ID.equals("ceil") || ID.equals("factorial") || ID.equals("exp") || ID.equals("floor")
|| ID.equals("ln") || ID.equals("log") || ID.equals("sqr") || ID.equals("log10")
|| ID.equals("pow") || ID.equals("sqrt") || ID.equals("root") || ID.equals("piecewise")
|| ID.equals("sec") || ID.equals("sech") || ID.equals("sin") || ID.equals("sinh")
|| ID.equals("tan") || ID.equals("tanh") || ID.equals("and") || ID.equals("or")
|| ID.equals("xor") || ID.equals("not") || ID.equals("eq") || ID.equals("geq")
|| ID.equals("leq") || ID.equals("gt") || ID.equals("neq") || ID.equals("lt")
|| ID.equals("delay")) {
JOptionPane.showMessageDialog(biosim.frame(), "ID cannot be a reserved word.", "Illegal ID",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (usedIDs.contains(ID) && !ID.equals(selectedID)) {
if (isReacParam) {
JOptionPane.showMessageDialog(biosim.frame(), "ID shadows a global ID.", "Not a Unique ID",
JOptionPane.WARNING_MESSAGE);
}
else {
JOptionPane.showMessageDialog(biosim.frame(), "ID is not unique.", "Enter a Unique ID",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
return false;
}
/**
* Creates a frame used to edit functions or create new ones.
*/
private void functionEditor(String option) {
if (option.equals("OK") && functions.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No function selected.",
"Must Select a Function", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel functionPanel = new JPanel();
JPanel funcPanel = new JPanel(new GridLayout(4, 2));
JLabel idLabel = new JLabel("ID:");
JLabel nameLabel = new JLabel("Name:");
JLabel argLabel = new JLabel("Arguments:");
JLabel eqnLabel = new JLabel("Definition:");
funcID = new JTextField(12);
funcName = new JTextField(12);
args = new JTextField(12);
eqn = new JTextField(12);
String selectedID = "";
if (option.equals("OK")) {
try {
FunctionDefinition function = document.getModel().getFunctionDefinition(
(((String) functions.getSelectedValue()).split(" ")[0]));
funcID.setText(function.getId());
selectedID = function.getId();
funcName.setText(function.getName());
String argStr = "";
for (long j = 0; j < function.getNumArguments(); j++) {
if (j != 0) {
argStr += ", ";
}
argStr += myFormulaToString(function.getArgument(j));
}
args.setText(argStr);
if (function.isSetMath()) {
eqn.setText("" + myFormulaToString(function.getBody()));
}
else {
eqn.setText("");
}
}
catch (Exception e) {
}
}
funcPanel.add(idLabel);
funcPanel.add(funcID);
funcPanel.add(nameLabel);
funcPanel.add(funcName);
funcPanel.add(argLabel);
funcPanel.add(args);
funcPanel.add(eqnLabel);
funcPanel.add(eqn);
functionPanel.add(funcPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), functionPanel, "Function Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = checkID(funcID.getText().trim(), selectedID, false);
if (!error) {
String[] vars = eqn.getText().trim().split(" |\\(|\\)|\\,|\\*|\\+|\\/|\\-");
for (int i = 0; i < vars.length; i++) {
if (vars[i].equals(funcID.getText().trim())) {
JOptionPane.showMessageDialog(biosim.frame(), "Recursive functions are not allowed.",
"Recursion Illegal", JOptionPane.ERROR_MESSAGE);
error = true;
break;
}
}
}
if (!error) {
if (eqn.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "Formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (args.getText().trim().equals("")
&& libsbml.parseFormula("lambda(" + eqn.getText().trim() + ")") == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (!args.getText().trim().equals("")
&& libsbml.parseFormula("lambda(" + args.getText().trim() + "," + eqn.getText().trim()
+ ")") == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariables(eqn.getText().trim(), false, args
.getText().trim(), true);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Function can only contain the arguments or other function calls.\n\n"
+ "Illegal variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Illegal Variables",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
if (!error) {
error = checkNumFunctionArguments(myParseFormula(eqn.getText().trim()));
}
if (!error) {
if (option.equals("OK")) {
int index = functions.getSelectedIndex();
String val = ((String) functions.getSelectedValue()).split(" ")[0];
functions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
funcs = Buttons.getList(funcs, functions);
functions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
FunctionDefinition f = document.getModel().getFunctionDefinition(val);
f.setId(funcID.getText().trim());
f.setName(funcName.getText().trim());
if (args.getText().trim().equals("")) {
f.setMath(libsbml.parseFormula("lambda(" + eqn.getText().trim() + ")"));
}
else {
f.setMath(libsbml.parseFormula("lambda(" + args.getText().trim() + ","
+ eqn.getText().trim() + ")"));
}
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(val)) {
usedIDs.set(i, funcID.getText().trim());
}
}
String oldVal = funcs[index];
funcs[index] = funcID.getText().trim() + " ( " + args.getText().trim() + " ) = "
+ eqn.getText().trim();
try {
funcs = sortFunctions(funcs);
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in functions.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
error = true;
funcs[index] = oldVal;
}
functions.setListData(funcs);
functions.setSelectedIndex(index);
updateVarId(false, val, funcID.getText().trim());
}
else {
int index = functions.getSelectedIndex();
JList add = new JList();
String addStr;
addStr = funcID.getText().trim() + " ( " + args.getText().trim() + " ) = "
+ eqn.getText().trim();
Object[] adding = { addStr };
add.setListData(adding);
add.setSelectedIndex(0);
functions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(funcs, functions, add, false, null, null, null, null, null, null,
biosim.frame());
String[] oldVal = funcs;
funcs = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
funcs[i] = (String) adding[i];
}
try {
funcs = sortFunctions(funcs);
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in functions.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
error = true;
funcs = oldVal;
}
if (!error) {
FunctionDefinition f = document.getModel().createFunctionDefinition();
f.setId(funcID.getText().trim());
f.setName(funcName.getText().trim());
if (args.getText().trim().equals("")) {
f.setMath(libsbml.parseFormula("lambda(" + eqn.getText().trim() + ")"));
}
else {
f.setMath(libsbml.parseFormula("lambda(" + args.getText().trim() + ","
+ eqn.getText().trim() + ")"));
}
usedIDs.add(funcID.getText().trim());
}
functions.setListData(funcs);
functions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumFunctionDefinitions() == 1) {
functions.setSelectedIndex(0);
}
else {
functions.setSelectedIndex(index);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), functionPanel, "Function Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Sort functions in order to be evaluated
*/
private String[] sortFunctions(String[] funcs) {
String[] result = new String[funcs.length];
String temp;
String temp2;
int j = 0;
int start = 0;
int end = 0;
for (int i = 0; i < funcs.length; i++) {
String[] func = funcs[i].split(" |\\(|\\)|\\,|\\*|\\+|\\/|\\-");
start = -1;
end = -1;
for (int k = 0; k < j; k++) {
String[] f = result[k].split(" |\\(|\\)|\\,|\\*|\\+|\\/|\\-");
for (int l = 1; l < f.length; l++) {
if (f[l].equals(func[0])) {
end = k;
}
}
for (int l = 1; l < func.length; l++) {
if (func[l].equals(f[0])) {
start = k;
}
}
}
if (end == -1) {
result[j] = funcs[i];
}
else if (start < end) {
temp = result[end];
result[end] = funcs[i];
for (int k = end + 1; k < j; k++) {
temp2 = result[k];
result[k] = temp;
temp = temp2;
}
result[j] = temp;
}
else {
result[j] = funcs[i];
throw new RuntimeException();
}
j++;
}
return result;
}
/**
* Creates a frame used to edit units or create new ones.
*/
private void unitEditor(String option) {
if (option.equals("OK") && unitDefs.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No unit definition selected.",
"Must Select a Unit Definition", JOptionPane.ERROR_MESSAGE);
return;
}
String[] kinds = { "ampere", "becquerel", "candela", "celsius", "coulomb", "dimensionless",
"farad", "gram", "gray", "henry", "hertz", "item", "joule", "katal", "kelvin", "kilogram",
"litre", "lumen", "lux", "metre", "mole", "newton", "ohm", "pascal", "radian", "second",
"siemens", "sievert", "steradian", "tesla", "volt", "watt", "weber" };
JPanel unitDefPanel = new JPanel(new BorderLayout());
JPanel unitPanel = new JPanel(new GridLayout(2, 2));
JLabel idLabel = new JLabel("ID:");
unitID = new JTextField(12);
JLabel nameLabel = new JLabel("Name:");
unitName = new JTextField(12);
JPanel unitListPanel = new JPanel(new BorderLayout());
JPanel addUnitList = new JPanel();
addList = new JButton("Add to List");
removeList = new JButton("Remove from List");
editList = new JButton("Edit List");
addUnitList.add(addList);
addUnitList.add(removeList);
addUnitList.add(editList);
addList.addActionListener(this);
removeList.addActionListener(this);
editList.addActionListener(this);
JLabel unitListLabel = new JLabel("List of Units:");
unitList = new JList();
unitList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(260, 220));
scroll.setPreferredSize(new Dimension(276, 152));
scroll.setViewportView(unitList);
uList = new String[0];
if (option.equals("OK")) {
try {
UnitDefinition unit = document.getModel().getUnitDefinition(
(((String) unitDefs.getSelectedValue()).split(" ")[0]));
unitID.setText(unit.getId());
unitName.setText(unit.getName());
uList = new String[(int) unit.getNumUnits()];
for (int i = 0; i < unit.getNumUnits(); i++) {
uList[i] = "";
if (unit.getUnit(i).getMultiplier() != 1.0) {
uList[i] = unit.getUnit(i).getMultiplier() + " * ";
}
if (unit.getUnit(i).getScale() != 0) {
uList[i] = uList[i] + "10^" + unit.getUnit(i).getScale() + " * ";
}
uList[i] = uList[i] + unitToString(unit.getUnit(i));
if (unit.getUnit(i).getExponent() != 1) {
uList[i] = "( " + uList[i] + " )^" + unit.getUnit(i).getExponent();
}
}
}
catch (Exception e) {
}
}
sort(uList);
unitList.setListData(uList);
unitList.setSelectedIndex(0);
unitList.addMouseListener(this);
unitListPanel.add(unitListLabel, "North");
unitListPanel.add(scroll, "Center");
unitListPanel.add(addUnitList, "South");
unitPanel.add(idLabel);
unitPanel.add(unitID);
unitPanel.add(nameLabel);
unitPanel.add(unitName);
unitDefPanel.add(unitPanel, "North");
unitDefPanel.add(unitListPanel, "South");
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), unitDefPanel,
"Unit Definition Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
if (unitID.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "A unit definition ID is required.",
"Enter an ID", JOptionPane.ERROR_MESSAGE);
error = true;
value = JOptionPane.showOptionDialog(biosim.frame(), unitDefPanel,
"Unit Definition Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
}
else {
String addUnit = "";
addUnit = unitID.getText().trim();
if (!(IDpat.matcher(addUnit).matches())) {
JOptionPane.showMessageDialog(biosim.frame(),
"A unit definition ID can only contain letters, numbers, and underscores.",
"Invalid ID", JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
for (int i = 0; i < kinds.length; i++) {
if (kinds[i].equals(addUnit)) {
JOptionPane.showMessageDialog(biosim.frame(), "Unit ID matches a predefined unit.",
"Enter a Unique ID", JOptionPane.ERROR_MESSAGE);
error = true;
break;
}
}
}
if (!error) {
for (int i = 0; i < units.length; i++) {
if (option.equals("OK")) {
if (units[i].equals((String) unitDefs.getSelectedValue()))
continue;
}
if (units[i].equals(addUnit)) {
JOptionPane.showMessageDialog(biosim.frame(), "Unit ID is not unique.",
"Enter a Unique ID", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
if ((!error) && (uList.length == 0)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Unit definition must have at least one unit.", "Unit Needed",
JOptionPane.ERROR_MESSAGE);
error = true;
}
if ((!error)
&& ((addUnit.equals("substance")) || (addUnit.equals("length"))
|| (addUnit.equals("area")) || (addUnit.equals("volume")) || (addUnit
.equals("time")))) {
if (uList.length > 1) {
JOptionPane.showMessageDialog(biosim.frame(),
"Redefinition of built-in unit must have a single unit.", "Single Unit Required",
JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
if (addUnit.equals("substance")) {
if (!(extractUnitKind(uList[0]).equals("dimensionless")
|| (extractUnitKind(uList[0]).equals("mole") && Integer
.valueOf(extractUnitExp(uList[0])) == 1)
|| (extractUnitKind(uList[0]).equals("item") && Integer
.valueOf(extractUnitExp(uList[0])) == 1)
|| (extractUnitKind(uList[0]).equals("gram") && Integer
.valueOf(extractUnitExp(uList[0])) == 1) || (extractUnitKind(uList[0])
.equals("kilogram") && Integer.valueOf(extractUnitExp(uList[0])) == 1))) {
JOptionPane
.showMessageDialog(
biosim.frame(),
"Redefinition of substance must be dimensionless or\n in terms of moles, items, grams, or kilograms.",
"Incorrect Redefinition", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
else if (addUnit.equals("time")) {
if (!(extractUnitKind(uList[0]).equals("dimensionless") || (extractUnitKind(uList[0])
.equals("second") && Integer.valueOf(extractUnitExp(uList[0])) == 1))) {
JOptionPane.showMessageDialog(biosim.frame(),
"Redefinition of time must be dimensionless or in terms of seconds.",
"Incorrect Redefinition", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
else if (addUnit.equals("length")) {
if (!(extractUnitKind(uList[0]).equals("dimensionless") || (extractUnitKind(uList[0])
.equals("metre") && Integer.valueOf(extractUnitExp(uList[0])) == 1))) {
JOptionPane.showMessageDialog(biosim.frame(),
"Redefinition of length must be dimensionless or in terms of metres.",
"Incorrect Redefinition", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
else if (addUnit.equals("area")) {
if (!(extractUnitKind(uList[0]).equals("dimensionless") || (extractUnitKind(uList[0])
.equals("metre") && Integer.valueOf(extractUnitExp(uList[0])) == 2))) {
JOptionPane.showMessageDialog(biosim.frame(),
"Redefinition of area must be dimensionless or in terms of metres^2.",
"Incorrect Redefinition", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
else if (addUnit.equals("volume")) {
if (!(extractUnitKind(uList[0]).equals("dimensionless")
|| (extractUnitKind(uList[0]).equals("litre") && Integer
.valueOf(extractUnitExp(uList[0])) == 1) || (extractUnitKind(uList[0])
.equals("metre") && Integer.valueOf(extractUnitExp(uList[0])) == 3))) {
JOptionPane
.showMessageDialog(
biosim.frame(),
"Redefinition of volume must be dimensionless or in terms of litres or metres^3.",
"Incorrect Redefinition", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
}
if (!error) {
if (option.equals("OK")) {
int index = unitDefs.getSelectedIndex();
String val = ((String) unitDefs.getSelectedValue()).split(" ")[0];
unitDefs.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
units = Buttons.getList(units, unitDefs);
unitDefs.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
UnitDefinition u = document.getModel().getUnitDefinition(val);
u.setId(unitID.getText().trim());
u.setName(unitName.getText().trim());
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(val)) {
usedIDs.set(i, addUnit);
}
}
while (u.getNumUnits() > 0) {
u.getListOfUnits().remove(0);
}
for (int i = 0; i < uList.length; i++) {
Unit unit = new Unit(extractUnitKind(uList[i]), Integer.valueOf(
extractUnitExp(uList[i])).intValue(), Integer.valueOf(extractUnitScale(uList[i]))
.intValue(), Double.valueOf(extractUnitMult(uList[i])).doubleValue());
u.addUnit(unit);
}
units[index] = addUnit;
sort(units);
unitDefs.setListData(units);
unitDefs.setSelectedIndex(index);
updateUnitId(val, unitID.getText().trim());
}
else {
int index = unitDefs.getSelectedIndex();
UnitDefinition u = document.getModel().createUnitDefinition();
u.setId(unitID.getText().trim());
u.setName(unitName.getText().trim());
usedIDs.add(addUnit);
for (int i = 0; i < uList.length; i++) {
Unit unit = new Unit(extractUnitKind(uList[i]), Integer.valueOf(
extractUnitExp(uList[i])).intValue(), Integer.valueOf(extractUnitScale(uList[i]))
.intValue(), Double.valueOf(extractUnitMult(uList[i])).doubleValue());
u.addUnit(unit);
}
JList add = new JList();
Object[] adding = { addUnit };
add.setListData(adding);
add.setSelectedIndex(0);
unitDefs.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(units, unitDefs, add, false, null, null, null, null, null, null,
biosim.frame());
units = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
units[i] = (String) adding[i];
}
sort(units);
unitDefs.setListData(units);
unitDefs.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumUnitDefinitions() == 1) {
unitDefs.setSelectedIndex(0);
}
else {
unitDefs.setSelectedIndex(index);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), unitDefPanel,
"Unit Definition Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
}
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit unit list elements or create new ones.
*/
private void unitListEditor(String option) {
if (option.equals("OK") && unitList.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No unit selected.", "Must Select an Unit",
JOptionPane.ERROR_MESSAGE);
return;
}
JPanel unitListPanel = new JPanel();
JPanel ULPanel = new JPanel(new GridLayout(4, 2));
JLabel kindLabel = new JLabel("Kind:");
JLabel expLabel = new JLabel("Exponent:");
JLabel scaleLabel = new JLabel("Scale:");
JLabel multLabel = new JLabel("Multiplier:");
String[] kinds = { "ampere", "becquerel", "candela", "celsius", "coulomb", "dimensionless",
"farad", "gram", "gray", "henry", "hertz", "item", "joule", "katal", "kelvin", "kilogram",
"litre", "lumen", "lux", "metre", "mole", "newton", "ohm", "pascal", "radian", "second",
"siemens", "sievert", "steradian", "tesla", "volt", "watt", "weber" };
final JComboBox kindBox = new JComboBox(kinds);
exp = new JTextField(12);
exp.setText("1");
scale = new JTextField(12);
scale.setText("0");
mult = new JTextField(12);
mult.setText("1.0");
if (option.equals("OK")) {
String selected = (String) unitList.getSelectedValue();
kindBox.setSelectedItem(extractUnitKind(selected));
exp.setText(extractUnitExp(selected));
scale.setText(extractUnitScale(selected));
mult.setText(extractUnitMult(selected));
}
ULPanel.add(kindLabel);
ULPanel.add(kindBox);
ULPanel.add(expLabel);
ULPanel.add(exp);
ULPanel.add(scaleLabel);
ULPanel.add(scale);
ULPanel.add(multLabel);
ULPanel.add(mult);
unitListPanel.add(ULPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), unitListPanel, "Unit List Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
try {
Integer.valueOf(exp.getText().trim()).intValue();
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Exponent must be an integer.",
"Integer Expected", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
try {
Integer.valueOf(scale.getText().trim()).intValue();
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Scale must be an integer.",
"Integer Expected", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
try {
Double.valueOf(mult.getText().trim()).doubleValue();
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Multiplier must be a double.",
"Double Expected", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
if (option.equals("OK")) {
int index = unitList.getSelectedIndex();
unitList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
uList = Buttons.getList(uList, unitList);
unitList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
uList[index] = "";
if (!mult.getText().trim().equals("1.0")) {
uList[index] = mult.getText().trim() + " * ";
}
if (!scale.getText().trim().equals("0")) {
uList[index] = uList[index] + "10^" + scale.getText().trim() + " * ";
}
uList[index] = uList[index] + kindBox.getSelectedItem();
if (!exp.getText().trim().equals("1")) {
uList[index] = "( " + uList[index] + " )^" + exp.getText().trim();
}
sort(uList);
unitList.setListData(uList);
unitList.setSelectedIndex(index);
}
else {
JList add = new JList();
int index = unitList.getSelectedIndex();
String addStr;
addStr = "";
if (!mult.getText().trim().equals("1.0")) {
addStr = mult.getText().trim() + " * ";
}
if (!scale.getText().trim().equals("0")) {
addStr = addStr + "10^" + scale.getText().trim() + " * ";
}
addStr = addStr + kindBox.getSelectedItem();
if (!exp.getText().trim().equals("1")) {
addStr = "( " + addStr + " )^" + exp.getText().trim();
}
Object[] adding = { addStr };
add.setListData(adding);
add.setSelectedIndex(0);
unitList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(uList, unitList, add, false, null, null, null, null, null, null,
biosim.frame());
uList = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
uList[i] = (String) adding[i];
}
sort(uList);
unitList.setListData(uList);
unitList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (adding.length == 1) {
unitList.setSelectedIndex(0);
}
else {
unitList.setSelectedIndex(index);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), unitListPanel, "Unit List Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Convert unit kind to string
*/
private String unitToString(Unit unit) {
if (unit.isAmpere()) {
return "ampere";
}
else if (unit.isBecquerel()) {
return "becquerel";
}
else if (unit.isCandela()) {
return "candela";
}
else if (unit.isCelsius()) {
return "celsius";
}
else if (unit.isCoulomb()) {
return "coulomb";
}
else if (unit.isDimensionless()) {
return "dimensionless";
}
else if (unit.isFarad()) {
return "farad";
}
else if (unit.isGram()) {
return "gram";
}
else if (unit.isGray()) {
return "gray";
}
else if (unit.isHenry()) {
return "henry";
}
else if (unit.isHertz()) {
return "hertz";
}
else if (unit.isItem()) {
return "item";
}
else if (unit.isJoule()) {
return "joule";
}
else if (unit.isKatal()) {
return "katal";
}
else if (unit.isKelvin()) {
return "kelvin";
}
else if (unit.isKilogram()) {
return "kilogram";
}
else if (unit.isLitre()) {
return "litre";
}
else if (unit.isLumen()) {
return "lumen";
}
else if (unit.isLux()) {
return "lux";
}
else if (unit.isMetre()) {
return "metre";
}
else if (unit.isMole()) {
return "mole";
}
else if (unit.isNewton()) {
return "newton";
}
else if (unit.isOhm()) {
return "ohm";
}
else if (unit.isPascal()) {
return "pascal";
}
else if (unit.isRadian()) {
return "radian";
}
else if (unit.isSecond()) {
return "second";
}
else if (unit.isSiemens()) {
return "siemens";
}
else if (unit.isSievert()) {
return "sievert";
}
else if (unit.isSteradian()) {
return "steradian";
}
else if (unit.isTesla()) {
return "tesla";
}
else if (unit.isVolt()) {
return "volt";
}
else if (unit.isWatt()) {
return "watt";
}
else if (unit.isWeber()) {
return "weber";
}
return "Unknown";
}
/**
* Extract unit kind from string
*/
private String extractUnitKind(String selected) {
if (selected.contains(")^")) {
if (selected.contains("10^")) {
return selected.substring(selected.lastIndexOf("*") + 2, selected.indexOf(")") - 1);
}
else if (selected.contains("*")) {
return selected.substring(selected.lastIndexOf("*") + 2, selected.indexOf(")") - 1);
}
else {
return selected.substring(2, selected.indexOf(")") - 1);
}
}
else if (selected.contains("10^")) {
return selected.substring(selected.lastIndexOf("*") + 2);
}
else if (selected.contains("*")) {
mult.setText(selected.substring(0, selected.indexOf("*") - 1));
return selected.substring(selected.indexOf("*") + 2);
}
else {
return selected;
}
}
/**
* Extract unit exponent from string
*/
private String extractUnitExp(String selected) {
if (selected.contains(")^")) {
return selected.substring(selected.indexOf(")^") + 2);
}
return "1";
}
/**
* Extract unit scale from string
*/
private String extractUnitScale(String selected) {
if (selected.contains(")^")) {
if (selected.contains("10^")) {
return selected.substring(selected.indexOf("10^") + 3, selected.lastIndexOf("*") - 1);
}
}
else if (selected.contains("10^")) {
return selected.substring(selected.indexOf("10^") + 3, selected.lastIndexOf("*") - 1);
}
return "0";
}
/**
* Extract unit multiplier from string
*/
private String extractUnitMult(String selected) {
if (selected.contains(")^")) {
if (selected.contains("10^")) {
String multStr = selected.substring(2, selected.indexOf("*") - 1);
if (!multStr.contains("10^")) {
return multStr;
}
}
else if (selected.contains("*")) {
return selected.substring(2, selected.indexOf("*") - 1);
}
else if (selected.contains("10^")) {
String multStr = selected.substring(0, selected.indexOf("*") - 1);
if (!multStr.contains("10^")) {
return multStr;
}
}
else if (selected.contains("*")) {
return selected.substring(0, selected.indexOf("*") - 1);
}
}
return "1.0";
}
/**
* Creates a frame used to edit compartment types or create new ones.
*/
private void compTypeEditor(String option) {
if (option.equals("OK") && compTypes.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No compartment type selected.",
"Must Select a Compartment Type", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel compTypePanel = new JPanel();
JPanel cpTypPanel = new JPanel(new GridLayout(2, 2));
JLabel idLabel = new JLabel("ID:");
JLabel nameLabel = new JLabel("Name:");
compTypeID = new JTextField(12);
compTypeName = new JTextField(12);
String selectedID = "";
if (option.equals("OK")) {
try {
CompartmentType compType = document.getModel().getCompartmentType(
(((String) compTypes.getSelectedValue()).split(" ")[0]));
compTypeID.setText(compType.getId());
selectedID = compType.getId();
compTypeName.setText(compType.getName());
}
catch (Exception e) {
}
}
cpTypPanel.add(idLabel);
cpTypPanel.add(compTypeID);
cpTypPanel.add(nameLabel);
cpTypPanel.add(compTypeName);
compTypePanel.add(cpTypPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), compTypePanel,
"Compartment Type Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = checkID(compTypeID.getText().trim(), selectedID, false);
if (!error) {
if (option.equals("OK")) {
int index = compTypes.getSelectedIndex();
String val = ((String) compTypes.getSelectedValue()).split(" ")[0];
compTypes.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
cpTyp = Buttons.getList(cpTyp, compTypes);
compTypes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
CompartmentType c = document.getModel().getCompartmentType(val);
c.setId(compTypeID.getText().trim());
c.setName(compTypeName.getText().trim());
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(val)) {
usedIDs.set(i, compTypeID.getText().trim());
}
}
cpTyp[index] = compTypeID.getText().trim();
sort(cpTyp);
compTypes.setListData(cpTyp);
compTypes.setSelectedIndex(index);
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = document.getModel().getCompartment(i);
if (compartment.getCompartmentType().equals(val)) {
compartment.setCompartmentType(compTypeID.getText().trim());
}
}
int index1 = compartments.getSelectedIndex();
compartments.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
comps = Buttons.getList(comps, compartments);
compartments.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
for (int i = 0; i < comps.length; i++) {
if (comps[i].split(" ")[1].equals(val)) {
comps[i] = comps[i].split(" ")[0] + " " + compTypeID.getText().trim() + " "
+ comps[i].split(" ")[2];
}
}
sort(comps);
compartments.setListData(comps);
compartments.setSelectedIndex(index1);
}
else {
int index = compTypes.getSelectedIndex();
CompartmentType c = document.getModel().createCompartmentType();
c.setId(compTypeID.getText().trim());
c.setName(compTypeName.getText().trim());
usedIDs.add(compTypeID.getText().trim());
JList add = new JList();
Object[] adding = { compTypeID.getText().trim() };
add.setListData(adding);
add.setSelectedIndex(0);
compTypes.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(cpTyp, compTypes, add, false, null, null, null, null, null, null,
biosim.frame());
cpTyp = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
cpTyp[i] = (String) adding[i];
}
sort(cpTyp);
compTypes.setListData(cpTyp);
compTypes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumCompartmentTypes() == 1) {
compTypes.setSelectedIndex(0);
}
else {
compTypes.setSelectedIndex(index);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), compTypePanel,
"Compartment Type Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit species types or create new ones.
*/
private void specTypeEditor(String option) {
if (option.equals("OK") && specTypes.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No species type selected.",
"Must Select a Species Type", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel specTypePanel = new JPanel();
JPanel spTypPanel = new JPanel(new GridLayout(2, 2));
JLabel idLabel = new JLabel("ID:");
JLabel nameLabel = new JLabel("Name:");
specTypeID = new JTextField(12);
specTypeName = new JTextField(12);
String selectedID = "";
if (option.equals("OK")) {
try {
SpeciesType specType = document.getModel().getSpeciesType(
(((String) specTypes.getSelectedValue()).split(" ")[0]));
specTypeID.setText(specType.getId());
selectedID = specType.getId();
specTypeName.setText(specType.getName());
}
catch (Exception e) {
}
}
spTypPanel.add(idLabel);
spTypPanel.add(specTypeID);
spTypPanel.add(nameLabel);
spTypPanel.add(specTypeName);
specTypePanel.add(spTypPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), specTypePanel, "Species Type Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = checkID(specTypeID.getText().trim(), selectedID, false);
if (!error) {
if (option.equals("OK")) {
int index = specTypes.getSelectedIndex();
String val = ((String) specTypes.getSelectedValue()).split(" ")[0];
specTypes.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
spTyp = Buttons.getList(spTyp, specTypes);
specTypes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
SpeciesType s = document.getModel().getSpeciesType(val);
s.setId(specTypeID.getText().trim());
s.setName(specTypeName.getText().trim());
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(val)) {
usedIDs.set(i, specTypeID.getText().trim());
}
}
spTyp[index] = specTypeID.getText().trim();
sort(spTyp);
specTypes.setListData(spTyp);
specTypes.setSelectedIndex(index);
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
Species species = document.getModel().getSpecies(i);
if (species.getSpeciesType().equals(val)) {
species.setSpeciesType(specTypeID.getText().trim());
}
}
int index1 = species.getSelectedIndex();
species.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
specs = Buttons.getList(specs, species);
species.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
for (int i = 0; i < specs.length; i++) {
if (specs[i].split(" ")[1].equals(val)) {
specs[i] = specs[i].split(" ")[0] + " " + specTypeID.getText().trim() + " "
+ specs[i].split(" ")[2] + " " + specs[i].split(" ")[3];
}
}
sort(specs);
species.setListData(specs);
species.setSelectedIndex(index1);
}
else {
int index = specTypes.getSelectedIndex();
SpeciesType s = document.getModel().createSpeciesType();
s.setId(specTypeID.getText().trim());
s.setName(specTypeName.getText().trim());
usedIDs.add(specTypeID.getText().trim());
JList add = new JList();
Object[] adding = { specTypeID.getText().trim() };
add.setListData(adding);
add.setSelectedIndex(0);
specTypes.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(spTyp, specTypes, add, false, null, null, null, null, null, null,
biosim.frame());
spTyp = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
spTyp[i] = (String) adding[i];
}
sort(spTyp);
specTypes.setListData(spTyp);
specTypes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumSpeciesTypes() == 1) {
specTypes.setSelectedIndex(0);
}
else {
specTypes.setSelectedIndex(index);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), specTypePanel, "Species Type Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit initial assignments or create new ones.
*/
private void initEditor(String option) {
if (option.equals("OK") && initAssigns.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No initial assignment selected.",
"Must Select an Initial Assignment", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel initAssignPanel = new JPanel();
JPanel initPanel = new JPanel(new GridLayout(2, 2));
JLabel varLabel = new JLabel("Symbol:");
JLabel assignLabel = new JLabel("Assignment:");
initVar = new JComboBox();
String selected;
if (option.equals("OK")) {
selected = ((String) initAssigns.getSelectedValue());
}
else {
selected = new String("");
}
Model model = document.getModel();
ListOf ids = model.getListOfCompartments();
for (int i = 0; i < model.getNumCompartments(); i++) {
String id = ((Compartment) ids.get(i)).getId();
if (keepVar(selected.split(" ")[0], id, true, false, false, false)
&& ((Compartment) ids.get(i)).getSpatialDimensions() != 0) {
initVar.addItem(id);
}
}
ids = model.getListOfParameters();
for (int i = 0; i < model.getNumParameters(); i++) {
String id = ((Parameter) ids.get(i)).getId();
if (keepVar(selected.split(" ")[0], id, true, false, false, false)) {
initVar.addItem(id);
}
}
ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
String id = ((Species) ids.get(i)).getId();
if (keepVar(selected.split(" ")[0], id, true, false, false, false)) {
initVar.addItem(id);
}
}
initMath = new JTextField(12);
int Rindex = -1;
if (option.equals("OK")) {
initVar.setSelectedItem(selected.split(" ")[0]);
initMath.setText(selected.substring(selected.indexOf('=') + 2));
ListOf r = document.getModel().getListOfInitialAssignments();
for (int i = 0; i < document.getModel().getNumInitialAssignments(); i++) {
if (myFormulaToString(((InitialAssignment) r.get(i)).getMath()).equals(initMath.getText())
&& ((InitialAssignment) r.get(i)).getSymbol().equals(initVar.getSelectedItem())) {
Rindex = i;
}
}
}
initPanel.add(varLabel);
initPanel.add(initVar);
initPanel.add(assignLabel);
initPanel.add(initMath);
initAssignPanel.add(initPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), initAssignPanel,
"Initial Assignment Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
String addVar = "";
addVar = (String) initVar.getSelectedItem();
if (initMath.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "Initial assignment is missing.",
"Enter Assignment", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (myParseFormula(initMath.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Initial assignment is not valid.",
"Enter Valid Assignment", JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariables(initMath.getText().trim(), false, "",
false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Rule contains unknown variables.\n\n" + "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Unknown Variables",
JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = checkNumFunctionArguments(myParseFormula(initMath.getText().trim()));
}
if (!error) {
if (myParseFormula(initMath.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Initial assignment must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
if (!error) {
if (option.equals("OK")) {
int index = initAssigns.getSelectedIndex();
initAssigns.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
inits = Buttons.getList(inits, initAssigns);
initAssigns.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
InitialAssignment r = (InitialAssignment) (document.getModel()
.getListOfInitialAssignments()).get(Rindex);
String oldSymbol = r.getSymbol();
String oldInit = myFormulaToString(r.getMath());
String oldVal = inits[index];
r.setSymbol(addVar);
r.setMath(myParseFormula(initMath.getText().trim()));
inits[index] = addVar + " = " + myFormulaToString(r.getMath());
error = checkInitialAssignmentUnits(r);
if (!error) {
try {
inits = sortInitRules(inits);
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected in initial assignments.", "Cycle Detected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error && checkCycles(inits, rul)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected within initial assignments and assignment rules.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (error) {
r.setSymbol(oldSymbol);
r.setMath(myParseFormula(oldInit));
inits[index] = oldVal;
}
initAssigns.setListData(inits);
initAssigns.setSelectedIndex(index);
}
else {
JList add = new JList();
int index = rules.getSelectedIndex();
String addStr;
InitialAssignment r = document.getModel().createInitialAssignment();
r.setSymbol(addVar);
r.setMath(myParseFormula(initMath.getText().trim()));
addStr = addVar + " = " + myFormulaToString(r.getMath());
Object[] adding = { addStr };
add.setListData(adding);
add.setSelectedIndex(0);
initAssigns.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(inits, initAssigns, add, false, null, null, null, null, null, null,
biosim.frame());
String[] oldInits = inits;
inits = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
inits[i] = (String) adding[i];
}
error = checkInitialAssignmentUnits(r);
if (!error) {
try {
inits = sortInitRules(inits);
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected in initial assignments.", "Cycle Detected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error && checkCycles(inits, rul)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected within initial assignments and assignment rules.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (error) {
inits = oldInits;
ListOf ia = document.getModel().getListOfInitialAssignments();
for (int i = 0; i < document.getModel().getNumInitialAssignments(); i++) {
if (myFormulaToString(((InitialAssignment) ia.get(i)).getMath()).equals(
myFormulaToString(r.getMath()))
&& ((InitialAssignment) ia.get(i)).getSymbol().equals(r.getSymbol())) {
ia.remove(i);
}
}
}
initAssigns.setListData(inits);
initAssigns.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumInitialAssignments() == 1) {
initAssigns.setSelectedIndex(0);
}
else {
initAssigns.setSelectedIndex(index);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), initAssignPanel,
"Initial Assignment Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Determines if a variable is already in an initial or assignment rule
*/
private boolean keepVar(String selected, String id, boolean checkInit, boolean checkRate,
boolean checkEventAssign, boolean checkOnlyCurEvent) {
if (!selected.equals(id)) {
if (checkInit) {
for (int j = 0; j < inits.length; j++) {
if (id.equals(inits[j].split(" ")[0])) {
return false;
}
}
}
if (checkOnlyCurEvent) {
for (int j = 0; j < assign.length; j++) {
if (id.equals(assign[j].split(" ")[0])) {
return false;
}
}
}
if (checkEventAssign) {
ListOf e = document.getModel().getListOfEvents();
for (int i = 0; i < document.getModel().getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) e.get(i);
for (int j = 0; j < event.getNumEventAssignments(); j++) {
if (id.equals(event.getEventAssignment(j).getVariable())) {
return false;
}
}
}
}
for (int j = 0; j < rul.length; j++) {
if (id.equals(rul[j].split(" ")[0])) {
return false;
}
if (checkRate && id.equals(rul[j].split(" ")[1])) {
return false;
}
}
}
return true;
}
/**
* Creates a frame used to edit rules or create new ones.
*/
private void ruleEditor(String option) {
if (option.equals("OK") && rules.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No rule selected.", "Must Select a Rule",
JOptionPane.ERROR_MESSAGE);
return;
}
JPanel rulePanel = new JPanel();
JPanel rulPanel = new JPanel(new GridLayout(3, 2));
JLabel typeLabel = new JLabel("Type:");
JLabel varLabel = new JLabel("Variable:");
JLabel ruleLabel = new JLabel("Rule:");
String[] list = { "Algebraic", "Assignment", "Rate" };
ruleType = new JComboBox(list);
ruleVar = new JComboBox();
ruleMath = new JTextField(12);
ruleVar.setEnabled(false);
ruleType.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((String) ruleType.getSelectedItem()).equals("Assignment")) {
assignRuleVar("");
ruleVar.setEnabled(true);
}
else if (((String) ruleType.getSelectedItem()).equals("Rate")) {
rateRuleVar("");
ruleVar.setEnabled(true);
}
else {
ruleVar.removeAllItems();
ruleVar.setEnabled(false);
}
}
});
int Rindex = -1;
if (option.equals("OK")) {
ruleType.setEnabled(false);
String selected = ((String) rules.getSelectedValue());
// algebraic rule
if ((selected.split(" ")[0]).equals("0")) {
ruleType.setSelectedItem("Algebraic");
ruleVar.setEnabled(false);
ruleMath.setText(selected.substring(4));
ListOf r = document.getModel().getListOfRules();
for (int i = 0; i < document.getModel().getNumRules(); i++) {
if ((((Rule) r.get(i)).isAlgebraic())
&& (myFormulaToString(((Rule) r.get(i)).getMath()).equals(ruleMath.getText()))) {
Rindex = i;
}
}
}
else if ((selected.split(" ")[0]).equals("d(")) {
ruleType.setSelectedItem("Rate");
rateRuleVar(selected.split(" ")[1]);
ruleVar.setEnabled(true);
ruleVar.setSelectedItem(selected.split(" ")[1]);
ruleMath.setText(selected.substring(selected.indexOf('=') + 2));
ListOf r = document.getModel().getListOfRules();
for (int i = 0; i < document.getModel().getNumRules(); i++) {
if ((((Rule) r.get(i)).isRate())
&& ((Rule) r.get(i)).getVariable().equals(ruleVar.getSelectedItem())) {
Rindex = i;
}
}
}
else {
ruleType.setSelectedItem("Assignment");
assignRuleVar(selected.split(" ")[0]);
ruleVar.setEnabled(true);
ruleVar.setSelectedItem(selected.split(" ")[0]);
ruleMath.setText(selected.substring(selected.indexOf('=') + 2));
ListOf r = document.getModel().getListOfRules();
for (int i = 0; i < document.getModel().getNumRules(); i++) {
if ((((Rule) r.get(i)).isAssignment())
&& ((Rule) r.get(i)).getVariable().equals(ruleVar.getSelectedItem())) {
Rindex = i;
}
}
}
}
else {
if (!assignRuleVar("") && !rateRuleVar("")) {
String[] list1 = { "Algebraic" };
ruleType = new JComboBox(list1);
}
else if (!assignRuleVar("")) {
String[] list1 = { "Algebraic", "Rate" };
ruleType = new JComboBox(list1);
}
else if (!rateRuleVar("")) {
String[] list1 = { "Algebraic", "Assignment" };
ruleType = new JComboBox(list1);
}
}
rulPanel.add(typeLabel);
rulPanel.add(ruleType);
rulPanel.add(varLabel);
rulPanel.add(ruleVar);
rulPanel.add(ruleLabel);
rulPanel.add(ruleMath);
rulePanel.add(rulPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), rulePanel, "Rule Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
String addVar = "";
addVar = (String) ruleVar.getSelectedItem();
if (ruleMath.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "Rule must have formula.",
"Enter Rule Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (myParseFormula(ruleMath.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Rule formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariables(ruleMath.getText().trim(), false, "",
false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Rule contains unknown variables.\n\n" + "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Unknown Variables",
JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = checkNumFunctionArguments(myParseFormula(ruleMath.getText().trim()));
}
if (!error) {
if (myParseFormula(ruleMath.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(), "Rule must evaluate to a number.",
"Number Expected", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
if (!error) {
if (option.equals("OK")) {
int index = rules.getSelectedIndex();
rules.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
rul = Buttons.getList(rul, rules);
rules.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Rule r = (Rule) (document.getModel().getListOfRules()).get(Rindex);
String addStr;
String oldVar = "";
String oldMath = myFormulaToString(r.getMath());
if (ruleType.getSelectedItem().equals("Algebraic")) {
r.setMath(myParseFormula(ruleMath.getText().trim()));
addStr = "0 = " + myFormulaToString(r.getMath());
// checkOverDetermined();
}
else if (ruleType.getSelectedItem().equals("Rate")) {
oldVar = r.getVariable();
r.setVariable(addVar);
r.setMath(myParseFormula(ruleMath.getText().trim()));
error = checkRateRuleUnits(r);
addStr = "d( " + addVar + " )/dt = " + myFormulaToString(r.getMath());
}
else {
oldVar = r.getVariable();
r.setVariable(addVar);
r.setMath(myParseFormula(ruleMath.getText().trim()));
error = checkAssignmentRuleUnits(r);
addStr = addVar + " = " + myFormulaToString(r.getMath());
}
String oldVal = rul[index];
rul[index] = addStr;
if (!error) {
try {
rul = sortRules(rul);
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in assignments.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error && checkCycles(inits, rul)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected within initial assignments and assignment rules.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (error) {
if (!oldVar.equals("")) {
r.setVariable(oldVar);
}
r.setMath(myParseFormula(oldMath));
rul[index] = oldVal;
}
updateRules();
rules.setListData(rul);
rules.setSelectedIndex(index);
}
else {
JList add = new JList();
int index = rules.getSelectedIndex();
String addStr;
if (ruleType.getSelectedItem().equals("Algebraic")) {
addStr = "0 = " + myFormulaToString(myParseFormula(ruleMath.getText().trim()));
}
else if (ruleType.getSelectedItem().equals("Rate")) {
addStr = "d( " + addVar + " )/dt = "
+ myFormulaToString(myParseFormula(ruleMath.getText().trim()));
}
else {
addStr = addVar + " = " + myFormulaToString(myParseFormula(ruleMath.getText().trim()));
}
Object[] adding = { addStr };
add.setListData(adding);
add.setSelectedIndex(0);
rules.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(rul, rules, add, false, null, null, null, null, null, null, biosim
.frame());
String[] oldRul = rul;
rul = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
rul[i] = (String) adding[i];
}
try {
rul = sortRules(rul);
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in assignments.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
error = true;
rul = oldRul;
}
if (!error && checkCycles(inits, rul)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected within initial assignments and assignment rules.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
error = true;
rul = oldRul;
}
if (!error) {
if (ruleType.getSelectedItem().equals("Algebraic")) {
AlgebraicRule r = document.getModel().createAlgebraicRule();
r.setMath(myParseFormula(ruleMath.getText().trim()));
// checkOverDetermined();
}
else if (ruleType.getSelectedItem().equals("Rate")) {
RateRule r = document.getModel().createRateRule();
r.setVariable(addVar);
r.setMath(myParseFormula(ruleMath.getText().trim()));
error = checkRateRuleUnits(r);
}
else {
AssignmentRule r = document.getModel().createAssignmentRule();
r.setVariable(addVar);
r.setMath(myParseFormula(ruleMath.getText().trim()));
error = checkAssignmentRuleUnits(r);
}
}
if (error) {
rul = oldRul;
removeTheRule(addStr);
}
updateRules();
rules.setListData(rul);
rules.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumRules() == 1) {
rules.setSelectedIndex(0);
}
else {
rules.setSelectedIndex(index);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), rulePanel, "Rule Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Update rules
*/
private void updateRules() {
ListOf r = document.getModel().getListOfRules();
while (document.getModel().getNumRules() > 0) {
r.remove(0);
}
for (int i = 0; i < rul.length; i++) {
if (rul[i].split(" ")[0].equals("0")) {
AlgebraicRule rule = document.getModel().createAlgebraicRule();
rule.setMath(myParseFormula(rul[i].substring(rul[i].indexOf("=") + 1)));
}
else if (rul[i].split(" ")[0].equals("d(")) {
RateRule rule = document.getModel().createRateRule();
rule.setVariable(rul[i].split(" ")[1]);
rule.setMath(myParseFormula(rul[i].substring(rul[i].indexOf("=") + 1)));
}
else {
AssignmentRule rule = document.getModel().createAssignmentRule();
rule.setVariable(rul[i].split(" ")[0]);
rule.setMath(myParseFormula(rul[i].substring(rul[i].indexOf("=") + 1)));
}
}
}
/**
* Sort rules in order to be evaluated
*/
private String[] sortRules(String[] rules) {
String[] result = new String[rules.length];
int j = 0;
boolean[] used = new boolean[rules.length];
for (int i = 0; i < rules.length; i++) {
used[i] = false;
}
for (int i = 0; i < rules.length; i++) {
if (rules[i].split(" ")[0].equals("0")) {
result[j] = rules[i];
used[i] = true;
j++;
}
}
boolean progress;
do {
progress = false;
for (int i = 0; i < rules.length; i++) {
if (used[i] || (rules[i].split(" ")[0].equals("0"))
|| (rules[i].split(" ")[0].equals("d(")))
continue;
String[] rule = rules[i].split(" ");
boolean insert = true;
for (int k = 1; k < rule.length; k++) {
for (int l = 0; l < rules.length; l++) {
if (used[l] || (rules[l].split(" ")[0].equals("0"))
|| (rules[l].split(" ")[0].equals("d(")))
continue;
String[] rule2 = rules[l].split(" ");
if (rule[k].equals(rule2[0])) {
insert = false;
break;
}
}
if (!insert)
break;
}
if (insert) {
result[j] = rules[i];
j++;
progress = true;
used[i] = true;
}
}
}
while ((progress) && (j < rules.length));
for (int i = 0; i < rules.length; i++) {
if (rules[i].split(" ")[0].equals("d(")) {
result[j] = rules[i];
j++;
}
}
if (j != rules.length) {
throw new RuntimeException();
}
return result;
}
/**
* Sort initial rules in order to be evaluated
*/
private String[] sortInitRules(String[] initRules) {
String[] result = new String[initRules.length];
int j = 0;
boolean[] used = new boolean[initRules.length];
for (int i = 0; i < initRules.length; i++) {
used[i] = false;
}
boolean progress;
do {
progress = false;
for (int i = 0; i < initRules.length; i++) {
if (used[i])
continue;
String[] initRule = initRules[i].split(" ");
boolean insert = true;
for (int k = 1; k < initRule.length; k++) {
for (int l = 0; l < initRules.length; l++) {
if (used[l])
continue;
String[] initRule2 = initRules[l].split(" ");
if (initRule[k].equals(initRule2[0])) {
insert = false;
break;
}
}
if (!insert)
break;
}
if (insert) {
result[j] = initRules[i];
j++;
progress = true;
used[i] = true;
}
}
}
while ((progress) && (j < initRules.length));
if (j != initRules.length) {
throw new RuntimeException();
}
return result;
}
/**
* Check for cycles in initialAssignments and assignmentRules
*/
private boolean checkCycles(String[] initRules, String[] rules) {
String[] result = new String[rules.length + initRules.length];
int j = 0;
boolean[] used = new boolean[rules.length + initRules.length];
for (int i = 0; i < rules.length + initRules.length; i++) {
used[i] = false;
}
for (int i = 0; i < rules.length; i++) {
if (rules[i].split(" ")[0].equals("0")) {
result[j] = rules[i];
used[i] = true;
j++;
}
}
boolean progress;
do {
progress = false;
for (int i = 0; i < rules.length + initRules.length; i++) {
String[] rule;
if (i < rules.length) {
if (used[i] || (rules[i].split(" ")[0].equals("0"))
|| (rules[i].split(" ")[0].equals("d(")))
continue;
rule = rules[i].split(" ");
}
else {
if (used[i])
continue;
rule = initRules[i - rules.length].split(" ");
}
boolean insert = true;
for (int k = 1; k < rule.length; k++) {
for (int l = 0; l < rules.length + initRules.length; l++) {
String rule2;
if (l < rules.length) {
if (used[l] || (rules[l].split(" ")[0].equals("0"))
|| (rules[l].split(" ")[0].equals("d(")))
continue;
rule2 = rules[l].split(" ")[0];
}
else {
if (used[l])
continue;
rule2 = initRules[l - rules.length].split(" ")[0];
}
if (rule[k].equals(rule2)) {
insert = false;
break;
}
}
if (!insert)
break;
}
if (insert) {
if (i < rules.length) {
result[j] = rules[i];
}
else {
result[j] = initRules[i - rules.length];
}
j++;
progress = true;
used[i] = true;
}
}
}
while ((progress) && (j < rules.length + initRules.length));
for (int i = 0; i < rules.length; i++) {
if (rules[i].split(" ")[0].equals("d(")) {
result[j] = rules[i];
j++;
}
}
if (j != rules.length + initRules.length) {
return true;
}
return false;
}
/**
* Create check if species used in reaction
*/
private boolean usedInReaction(String id) {
for (int i = 0; i < document.getModel().getNumReactions(); i++) {
for (int j = 0; j < document.getModel().getReaction(i).getNumReactants(); j++) {
if (document.getModel().getReaction(i).getReactant(j).getSpecies().equals(id)) {
return true;
}
}
for (int j = 0; j < document.getModel().getReaction(i).getNumProducts(); j++) {
if (document.getModel().getReaction(i).getProduct(j).getSpecies().equals(id)) {
return true;
}
}
}
return false;
}
/**
* Create comboBox for assignments rules
*/
private boolean assignRuleVar(String selected) {
boolean assignOK = false;
ruleVar.removeAllItems();
Model model = document.getModel();
ListOf ids = model.getListOfCompartments();
for (int i = 0; i < model.getNumCompartments(); i++) {
String id = ((Compartment) ids.get(i)).getId();
if (!((Compartment) ids.get(i)).getConstant()) {
if (keepVar(selected, id, true, true, true, false)) {
ruleVar.addItem(((Compartment) ids.get(i)).getId());
assignOK = true;
}
}
}
ids = model.getListOfParameters();
for (int i = 0; i < model.getNumParameters(); i++) {
String id = ((Parameter) ids.get(i)).getId();
if (!((Parameter) ids.get(i)).getConstant()) {
if (keepVar(selected, id, true, true, true, false)) {
ruleVar.addItem(((Parameter) ids.get(i)).getId());
assignOK = true;
}
}
}
ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
String id = ((Species) ids.get(i)).getId();
if (!((Species) ids.get(i)).getConstant()) {
if (keepVar(selected, id, true, true, true, false))
if (((Species) ids.get(i)).getBoundaryCondition() || !usedInReaction(id)) {
ruleVar.addItem(((Species) ids.get(i)).getId());
assignOK = true;
}
}
}
return assignOK;
}
/**
* Create comboBox for rate rules
*/
private boolean rateRuleVar(String selected) {
boolean rateOK = false;
ruleVar.removeAllItems();
Model model = document.getModel();
ListOf ids = model.getListOfCompartments();
for (int i = 0; i < model.getNumCompartments(); i++) {
String id = ((Compartment) ids.get(i)).getId();
if (!((Compartment) ids.get(i)).getConstant()) {
if (keepVar(selected, id, false, true, false, false)) {
ruleVar.addItem(((Compartment) ids.get(i)).getId());
rateOK = true;
}
}
}
ids = model.getListOfParameters();
for (int i = 0; i < model.getNumParameters(); i++) {
String id = ((Parameter) ids.get(i)).getId();
if (!((Parameter) ids.get(i)).getConstant()) {
if (keepVar(selected, id, false, true, false, false)) {
ruleVar.addItem(((Parameter) ids.get(i)).getId());
rateOK = true;
}
}
}
ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
String id = ((Species) ids.get(i)).getId();
if (!((Species) ids.get(i)).getConstant()) {
if (keepVar(selected, id, false, true, false, false))
if (((Species) ids.get(i)).getBoundaryCondition() || !usedInReaction(id)) {
ruleVar.addItem(((Species) ids.get(i)).getId());
rateOK = true;
}
}
}
return rateOK;
}
/**
* Creates a frame used to edit events or create new ones.
*/
private void eventEditor(String option) {
if (option.equals("OK") && events.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No event selected.", "Must Select an Event",
JOptionPane.ERROR_MESSAGE);
return;
}
JPanel eventPanel = new JPanel(new BorderLayout());
// JPanel evPanel = new JPanel(new GridLayout(2, 2));
JPanel evPanel = new JPanel(new GridLayout(4, 2));
JLabel IDLabel = new JLabel("ID:");
JLabel NameLabel = new JLabel("Name:");
JLabel triggerLabel = new JLabel("Trigger:");
JLabel delayLabel = new JLabel("Delay:");
eventID = new JTextField(12);
eventName = new JTextField(12);
eventTrigger = new JTextField(12);
eventDelay = new JTextField(12);
JPanel eventAssignPanel = new JPanel(new BorderLayout());
JPanel addEventAssign = new JPanel();
addAssignment = new JButton("Add Assignment");
removeAssignment = new JButton("Remove Assignment");
editAssignment = new JButton("Edit Assignment");
addEventAssign.add(addAssignment);
addEventAssign.add(removeAssignment);
addEventAssign.add(editAssignment);
addAssignment.addActionListener(this);
removeAssignment.addActionListener(this);
editAssignment.addActionListener(this);
JLabel eventAssignLabel = new JLabel("List of Event Assignments:");
eventAssign = new JList();
eventAssign.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(260, 220));
scroll.setPreferredSize(new Dimension(276, 152));
scroll.setViewportView(eventAssign);
assign = new String[0];
int Eindex = -1;
if (option.equals("OK")) {
String selected = ((String) events.getSelectedValue());
eventTrigger.setText(selected);
ListOf e = document.getModel().getListOfEvents();
for (int i = 0; i < document.getModel().getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) e.get(i);
if (myFormulaToString(event.getTrigger().getMath()).equals(selected)) {
Eindex = i;
eventID.setText(event.getId());
eventName.setText(event.getName());
if (event.isSetDelay()) {
eventDelay.setText(myFormulaToString(event.getDelay().getMath()));
}
assign = new String[(int) event.getNumEventAssignments()];
origAssign = new String[(int) event.getNumEventAssignments()];
for (int j = 0; j < event.getNumEventAssignments(); j++) {
assign[j] = event.getEventAssignment(j).getVariable() + " = "
+ myFormulaToString(event.getEventAssignment(j).getMath());
origAssign[j] = event.getEventAssignment(j).getVariable() + " = "
+ myFormulaToString(event.getEventAssignment(j).getMath());
}
}
}
}
sort(assign);
eventAssign.setListData(assign);
eventAssign.setSelectedIndex(0);
eventAssign.addMouseListener(this);
eventAssignPanel.add(eventAssignLabel, "North");
eventAssignPanel.add(scroll, "Center");
eventAssignPanel.add(addEventAssign, "South");
evPanel.add(IDLabel);
evPanel.add(eventID);
evPanel.add(NameLabel);
evPanel.add(eventName);
evPanel.add(triggerLabel);
evPanel.add(eventTrigger);
evPanel.add(delayLabel);
evPanel.add(eventDelay);
eventPanel.add(evPanel, "North");
eventPanel.add(eventAssignPanel, "South");
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), eventPanel, "Event Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
if (eventTrigger.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "Event must have a trigger formula.",
"Enter Trigger Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (myParseFormula(eventTrigger.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Trigger formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (!myParseFormula(eventTrigger.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(), "Trigger formula must be of type Boolean.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (!eventDelay.getText().trim().equals("")
&& myParseFormula(eventDelay.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Delay formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (assign.length == 0) {
JOptionPane.showMessageDialog(biosim.frame(),
"Event must have at least one event assignment.", "Event Assignment Needed",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariables(eventTrigger.getText().trim(), false,
"", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Event trigger contains unknown variables.\n\n" + "Unknown variables:\n"
+ invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Unknown Variables",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
invalidVars = getInvalidVariables(eventDelay.getText().trim(), false, "", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Event delay contains unknown variables.\n\n" + "Unknown variables:\n"
+ invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Unknown Variables",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
error = checkNumFunctionArguments(myParseFormula(eventTrigger.getText().trim()));
}
if ((!error) && (!eventDelay.getText().trim().equals(""))) {
error = checkNumFunctionArguments(myParseFormula(eventDelay.getText().trim()));
if (!error) {
if (myParseFormula(eventDelay.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Event delay must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
}
if (!error) {
if (option.equals("OK")) {
int index = events.getSelectedIndex();
events.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
ev = Buttons.getList(ev, events);
events.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
org.sbml.libsbml.Event e = (org.sbml.libsbml.Event) (document.getModel()
.getListOfEvents()).get(Eindex);
while (e.getNumEventAssignments() > 0) {
e.getListOfEventAssignments().remove(0);
}
for (int i = 0; i < assign.length; i++) {
EventAssignment ea = e.createEventAssignment();
ea.setVariable(assign[i].split(" ")[0]);
ea.setMath(myParseFormula(assign[i].split("=")[1].trim()));
error = checkEventAssignmentUnits(ea);
if (error)
break;
}
if (!error) {
if (eventDelay.getText().trim().equals("")) {
e.unsetDelay();
}
else {
String oldDelayStr = "";
if (e.isSetDelay()) {
oldDelayStr = myFormulaToString(e.getDelay().getMath());
}
Delay delay = new Delay(myParseFormula(eventDelay.getText().trim()));
e.setDelay(delay);
error = checkEventDelayUnits(delay);
if (error) {
if (oldDelayStr.equals("")) {
e.unsetDelay();
}
else {
Delay oldDelay = new Delay(myParseFormula(oldDelayStr));
e.setDelay(oldDelay);
}
}
}
}
if (!error) {
Trigger trigger = new Trigger(myParseFormula(eventTrigger.getText().trim()));
e.setTrigger(trigger);
if (eventID.getText().trim().equals("")) {
e.unsetId();
}
else {
e.setId(eventID.getText().trim());
}
if (eventName.getText().trim().equals("")) {
e.unsetName();
}
else {
e.setName(eventName.getText().trim());
}
ev[index] = myFormulaToString(e.getTrigger().getMath());
sort(ev);
events.setListData(ev);
events.setSelectedIndex(index);
}
else {
while (e.getNumEventAssignments() > 0) {
e.getListOfEventAssignments().remove(0);
}
for (int i = 0; i < origAssign.length; i++) {
EventAssignment ea = e.createEventAssignment();
ea.setVariable(origAssign[i].split(" ")[0]);
ea.setMath(myParseFormula(origAssign[i].split("=")[1].trim()));
}
}
}
else {
JList add = new JList();
int index = events.getSelectedIndex();
org.sbml.libsbml.Event e = document.getModel().createEvent();
Trigger trigger = new Trigger(myParseFormula(eventTrigger.getText().trim()));
e.setTrigger(trigger);
if (!eventDelay.getText().trim().equals("")) {
Delay delay = new Delay(myParseFormula(eventDelay.getText().trim()));
e.setDelay(delay);
error = checkEventDelayUnits(delay);
}
if (!error) {
for (int i = 0; i < assign.length; i++) {
EventAssignment ea = e.createEventAssignment();
ea.setVariable(assign[i].split(" ")[0]);
ea.setMath(myParseFormula(assign[i].split("=")[1].trim()));
error = checkEventAssignmentUnits(ea);
if (error)
break;
}
}
if (!eventID.getText().trim().equals("")) {
e.setId(eventID.getText().trim());
}
if (!eventName.getText().trim().equals("")) {
e.setName(eventName.getText().trim());
}
Object[] adding = { myFormulaToString(e.getTrigger().getMath()) };
add.setListData(adding);
add.setSelectedIndex(0);
events.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(ev, events, add, false, null, null, null, null, null, null, biosim
.frame());
ev = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
ev[i] = (String) adding[i];
}
sort(ev);
events.setListData(ev);
events.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumEvents() == 1) {
events.setSelectedIndex(0);
}
else {
events.setSelectedIndex(index);
}
if (error) {
removeTheEvent(myFormulaToString(e.getTrigger().getMath()));
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), eventPanel, "Event Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit event assignments or create new ones.
*/
private void eventAssignEditor(String option) {
if (option.equals("OK") && eventAssign.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No event assignment selected.",
"Must Select an Event Assignment", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel eventAssignPanel = new JPanel();
JPanel EAPanel = new JPanel(new GridLayout(2, 2));
JLabel idLabel = new JLabel("Variable:");
JLabel eqnLabel = new JLabel("Assignment:");
eaID = new JComboBox();
String selected;
if (option.equals("OK")) {
selected = ((String) eventAssign.getSelectedValue()).split(" ")[0];
}
else {
selected = "";
}
Model model = document.getModel();
ListOf ids = model.getListOfCompartments();
for (int i = 0; i < model.getNumCompartments(); i++) {
String id = ((Compartment) ids.get(i)).getId();
if (!((Compartment) ids.get(i)).getConstant()) {
if (keepVar(selected, id, false, false, false, true)) {
eaID.addItem(id);
}
}
}
ids = model.getListOfParameters();
for (int i = 0; i < model.getNumParameters(); i++) {
String id = ((Parameter) ids.get(i)).getId();
if (!((Parameter) ids.get(i)).getConstant()) {
if (keepVar(selected, id, false, false, false, true)) {
eaID.addItem(id);
}
}
}
ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
String id = ((Species) ids.get(i)).getId();
if (!((Species) ids.get(i)).getConstant()) {
if (keepVar(selected, id, false, false, false, true)) {
eaID.addItem(id);
}
}
}
eqn = new JTextField(12);
if (option.equals("OK")) {
String selectAssign = ((String) eventAssign.getSelectedValue());
eaID.setSelectedItem(selectAssign.split(" ")[0]);
eqn.setText(selectAssign.split("=")[1].trim());
}
EAPanel.add(idLabel);
EAPanel.add(eaID);
EAPanel.add(eqnLabel);
EAPanel.add(eqn);
eventAssignPanel.add(EAPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), eventAssignPanel,
"Event Asssignment Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
if (eqn.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "Event assignment is missing.",
"Enter Assignment", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (myParseFormula(eqn.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Event assignment is not valid.",
"Enter Valid Assignment", JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariables(eqn.getText().trim(), false, "", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Event assignment contains unknown variables.\n\n" + "Unknown variables:\n"
+ invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Unknown Variables",
JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = checkNumFunctionArguments(myParseFormula(eqn.getText().trim()));
}
if (!error) {
if (myParseFormula(eqn.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Event assignment must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
if (!error) {
if (option.equals("OK")) {
int index = eventAssign.getSelectedIndex();
eventAssign.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
assign = Buttons.getList(assign, eventAssign);
eventAssign.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
assign[index] = eaID.getSelectedItem() + " = " + eqn.getText().trim();
sort(assign);
eventAssign.setListData(assign);
eventAssign.setSelectedIndex(index);
}
else {
JList add = new JList();
int index = eventAssign.getSelectedIndex();
Object[] adding = { eaID.getSelectedItem() + " = " + eqn.getText().trim() };
add.setListData(adding);
add.setSelectedIndex(0);
eventAssign.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(assign, eventAssign, add, false, null, null, null, null, null, null,
biosim.frame());
assign = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
assign[i] = (String) adding[i];
}
sort(assign);
eventAssign.setListData(assign);
eventAssign.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (adding.length == 1) {
eventAssign.setSelectedIndex(0);
}
else {
eventAssign.setSelectedIndex(index);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), eventAssignPanel,
"Event Assignment Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit constraints or create new ones.
*/
private void constraintEditor(String option) {
if (option.equals("OK") && constraints.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No constraint selected.",
"Must Select a Constraint", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel constraintPanel = new JPanel();
JPanel consPanel = new JPanel(new GridLayout(3, 2));
JLabel IDLabel = new JLabel("ID:");
JLabel mathLabel = new JLabel("Constraint:");
JLabel messageLabel = new JLabel("Messsage:");
consID = new JTextField(20);
consMath = new JTextField(20);
consMessage = new JTextField(20);
String selectedID = "";
int Cindex = -1;
if (option.equals("OK")) {
String selected = ((String) constraints.getSelectedValue());
consMath.setText(selected);
ListOf c = document.getModel().getListOfConstraints();
for (int i = 0; i < document.getModel().getNumConstraints(); i++) {
if (myFormulaToString(((Constraint) c.get(i)).getMath()).equals(selected)) {
Cindex = i;
if (((Constraint) c.get(i)).isSetMetaId()) {
selectedID = ((Constraint) c.get(i)).getMetaId();
consID.setText(selectedID);
}
if (((Constraint) c.get(i)).isSetMessage()) {
String message = XMLNode.convertXMLNodeToString(((Constraint) c.get(i)).getMessage());
message = message.substring(message.indexOf("xhtml\">") + 7, message.indexOf("</p>"));
consMessage.setText(message);
}
}
}
}
consPanel.add(IDLabel);
consPanel.add(consID);
consPanel.add(mathLabel);
consPanel.add(consMath);
consPanel.add(messageLabel);
consPanel.add(consMessage);
constraintPanel.add(consPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), constraintPanel, "Constraint Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = checkID(consID.getText().trim(), selectedID, false);
if (!error) {
if (consMath.getText().trim().equals("")
|| myParseFormula(consMath.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (!myParseFormula(consMath.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Constraint formula must be of type Boolean.", "Enter Valid Formula",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariables(consMath.getText().trim(), false, "",
false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Constraint contains unknown variables.\n\n" + "Unknown variables:\n"
+ invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Unknown Variables",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
if (option.equals("OK")) {
int index = constraints.getSelectedIndex();
constraints.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
cons = Buttons.getList(cons, constraints);
constraints.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Constraint c = (Constraint) (document.getModel().getListOfConstraints()).get(Cindex);
c.setMath(myParseFormula(consMath.getText().trim()));
c.setMetaId(consID.getText().trim());
if (!consMessage.getText().trim().equals("")) {
XMLNode xmlNode = XMLNode
.convertStringToXMLNode("<message><p xmlns=\"http://www.w3.org/1999/xhtml\">"
+ consMessage.getText().trim() + "</p></message>");
c.setMessage(xmlNode);
}
else {
c.unsetMessage();
}
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(selectedID)) {
usedIDs.set(i, consID.getText().trim());
}
}
cons[index] = myFormulaToString(c.getMath());
sort(cons);
constraints.setListData(cons);
constraints.setSelectedIndex(index);
}
else {
JList add = new JList();
int index = rules.getSelectedIndex();
Constraint c = document.getModel().createConstraint();
c.setMath(myParseFormula(consMath.getText().trim()));
c.setMetaId(consID.getText().trim());
if (!consMessage.getText().trim().equals("")) {
XMLNode xmlNode = XMLNode
.convertStringToXMLNode("<message><p xmlns=\"http://www.w3.org/1999/xhtml\">"
+ consMessage.getText().trim() + "</p></message>");
c.setMessage(xmlNode);
}
usedIDs.add(consID.getText().trim());
Object[] adding = { myFormulaToString(c.getMath()) };
add.setListData(adding);
add.setSelectedIndex(0);
constraints.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(cons, constraints, add, false, null, null, null, null, null, null,
biosim.frame());
cons = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
cons[i] = (String) adding[i];
}
sort(cons);
constraints.setListData(cons);
constraints.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumConstraints() == 1) {
constraints.setSelectedIndex(0);
}
else {
constraints.setSelectedIndex(index);
}
}
change = true;
}
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), constraintPanel, "Constraint Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit compartments or create new ones.
*/
private void compartEditor(String option) {
if (option.equals("OK") && compartments.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No compartment selected.",
"Must Select a Compartment", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel compartPanel = new JPanel();
JPanel compPanel;
if (paramsOnly) {
compPanel = new JPanel(new GridLayout(13, 2));
}
else {
compPanel = new JPanel(new GridLayout(8, 2));
}
JLabel idLabel = new JLabel("ID:");
JLabel nameLabel = new JLabel("Name:");
JLabel compTypeLabel = new JLabel("Type:");
JLabel dimLabel = new JLabel("Dimensions:");
JLabel outsideLabel = new JLabel("Outside:");
JLabel constLabel = new JLabel("Constant:");
JLabel sizeLabel = new JLabel("Size:");
JLabel compUnitsLabel = new JLabel("Units:");
JLabel startLabel = new JLabel("Start:");
JLabel stopLabel = new JLabel("Stop:");
JLabel stepLabel = new JLabel("Step:");
JLabel levelLabel = new JLabel("Level:");
compID = new JTextField(12);
compName = new JTextField(12);
ListOf listOfCompTypes = document.getModel().getListOfCompartmentTypes();
String[] compTypeList = new String[(int) document.getModel().getNumCompartmentTypes() + 1];
compTypeList[0] = "( none )";
for (int i = 0; i < document.getModel().getNumCompartmentTypes(); i++) {
compTypeList[i + 1] = ((CompartmentType) listOfCompTypes.get(i)).getId();
}
sort(compTypeList);
Object[] choices = compTypeList;
compTypeBox = new JComboBox(choices);
Object[] dims = { "0", "1", "2", "3" };
dimBox = new JComboBox(dims);
dimBox.setSelectedItem("3");
compSize = new JTextField(12);
compSize.setText("1.0");
compUnits = new JComboBox();
compOutside = new JComboBox();
String[] optionsTF = { "true", "false" };
compConstant = new JComboBox(optionsTF);
compConstant.setSelectedItem("true");
String selected = "";
editComp = false;
String selectedID = "";
if (option.equals("OK")) {
selected = ((String) compartments.getSelectedValue()).split(" ")[0];
editComp = true;
}
setCompartOptions(selected, "3");
dimBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (editComp) {
setCompartOptions(((String) compartments.getSelectedValue()).split(" ")[0],
(String) dimBox.getSelectedItem());
}
else {
setCompartOptions("", (String) dimBox.getSelectedItem());
}
}
});
String[] list = { "Original", "Custom", "Sweep" };
String[] list1 = { "1", "2" };
final JComboBox type = new JComboBox(list);
final JTextField start = new JTextField();
final JTextField stop = new JTextField();
final JTextField step = new JTextField();
final JComboBox level = new JComboBox(list1);
if (paramsOnly) {
compID.setEnabled(false);
compName.setEnabled(false);
compTypeBox.setEnabled(false);
dimBox.setEnabled(false);
compUnits.setEnabled(false);
compOutside.setEnabled(false);
compConstant.setEnabled(false);
compSize.setEnabled(false);
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
}
if (option.equals("OK")) {
try {
Compartment compartment = document.getModel().getCompartment(
(((String) compartments.getSelectedValue()).split(" ")[0]));
compID.setText(compartment.getId());
selectedID = compartment.getId();
compName.setText(compartment.getName());
if (compartment.isSetCompartmentType()) {
compTypeBox.setSelectedItem(compartment.getCompartmentType());
}
dimBox.setSelectedItem(String.valueOf(compartment.getSpatialDimensions()));
setCompartOptions(((String) compartments.getSelectedValue()).split(" ")[0], String
.valueOf(compartment.getSpatialDimensions()));
if (compartment.isSetSize()) {
compSize.setText("" + compartment.getSize());
}
if (compartment.isSetUnits()) {
compUnits.setSelectedItem(compartment.getUnits());
}
else {
compUnits.setSelectedItem("( none )");
}
if (compartment.isSetOutside()) {
compOutside.setSelectedItem(compartment.getOutside());
}
else {
compOutside.setSelectedItem("( none )");
}
if (compartment.getConstant()) {
compConstant.setSelectedItem("true");
}
else {
compConstant.setSelectedItem("false");
}
if (paramsOnly
&& (((String) compartments.getSelectedValue()).contains("Custom") || ((String) compartments
.getSelectedValue()).contains("Sweep"))) {
if (((String) compartments.getSelectedValue()).contains("Custom")) {
type.setSelectedItem("Custom");
}
else {
type.setSelectedItem("Sweep");
}
if (((String) type.getSelectedItem()).equals("Sweep")) {
String[] splits = ((String) compartments.getSelectedValue()).split(" ");
String sweepVal = splits[splits.length - 1];
start.setText((sweepVal).split(",")[0].substring(1).trim());
stop.setText((sweepVal).split(",")[1].trim());
step.setText((sweepVal).split(",")[2].trim());
level.setSelectedItem((sweepVal).split(",")[3].replace(")", "").trim());
start.setEnabled(true);
stop.setEnabled(true);
step.setEnabled(true);
level.setEnabled(true);
compSize.setEnabled(false);
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
compSize.setEnabled(true);
}
}
}
catch (Exception e) {
}
}
compPanel.add(idLabel);
compPanel.add(compID);
compPanel.add(nameLabel);
compPanel.add(compName);
compPanel.add(compTypeLabel);
compPanel.add(compTypeBox);
compPanel.add(dimLabel);
compPanel.add(dimBox);
compPanel.add(outsideLabel);
compPanel.add(compOutside);
compPanel.add(constLabel);
compPanel.add(compConstant);
if (paramsOnly) {
JLabel typeLabel = new JLabel("Value Type:");
type.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!((String) type.getSelectedItem()).equals("Original")) {
if (((String) type.getSelectedItem()).equals("Sweep")) {
start.setEnabled(true);
stop.setEnabled(true);
step.setEnabled(true);
level.setEnabled(true);
compSize.setEnabled(false);
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
compSize.setEnabled(true);
}
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
compSize.setEnabled(false);
SBMLReader reader = new SBMLReader();
SBMLDocument d = reader.readSBML(file);
if (d.getModel().getCompartment(
((String) compartments.getSelectedValue()).split(" ")[0]).isSetSize()) {
compSize.setText(d.getModel().getCompartment(
((String) compartments.getSelectedValue()).split(" ")[0]).getSize()
+ "");
}
}
}
});
compPanel.add(typeLabel);
compPanel.add(type);
}
compPanel.add(sizeLabel);
compPanel.add(compSize);
compPanel.add(compUnitsLabel);
compPanel.add(compUnits);
if (paramsOnly) {
compPanel.add(startLabel);
compPanel.add(start);
compPanel.add(stopLabel);
compPanel.add(stop);
compPanel.add(stepLabel);
compPanel.add(step);
compPanel.add(levelLabel);
compPanel.add(level);
}
compartPanel.add(compPanel);
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), compartPanel, "Compartment Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = checkID(compID.getText().trim(), selectedID, false);
if (!error && option.equals("OK") && compConstant.getSelectedItem().equals("true")) {
String val = ((String) compartments.getSelectedValue()).split(" ")[0];
error = checkConstant("Compartment", val);
}
if (!error && option.equals("OK") && dimBox.getSelectedItem().equals("0")) {
String val = ((String) compartments.getSelectedValue()).split(" ")[0];
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
Species species = document.getModel().getSpecies(i);
if ((species.getCompartment().equals(val)) && (species.isSetInitialConcentration())) {
JOptionPane
.showMessageDialog(
biosim.frame(),
"Compartment with 0-dimensions cannot contain species with an initial concentration.",
"Cannot be 0 Dimensions", JOptionPane.ERROR_MESSAGE);
error = true;
break;
}
}
if (!error) {
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = document.getModel().getCompartment(i);
if (compartment.getOutside().equals(val)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Compartment with 0-dimensions cannot be outside another compartment.",
"Cannot be 0 Dimensions", JOptionPane.ERROR_MESSAGE);
error = true;
break;
}
}
}
}
Double addCompSize = 1.0;
if ((!error) && (Integer.parseInt((String) dimBox.getSelectedItem()) != 0)) {
try {
addCompSize = Double.parseDouble(compSize.getText().trim());
}
catch (Exception e1) {
error = true;
JOptionPane.showMessageDialog(biosim.frame(),
"The compartment size must be a real number.", "Enter a Valid Size",
JOptionPane.ERROR_MESSAGE);
}
}
if (!error) {
if (!compOutside.getSelectedItem().equals("( none )")) {
if (checkOutsideCycle(compID.getText().trim(), (String) compOutside.getSelectedItem(), 0)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Compartment contains itself through outside references.",
"Cycle in Outside References", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
if (!error) {
if (((String) dimBox.getSelectedItem()).equals("0") && (variableInUse(selected, true))) {
error = true;
}
}
if (!error) {
String addComp = "";
String selCompType = (String) compTypeBox.getSelectedItem();
String unit = (String) compUnits.getSelectedItem();
if (paramsOnly && !((String) type.getSelectedItem()).equals("Original")) {
int index = compartments.getSelectedIndex();
String[] splits = comps[index].split(" ");
for (int i = 0; i < splits.length - 2; i++) {
addComp += splits[i] + " ";
}
if (!splits[splits.length - 2].equals("Custom")
&& !splits[splits.length - 2].equals("Sweep")) {
addComp += splits[splits.length - 2] + " " + splits[splits.length - 1] + " ";
}
if (((String) type.getSelectedItem()).equals("Sweep")) {
try {
double startVal = Double.parseDouble(start.getText().trim());
double stopVal = Double.parseDouble(stop.getText().trim());
double stepVal = Double.parseDouble(step.getText().trim());
addComp += "Sweep (" + startVal + "," + stopVal + "," + stepVal + ","
+ level.getSelectedItem() + ")";
}
catch (Exception e1) {
error = true;
JOptionPane.showMessageDialog(biosim.frame(),
"The start, stop, and step fields must be real numbers.", "Enter a Valid Sweep",
JOptionPane.ERROR_MESSAGE);
}
}
else {
addComp += "Custom " + addCompSize;
}
}
else {
addComp = compID.getText().trim();
if (!selCompType.equals("( none )")) {
addComp += " " + selCompType;
}
if (!unit.equals("( none )")) {
addComp += " " + addCompSize + " " + unit;
}
else {
addComp += " " + addCompSize;
}
}
if (!error) {
if (option.equals("OK")) {
int index = compartments.getSelectedIndex();
String val = ((String) compartments.getSelectedValue()).split(" ")[0];
compartments.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
comps = Buttons.getList(comps, compartments);
compartments.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Compartment c = document.getModel().getCompartment(val);
c.setId(compID.getText().trim());
c.setName(compName.getText().trim());
if (!selCompType.equals("( none )")) {
c.setCompartmentType(selCompType);
}
else {
c.unsetCompartmentType();
}
c.setSpatialDimensions(Integer.parseInt((String) dimBox.getSelectedItem()));
if (compSize.getText().trim().equals("")) {
c.unsetSize();
}
else {
c.setSize(Double.parseDouble(compSize.getText().trim()));
}
if (compUnits.getSelectedItem().equals("( none )")) {
c.unsetUnits();
}
else {
c.setUnits((String) compUnits.getSelectedItem());
}
if (compOutside.getSelectedItem().equals("( none )")) {
c.unsetOutside();
}
else {
c.setOutside((String) compOutside.getSelectedItem());
}
if (compConstant.getSelectedItem().equals("true")) {
c.setConstant(true);
}
else {
c.setConstant(false);
}
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(val)) {
usedIDs.set(i, compID.getText().trim());
}
}
comps[index] = addComp;
sort(comps);
compartments.setListData(comps);
compartments.setSelectedIndex(index);
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
Species species = document.getModel().getSpecies(i);
if (species.getCompartment().equals(val)) {
species.setCompartment(compID.getText().trim());
}
}
int index1 = species.getSelectedIndex();
species.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
specs = Buttons.getList(specs, species);
species.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
for (int i = 0; i < specs.length; i++) {
if (specs[i].split(" ")[1].equals(val)) {
specs[i] = specs[i].split(" ")[0] + " " + compID.getText().trim() + " "
+ specs[i].split(" ")[2];
}
else if (specs[i].split(" ")[2].equals(val)) {
specs[i] = specs[i].split(" ")[0] + " " + specs[i].split(" ")[1] + " "
+ compID.getText().trim() + " " + specs[i].split(" ")[3];
}
}
sort(specs);
species.setListData(specs);
species.setSelectedIndex(index1);
if (paramsOnly) {
int remove = -1;
for (int i = 0; i < parameterChanges.size(); i++) {
if (parameterChanges.get(i).split(" ")[0].equals(compID.getText().trim())) {
remove = i;
}
}
if (remove != -1) {
parameterChanges.remove(remove);
}
if (!((String) type.getSelectedItem()).equals("Original")) {
parameterChanges.add(comps[index]);
}
}
else {
updateVarId(false, val, compID.getText().trim());
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = document.getModel().getCompartment(i);
if (compartment.getOutside().equals(val)) {
compartment.setOutside(compID.getText().trim());
}
}
}
}
else {
int index = compartments.getSelectedIndex();
Compartment c = document.getModel().createCompartment();
c.setId(compID.getText().trim());
c.setName(compName.getText().trim());
if (!selCompType.equals("( none )")) {
c.setCompartmentType(selCompType);
}
c.setSpatialDimensions(Integer.parseInt((String) dimBox.getSelectedItem()));
if (!compSize.getText().trim().equals("")) {
c.setSize(Double.parseDouble(compSize.getText().trim()));
}
if (!compUnits.getSelectedItem().equals("( none )")) {
c.setUnits((String) compUnits.getSelectedItem());
}
if (!compOutside.getSelectedItem().equals("( none )")) {
c.setOutside((String) compOutside.getSelectedItem());
}
if (compConstant.getSelectedItem().equals("true")) {
c.setConstant(true);
}
else {
c.setConstant(false);
}
usedIDs.add(compID.getText().trim());
JList add = new JList();
String addStr;
if (!selCompType.equals("( none )")) {
addStr = compID.getText().trim() + " " + selCompType + " "
+ compSize.getText().trim();
}
else {
addStr = compID.getText().trim() + " " + compSize.getText().trim();
}
if (!compUnits.getSelectedItem().equals("( none )")) {
addStr += " " + compUnits.getSelectedItem();
}
Object[] adding = { addStr };
add.setListData(adding);
add.setSelectedIndex(0);
compartments.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(comps, compartments, add, false, null, null, null, null, null,
null, biosim.frame());
comps = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
comps[i] = (String) adding[i];
}
sort(comps);
compartments.setListData(comps);
compartments.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumCompartments() == 1) {
compartments.setSelectedIndex(0);
}
else {
compartments.setSelectedIndex(index);
}
}
change = true;
}
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), compartPanel, "Compartment Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Variable that is updated by a rule or event cannot be constant
*/
private boolean checkOutsideCycle(String compID, String outside, int depth) {
depth++;
if (depth > document.getModel().getNumCompartments())
return true;
Compartment compartment = document.getModel().getCompartment(outside);
if (compartment.isSetOutside()) {
if (compartment.getOutside().equals(compID)) {
return true;
}
return checkOutsideCycle(compID, compartment.getOutside(), depth);
}
return false;
}
/**
* Variable that is updated by a rule or event cannot be constant
*/
private boolean checkConstant(String varType, String val) {
for (int i = 0; i < document.getModel().getNumRules(); i++) {
Rule rule = document.getModel().getRule(i);
if (rule.getVariable().equals(val)) {
JOptionPane.showMessageDialog(biosim.frame(), varType
+ " cannot be constant if updated by a rule.", varType + " Cannot Be Constant",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
for (int i = 0; i < document.getModel().getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) document.getModel().getListOfEvents()
.get(i);
for (int j = 0; j < event.getNumEventAssignments(); j++) {
EventAssignment ea = (EventAssignment) event.getListOfEventAssignments().get(j);
if (ea.getVariable().equals(val)) {
JOptionPane.showMessageDialog(biosim.frame(), varType
+ " cannot be constant if updated by an event.", varType + " Cannot Be Constant",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
}
return false;
}
/**
* Species that is a reactant or product cannot be constant unless it is a
* boundary condition
*/
private boolean checkBoundary(String val, boolean checkRule) {
Model model = document.getModel();
boolean inRule = false;
if (checkRule) {
if (model.getNumRules() > 0) {
for (int i = 0; i < model.getNumRules(); i++) {
Rule rule = (Rule) model.getListOfRules().get(i);
if (rule.isSetVariable() && val.equals(rule.getVariable())) {
inRule = true;
break;
}
}
}
if (!inRule)
return false;
}
for (int i = 0; i < model.getNumReactions(); i++) {
Reaction reaction = (Reaction) model.getListOfReactions().get(i);
for (int j = 0; j < reaction.getNumProducts(); j++) {
if (reaction.getProduct(j).isSetSpecies()) {
SpeciesReference specRef = reaction.getProduct(j);
if (val.equals(specRef.getSpecies())) {
if (checkRule) {
JOptionPane.showMessageDialog(biosim.frame(),
"Boundary condition cannot be false if a species is used\n"
+ "in a rule and as a reactant or product in a reaction.",
"Boundary Condition Cannot be False", JOptionPane.ERROR_MESSAGE);
}
else {
JOptionPane.showMessageDialog(biosim.frame(),
"Species cannot be reactant if constant and not a boundary condition.",
"Invalid Species Attributes", JOptionPane.ERROR_MESSAGE);
}
return true;
}
}
}
for (int j = 0; j < reaction.getNumReactants(); j++) {
if (reaction.getReactant(j).isSetSpecies()) {
SpeciesReference specRef = reaction.getReactant(j);
if (val.equals(specRef.getSpecies())) {
if (checkRule) {
JOptionPane.showMessageDialog(biosim.frame(),
"Boundary condition cannot be false if a species is used\n"
+ "in a rule and as a reactant or product in a reaction.",
"Boundary Condition Cannot be False", JOptionPane.ERROR_MESSAGE);
}
else {
JOptionPane.showMessageDialog(biosim.frame(),
"Species cannot be product if constant and not a boundary condition.",
"Invalid Species Attributes", JOptionPane.ERROR_MESSAGE);
}
return true;
}
}
}
}
return false;
}
/**
* Set compartment options based on number of dimensions
*/
private void setCompartOptions(String selected, String dim) {
if (dim.equals("3")) {
compUnits.removeAllItems();
compUnits.addItem("( none )");
ListOf listOfUnits = document.getModel().getListOfUnitDefinitions();
for (int i = 0; i < document.getModel().getNumUnitDefinitions(); i++) {
UnitDefinition unit = (UnitDefinition) listOfUnits.get(i);
if ((unit.getNumUnits() == 1)
&& (unit.getUnit(0).isLitre() && unit.getUnit(0).getExponent() == 1)
|| (unit.getUnit(0).isMetre() && unit.getUnit(0).getExponent() == 3)) {
if (!unit.getId().equals("volume")) {
compUnits.addItem(unit.getId());
}
}
}
String[] unitIds = { "volume", "litre", "dimensionless" };
for (int i = 0; i < unitIds.length; i++) {
compUnits.addItem(unitIds[i]);
}
compOutside.removeAllItems();
compOutside.addItem("( none )");
ListOf listOfComps = document.getModel().getListOfCompartments();
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = (Compartment) listOfComps.get(i);
if (!compartment.getId().equals(selected) && compartment.getSpatialDimensions() != 0) {
compOutside.addItem(compartment.getId());
}
}
if (!paramsOnly) {
compConstant.setEnabled(true);
compSize.setEnabled(true);
}
}
else if (dim.equals("2")) {
compUnits.removeAllItems();
compUnits.addItem("( none )");
ListOf listOfUnits = document.getModel().getListOfUnitDefinitions();
for (int i = 0; i < document.getModel().getNumUnitDefinitions(); i++) {
UnitDefinition unit = (UnitDefinition) listOfUnits.get(i);
if ((unit.getNumUnits() == 1)
&& (unit.getUnit(0).isMetre() && unit.getUnit(0).getExponent() == 2)) {
if (!unit.getId().equals("area")) {
compUnits.addItem(unit.getId());
}
}
}
String[] unitIds = { "area", "dimensionless" };
for (int i = 0; i < unitIds.length; i++) {
compUnits.addItem(unitIds[i]);
}
compOutside.removeAllItems();
compOutside.addItem("( none )");
ListOf listOfComps = document.getModel().getListOfCompartments();
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = (Compartment) listOfComps.get(i);
if (!compartment.getId().equals(selected) && compartment.getSpatialDimensions() != 0) {
compOutside.addItem(compartment.getId());
}
}
if (!paramsOnly) {
compConstant.setEnabled(true);
compSize.setEnabled(true);
}
}
else if (dim.equals("1")) {
compUnits.removeAllItems();
compUnits.addItem("( none )");
ListOf listOfUnits = document.getModel().getListOfUnitDefinitions();
for (int i = 0; i < document.getModel().getNumUnitDefinitions(); i++) {
UnitDefinition unit = (UnitDefinition) listOfUnits.get(i);
if ((unit.getNumUnits() == 1)
&& (unit.getUnit(0).isMetre() && unit.getUnit(0).getExponent() == 1)) {
if (!unit.getId().equals("length")) {
compUnits.addItem(unit.getId());
}
}
}
String[] unitIds = { "length", "metre", "dimensionless" };
for (int i = 0; i < unitIds.length; i++) {
compUnits.addItem(unitIds[i]);
}
compOutside.removeAllItems();
compOutside.addItem("( none )");
ListOf listOfComps = document.getModel().getListOfCompartments();
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = (Compartment) listOfComps.get(i);
if (!compartment.getId().equals(selected) && compartment.getSpatialDimensions() != 0) {
compOutside.addItem(compartment.getId());
}
}
if (!paramsOnly) {
compConstant.setEnabled(true);
compSize.setEnabled(true);
}
}
else if (dim.equals("0")) {
compSize.setText("");
compUnits.removeAllItems();
compUnits.addItem("( none )");
compOutside.removeAllItems();
compOutside.addItem("( none )");
ListOf listOfComps = document.getModel().getListOfCompartments();
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
Compartment compartment = (Compartment) listOfComps.get(i);
if (!compartment.getId().equals(selected)) {
compOutside.addItem(compartment.getId());
}
}
compConstant.setEnabled(false);
compSize.setEnabled(false);
}
if (!selected.equals("")) {
Compartment compartment = document.getModel().getCompartment(selected);
if (compartment.isSetOutside()) {
compOutside.setSelectedItem(compartment.getOutside());
}
if (compartment.isSetUnits()) {
compUnits.setSelectedItem(compartment.getUnits());
}
}
}
/**
* Creates a frame used to edit species or create new ones.
*/
private void speciesEditor(String option) {
if (option.equals("OK") && species.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No species selected.",
"Must Select A Species", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel speciesPanel;
if (paramsOnly) {
speciesPanel = new JPanel(new GridLayout(13, 2));
}
else {
speciesPanel = new JPanel(new GridLayout(8, 2));
}
JLabel idLabel = new JLabel("ID:");
JLabel nameLabel = new JLabel("Name:");
JLabel specTypeLabel = new JLabel("Type:");
JLabel compLabel = new JLabel("Compartment:");
String[] initLabels = { "Initial Amount", "Initial Concentration" };
initLabel = new JComboBox(initLabels);
JLabel unitLabel = new JLabel("Units:");
JLabel boundLabel = new JLabel("Boundary Condition:");
JLabel constLabel = new JLabel("Constant:");
ID = new JTextField();
String selectedID = "";
Name = new JTextField();
init = new JTextField("0.0");
specUnits = new JComboBox();
specUnits.addItem("( none )");
ListOf listOfUnits = document.getModel().getListOfUnitDefinitions();
for (int i = 0; i < document.getModel().getNumUnitDefinitions(); i++) {
UnitDefinition unit = (UnitDefinition) listOfUnits.get(i);
if ((unit.getNumUnits() == 1)
&& (unit.getUnit(0).isMole() || unit.getUnit(0).isItem() || unit.getUnit(0).isGram() || unit
.getUnit(0).isKilogram()) && (unit.getUnit(0).getExponent() == 1)) {
if (!unit.getId().equals("substance")) {
specUnits.addItem(unit.getId());
}
}
}
String[] unitIds = { "substance", "dimensionless", "gram", "item", "kilogram", "mole" };
for (int i = 0; i < unitIds.length; i++) {
specUnits.addItem(unitIds[i]);
}
String[] optionsTF = { "true", "false" };
specBoundary = new JComboBox(optionsTF);
specBoundary.setSelectedItem("false");
specConstant = new JComboBox(optionsTF);
specConstant.setSelectedItem("false");
JLabel startLabel = new JLabel("Start:");
JLabel stopLabel = new JLabel("Stop:");
JLabel stepLabel = new JLabel("Step:");
JLabel levelLabel = new JLabel("Level:");
ListOf listOfSpecTypes = document.getModel().getListOfSpeciesTypes();
String[] specTypeList = new String[(int) document.getModel().getNumSpeciesTypes() + 1];
specTypeList[0] = "( none )";
for (int i = 0; i < document.getModel().getNumSpeciesTypes(); i++) {
specTypeList[i + 1] = ((SpeciesType) listOfSpecTypes.get(i)).getId();
}
sort(specTypeList);
Object[] choices = specTypeList;
specTypeBox = new JComboBox(choices);
ListOf listOfCompartments = document.getModel().getListOfCompartments();
String[] add = new String[(int) document.getModel().getNumCompartments()];
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
add[i] = ((Compartment) listOfCompartments.get(i)).getId();
}
try {
add[0].getBytes();
}
catch (Exception e) {
add = new String[1];
add[0] = "default";
}
comp = new JComboBox(add);
String[] list = { "Original", "Custom", "Sweep" };
String[] list1 = { "1", "2" };
final JComboBox type = new JComboBox(list);
final JTextField start = new JTextField();
final JTextField stop = new JTextField();
final JTextField step = new JTextField();
final JComboBox level = new JComboBox(list1);
if (paramsOnly) {
ID.setEditable(false);
Name.setEditable(false);
specTypeBox.setEnabled(false);
specBoundary.setEnabled(false);
specConstant.setEnabled(false);
comp.setEnabled(false);
init.setEnabled(false);
initLabel.setEnabled(false);
specUnits.setEnabled(false);
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
}
if (option.equals("OK")) {
try {
Species specie = document.getModel().getSpecies(
((String) species.getSelectedValue()).split(" ")[0]);
ID.setText(specie.getId());
selectedID = specie.getId();
Name.setText(specie.getName());
specTypeBox.setSelectedItem(specie.getSpeciesType());
if (specie.getBoundaryCondition()) {
specBoundary.setSelectedItem("true");
}
else {
specBoundary.setSelectedItem("false");
}
if (specie.getConstant()) {
specConstant.setSelectedItem("true");
}
else {
specConstant.setSelectedItem("false");
}
if (specie.isSetInitialAmount()) {
init.setText("" + specie.getInitialAmount());
initLabel.setSelectedItem("Initial Amount");
}
else {
init.setText("" + specie.getInitialConcentration());
initLabel.setSelectedItem("Initial Concentration");
}
specUnits.setSelectedItem(specie.getUnits());
comp.setSelectedItem(specie.getCompartment());
if (paramsOnly
&& (((String) species.getSelectedValue()).contains("Custom") || ((String) species
.getSelectedValue()).contains("Sweep"))) {
if (((String) species.getSelectedValue()).contains("Custom")) {
type.setSelectedItem("Custom");
}
else {
type.setSelectedItem("Sweep");
}
if (((String) type.getSelectedItem()).equals("Sweep")) {
String[] splits = ((String) compartments.getSelectedValue()).split(" ");
String sweepVal = splits[splits.length - 1];
start.setText((sweepVal).split(",")[0].substring(1).trim());
stop.setText((sweepVal).split(",")[1].trim());
step.setText((sweepVal).split(",")[2].trim());
level.setSelectedItem((sweepVal).split(",")[3].replace(")", "").trim());
start.setEnabled(true);
stop.setEnabled(true);
step.setEnabled(true);
level.setEnabled(true);
init.setEnabled(false);
initLabel.setEnabled(false);
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
init.setEnabled(true);
initLabel.setEnabled(false);
}
}
}
catch (Exception e) {
}
}
speciesPanel.add(idLabel);
speciesPanel.add(ID);
speciesPanel.add(nameLabel);
speciesPanel.add(Name);
speciesPanel.add(specTypeLabel);
speciesPanel.add(specTypeBox);
speciesPanel.add(compLabel);
speciesPanel.add(comp);
speciesPanel.add(boundLabel);
speciesPanel.add(specBoundary);
speciesPanel.add(constLabel);
speciesPanel.add(specConstant);
if (paramsOnly) {
JLabel typeLabel = new JLabel("Value Type:");
type.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!((String) type.getSelectedItem()).equals("Original")) {
if (((String) type.getSelectedItem()).equals("Sweep")) {
start.setEnabled(true);
stop.setEnabled(true);
step.setEnabled(true);
level.setEnabled(true);
init.setEnabled(false);
initLabel.setEnabled(false);
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
init.setEnabled(true);
initLabel.setEnabled(false);
}
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
init.setEnabled(false);
initLabel.setEnabled(false);
SBMLReader reader = new SBMLReader();
SBMLDocument d = reader.readSBML(file);
if (d.getModel().getSpecies(((String) species.getSelectedValue()).split(" ")[0])
.isSetInitialAmount()) {
init.setText(d.getModel().getSpecies(
((String) species.getSelectedValue()).split(" ")[0]).getInitialAmount()
+ "");
initLabel.setSelectedItem("Initial Amount");
}
else {
init.setText(d.getModel().getSpecies(
((String) species.getSelectedValue()).split(" ")[0]).getInitialConcentration()
+ "");
initLabel.setSelectedItem("Initial Concentration");
}
}
}
});
speciesPanel.add(typeLabel);
speciesPanel.add(type);
}
speciesPanel.add(initLabel);
speciesPanel.add(init);
speciesPanel.add(unitLabel);
speciesPanel.add(specUnits);
if (paramsOnly) {
speciesPanel.add(startLabel);
speciesPanel.add(start);
speciesPanel.add(stopLabel);
speciesPanel.add(stop);
speciesPanel.add(stepLabel);
speciesPanel.add(step);
speciesPanel.add(levelLabel);
speciesPanel.add(level);
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), speciesPanel, "Species Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = checkID(ID.getText().trim(), selectedID, false);
double initial = 0;
if (!error) {
try {
initial = Double.parseDouble(init.getText().trim());
}
catch (Exception e1) {
error = true;
JOptionPane.showMessageDialog(biosim.frame(),
"The initial value field must be a real number.", "Enter a Valid Initial Value",
JOptionPane.ERROR_MESSAGE);
}
String unit = (String) specUnits.getSelectedItem();
String addSpec = "";
String selSpecType = (String) specTypeBox.getSelectedItem();
if (paramsOnly && !((String) type.getSelectedItem()).equals("Original")) {
int index = species.getSelectedIndex();
String[] splits = specs[index].split(" ");
for (int i = 0; i < splits.length - 2; i++) {
addSpec += splits[i] + " ";
}
if (!splits[splits.length - 2].equals("Custom")
&& !splits[splits.length - 2].equals("Sweep")) {
addSpec += splits[splits.length - 2] + " " + splits[splits.length - 1] + " ";
}
if (((String) type.getSelectedItem()).equals("Sweep")) {
double startVal = Double.parseDouble(start.getText().trim());
double stopVal = Double.parseDouble(stop.getText().trim());
double stepVal = Double.parseDouble(step.getText().trim());
addSpec += "Sweep (" + startVal + "," + stopVal + "," + stepVal + ","
+ level.getSelectedItem() + ")";
}
else {
addSpec += "Custom " + initial;
}
}
else {
addSpec = ID.getText().trim();
if (!selSpecType.equals("( none )")) {
addSpec += " " + selSpecType;
}
addSpec += " " + comp.getSelectedItem() + " " + initial;
if (!unit.equals("( none )")) {
addSpec += " " + unit;
}
}
if (!error) {
ListOf listOfSpecies = document.getModel().getListOfSpecies();
String selected = "";
if (option.equals("OK")) {
selected = ((String) species.getSelectedValue()).split(" ")[0];
}
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
if (!listOfSpecies.get(i).getId().equals(selected)) {
if (((Species) listOfSpecies.get(i)).getCompartment().equals(
(String) comp.getSelectedItem())
&& ((Species) listOfSpecies.get(i)).getSpeciesType().equals(selSpecType)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Compartment already contains another species of this type.",
"Species Type Not Unique", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
}
if (!error) {
Compartment compartment = document.getModel().getCompartment(
(String) comp.getSelectedItem());
if (initLabel.getSelectedItem().equals("Initial Concentration")
&& compartment.getSpatialDimensions() == 0) {
JOptionPane.showMessageDialog(biosim.frame(),
"Species in a 0 dimensional compartment cannot have an initial concentration.",
"Concentration Not Possible", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error && option.equals("OK") && specConstant.getSelectedItem().equals("true")) {
String val = ((String) species.getSelectedValue()).split(" ")[0];
error = checkConstant("Species", val);
}
if (!error && option.equals("OK") && specBoundary.getSelectedItem().equals("false")) {
String val = ((String) species.getSelectedValue()).split(" ")[0];
error = checkBoundary(val, specConstant.getSelectedItem().equals("false"));
}
if (!error) {
if (option.equals("OK")) {
int index1 = species.getSelectedIndex();
String val = ((String) species.getSelectedValue()).split(" ")[0];
species.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
specs = Buttons.getList(specs, species);
species.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Species specie = document.getModel().getSpecies(val);
String speciesName = specie.getId();
specie.setCompartment((String) comp.getSelectedItem());
specie.setId(ID.getText().trim());
specie.setName(Name.getText().trim());
if (specBoundary.getSelectedItem().equals("true")) {
specie.setBoundaryCondition(true);
}
else {
specie.setBoundaryCondition(false);
}
if (specConstant.getSelectedItem().equals("true")) {
specie.setConstant(true);
}
else {
specie.setConstant(false);
}
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(val)) {
usedIDs.set(i, ID.getText().trim());
}
}
if (!selSpecType.equals("( none )")) {
specie.setSpeciesType(selSpecType);
}
else {
specie.unsetSpeciesType();
}
if (initLabel.getSelectedItem().equals("Initial Amount")) {
specie.setInitialAmount(initial);
specie.unsetInitialConcentration();
specie.setHasOnlySubstanceUnits(true);
}
else {
specie.unsetInitialAmount();
specie.setInitialConcentration(initial);
specie.setHasOnlySubstanceUnits(false);
}
if (unit.equals("( none )")) {
specie.unsetUnits();
}
else {
specie.setUnits(unit);
}
specs[index1] = addSpec;
sort(specs);
species.setListData(specs);
species.setSelectedIndex(index1);
if (paramsOnly) {
int remove = -1;
for (int i = 0; i < parameterChanges.size(); i++) {
if (parameterChanges.get(i).split(" ")[0].equals(ID.getText().trim())) {
remove = i;
}
}
if (remove != -1) {
parameterChanges.remove(remove);
}
if (!((String) type.getSelectedItem()).equals("Original")) {
parameterChanges.add(addSpec);
}
}
else {
updateVarId(true, speciesName, specie.getId());
}
}
else {
int index1 = species.getSelectedIndex();
Species specie = document.getModel().createSpecies();
specie.setCompartment((String) comp.getSelectedItem());
specie.setId(ID.getText().trim());
specie.setName(Name.getText().trim());
if (specBoundary.getSelectedItem().equals("true")) {
specie.setBoundaryCondition(true);
}
else {
specie.setBoundaryCondition(false);
}
if (specConstant.getSelectedItem().equals("true")) {
specie.setConstant(true);
}
else {
specie.setConstant(false);
}
usedIDs.add(ID.getText().trim());
if (!selSpecType.equals("( none )")) {
specie.setSpeciesType(selSpecType);
}
if (initLabel.getSelectedItem().equals("Initial Amount")) {
specie.setInitialAmount(initial);
specie.setHasOnlySubstanceUnits(true);
}
else {
specie.setInitialConcentration(initial);
specie.setHasOnlySubstanceUnits(false);
}
if (!unit.equals("( none )")) {
specie.setUnits(unit);
}
JList addIt = new JList();
Object[] adding = { addSpec };
addIt.setListData(adding);
addIt.setSelectedIndex(0);
species.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(specs, species, addIt, false, null, null, null, null, null, null,
biosim.frame());
specs = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
specs[i] = (String) adding[i];
}
sort(specs);
species.setListData(specs);
species.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumSpecies() == 1) {
species.setSelectedIndex(0);
}
else {
species.setSelectedIndex(index1);
}
}
change = true;
}
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), speciesPanel, "Species Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Update variable Id
*/
private void updateVarId(boolean isSpecies, String origId, String newId) {
if (origId.equals(newId))
return;
Model model = document.getModel();
for (int i = 0; i < model.getNumReactions(); i++) {
Reaction reaction = (Reaction) model.getListOfReactions().get(i);
for (int j = 0; j < reaction.getNumProducts(); j++) {
if (reaction.getProduct(j).isSetSpecies()) {
SpeciesReference specRef = reaction.getProduct(j);
if (isSpecies && origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
if (specRef.isSetStoichiometryMath()) {
StoichiometryMath sm = new StoichiometryMath(updateMathVar(specRef
.getStoichiometryMath().getMath(), origId, newId));
specRef.setStoichiometryMath(sm);
}
}
}
if (isSpecies) {
for (int j = 0; j < reaction.getNumModifiers(); j++) {
if (reaction.getModifier(j).isSetSpecies()) {
ModifierSpeciesReference specRef = reaction.getModifier(j);
if (origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
}
}
}
for (int j = 0; j < reaction.getNumReactants(); j++) {
if (reaction.getReactant(j).isSetSpecies()) {
SpeciesReference specRef = reaction.getReactant(j);
if (isSpecies && origId.equals(specRef.getSpecies())) {
specRef.setSpecies(newId);
}
if (specRef.isSetStoichiometryMath()) {
StoichiometryMath sm = new StoichiometryMath(updateMathVar(specRef
.getStoichiometryMath().getMath(), origId, newId));
specRef.setStoichiometryMath(sm);
}
}
}
reaction.getKineticLaw().setMath(
updateMathVar(reaction.getKineticLaw().getMath(), origId, newId));
}
if (model.getNumInitialAssignments() > 0) {
for (int i = 0; i < model.getNumInitialAssignments(); i++) {
InitialAssignment init = (InitialAssignment) model.getListOfInitialAssignments().get(i);
if (origId.equals(init.getSymbol())) {
init.setSymbol(newId);
}
init.setMath(updateMathVar(init.getMath(), origId, newId));
inits[i] = init.getSymbol() + " = " + myFormulaToString(init.getMath());
}
String[] oldInits = inits;
try {
inits = sortInitRules(inits);
if (checkCycles(inits, rul)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected within initial assignments and assignment rules.", "Cycle Detected",
JOptionPane.ERROR_MESSAGE);
inits = oldInits;
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in assignments.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
inits = oldInits;
}
initAssigns.setListData(inits);
initAssigns.setSelectedIndex(0);
}
if (model.getNumRules() > 0) {
for (int i = 0; i < model.getNumRules(); i++) {
Rule rule = (Rule) model.getListOfRules().get(i);
if (rule.isSetVariable() && origId.equals(rule.getVariable())) {
rule.setVariable(newId);
}
rule.setMath(updateMathVar(rule.getMath(), origId, newId));
if (rule.isAlgebraic()) {
rul[i] = "0 = " + myFormulaToString(rule.getMath());
}
else if (rule.isAssignment()) {
rul[i] = rule.getVariable() + " = " + myFormulaToString(rule.getMath());
}
else {
rul[i] = "d( " + rule.getVariable() + " )/dt = " + myFormulaToString(rule.getMath());
}
}
String[] oldRul = rul;
try {
rul = sortRules(rul);
if (checkCycles(inits, rul)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Cycle detected within initial assignments and assignment rules.", "Cycle Detected",
JOptionPane.ERROR_MESSAGE);
rul = oldRul;
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(biosim.frame(), "Cycle detected in assignments.",
"Cycle Detected", JOptionPane.ERROR_MESSAGE);
rul = oldRul;
}
rules.setListData(rul);
rules.setSelectedIndex(0);
}
if (model.getNumConstraints() > 0) {
for (int i = 0; i < model.getNumConstraints(); i++) {
Constraint constraint = (Constraint) model.getListOfConstraints().get(i);
constraint.setMath(updateMathVar(constraint.getMath(), origId, newId));
cons[i] = myFormulaToString(constraint.getMath());
}
sort(cons);
constraints.setListData(cons);
constraints.setSelectedIndex(0);
}
if (model.getNumEvents() > 0) {
for (int i = 0; i < model.getNumEvents(); i++) {
org.sbml.libsbml.Event event = (org.sbml.libsbml.Event) model.getListOfEvents().get(i);
if (event.isSetTrigger()) {
Trigger trigger = new Trigger(updateMathVar(event.getTrigger().getMath(), origId, newId));
event.setTrigger(trigger);
}
if (event.isSetDelay()) {
Delay delay = new Delay(updateMathVar(event.getDelay().getMath(), origId, newId));
event.setDelay(delay);
}
ev[i] = myFormulaToString(event.getTrigger().getMath());
for (int j = 0; j < event.getNumEventAssignments(); j++) {
EventAssignment ea = (EventAssignment) event.getListOfEventAssignments().get(j);
if (ea.getVariable().equals(origId)) {
ea.setVariable(newId);
}
if (ea.isSetMath()) {
ea.setMath(updateMathVar(ea.getMath(), origId, newId));
}
}
}
sort(ev);
events.setListData(ev);
events.setSelectedIndex(0);
}
}
/**
* Update variable in math formula using String
*/
private String updateFormulaVar(String s, String origVar, String newVar) {
s = " " + s + " ";
s = s.replace(" " + origVar + " ", " " + newVar + " ");
s = s.replace(" " + origVar + "(", " " + newVar + "(");
s = s.replace("(" + origVar + ")", "(" + newVar + ")");
s = s.replace("(" + origVar + " ", "(" + newVar + " ");
s = s.replace("(" + origVar + ",", "(" + newVar + ",");
s = s.replace(" " + origVar + ")", " " + newVar + ")");
return s.trim();
}
/**
* Update variable in math formula using ASTNode
*/
private ASTNode updateMathVar(ASTNode math, String origVar, String newVar) {
String s = updateFormulaVar(myFormulaToString(math), origVar, newVar);
return myParseFormula(s);
}
/**
* Update unit Id
*/
private void updateUnitId(String origId, String newId) {
if (origId.equals(newId))
return;
Model model = document.getModel();
if (model.getNumCompartments() > 0) {
for (int i = 0; i < model.getNumCompartments(); i++) {
Compartment compartment = (Compartment) model.getListOfCompartments().get(i);
if (compartment.getUnits().equals(origId)) {
compartment.setUnits(newId);
}
comps[i] = compartment.getId();
if (compartment.isSetCompartmentType()) {
comps[i] += " " + compartment.getCompartmentType();
}
if (compartment.isSetSize()) {
comps[i] += " " + compartment.getSize();
}
if (compartment.isSetUnits()) {
comps[i] += " " + compartment.getUnits();
}
}
sort(comps);
compartments.setListData(comps);
compartments.setSelectedIndex(0);
}
if (model.getNumSpecies() > 0) {
for (int i = 0; i < model.getNumSpecies(); i++) {
Species species = (Species) model.getListOfSpecies().get(i);
if (species.getUnits().equals(origId)) {
species.setUnits(newId);
}
if (species.isSetSpeciesType()) {
specs[i] = species.getId() + " " + species.getSpeciesType() + " "
+ species.getCompartment();
}
else {
specs[i] = species.getId() + " " + species.getCompartment();
}
if (species.isSetInitialAmount()) {
specs[i] += " " + species.getInitialAmount();
}
else {
specs[i] += " " + species.getInitialConcentration();
}
if (species.isSetUnits()) {
specs[i] += " " + species.getUnits();
}
}
sort(specs);
species.setListData(specs);
species.setSelectedIndex(0);
}
if (model.getNumParameters() > 0) {
for (int i = 0; i < model.getNumParameters(); i++) {
Parameter parameter = (Parameter) model.getListOfParameters().get(i);
if (parameter.getUnits().equals(origId)) {
parameter.setUnits(newId);
}
if (parameter.isSetUnits()) {
params[i] = parameter.getId() + " " + parameter.getValue() + " " + parameter.getUnits();
}
else {
params[i] = parameter.getId() + " " + parameter.getValue();
}
}
sort(params);
parameters.setListData(params);
parameters.setSelectedIndex(0);
}
for (int i = 0; i < model.getNumReactions(); i++) {
KineticLaw kineticLaw = (KineticLaw) model.getReaction(i).getKineticLaw();
for (int j = 0; j < kineticLaw.getNumParameters(); j++) {
if (kineticLaw.getParameter(j).getUnits().equals(origId)) {
kineticLaw.getParameter(j).setUnits(newId);
}
}
}
}
/**
* Creates a frame used to edit reactions or create new ones.
*/
private void reactionsEditor(String option) {
if (option.equals("OK") && reactions.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No reaction selected.",
"Must Select A Reaction", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel reactionPanelNorth = new JPanel();
JPanel reactionPanelNorth1 = new JPanel();
JPanel reactionPanelNorth1b = new JPanel();
JPanel reactionPanelNorth2 = new JPanel();
JPanel reactionPanelCentral = new JPanel(new GridLayout(1, 3));
JPanel reactionPanelSouth = new JPanel(new GridLayout(1, 2));
JPanel reactionPanel = new JPanel(new BorderLayout());
JLabel id = new JLabel("ID:");
reacID = new JTextField(15);
JLabel name = new JLabel("Name:");
reacName = new JTextField(50);
JLabel reverse = new JLabel("Reversible:");
String[] options = { "true", "false" };
reacReverse = new JComboBox(options);
reacReverse.setSelectedItem("false");
JLabel fast = new JLabel("Fast:");
reacFast = new JComboBox(options);
reacFast.setSelectedItem("false");
String selectedID = "";
if (option.equals("OK")) {
Reaction reac = document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]);
reacID.setText(reac.getId());
selectedID = reac.getId();
reacName.setText(reac.getName());
if (reac.getReversible()) {
reacReverse.setSelectedItem("true");
}
else {
reacReverse.setSelectedItem("false");
}
if (reac.getFast()) {
reacFast.setSelectedItem("true");
}
else {
reacFast.setSelectedItem("false");
}
}
JPanel param = new JPanel(new BorderLayout());
JPanel addParams = new JPanel();
reacAddParam = new JButton("Add Parameter");
reacRemoveParam = new JButton("Remove Parameter");
reacEditParam = new JButton("Edit Parameter");
addParams.add(reacAddParam);
addParams.add(reacRemoveParam);
addParams.add(reacEditParam);
reacAddParam.addActionListener(this);
reacRemoveParam.addActionListener(this);
reacEditParam.addActionListener(this);
JLabel parametersLabel = new JLabel("List Of Local Parameters:");
reacParameters = new JList();
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(260, 220));
scroll.setPreferredSize(new Dimension(276, 152));
scroll.setViewportView(reacParameters);
reacParams = new String[0];
changedParameters = new ArrayList<Parameter>();
thisReactionParams = new ArrayList<String>();
if (option.equals("OK")) {
Reaction reac = document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]);
ListOf listOfParameters = reac.getKineticLaw().getListOfParameters();
reacParams = new String[(int) reac.getKineticLaw().getNumParameters()];
for (int i = 0; i < reac.getKineticLaw().getNumParameters(); i++) {
Parameter parameter = (Parameter) listOfParameters.get(i);
changedParameters.add(parameter);
thisReactionParams.add(parameter.getId());
String p;
if (parameter.isSetUnits()) {
p = parameter.getId() + " " + parameter.getValue() + " " + parameter.getUnits();
}
else {
p = parameter.getId() + " " + parameter.getValue();
}
if (paramsOnly) {
for (int j = 0; j < parameterChanges.size(); j++) {
if (parameterChanges.get(j).split(" ")[0]
.equals(((String) reactions.getSelectedValue()).split(" ")[0] + "/"
+ parameter.getId())) {
p = parameterChanges.get(j).split("/")[1];
}
}
}
reacParams[i] = p;
}
}
else {
Parameter p = new Parameter();
p.setId("kf");
p.setValue(0.1);
changedParameters.add(p);
p = new Parameter();
p.setId("kr");
p.setValue(0.1);
changedParameters.add(p);
reacParams = new String[2];
reacParams[0] = "kf 0.1";
reacParams[1] = "kr 0.1";
thisReactionParams.add("kf");
thisReactionParams.add("kr");
}
sort(reacParams);
reacParameters.setListData(reacParams);
reacParameters.setSelectedIndex(0);
reacParameters.addMouseListener(this);
param.add(parametersLabel, "North");
param.add(scroll, "Center");
param.add(addParams, "South");
JPanel reactantsPanel = new JPanel(new BorderLayout());
JPanel addReactants = new JPanel();
addReactant = new JButton("Add Reactant");
removeReactant = new JButton("Remove Reactant");
editReactant = new JButton("Edit Reactant");
addReactants.add(addReactant);
addReactants.add(removeReactant);
addReactants.add(editReactant);
addReactant.addActionListener(this);
removeReactant.addActionListener(this);
editReactant.addActionListener(this);
JLabel reactantsLabel = new JLabel("List Of Reactants:");
reactants = new JList();
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll2 = new JScrollPane();
scroll2.setMinimumSize(new Dimension(260, 220));
scroll2.setPreferredSize(new Dimension(276, 152));
scroll2.setViewportView(reactants);
reacta = new String[0];
changedReactants = new ArrayList<SpeciesReference>();
if (option.equals("OK")) {
Reaction reac = document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]);
ListOf listOfReactants = reac.getListOfReactants();
reacta = new String[(int) reac.getNumReactants()];
for (int i = 0; i < reac.getNumReactants(); i++) {
SpeciesReference reactant = (SpeciesReference) listOfReactants.get(i);
changedReactants.add(reactant);
if (reactant.isSetStoichiometryMath()) {
reacta[i] = reactant.getSpecies() + " "
+ myFormulaToString(reactant.getStoichiometryMath().getMath());
}
else {
reacta[i] = reactant.getSpecies() + " " + reactant.getStoichiometry();
}
}
}
sort(reacta);
reactants.setListData(reacta);
reactants.setSelectedIndex(0);
reactants.addMouseListener(this);
reactantsPanel.add(reactantsLabel, "North");
reactantsPanel.add(scroll2, "Center");
reactantsPanel.add(addReactants, "South");
JPanel productsPanel = new JPanel(new BorderLayout());
JPanel addProducts = new JPanel();
addProduct = new JButton("Add Product");
removeProduct = new JButton("Remove Product");
editProduct = new JButton("Edit Product");
addProducts.add(addProduct);
addProducts.add(removeProduct);
addProducts.add(editProduct);
addProduct.addActionListener(this);
removeProduct.addActionListener(this);
editProduct.addActionListener(this);
JLabel productsLabel = new JLabel("List Of Products:");
products = new JList();
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll3 = new JScrollPane();
scroll3.setMinimumSize(new Dimension(260, 220));
scroll3.setPreferredSize(new Dimension(276, 152));
scroll3.setViewportView(products);
product = new String[0];
changedProducts = new ArrayList<SpeciesReference>();
if (option.equals("OK")) {
Reaction reac = document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]);
ListOf listOfProducts = reac.getListOfProducts();
product = new String[(int) reac.getNumProducts()];
for (int i = 0; i < reac.getNumProducts(); i++) {
SpeciesReference product = (SpeciesReference) listOfProducts.get(i);
changedProducts.add(product);
if (product.isSetStoichiometryMath()) {
this.product[i] = product.getSpecies() + " "
+ myFormulaToString(product.getStoichiometryMath().getMath());
}
else {
this.product[i] = product.getSpecies() + " " + product.getStoichiometry();
}
}
}
sort(product);
products.setListData(product);
products.setSelectedIndex(0);
products.addMouseListener(this);
productsPanel.add(productsLabel, "North");
productsPanel.add(scroll3, "Center");
productsPanel.add(addProducts, "South");
JPanel modifierPanel = new JPanel(new BorderLayout());
JPanel addModifiers = new JPanel();
addModifier = new JButton("Add Modifier");
removeModifier = new JButton("Remove Modifier");
editModifier = new JButton("Edit Modifier");
addModifiers.add(addModifier);
addModifiers.add(removeModifier);
addModifiers.add(editModifier);
addModifier.addActionListener(this);
removeModifier.addActionListener(this);
editModifier.addActionListener(this);
JLabel modifiersLabel = new JLabel("List Of Modifiers:");
modifiers = new JList();
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll5 = new JScrollPane();
scroll5.setMinimumSize(new Dimension(260, 220));
scroll5.setPreferredSize(new Dimension(276, 152));
scroll5.setViewportView(modifiers);
modifier = new String[0];
changedModifiers = new ArrayList<ModifierSpeciesReference>();
if (option.equals("OK")) {
Reaction reac = document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]);
ListOf listOfModifiers = reac.getListOfModifiers();
modifier = new String[(int) reac.getNumModifiers()];
for (int i = 0; i < reac.getNumModifiers(); i++) {
ModifierSpeciesReference modifier = (ModifierSpeciesReference) listOfModifiers.get(i);
changedModifiers.add(modifier);
this.modifier[i] = modifier.getSpecies();
}
}
sort(modifier);
modifiers.setListData(modifier);
modifiers.setSelectedIndex(0);
modifiers.addMouseListener(this);
modifierPanel.add(modifiersLabel, "North");
modifierPanel.add(scroll5, "Center");
modifierPanel.add(addModifiers, "South");
JLabel kineticLabel = new JLabel("Kinetic Law:");
kineticLaw = new JTextArea();
kineticLaw.setLineWrap(true);
kineticLaw.setWrapStyleWord(true);
useMassAction = new JButton("Use Mass Action");
clearKineticLaw = new JButton("Clear");
useMassAction.addActionListener(this);
clearKineticLaw.addActionListener(this);
JPanel kineticButtons = new JPanel();
kineticButtons.add(useMassAction);
kineticButtons.add(clearKineticLaw);
JScrollPane scroll4 = new JScrollPane();
scroll4.setMinimumSize(new Dimension(100, 100));
scroll4.setPreferredSize(new Dimension(100, 100));
scroll4.setViewportView(kineticLaw);
if (option.equals("OK")) {
kineticLaw.setText(document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]).getKineticLaw().getFormula());
}
JPanel kineticPanel = new JPanel(new BorderLayout());
kineticPanel.add(kineticLabel, "North");
kineticPanel.add(scroll4, "Center");
kineticPanel.add(kineticButtons, "South");
reactionPanelNorth1.add(id);
reactionPanelNorth1.add(reacID);
reactionPanelNorth1.add(name);
reactionPanelNorth1.add(reacName);
reactionPanelNorth1b.add(reverse);
reactionPanelNorth1b.add(reacReverse);
reactionPanelNorth1b.add(fast);
reactionPanelNorth1b.add(reacFast);
reactionPanelNorth2.add(reactionPanelNorth1);
reactionPanelNorth2.add(reactionPanelNorth1b);
reactionPanelNorth.add(reactionPanelNorth2);
reactionPanelCentral.add(reactantsPanel);
reactionPanelCentral.add(productsPanel);
reactionPanelCentral.add(modifierPanel);
reactionPanelSouth.add(param);
reactionPanelSouth.add(kineticPanel);
reactionPanel.add(reactionPanelNorth, "North");
reactionPanel.add(reactionPanelCentral, "Center");
reactionPanel.add(reactionPanelSouth, "South");
if (paramsOnly) {
reacID.setEditable(false);
reacName.setEditable(false);
reacReverse.setEnabled(false);
reacFast.setEnabled(false);
reacAddParam.setEnabled(false);
reacRemoveParam.setEnabled(false);
addReactant.setEnabled(false);
removeReactant.setEnabled(false);
editReactant.setEnabled(false);
addProduct.setEnabled(false);
removeProduct.setEnabled(false);
editProduct.setEnabled(false);
addModifier.setEnabled(false);
removeModifier.setEnabled(false);
editModifier.setEnabled(false);
kineticLaw.setEditable(false);
useMassAction.setEnabled(false);
clearKineticLaw.setEnabled(false);
}
Object[] options1 = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), reactionPanel, "Reaction Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options1, options1[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
String reac = reacID.getText().trim();
error = checkID(reac, selectedID, false);
if (!error) {
if (kineticLaw.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "A reaction must have a kinetic law.",
"Enter A Kinetic Law", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if ((changedReactants.size() == 0) && (changedProducts.size() == 0)) {
JOptionPane.showMessageDialog(biosim.frame(),
"A reaction must have at least one reactant or product.", "No Reactants or Products",
JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (myParseFormula(kineticLaw.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to parse kinetic law.",
"Kinetic Law Error", JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidKineticVars = getInvalidVariables(kineticLaw.getText().trim(),
true, "", false);
if (invalidKineticVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidKineticVars.size(); i++) {
if (i == invalidKineticVars.size() - 1) {
invalid += invalidKineticVars.get(i);
}
else {
invalid += invalidKineticVars.get(i) + "\n";
}
}
String message;
message = "Kinetic law contains unknown variables.\n\n" + "Unknown variables:\n"
+ invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Kinetic Law Error",
JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = checkNumFunctionArguments(myParseFormula(kineticLaw.getText().trim()));
}
}
}
if (!error) {
if (myParseFormula(kineticLaw.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(), "Kinetic law must evaluate to a number.",
"Number Expected", JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
if (option.equals("OK")) {
int index = reactions.getSelectedIndex();
String val = ((String) reactions.getSelectedValue()).split(" ")[0];
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacts = Buttons.getList(reacts, reactions);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Reaction react = document.getModel().getReaction(val);
Reaction copyReact = (Reaction) react.cloneObject();
ListOf remove;
long size;
remove = react.getKineticLaw().getListOfParameters();
size = react.getKineticLaw().getNumParameters();
for (int i = 0; i < size; i++) {
remove.remove(0);
}
for (int i = 0; i < changedParameters.size(); i++) {
react.getKineticLaw().addParameter(changedParameters.get(i));
}
remove = react.getListOfProducts();
size = react.getNumProducts();
for (int i = 0; i < size; i++) {
remove.remove(0);
}
for (int i = 0; i < changedProducts.size(); i++) {
react.addProduct(changedProducts.get(i));
}
remove = react.getListOfModifiers();
size = react.getNumModifiers();
for (int i = 0; i < size; i++) {
remove.remove(0);
}
for (int i = 0; i < changedModifiers.size(); i++) {
react.addModifier(changedModifiers.get(i));
}
remove = react.getListOfReactants();
size = react.getNumReactants();
for (int i = 0; i < size; i++) {
remove.remove(0);
}
for (int i = 0; i < changedReactants.size(); i++) {
react.addReactant(changedReactants.get(i));
}
if (reacReverse.getSelectedItem().equals("true")) {
react.setReversible(true);
}
else {
react.setReversible(false);
}
if (reacFast.getSelectedItem().equals("true")) {
react.setFast(true);
}
else {
react.setFast(false);
}
react.setId(reacID.getText().trim());
react.setName(reacName.getText().trim());
react.getKineticLaw().setFormula(kineticLaw.getText().trim());
error = checkKineticLawUnits(react.getKineticLaw());
if (!error) {
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(val)) {
usedIDs.set(i, reacID.getText().trim());
}
}
if (!paramsOnly) {
reacts[index] = reac;
}
sort(reacts);
reactions.setListData(reacts);
reactions.setSelectedIndex(index);
}
else {
removeTheReaction(reac);
document.getModel().addReaction(copyReact);
}
}
else {
Reaction react = document.getModel().createReaction();
react.setKineticLaw(new KineticLaw());
int index = reactions.getSelectedIndex();
for (int i = 0; i < changedParameters.size(); i++) {
react.getKineticLaw().addParameter(changedParameters.get(i));
}
for (int i = 0; i < changedProducts.size(); i++) {
react.addProduct(changedProducts.get(i));
}
for (int i = 0; i < changedModifiers.size(); i++) {
react.addModifier(changedModifiers.get(i));
}
for (int i = 0; i < changedReactants.size(); i++) {
react.addReactant(changedReactants.get(i));
}
if (reacReverse.getSelectedItem().equals("true")) {
react.setReversible(true);
}
else {
react.setReversible(false);
}
if (reacFast.getSelectedItem().equals("true")) {
react.setFast(true);
}
else {
react.setFast(false);
}
react.setId(reacID.getText().trim());
react.setName(reacName.getText().trim());
react.getKineticLaw().setFormula(kineticLaw.getText().trim());
error = checkKineticLawUnits(react.getKineticLaw());
if (!error) {
usedIDs.add(reacID.getText().trim());
JList add = new JList();
Object[] adding = { reac };
add.setListData(adding);
add.setSelectedIndex(0);
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(reacts, reactions, add, false, null, null, null, null, null, null,
biosim.frame());
reacts = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
reacts[i] = (String) adding[i];
}
sort(reacts);
reactions.setListData(reacts);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumReactions() == 1) {
reactions.setSelectedIndex(0);
}
else {
reactions.setSelectedIndex(index);
}
}
else {
removeTheReaction(reac);
}
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), reactionPanel, "Reaction Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options1, options1[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Find invalid reaction variables in a formula
*/
private ArrayList<String> getInvalidVariables(String formula, boolean isReaction,
String arguments, boolean isFunction) {
ArrayList<String> validVars = new ArrayList<String>();
ArrayList<String> invalidVars = new ArrayList<String>();
ListOf sbml = document.getModel().getListOfFunctionDefinitions();
for (int i = 0; i < document.getModel().getNumFunctionDefinitions(); i++) {
validVars.add(((FunctionDefinition) sbml.get(i)).getId());
}
if (isReaction) {
for (int i = 0; i < changedParameters.size(); i++) {
validVars.add(((Parameter) changedParameters.get(i)).getId());
}
for (int i = 0; i < changedReactants.size(); i++) {
validVars.add(((SpeciesReference) changedReactants.get(i)).getSpecies());
}
for (int i = 0; i < changedProducts.size(); i++) {
validVars.add(((SpeciesReference) changedProducts.get(i)).getSpecies());
}
for (int i = 0; i < changedModifiers.size(); i++) {
validVars.add(((ModifierSpeciesReference) changedModifiers.get(i)).getSpecies());
}
}
else if (!isFunction) {
sbml = document.getModel().getListOfSpecies();
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
validVars.add(((Species) sbml.get(i)).getId());
}
}
if (isFunction) {
String[] args = arguments.split(" |\\,");
for (int i = 0; i < args.length; i++) {
validVars.add(args[i]);
}
}
else {
sbml = document.getModel().getListOfCompartments();
for (int i = 0; i < document.getModel().getNumCompartments(); i++) {
if (((Compartment) sbml.get(i)).getSpatialDimensions() != 0) {
validVars.add(((Compartment) sbml.get(i)).getId());
}
}
sbml = document.getModel().getListOfParameters();
for (int i = 0; i < document.getModel().getNumParameters(); i++) {
validVars.add(((Parameter) sbml.get(i)).getId());
}
sbml = document.getModel().getListOfReactions();
for (int i = 0; i < document.getModel().getNumReactions(); i++) {
validVars.add(((Reaction) sbml.get(i)).getId());
}
}
String[] splitLaw = formula.split(" |\\(|\\)|\\,|\\*|\\+|\\/|\\-");
for (int i = 0; i < splitLaw.length; i++) {
if (splitLaw[i].equals("abs") || splitLaw[i].equals("arccos")
|| splitLaw[i].equals("arccosh") || splitLaw[i].equals("arcsin")
|| splitLaw[i].equals("arcsinh") || splitLaw[i].equals("arctan")
|| splitLaw[i].equals("arctanh") || splitLaw[i].equals("arccot")
|| splitLaw[i].equals("arccoth") || splitLaw[i].equals("arccsc")
|| splitLaw[i].equals("arccsch") || splitLaw[i].equals("arcsec")
|| splitLaw[i].equals("arcsech") || splitLaw[i].equals("acos")
|| splitLaw[i].equals("acosh") || splitLaw[i].equals("asin")
|| splitLaw[i].equals("asinh") || splitLaw[i].equals("atan")
|| splitLaw[i].equals("atanh") || splitLaw[i].equals("acot")
|| splitLaw[i].equals("acoth") || splitLaw[i].equals("acsc")
|| splitLaw[i].equals("acsch") || splitLaw[i].equals("asec")
|| splitLaw[i].equals("asech") || splitLaw[i].equals("cos") || splitLaw[i].equals("cosh")
|| splitLaw[i].equals("cot") || splitLaw[i].equals("coth") || splitLaw[i].equals("csc")
|| splitLaw[i].equals("csch") || splitLaw[i].equals("ceil")
|| splitLaw[i].equals("factorial") || splitLaw[i].equals("exp")
|| splitLaw[i].equals("floor") || splitLaw[i].equals("ln") || splitLaw[i].equals("log")
|| splitLaw[i].equals("sqr") || splitLaw[i].equals("log10") || splitLaw[i].equals("pow")
|| splitLaw[i].equals("sqrt") || splitLaw[i].equals("root")
|| splitLaw[i].equals("piecewise") || splitLaw[i].equals("sec")
|| splitLaw[i].equals("sech") || splitLaw[i].equals("sin") || splitLaw[i].equals("sinh")
|| splitLaw[i].equals("tan") || splitLaw[i].equals("tanh") || splitLaw[i].equals("")
|| splitLaw[i].equals("and") || splitLaw[i].equals("or") || splitLaw[i].equals("xor")
|| splitLaw[i].equals("not") || splitLaw[i].equals("eq") || splitLaw[i].equals("geq")
|| splitLaw[i].equals("leq") || splitLaw[i].equals("gt") || splitLaw[i].equals("neq")
|| splitLaw[i].equals("lt") || splitLaw[i].equals("delay") || splitLaw[i].equals("t")
|| splitLaw[i].equals("true") || splitLaw[i].equals("false") || splitLaw[i].equals("pi")
|| splitLaw[i].equals("exponentiale")) {
}
else {
String temp = splitLaw[i];
if (splitLaw[i].substring(splitLaw[i].length() - 1, splitLaw[i].length()).equals("e")) {
temp = splitLaw[i].substring(0, splitLaw[i].length() - 1);
}
try {
Double.parseDouble(temp);
}
catch (Exception e1) {
if (!validVars.contains(splitLaw[i])) {
invalidVars.add(splitLaw[i]);
}
}
}
}
return invalidVars;
}
/**
* Creates a frame used to edit parameters or create new ones.
*/
private void parametersEditor(String option) {
if (option.equals("OK") && parameters.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No parameter selected.",
"Must Select A Parameter", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel parametersPanel;
if (paramsOnly) {
parametersPanel = new JPanel(new GridLayout(10, 2));
}
else {
parametersPanel = new JPanel(new GridLayout(5, 2));
}
JLabel idLabel = new JLabel("ID:");
JLabel nameLabel = new JLabel("Name:");
JLabel valueLabel = new JLabel("Value:");
JLabel unitLabel = new JLabel("Units:");
JLabel constLabel = new JLabel("Constant:");
JLabel startLabel = new JLabel("Start:");
JLabel stopLabel = new JLabel("Stop:");
JLabel stepLabel = new JLabel("Step:");
JLabel levelLabel = new JLabel("Level:");
paramID = new JTextField();
paramName = new JTextField();
paramValue = new JTextField();
paramUnits = new JComboBox();
paramUnits.addItem("( none )");
for (int i = 0; i < units.length; i++) {
if (!units[i].equals("substance") && !units[i].equals("volume") && !units[i].equals("area")
&& !units[i].equals("length") && !units[i].equals("time")) {
paramUnits.addItem(units[i]);
}
}
String[] unitIds = { "substance", "volume", "area", "length", "time", "ampere", "becquerel",
"candela", "celsius", "coulomb", "dimensionless", "farad", "gram", "gray", "henry",
"hertz", "item", "joule", "katal", "kelvin", "kilogram", "litre", "lumen", "lux", "metre",
"mole", "newton", "ohm", "pascal", "radian", "second", "siemens", "sievert", "steradian",
"tesla", "volt", "watt", "weber" };
for (int i = 0; i < unitIds.length; i++) {
paramUnits.addItem(unitIds[i]);
}
paramConst = new JComboBox();
paramConst.addItem("true");
paramConst.addItem("false");
String[] list = { "Original", "Custom", "Sweep" };
String[] list1 = { "1", "2" };
final JComboBox type = new JComboBox(list);
final JTextField start = new JTextField();
final JTextField stop = new JTextField();
final JTextField step = new JTextField();
final JComboBox level = new JComboBox(list1);
if (paramsOnly) {
paramID.setEditable(false);
paramName.setEditable(false);
paramValue.setEnabled(false);
paramUnits.setEnabled(false);
paramConst.setEnabled(false);
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
}
String selectedID = "";
if (option.equals("OK")) {
try {
Parameter paramet = document.getModel().getParameter(
((String) parameters.getSelectedValue()).split(" ")[0]);
paramID.setText(paramet.getId());
selectedID = paramet.getId();
paramName.setText(paramet.getName());
if (paramet.getConstant()) {
paramConst.setSelectedItem("true");
}
else {
paramConst.setSelectedItem("false");
}
if (paramet.isSetValue()) {
paramValue.setText("" + paramet.getValue());
}
if (paramet.isSetUnits()) {
paramUnits.setSelectedItem(paramet.getUnits());
}
if (paramsOnly && (((String) parameters.getSelectedValue()).contains("Custom"))
|| (((String) parameters.getSelectedValue()).contains("Sweep"))) {
if (((String) parameters.getSelectedValue()).contains("Custom")) {
type.setSelectedItem("Custom");
}
else {
type.setSelectedItem("Sweep");
}
if (((String) type.getSelectedItem()).equals("Sweep")) {
String[] splits = ((String) parameters.getSelectedValue()).split(" ");
String sweepVal = splits[splits.length - 1];
start.setText((sweepVal).split(",")[0].substring(1).trim());
stop.setText((sweepVal).split(",")[1].trim());
step.setText((sweepVal).split(",")[2].trim());
level.setSelectedItem((sweepVal).split(",")[3].replace(")", "").trim());
start.setEnabled(true);
stop.setEnabled(true);
step.setEnabled(true);
level.setEnabled(true);
paramValue.setEnabled(false);
paramUnits.setEnabled(false);
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
paramValue.setEnabled(true);
paramUnits.setEnabled(false);
}
}
}
catch (Exception e) {
}
}
parametersPanel.add(idLabel);
parametersPanel.add(paramID);
parametersPanel.add(nameLabel);
parametersPanel.add(paramName);
if (paramsOnly) {
JLabel typeLabel = new JLabel("Type:");
type.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!((String) type.getSelectedItem()).equals("Original")) {
if (((String) type.getSelectedItem()).equals("Sweep")) {
start.setEnabled(true);
stop.setEnabled(true);
step.setEnabled(true);
level.setEnabled(true);
paramValue.setEnabled(false);
paramUnits.setEnabled(false);
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
paramValue.setEnabled(true);
paramUnits.setEnabled(false);
}
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
paramValue.setEnabled(false);
paramUnits.setEnabled(false);
SBMLReader reader = new SBMLReader();
SBMLDocument d = reader.readSBML(file);
if (d.getModel().getParameter(((String) parameters.getSelectedValue()).split(" ")[0])
.isSetValue()) {
paramValue.setText(d.getModel().getParameter(
((String) parameters.getSelectedValue()).split(" ")[0]).getValue()
+ "");
}
else {
paramValue.setText("");
}
if (d.getModel().getParameter(((String) parameters.getSelectedValue()).split(" ")[0])
.isSetUnits()) {
paramUnits.setSelectedItem(d.getModel().getParameter(
((String) parameters.getSelectedValue()).split(" ")[0]).getUnits()
+ "");
}
}
}
});
parametersPanel.add(typeLabel);
parametersPanel.add(type);
}
parametersPanel.add(valueLabel);
parametersPanel.add(paramValue);
parametersPanel.add(unitLabel);
parametersPanel.add(paramUnits);
parametersPanel.add(constLabel);
parametersPanel.add(paramConst);
if (paramsOnly) {
parametersPanel.add(startLabel);
parametersPanel.add(start);
parametersPanel.add(stopLabel);
parametersPanel.add(stop);
parametersPanel.add(stepLabel);
parametersPanel.add(step);
parametersPanel.add(levelLabel);
parametersPanel.add(level);
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), parametersPanel, "Parameter Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = checkID(paramID.getText().trim(), selectedID, false);
if (!error) {
double val = 0.0;
try {
val = Double.parseDouble(paramValue.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "The value must be a real number.",
"Enter A Valid Value", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
String unit = (String) paramUnits.getSelectedItem();
String param = "";
if (paramsOnly && !((String) type.getSelectedItem()).equals("Original")) {
int index = parameters.getSelectedIndex();
String[] splits = params[index].split(" ");
for (int i = 0; i < splits.length - 2; i++) {
param += splits[i] + " ";
}
if (!splits[splits.length - 2].equals("Custom")
&& !splits[splits.length - 2].equals("Sweep")) {
param += splits[splits.length - 2] + " " + splits[splits.length - 1] + " ";
}
if (((String) type.getSelectedItem()).equals("Sweep")) {
double startVal = Double.parseDouble(start.getText().trim());
double stopVal = Double.parseDouble(stop.getText().trim());
double stepVal = Double.parseDouble(step.getText().trim());
param += "Sweep (" + startVal + "," + stopVal + "," + stepVal + ","
+ level.getSelectedItem() + ")";
}
else {
param += "Custom " + val;
}
}
else {
param = paramID.getText().trim() + " " + val;
if (!unit.equals("( none )")) {
param = paramID.getText().trim() + " " + val + " " + unit;
}
}
if (!error && option.equals("OK") && paramConst.getSelectedItem().equals("true")) {
String v = ((String) parameters.getSelectedValue()).split(" ")[0];
error = checkConstant("Parameters", v);
}
if (!error) {
if (option.equals("OK")) {
int index = parameters.getSelectedIndex();
String v = ((String) parameters.getSelectedValue()).split(" ")[0];
Parameter paramet = document.getModel().getParameter(v);
parameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
params = Buttons.getList(params, parameters);
parameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
paramet.setId(paramID.getText().trim());
paramet.setName(paramName.getText().trim());
if (paramConst.getSelectedItem().equals("true")) {
paramet.setConstant(true);
}
else {
paramet.setConstant(false);
}
for (int i = 0; i < usedIDs.size(); i++) {
if (usedIDs.get(i).equals(v)) {
usedIDs.set(i, paramID.getText().trim());
}
}
paramet.setValue(val);
if (unit.equals("( none )")) {
paramet.unsetUnits();
}
else {
paramet.setUnits(unit);
}
params[index] = param;
sort(params);
parameters.setListData(params);
parameters.setSelectedIndex(index);
if (paramsOnly) {
int remove = -1;
for (int i = 0; i < parameterChanges.size(); i++) {
if (parameterChanges.get(i).split(" ")[0].equals(paramID.getText().trim())) {
remove = i;
}
}
if (remove != -1) {
parameterChanges.remove(remove);
}
if (!((String) type.getSelectedItem()).equals("Original")) {
parameterChanges.add(param);
}
}
else {
updateVarId(false, v, paramID.getText().trim());
}
}
else {
int index = parameters.getSelectedIndex();
Parameter paramet = document.getModel().createParameter();
paramet.setId(paramID.getText().trim());
paramet.setName(paramName.getText().trim());
usedIDs.add(paramID.getText().trim());
if (paramConst.getSelectedItem().equals("true")) {
paramet.setConstant(true);
}
else {
paramet.setConstant(false);
}
paramet.setValue(val);
if (!unit.equals("( none )")) {
paramet.setUnits(unit);
}
JList add = new JList();
Object[] adding = { param };
add.setListData(adding);
add.setSelectedIndex(0);
parameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(params, parameters, add, false, null, null, null, null, null,
null, biosim.frame());
params = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
params[i] = (String) adding[i];
}
sort(params);
parameters.setListData(params);
parameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (document.getModel().getNumParameters() == 1) {
parameters.setSelectedIndex(0);
}
else {
parameters.setSelectedIndex(index);
}
}
change = true;
}
}
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), parametersPanel, "Parameter Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit reactions parameters or create new ones.
*/
private void reacParametersEditor(String option) {
if (option.equals("OK") && reacParameters.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No parameter selected.",
"Must Select A Parameter", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel parametersPanel;
if (paramsOnly) {
parametersPanel = new JPanel(new GridLayout(9, 2));
}
else {
parametersPanel = new JPanel(new GridLayout(4, 2));
}
JLabel idLabel = new JLabel("ID:");
JLabel nameLabel = new JLabel("Name:");
JLabel valueLabel = new JLabel("Value:");
JLabel unitsLabel = new JLabel("Units:");
JLabel startLabel = new JLabel("Start:");
JLabel stopLabel = new JLabel("Stop:");
JLabel stepLabel = new JLabel("Step:");
JLabel levelLabel = new JLabel("Level:");
reacParamID = new JTextField();
reacParamName = new JTextField();
reacParamValue = new JTextField();
reacParamUnits = new JComboBox();
reacParamUnits.addItem("( none )");
for (int i = 0; i < units.length; i++) {
if (!units[i].equals("substance") && !units[i].equals("volume") && !units[i].equals("area")
&& !units[i].equals("length") && !units[i].equals("time")) {
reacParamUnits.addItem(units[i]);
}
}
String[] unitIds = { "substance", "volume", "area", "length", "time", "ampere", "becquerel",
"candela", "celsius", "coulomb", "dimensionless", "farad", "gram", "gray", "henry",
"hertz", "item", "joule", "katal", "kelvin", "kilogram", "litre", "lumen", "lux", "metre",
"mole", "newton", "ohm", "pascal", "radian", "second", "siemens", "sievert", "steradian",
"tesla", "volt", "watt", "weber" };
for (int i = 0; i < unitIds.length; i++) {
reacParamUnits.addItem(unitIds[i]);
}
String[] list = { "Original", "Custom", "Sweep" };
String[] list1 = { "1", "2" };
final JComboBox type = new JComboBox(list);
final JTextField start = new JTextField();
final JTextField stop = new JTextField();
final JTextField step = new JTextField();
final JComboBox level = new JComboBox(list1);
if (paramsOnly) {
reacParamID.setEditable(false);
reacParamName.setEditable(false);
reacParamValue.setEnabled(false);
reacParamUnits.setEnabled(false);
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
}
String selectedID = "";
if (option.equals("OK")) {
String v = ((String) reacParameters.getSelectedValue()).split(" ")[0];
Parameter paramet = null;
for (Parameter p : changedParameters) {
if (p.getId().equals(v)) {
paramet = p;
}
}
reacParamID.setText(paramet.getId());
selectedID = paramet.getId();
reacParamName.setText(paramet.getName());
reacParamValue.setText("" + paramet.getValue());
if (paramet.isSetUnits()) {
reacParamUnits.setSelectedItem(paramet.getUnits());
}
if (paramsOnly && (((String) reacParameters.getSelectedValue()).contains("Custom"))
|| (((String) reacParameters.getSelectedValue()).contains("Sweep"))) {
if (((String) reacParameters.getSelectedValue()).contains("Custom")) {
type.setSelectedItem("Custom");
}
else {
type.setSelectedItem("Sweep");
}
if (((String) type.getSelectedItem()).equals("Sweep")) {
String[] splits = ((String) reacParameters.getSelectedValue()).split(" ");
String sweepVal = splits[splits.length - 1];
start.setText((sweepVal).split(",")[0].substring(1).trim());
stop.setText((sweepVal).split(",")[1].trim());
step.setText((sweepVal).split(",")[2].trim());
level.setSelectedItem((sweepVal).split(",")[3].replace(")", "").trim());
start.setEnabled(true);
stop.setEnabled(true);
step.setEnabled(true);
level.setEnabled(true);
reacParamValue.setEnabled(false);
reacParamUnits.setEnabled(false);
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
reacParamValue.setEnabled(true);
reacParamUnits.setEnabled(false);
}
}
}
parametersPanel.add(idLabel);
parametersPanel.add(reacParamID);
parametersPanel.add(nameLabel);
parametersPanel.add(reacParamName);
if (paramsOnly) {
JLabel typeLabel = new JLabel("Type:");
type.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!((String) type.getSelectedItem()).equals("Original")) {
if (((String) type.getSelectedItem()).equals("Sweep")) {
start.setEnabled(true);
stop.setEnabled(true);
step.setEnabled(true);
level.setEnabled(true);
reacParamValue.setEnabled(false);
reacParamUnits.setEnabled(false);
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
reacParamValue.setEnabled(true);
reacParamUnits.setEnabled(false);
}
}
else {
start.setEnabled(false);
stop.setEnabled(false);
step.setEnabled(false);
level.setEnabled(false);
reacParamValue.setEnabled(false);
reacParamUnits.setEnabled(false);
SBMLReader reader = new SBMLReader();
SBMLDocument d = reader.readSBML(file);
KineticLaw KL = d.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]).getKineticLaw();
ListOf list = KL.getListOfParameters();
int number = -1;
for (int i = 0; i < KL.getNumParameters(); i++) {
if (((Parameter) list.get(i)).getId().equals(
((String) reacParameters.getSelectedValue()).split(" ")[0])) {
number = i;
}
}
reacParamValue.setText(d.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]).getKineticLaw()
.getParameter(number).getValue()
+ "");
if (d.getModel().getReaction(((String) reactions.getSelectedValue()).split(" ")[0])
.getKineticLaw().getParameter(number).isSetUnits()) {
reacParamUnits.setSelectedItem(d.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]).getKineticLaw()
.getParameter(number).getUnits());
}
reacParamValue.setText(d.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]).getKineticLaw()
.getParameter(number).getValue()
+ "");
}
}
});
parametersPanel.add(typeLabel);
parametersPanel.add(type);
}
parametersPanel.add(valueLabel);
parametersPanel.add(reacParamValue);
parametersPanel.add(unitsLabel);
parametersPanel.add(reacParamUnits);
if (paramsOnly) {
parametersPanel.add(startLabel);
parametersPanel.add(start);
parametersPanel.add(stopLabel);
parametersPanel.add(stop);
parametersPanel.add(stepLabel);
parametersPanel.add(step);
parametersPanel.add(levelLabel);
parametersPanel.add(level);
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), parametersPanel, "Parameter Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = checkID(reacParamID.getText().trim(), selectedID, true);
if (!error) {
if (thisReactionParams.contains(reacParamID.getText().trim())
&& (!reacParamID.getText().trim().equals(selectedID))) {
JOptionPane.showMessageDialog(biosim.frame(), "ID is not unique.", "ID Not Unique",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
if (!error) {
double val = 0;
try {
val = Double.parseDouble(reacParamValue.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "The value must be a real number.",
"Enter A Valid Value", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
String unit = (String) reacParamUnits.getSelectedItem();
String param = "";
if (paramsOnly && !((String) type.getSelectedItem()).equals("Original")) {
int index = reacParameters.getSelectedIndex();
String[] splits = reacParams[index].split(" ");
for (int i = 0; i < splits.length - 2; i++) {
param += splits[i] + " ";
}
if (!splits[splits.length - 2].equals("Custom")
&& !splits[splits.length - 2].equals("Sweep")) {
param += splits[splits.length - 2] + " " + splits[splits.length - 1] + " ";
}
if (((String) type.getSelectedItem()).equals("Sweep")) {
double startVal = Double.parseDouble(start.getText().trim());
double stopVal = Double.parseDouble(stop.getText().trim());
double stepVal = Double.parseDouble(step.getText().trim());
param += "Sweep (" + startVal + "," + stopVal + "," + stepVal + ","
+ level.getSelectedItem() + ")";
}
else {
param += "Custom " + val;
}
}
else {
if (unit.equals("( none )")) {
param = reacParamID.getText().trim() + " " + val;
}
else {
param = reacParamID.getText().trim() + " " + val + " " + unit;
}
}
if (option.equals("OK")) {
int index = reacParameters.getSelectedIndex();
String v = ((String) reacParameters.getSelectedValue()).split(" ")[0];
Parameter paramet = null;
for (Parameter p : changedParameters) {
if (p.getId().equals(v)) {
paramet = p;
}
}
reacParameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacParams = Buttons.getList(reacParams, reacParameters);
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
paramet.setId(reacParamID.getText().trim());
paramet.setName(reacParamName.getText().trim());
for (int i = 0; i < thisReactionParams.size(); i++) {
if (thisReactionParams.get(i).equals(v)) {
thisReactionParams.set(i, reacParamID.getText().trim());
}
}
paramet.setValue(val);
if (unit.equals("( none )")) {
paramet.unsetUnits();
}
else {
paramet.setUnits(unit);
}
reacParams[index] = param;
sort(reacParams);
reacParameters.setListData(reacParams);
reacParameters.setSelectedIndex(index);
if (paramsOnly) {
int remove = -1;
for (int i = 0; i < parameterChanges.size(); i++) {
if (parameterChanges.get(i).split(" ")[0].equals(((String) reactions
.getSelectedValue()).split(" ")[0]
+ "/" + reacParamID.getText().trim())) {
remove = i;
}
}
if (remove != -1) {
parameterChanges.remove(remove);
int index1 = reactions.getSelectedIndex();
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacts = Buttons.getList(reacts, reactions);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reacts[index1] = ((String) reactions.getSelectedValue()).split(" ")[0];
sort(reacts);
reactions.setListData(reacts);
reactions.setSelectedIndex(index1);
}
if (!((String) type.getSelectedItem()).equals("Original")) {
String reacValue = ((String) reactions.getSelectedValue()).split(" ")[0];
parameterChanges.add(reacValue + "/" + param);
int index1 = reactions.getSelectedIndex();
reactions.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacts = Buttons.getList(reacts, reactions);
reactions.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reacts[index1] = reacValue + " Modified";
sort(reacts);
reactions.setListData(reacts);
reactions.setSelectedIndex(index1);
}
}
else {
kineticLaw.setText(updateFormulaVar(kineticLaw.getText().trim(), v, reacParamID
.getText().trim()));
}
}
else {
int index = reacParameters.getSelectedIndex();
Parameter paramet = new Parameter();
changedParameters.add(paramet);
paramet.setId(reacParamID.getText().trim());
paramet.setName(reacParamName.getText().trim());
thisReactionParams.add(reacParamID.getText().trim());
paramet.setValue(val);
if (!unit.equals("( none )")) {
paramet.setUnits(unit);
}
JList add = new JList();
Object[] adding = { param };
add.setListData(adding);
add.setSelectedIndex(0);
reacParameters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(reacParams, reacParameters, add, false, null, null, null, null,
null, null, biosim.frame());
reacParams = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
reacParams[i] = (String) adding[i];
}
sort(reacParams);
reacParameters.setListData(reacParams);
reacParameters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
try {
if (document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]).getKineticLaw()
.getNumParameters() == 1) {
reacParameters.setSelectedIndex(0);
}
else {
reacParameters.setSelectedIndex(index);
}
}
catch (Exception e2) {
reacParameters.setSelectedIndex(0);
}
}
change = true;
}
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), parametersPanel, "Parameter Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit products or create new ones.
*/
public void productsEditor(String option) {
if (option.equals("OK") && products.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No product selected.",
"Must Select A Product", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel productsPanel = new JPanel(new GridLayout(2, 2));
JLabel speciesLabel = new JLabel("Species:");
Object[] stoiciOptions = { "Stoichiometry", "Stoichiometry Math" };
stoiciLabel = new JComboBox(stoiciOptions);
ListOf listOfSpecies = document.getModel().getListOfSpecies();
String[] speciesList = new String[(int) document.getModel().getNumSpecies()];
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
speciesList[i] = ((Species) listOfSpecies.get(i)).getId();
}
sort(speciesList);
productSpecies = new JComboBox();
for (int i = 0; i < speciesList.length; i++) {
Species species = document.getModel().getSpecies(speciesList[i]);
if (species.getBoundaryCondition()
|| (!species.getConstant() && keepVar("", speciesList[i], false, true, false, false))) {
productSpecies.addItem(speciesList[i]);
}
}
productStoiciometry = new JTextField("1");
if (option.equals("OK")) {
String v = ((String) products.getSelectedValue()).split(" ")[0];
SpeciesReference product = null;
for (SpeciesReference p : changedProducts) {
if (p.getSpecies().equals(v)) {
product = p;
}
}
productSpecies.setSelectedItem(product.getSpecies());
if (product.isSetStoichiometryMath()) {
stoiciLabel.setSelectedItem("Stoichiometry Math");
productStoiciometry.setText(""
+ myFormulaToString(product.getStoichiometryMath().getMath()));
}
else {
productStoiciometry.setText("" + product.getStoichiometry());
}
}
productsPanel.add(speciesLabel);
productsPanel.add(productSpecies);
productsPanel.add(stoiciLabel);
productsPanel.add(productStoiciometry);
if (speciesList.length == 0) {
JOptionPane.showMessageDialog(biosim.frame(),
"There are no species availiable to be products."
+ "\nAdd species to this sbml file first.", "No Species", JOptionPane.ERROR_MESSAGE);
return;
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), productsPanel, "Products Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
String prod;
double val = 1.0;
if (stoiciLabel.getSelectedItem().equals("Stoichiometry")) {
try {
val = Double.parseDouble(productStoiciometry.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "The stoichiometry must be a real number.",
"Enter A Valid Value", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (val <= 0) {
JOptionPane.showMessageDialog(biosim.frame(),
"The stoichiometry value must be greater than 0.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
}
prod = productSpecies.getSelectedItem() + " " + val;
}
else {
prod = productSpecies.getSelectedItem() + " " + productStoiciometry.getText().trim();
}
int index = -1;
if (!error) {
if (option.equals("OK")) {
index = products.getSelectedIndex();
}
products.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
product = Buttons.getList(product, products);
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index >= 0) {
products.setSelectedIndex(index);
}
for (int i = 0; i < product.length; i++) {
if (i != index) {
if (product[i].split(" ")[0].equals(productSpecies.getSelectedItem())) {
error = true;
JOptionPane.showMessageDialog(biosim.frame(), "Unable to add species as a product.\n"
+ "Each species can only be used as a product once.",
"Species Can Only Be Used Once", JOptionPane.ERROR_MESSAGE);
}
}
}
}
if (!error) {
if (stoiciLabel.getSelectedItem().equals("Stoichiometry Math")) {
if (productStoiciometry.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "Stoichiometry math must have formula.",
"Enter Stoichiometry Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (myParseFormula(productStoiciometry.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Stoichiometry formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariables(productStoiciometry.getText()
.trim(), true, "", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Stoiciometry math contains unknown variables.\n\n"
+ "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Stoiciometry Math Error",
JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = checkNumFunctionArguments(myParseFormula(productStoiciometry.getText().trim()));
}
if (!error) {
if (myParseFormula(productStoiciometry.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Stoichiometry math must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
}
}
if (!error) {
if (option.equals("OK")) {
String v = ((String) products.getSelectedValue()).split(" ")[0];
SpeciesReference produ = null;
for (SpeciesReference p : changedProducts) {
if (p.getSpecies().equals(v)) {
produ = p;
}
}
products.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
product = Buttons.getList(product, products);
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
produ.setSpecies((String) productSpecies.getSelectedItem());
if (stoiciLabel.getSelectedItem().equals("Stoichiometry")) {
produ.setStoichiometry(val);
produ.unsetStoichiometryMath();
}
else {
StoichiometryMath sm = new StoichiometryMath(myParseFormula(productStoiciometry
.getText().trim()));
produ.setStoichiometryMath(sm);
produ.setStoichiometry(1);
}
product[index] = prod;
sort(product);
products.setListData(product);
products.setSelectedIndex(index);
}
else {
SpeciesReference produ = new SpeciesReference();
changedProducts.add(produ);
produ.setSpecies((String) productSpecies.getSelectedItem());
if (stoiciLabel.getSelectedItem().equals("Stoichiometry")) {
produ.setStoichiometry(val);
}
else {
StoichiometryMath sm = new StoichiometryMath(myParseFormula(productStoiciometry
.getText().trim()));
produ.setStoichiometryMath(sm);
}
JList add = new JList();
Object[] adding = { prod };
add.setListData(adding);
add.setSelectedIndex(0);
products.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(product, products, add, false, null, null, null, null, null, null,
biosim.frame());
product = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
product[i] = (String) adding[i];
}
sort(product);
products.setListData(product);
products.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
products.setSelectedIndex(0);
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), productsPanel, "Products Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit modifiers or create new ones.
*/
public void modifiersEditor(String option) {
if (option.equals("OK") && modifiers.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No modifier selected.",
"Must Select A Modifier", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel modifiersPanel = new JPanel(new GridLayout(1, 2));
JLabel speciesLabel = new JLabel("Species:");
ListOf listOfSpecies = document.getModel().getListOfSpecies();
String[] speciesList = new String[(int) document.getModel().getNumSpecies()];
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
speciesList[i] = ((Species) listOfSpecies.get(i)).getId();
}
sort(speciesList);
Object[] choices = speciesList;
modifierSpecies = new JComboBox(choices);
if (option.equals("OK")) {
String v = ((String) modifiers.getSelectedValue()).split(" ")[0];
ModifierSpeciesReference modifier = null;
for (ModifierSpeciesReference p : changedModifiers) {
if (p.getSpecies().equals(v)) {
modifier = p;
}
}
modifierSpecies.setSelectedItem(modifier.getSpecies());
}
modifiersPanel.add(speciesLabel);
modifiersPanel.add(modifierSpecies);
if (choices.length == 0) {
JOptionPane.showMessageDialog(biosim.frame(),
"There are no species availiable to be modifiers."
+ "\nAdd species to this sbml file first.", "No Species", JOptionPane.ERROR_MESSAGE);
return;
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), modifiersPanel, "Modifiers Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
String mod = (String) modifierSpecies.getSelectedItem();
if (option.equals("OK")) {
int index = modifiers.getSelectedIndex();
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modifier = Buttons.getList(modifier, modifiers);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
modifiers.setSelectedIndex(index);
for (int i = 0; i < modifier.length; i++) {
if (i != index) {
if (modifier[i].equals(modifierSpecies.getSelectedItem())) {
error = true;
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to add species as a modifier.\n"
+ "Each species can only be used as a modifier once.",
"Species Can Only Be Used Once", JOptionPane.ERROR_MESSAGE);
}
}
}
if (!error) {
String v = ((String) modifiers.getSelectedValue());
ModifierSpeciesReference modi = null;
for (ModifierSpeciesReference p : changedModifiers) {
if (p.getSpecies().equals(v)) {
modi = p;
}
}
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modifier = Buttons.getList(modifier, modifiers);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
modi.setSpecies((String) modifierSpecies.getSelectedItem());
modifier[index] = mod;
sort(modifier);
modifiers.setListData(modifier);
modifiers.setSelectedIndex(index);
}
}
else {
int index = modifiers.getSelectedIndex();
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
modifier = Buttons.getList(modifier, modifiers);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
modifiers.setSelectedIndex(index);
for (int i = 0; i < modifier.length; i++) {
if (modifier[i].equals(modifierSpecies.getSelectedItem())) {
error = true;
JOptionPane.showMessageDialog(biosim.frame(), "Unable to add species as a modifier.\n"
+ "Each species can only be used as a modifier once.",
"Species Can Only Be Used Once", JOptionPane.ERROR_MESSAGE);
}
}
if (!error) {
ModifierSpeciesReference modi = new ModifierSpeciesReference();
changedModifiers.add(modi);
modi.setSpecies((String) modifierSpecies.getSelectedItem());
JList add = new JList();
Object[] adding = { mod };
add.setListData(adding);
add.setSelectedIndex(0);
modifiers.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(modifier, modifiers, add, false, null, null, null, null, null, null,
biosim.frame());
modifier = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
modifier[i] = (String) adding[i];
}
sort(modifier);
modifiers.setListData(modifier);
modifiers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
try {
if (document.getModel().getReaction(
((String) reactions.getSelectedValue()).split(" ")[0]).getNumModifiers() == 1) {
modifiers.setSelectedIndex(0);
}
else {
modifiers.setSelectedIndex(index);
}
}
catch (Exception e2) {
modifiers.setSelectedIndex(0);
}
}
}
change = true;
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), modifiersPanel, "Modifiers Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Creates a frame used to edit reactants or create new ones.
*/
public void reactantsEditor(String option) {
if (option.equals("OK") && reactants.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(biosim.frame(), "No reactant selected.",
"Must Select A Reactant", JOptionPane.ERROR_MESSAGE);
return;
}
JPanel reactantsPanel = new JPanel(new GridLayout(2, 2));
JLabel speciesLabel = new JLabel("Species:");
Object[] stoiciOptions = { "Stoichiometry", "Stoichiometry Math" };
stoiciLabel = new JComboBox(stoiciOptions);
ListOf listOfSpecies = document.getModel().getListOfSpecies();
String[] speciesList = new String[(int) document.getModel().getNumSpecies()];
for (int i = 0; i < document.getModel().getNumSpecies(); i++) {
speciesList[i] = ((Species) listOfSpecies.get(i)).getId();
}
sort(speciesList);
reactantSpecies = new JComboBox();
for (int i = 0; i < speciesList.length; i++) {
Species species = document.getModel().getSpecies(speciesList[i]);
if (species.getBoundaryCondition()
|| (!species.getConstant() && keepVar("", speciesList[i], false, true, false, false))) {
reactantSpecies.addItem(speciesList[i]);
}
}
reactantStoiciometry = new JTextField("1");
if (option.equals("OK")) {
String v = ((String) reactants.getSelectedValue()).split(" ")[0];
SpeciesReference reactant = null;
for (SpeciesReference r : changedReactants) {
if (r.getSpecies().equals(v)) {
reactant = r;
}
}
reactantSpecies.setSelectedItem(reactant.getSpecies());
if (reactant.isSetStoichiometryMath()) {
stoiciLabel.setSelectedItem("Stoichiometry Math");
reactantStoiciometry.setText(""
+ myFormulaToString(reactant.getStoichiometryMath().getMath()));
}
else {
reactantStoiciometry.setText("" + reactant.getStoichiometry());
}
}
reactantsPanel.add(speciesLabel);
reactantsPanel.add(reactantSpecies);
reactantsPanel.add(stoiciLabel);
reactantsPanel.add(reactantStoiciometry);
if (speciesList.length == 0) {
JOptionPane.showMessageDialog(biosim.frame(),
"There are no species availiable to be reactants."
+ "\nAdd species to this sbml file first.", "No Species", JOptionPane.ERROR_MESSAGE);
return;
}
Object[] options = { option, "Cancel" };
int value = JOptionPane.showOptionDialog(biosim.frame(), reactantsPanel, "Reactants Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
boolean error = true;
while (error && value == JOptionPane.YES_OPTION) {
error = false;
String react;
double val = 1.0;
if (stoiciLabel.getSelectedItem().equals("Stoichiometry")) {
try {
val = Double.parseDouble(reactantStoiciometry.getText().trim());
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "The stoichiometry must be a real number.",
"Enter A Valid Value", JOptionPane.ERROR_MESSAGE);
error = true;
}
if (val <= 0) {
JOptionPane.showMessageDialog(biosim.frame(),
"The stoichiometry value must be greater than 0.", "Enter A Valid Value",
JOptionPane.ERROR_MESSAGE);
error = true;
}
react = reactantSpecies.getSelectedItem() + " " + val;
}
else {
react = reactantSpecies.getSelectedItem() + " " + reactantStoiciometry.getText().trim();
}
int index = -1;
if (!error) {
if (option.equals("OK")) {
index = reactants.getSelectedIndex();
}
reactants.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacta = Buttons.getList(reacta, reactants);
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
if (index >= 0) {
reactants.setSelectedIndex(index);
}
for (int i = 0; i < reacta.length; i++) {
if (i != index) {
if (reacta[i].split(" ")[0].equals(reactantSpecies.getSelectedItem())) {
error = true;
JOptionPane.showMessageDialog(biosim.frame(),
"Unable to add species as a reactant.\n"
+ "Each species can only be used as a reactant once.",
"Species Can Only Be Used Once", JOptionPane.ERROR_MESSAGE);
}
}
}
}
if (!error) {
if (stoiciLabel.getSelectedItem().equals("Stoichiometry Math")) {
if (reactantStoiciometry.getText().trim().equals("")) {
JOptionPane.showMessageDialog(biosim.frame(), "Stoichiometry math must have formula.",
"Enter Stoichiometry Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else if (myParseFormula(reactantStoiciometry.getText().trim()) == null) {
JOptionPane.showMessageDialog(biosim.frame(), "Stoichiometry formula is not valid.",
"Enter Valid Formula", JOptionPane.ERROR_MESSAGE);
error = true;
}
else {
ArrayList<String> invalidVars = getInvalidVariables(reactantStoiciometry.getText()
.trim(), true, "", false);
if (invalidVars.size() > 0) {
String invalid = "";
for (int i = 0; i < invalidVars.size(); i++) {
if (i == invalidVars.size() - 1) {
invalid += invalidVars.get(i);
}
else {
invalid += invalidVars.get(i) + "\n";
}
}
String message;
message = "Stoiciometry math contains unknown variables.\n\n"
+ "Unknown variables:\n" + invalid;
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setEditable(false);
JScrollPane scrolls = new JScrollPane();
scrolls.setMinimumSize(new Dimension(300, 300));
scrolls.setPreferredSize(new Dimension(300, 300));
scrolls.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scrolls, "Stoiciometry Math Error",
JOptionPane.ERROR_MESSAGE);
error = true;
}
if (!error) {
error = checkNumFunctionArguments(myParseFormula(reactantStoiciometry.getText()
.trim()));
}
if (!error) {
if (myParseFormula(reactantStoiciometry.getText().trim()).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Stoichiometry math must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
error = true;
}
}
}
}
}
if (!error) {
if (option.equals("OK")) {
String v = ((String) reactants.getSelectedValue()).split(" ")[0];
SpeciesReference reactan = null;
for (SpeciesReference r : changedReactants) {
if (r.getSpecies().equals(v)) {
reactan = r;
}
}
reactants.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
reacta = Buttons.getList(reacta, reactants);
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reactan.setSpecies((String) reactantSpecies.getSelectedItem());
if (stoiciLabel.getSelectedItem().equals("Stoichiometry")) {
reactan.setStoichiometry(val);
reactan.unsetStoichiometryMath();
}
else {
StoichiometryMath sm = new StoichiometryMath(myParseFormula(reactantStoiciometry
.getText().trim()));
reactan.setStoichiometryMath(sm);
reactan.setStoichiometry(1);
}
reacta[index] = react;
sort(reacta);
reactants.setListData(reacta);
reactants.setSelectedIndex(index);
}
else {
SpeciesReference reactan = new SpeciesReference();
changedReactants.add(reactan);
reactan.setSpecies((String) reactantSpecies.getSelectedItem());
if (stoiciLabel.getSelectedItem().equals("Stoichiometry")) {
reactan.setStoichiometry(val);
}
else {
StoichiometryMath sm = new StoichiometryMath(myParseFormula(reactantStoiciometry
.getText().trim()));
reactan.setStoichiometryMath(sm);
}
JList add = new JList();
Object[] adding = { react };
add.setListData(adding);
add.setSelectedIndex(0);
reactants.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
adding = Buttons.add(reacta, reactants, add, false, null, null, null, null, null, null,
biosim.frame());
reacta = new String[adding.length];
for (int i = 0; i < adding.length; i++) {
reacta[i] = (String) adding[i];
}
sort(reacta);
reactants.setListData(reacta);
reactants.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
reactants.setSelectedIndex(0);
}
change = true;
}
if (error) {
value = JOptionPane.showOptionDialog(biosim.frame(), reactantsPanel, "Reactants Editor",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
/**
* Invoked when the mouse is double clicked in one of the JLists. Opens the
* editor for the selected item.
*/
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
if (e.getSource() == compartments) {
if (!paramsOnly) {
compartEditor("OK");
}
}
else if (e.getSource() == functions) {
functionEditor("OK");
}
else if (e.getSource() == unitDefs) {
unitEditor("OK");
}
else if (e.getSource() == compTypes) {
compTypeEditor("OK");
}
else if (e.getSource() == specTypes) {
specTypeEditor("OK");
}
else if (e.getSource() == initAssigns) {
initEditor("OK");
}
else if (e.getSource() == rules) {
ruleEditor("OK");
}
else if (e.getSource() == events) {
eventEditor("OK");
}
else if (e.getSource() == constraints) {
constraintEditor("OK");
}
else if (e.getSource() == species) {
speciesEditor("OK");
}
else if (e.getSource() == reactions) {
reactionsEditor("OK");
}
else if (e.getSource() == parameters) {
parametersEditor("OK");
}
else if (e.getSource() == reacParameters) {
reacParametersEditor("OK");
}
else if (e.getSource() == reactants) {
if (!paramsOnly) {
reactantsEditor("OK");
}
}
else if (e.getSource() == products) {
if (!paramsOnly) {
productsEditor("OK");
}
}
else if (e.getSource() == modifiers) {
if (!paramsOnly) {
modifiersEditor("OK");
}
}
}
}
/**
* This method currently does nothing.
*/
public void mousePressed(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseReleased(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseExited(MouseEvent e) {
}
public boolean hasChanged() {
return change;
}
public void setChanged(boolean change) {
this.change = change;
}
/**
* Sorting function
*/
private void sort(String[] sort) {
int i, j;
String index;
for (i = 1; i < sort.length; i++) {
index = sort[i];
j = i;
while ((j > 0) && sort[j - 1].compareToIgnoreCase(index) > 0) {
sort[j] = sort[j - 1];
j = j - 1;
}
sort[j] = index;
}
}
/**
* Create the SBML file
*/
public void createSBML(String direct) {
try {
FileOutputStream out = new FileOutputStream(new File(paramFile));
out.write((refFile + "\n").getBytes());
for (String s : parameterChanges) {
out.write((s + "\n").getBytes());
}
out.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to save parameter file.",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
try {
if (!direct.equals(".")) {
String[] d = direct.split("_");
ArrayList<String> dd = new ArrayList<String>();
for (int i = 0; i < d.length; i++) {
if (!d[i].contains("=")) {
String di = d[i];
while (!d[i].contains("=")) {
i++;
di += "_" + d[i];
}
dd.add(di);
}
else {
dd.add(d[i]);
}
}
for (String di : dd) {
if (di.contains("/")) {
KineticLaw KL = document.getModel().getReaction(di.split("=")[0].split("/")[0])
.getKineticLaw();
ListOf p = KL.getListOfParameters();
for (int i = 0; i < KL.getNumParameters(); i++) {
Parameter param = ((Parameter) p.get(i));
if (param.getId().equals(di.split("=")[0].split("/")[1])) {
param.setValue(Double.parseDouble(di.split("=")[1]));
}
}
}
else {
if (document.getModel().getParameter(di.split("=")[0]) != null) {
document.getModel().getParameter(di.split("=")[0]).setValue(
Double.parseDouble(di.split("=")[1]));
}
else {
if (document.getModel().getSpecies(di.split("=")[0]).isSetInitialAmount()) {
document.getModel().getSpecies(di.split("=")[0]).setInitialAmount(
Double.parseDouble(di.split("=")[1]));
}
else {
document.getModel().getSpecies(di.split("=")[0]).setInitialConcentration(
Double.parseDouble(di.split("=")[1]));
}
}
}
}
}
direct = direct.replace("/", "-");
FileOutputStream out = new FileOutputStream(new File(simDir + separator + direct + separator
+ file.split(separator)[file.split(separator).length - 1]));
document.getModel().setName(modelName.getText().trim());
SBMLWriter writer = new SBMLWriter();
String doc = writer.writeToString(document);
byte[] output = doc.getBytes();
out.write(output);
out.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to create sbml file.",
"Error Creating File", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Checks consistency of the sbml file.
*/
public void checkOverDetermined() {
document.setConsistencyChecks(libsbml.LIBSBML_CAT_GENERAL_CONSISTENCY, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_IDENTIFIER_CONSISTENCY, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_UNITS_CONSISTENCY, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_MATHML_CONSISTENCY, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_SBO_CONSISTENCY, false);
document.setConsistencyChecks(libsbml.LIBSBML_CAT_MODELING_PRACTICE, false);
long numErrors = document.checkConsistency();
String message = "";
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage(); // .replace(". ",".\n");
message += i + ":" + error + "\n";
}
if (numErrors > 0) {
JOptionPane.showMessageDialog(biosim.frame(), "Algebraic rules make model overdetermined.",
"Model is Overdetermined", JOptionPane.WARNING_MESSAGE);
}
}
/**
* Checks consistency of the sbml file.
*/
public void check() {
// Hack to avoid wierd bug.
// By reloading the file before consistency checks, it seems to avoid a
// crash when attempting to save a newly added parameter with no units
SBMLReader reader = new SBMLReader();
document = reader.readSBML(file);
long numErrors = document.checkConsistency();
String message = "";
for (long i = 0; i < numErrors; i++) {
String error = document.getError(i).getMessage(); // .replace(". ",".\n");
message += i + ":" + error + "\n";
}
if (numErrors > 0) {
JTextArea messageArea = new JTextArea(message);
messageArea.setLineWrap(true);
messageArea.setEditable(false);
JScrollPane scroll = new JScrollPane();
scroll.setMinimumSize(new Dimension(600, 600));
scroll.setPreferredSize(new Dimension(600, 600));
scroll.setViewportView(messageArea);
JOptionPane.showMessageDialog(biosim.frame(), scroll, "SBML Errors and Warnings",
JOptionPane.ERROR_MESSAGE);
}
}
/**
* Saves the sbml file.
*/
public void save(boolean run) {
if (paramsOnly) {
if (run) {
ArrayList<String> sweepThese1 = new ArrayList<String>();
ArrayList<ArrayList<Double>> sweep1 = new ArrayList<ArrayList<Double>>();
ArrayList<String> sweepThese2 = new ArrayList<String>();
ArrayList<ArrayList<Double>> sweep2 = new ArrayList<ArrayList<Double>>();
for (String s : parameterChanges) {
if (s.split(" ")[s.split(" ").length - 2].equals("Sweep")) {
if ((s.split(" ")[s.split(" ").length - 1]).split(",")[3].replace(")", "").trim()
.equals("1")) {
sweepThese1.add(s.split(" ")[0]);
double start = Double
.parseDouble((s.split(" ")[s.split(" ").length - 1]).split(",")[0].substring(1)
.trim());
double stop = Double
.parseDouble((s.split(" ")[s.split(" ").length - 1]).split(",")[1].trim());
double step = Double
.parseDouble((s.split(" ")[s.split(" ").length - 1]).split(",")[2].trim());
ArrayList<Double> add = new ArrayList<Double>();
for (double i = start; i <= stop; i += step) {
add.add(i);
}
sweep1.add(add);
}
else {
sweepThese2.add(s.split(" ")[0]);
double start = Double
.parseDouble((s.split(" ")[s.split(" ").length - 1]).split(",")[0].substring(1)
.trim());
double stop = Double
.parseDouble((s.split(" ")[s.split(" ").length - 1]).split(",")[1].trim());
double step = Double
.parseDouble((s.split(" ")[s.split(" ").length - 1]).split(",")[2].trim());
ArrayList<Double> add = new ArrayList<Double>();
for (double i = start; i <= stop; i += step) {
add.add(i);
}
sweep2.add(add);
}
}
}
if (sweepThese1.size() > 0) {
int max = 0;
for (ArrayList<Double> d : sweep1) {
max = Math.max(max, d.size());
}
for (int j = 0; j < max; j++) {
String sweep = "";
for (int i = 0; i < sweepThese1.size(); i++) {
int k = j;
if (k >= sweep1.get(i).size()) {
k = sweep1.get(i).size() - 1;
}
if (sweep.equals("")) {
sweep += sweepThese1.get(i) + "=" + sweep1.get(i).get(k);
}
else {
sweep += "_" + sweepThese1.get(i) + "=" + sweep1.get(i).get(k);
}
}
if (sweepThese2.size() > 0) {
int max2 = 0;
for (ArrayList<Double> d : sweep2) {
max2 = Math.max(max2, d.size());
}
for (int l = 0; l < max2; l++) {
String sweepTwo = sweep;
for (int i = 0; i < sweepThese2.size(); i++) {
int k = l;
if (k >= sweep2.get(i).size()) {
k = sweep2.get(i).size() - 1;
}
if (sweepTwo.equals("")) {
sweepTwo += sweepThese2.get(i) + "=" + sweep2.get(i).get(k);
}
else {
sweepTwo += "_" + sweepThese2.get(i) + "=" + sweep2.get(i).get(k);
}
}
new File(simDir + separator + sweepTwo.replace("/", "-")).mkdir();
createSBML(sweepTwo);
new Reb2SacThread(reb2sac).start(sweepTwo.replace("/", "-"));
reb2sac.emptyFrames();
}
}
else {
new File(simDir + separator + sweep.replace("/", "-")).mkdir();
createSBML(sweep);
new Reb2SacThread(reb2sac).start(sweep.replace("/", "-"));
reb2sac.emptyFrames();
}
}
}
else {
createSBML(".");
new Reb2SacThread(reb2sac).start(".");
reb2sac.emptyFrames();
}
}
else {
createSBML(".");
}
change = false;
}
else {
try {
log.addText("Saving sbml file:\n" + file + "\n");
FileOutputStream out = new FileOutputStream(new File(file));
document.getModel().setName(modelName.getText().trim());
SBMLWriter writer = new SBMLWriter();
String doc = writer.writeToString(document);
byte[] output = doc.getBytes();
out.write(output);
out.close();
change = false;
if (paramsOnly) {
reb2sac.updateSpeciesList();
}
biosim.updateViews(file.split(separator)[file.split(separator).length - 1]);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(biosim.frame(), "Unable to save sbml file.",
"Error Saving File", JOptionPane.ERROR_MESSAGE);
}
}
}
public void updateSBML(int tab, int tab2) {
SBML_Editor sbml = new SBML_Editor(file, reb2sac, log, biosim, simDir, paramFile);
((JTabbedPane) (biosim.getTab().getComponentAt(tab))).setComponentAt(tab2, sbml);
reb2sac.setSbml(sbml);
((JTabbedPane) (biosim.getTab().getComponentAt(tab))).getComponentAt(tab2).setName(
"SBML Editor");
}
/**
* Set the file name
*/
public void setFile(String newFile) {
file = newFile;
}
/**
* Set the model ID
*/
public void setModelID(String modelID) {
this.modelID.setText(modelID);
document.getModel().setId(modelID);
}
/**
* Convert ASTNodes into a string
*/
public String myFormulaToString(ASTNode mathFormula) {
String formula = libsbml.formulaToString(mathFormula);
formula = formula.replaceAll("arccot", "acot");
formula = formula.replaceAll("arccoth", "acoth");
formula = formula.replaceAll("arccsc", "acsc");
formula = formula.replaceAll("arccsch", "acsch");
formula = formula.replaceAll("arcsec", "asec");
formula = formula.replaceAll("arcsech", "asech");
formula = formula.replaceAll("arccosh", "acosh");
formula = formula.replaceAll("arcsinh", "asinh");
formula = formula.replaceAll("arctanh", "atanh");
String newformula = formula.replaceFirst("00e", "0e");
while (!(newformula.equals(formula))) {
formula = newformula;
newformula = formula.replaceFirst("0e\\+", "e+");
newformula = newformula.replaceFirst("0e-", "e-");
}
formula = formula.replaceFirst("\\.e\\+", ".0e+");
formula = formula.replaceFirst("\\.e-", ".0e-");
return formula;
}
/**
* Convert String into ASTNodes
*/
public ASTNode myParseFormula(String formula) {
ASTNode mathFormula = libsbml.parseFormula(formula);
if (mathFormula == null)
return null;
setTimeAndTrigVar(mathFormula);
return mathFormula;
}
/**
* Recursive function to set time and trig functions
*/
public void setTimeAndTrigVar(ASTNode node) {
if (node.getType() == libsbml.AST_NAME) {
if (node.getName().equals("t")) {
node.setType(libsbml.AST_NAME_TIME);
}
}
if (node.getType() == libsbml.AST_FUNCTION) {
if (node.getName().equals("acot")) {
node.setType(libsbml.AST_FUNCTION_ARCCOT);
}
else if (node.getName().equals("acoth")) {
node.setType(libsbml.AST_FUNCTION_ARCCOTH);
}
else if (node.getName().equals("acsc")) {
node.setType(libsbml.AST_FUNCTION_ARCCSC);
}
else if (node.getName().equals("acsch")) {
node.setType(libsbml.AST_FUNCTION_ARCCSCH);
}
else if (node.getName().equals("asec")) {
node.setType(libsbml.AST_FUNCTION_ARCSEC);
}
else if (node.getName().equals("asech")) {
node.setType(libsbml.AST_FUNCTION_ARCSECH);
}
else if (node.getName().equals("acosh")) {
node.setType(libsbml.AST_FUNCTION_ARCCOSH);
}
else if (node.getName().equals("asinh")) {
node.setType(libsbml.AST_FUNCTION_ARCSINH);
}
else if (node.getName().equals("atanh")) {
node.setType(libsbml.AST_FUNCTION_ARCTANH);
}
}
for (int c = 0; c < node.getNumChildren(); c++)
setTimeAndTrigVar(node.getChild(c));
}
/**
* Check the number of arguments to a function
*/
public boolean checkNumFunctionArguments(ASTNode node) {
ListOf sbml = document.getModel().getListOfFunctionDefinitions();
switch (node.getType()) {
case libsbml.AST_FUNCTION_ABS:
case libsbml.AST_FUNCTION_ARCCOS:
case libsbml.AST_FUNCTION_ARCCOSH:
case libsbml.AST_FUNCTION_ARCSIN:
case libsbml.AST_FUNCTION_ARCSINH:
case libsbml.AST_FUNCTION_ARCTAN:
case libsbml.AST_FUNCTION_ARCTANH:
case libsbml.AST_FUNCTION_ARCCOT:
case libsbml.AST_FUNCTION_ARCCOTH:
case libsbml.AST_FUNCTION_ARCCSC:
case libsbml.AST_FUNCTION_ARCCSCH:
case libsbml.AST_FUNCTION_ARCSEC:
case libsbml.AST_FUNCTION_ARCSECH:
case libsbml.AST_FUNCTION_COS:
case libsbml.AST_FUNCTION_COSH:
case libsbml.AST_FUNCTION_SIN:
case libsbml.AST_FUNCTION_SINH:
case libsbml.AST_FUNCTION_TAN:
case libsbml.AST_FUNCTION_TANH:
case libsbml.AST_FUNCTION_COT:
case libsbml.AST_FUNCTION_COTH:
case libsbml.AST_FUNCTION_CSC:
case libsbml.AST_FUNCTION_CSCH:
case libsbml.AST_FUNCTION_SEC:
case libsbml.AST_FUNCTION_SECH:
case libsbml.AST_FUNCTION_CEILING:
case libsbml.AST_FUNCTION_FACTORIAL:
case libsbml.AST_FUNCTION_EXP:
case libsbml.AST_FUNCTION_FLOOR:
case libsbml.AST_FUNCTION_LN:
case libsbml.AST_FUNCTION_LOG:
if (node.getNumChildren() != 1) {
JOptionPane.showMessageDialog(biosim.frame(), "Expected 1 argument for " + node.getName()
+ " but found " + node.getNumChildren() + ".", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(), "Argument for " + node.getName()
+ " function must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_LOGICAL_NOT:
if (node.getNumChildren() != 1) {
JOptionPane.showMessageDialog(biosim.frame(), "Expected 1 argument for " + node.getName()
+ " but found " + node.getNumChildren() + ".", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (!node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument for not function must be of type Boolean.", "Boolean Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_LOGICAL_AND:
case libsbml.AST_LOGICAL_OR:
case libsbml.AST_LOGICAL_XOR:
if (node.getNumChildren() != 2) {
JOptionPane.showMessageDialog(biosim.frame(), "Expected 2 arguments for " + node.getName()
+ " but found " + node.getNumChildren() + ".", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (!node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(), "Argument 1 for " + node.getName()
+ " function is not of type Boolean.", "Boolean Expected", JOptionPane.ERROR_MESSAGE);
return true;
}
if (!node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(), "Argument 2 for " + node.getName()
+ " function is not of type Boolean.", "Boolean Expected", JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_PLUS:
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 1 for + operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 2 for + operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_MINUS:
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 1 for - operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 2 for - operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_TIMES:
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 1 for * operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 2 for * operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_DIVIDE:
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 1 for / operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 2 for / operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_POWER:
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 1 for ^ operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Argument 2 for ^ operator must evaluate to a number.", "Number Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_FUNCTION_DELAY:
case libsbml.AST_FUNCTION_POWER:
case libsbml.AST_FUNCTION_ROOT:
case libsbml.AST_RELATIONAL_GEQ:
case libsbml.AST_RELATIONAL_LEQ:
case libsbml.AST_RELATIONAL_LT:
case libsbml.AST_RELATIONAL_GT:
if (node.getNumChildren() != 2) {
JOptionPane.showMessageDialog(biosim.frame(), "Expected 2 arguments for " + node.getName()
+ " but found " + node.getNumChildren() + ".", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(0).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(), "Argument 1 for " + node.getName()
+ " function must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getChild(1).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(), "Argument 2 for " + node.getName()
+ " function must evaluate to a number.", "Number Expected", JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_RELATIONAL_EQ:
case libsbml.AST_RELATIONAL_NEQ:
if (node.getNumChildren() != 2) {
JOptionPane.showMessageDialog(biosim.frame(), "Expected 2 arguments for " + node.getName()
+ " but found " + node.getNumChildren() + ".", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
if ((node.getChild(0).isBoolean() && !node.getChild(1).isBoolean())
|| (!node.getChild(0).isBoolean() && node.getChild(1).isBoolean())) {
JOptionPane.showMessageDialog(biosim.frame(), "Arguments for " + node.getName()
+ " function must either both be numbers or Booleans.", "Argument Mismatch",
JOptionPane.ERROR_MESSAGE);
return true;
}
break;
case libsbml.AST_FUNCTION_PIECEWISE:
if (node.getNumChildren() < 1) {
JOptionPane.showMessageDialog(biosim.frame(),
"Piecewise function requires at least 1 argument.", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
for (int i = 1; i < node.getNumChildren(); i += 2) {
if (!node.getChild(i).isBoolean()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Even arguments of piecewise function must be of type Boolean.", "Boolean Expected",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
int pieceType = -1;
for (int i = 0; i < node.getNumChildren(); i += 2) {
if (node.getChild(i).isBoolean()) {
if (pieceType == 2) {
JOptionPane.showMessageDialog(biosim.frame(),
"All odd arguments of a piecewise function must agree.", "Type Mismatch",
JOptionPane.ERROR_MESSAGE);
return true;
}
pieceType = 1;
}
else {
if (pieceType == 1) {
JOptionPane.showMessageDialog(biosim.frame(),
"All odd arguments of a piecewise function must agree.", "Type Mismatch",
JOptionPane.ERROR_MESSAGE);
return true;
}
pieceType = 2;
}
}
case libsbml.AST_FUNCTION:
for (int i = 0; i < document.getModel().getNumFunctionDefinitions(); i++) {
if (((FunctionDefinition) sbml.get(i)).getId().equals(node.getName())) {
long numArgs = ((FunctionDefinition) sbml.get(i)).getNumArguments();
if (numArgs != node.getNumChildren()) {
JOptionPane.showMessageDialog(biosim.frame(), "Expected " + numArgs
+ " argument(s) for " + node.getName() + " but found " + node.getNumChildren()
+ ".", "Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE);
return true;
}
break;
}
}
break;
case libsbml.AST_NAME:
if (node.getName().equals("abs") || node.getName().equals("arccos")
|| node.getName().equals("arccosh") || node.getName().equals("arcsin")
|| node.getName().equals("arcsinh") || node.getName().equals("arctan")
|| node.getName().equals("arctanh") || node.getName().equals("arccot")
|| node.getName().equals("arccoth") || node.getName().equals("arccsc")
|| node.getName().equals("arccsch") || node.getName().equals("arcsec")
|| node.getName().equals("arcsech") || node.getName().equals("acos")
|| node.getName().equals("acosh") || node.getName().equals("asin")
|| node.getName().equals("asinh") || node.getName().equals("atan")
|| node.getName().equals("atanh") || node.getName().equals("acot")
|| node.getName().equals("acoth") || node.getName().equals("acsc")
|| node.getName().equals("acsch") || node.getName().equals("asec")
|| node.getName().equals("asech") || node.getName().equals("cos")
|| node.getName().equals("cosh") || node.getName().equals("cot")
|| node.getName().equals("coth") || node.getName().equals("csc")
|| node.getName().equals("csch") || node.getName().equals("ceil")
|| node.getName().equals("factorial") || node.getName().equals("exp")
|| node.getName().equals("floor") || node.getName().equals("ln")
|| node.getName().equals("log") || node.getName().equals("sqr")
|| node.getName().equals("log10") || node.getName().equals("sqrt")
|| node.getName().equals("sec") || node.getName().equals("sech")
|| node.getName().equals("sin") || node.getName().equals("sinh")
|| node.getName().equals("tan") || node.getName().equals("tanh")
|| node.getName().equals("not")) {
JOptionPane.showMessageDialog(biosim.frame(), "Expected 1 argument for " + node.getName()
+ " but found 0.", "Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getName().equals("and") || node.getName().equals("or")
|| node.getName().equals("xor") || node.getName().equals("pow")
|| node.getName().equals("eq") || node.getName().equals("geq")
|| node.getName().equals("leq") || node.getName().equals("gt")
|| node.getName().equals("neq") || node.getName().equals("lt")
|| node.getName().equals("delay") || node.getName().equals("root")) {
JOptionPane.showMessageDialog(biosim.frame(), "Expected 2 arguments for " + node.getName()
+ " but found 0.", "Number of Arguments Incorrect", JOptionPane.ERROR_MESSAGE);
return true;
}
if (node.getName().equals("piecewise")) {
JOptionPane.showMessageDialog(biosim.frame(),
"Piecewise function requires at least 1 argument.", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
for (int i = 0; i < document.getModel().getNumFunctionDefinitions(); i++) {
if (((FunctionDefinition) sbml.get(i)).getId().equals(node.getName())) {
long numArgs = ((FunctionDefinition) sbml.get(i)).getNumArguments();
JOptionPane.showMessageDialog(biosim.frame(), "Expected " + numArgs + " argument(s) for "
+ node.getName() + " but found 0.", "Number of Arguments Incorrect",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
break;
}
for (int c = 0; c < node.getNumChildren(); c++) {
if (checkNumFunctionArguments(node.getChild(c))) {
return true;
}
}
return false;
}
/**
* Check the units of a rate rule
*/
public boolean checkRateRuleUnits(Rule rule) {
document.getModel().populateListFormulaUnitsData();
if (rule.containsUndeclaredUnits()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Rate rule contains literals numbers or parameters with undeclared units.\n"
+ "Therefore, it is not possible to completely verify the consistency of the units.",
"Contains Undeclared Units", JOptionPane.WARNING_MESSAGE);
return false;
}
else {
UnitDefinition unitDef = rule.getDerivedUnitDefinition();
UnitDefinition unitDefVar;
Species species = document.getModel().getSpecies(rule.getVariable());
Compartment compartment = document.getModel().getCompartment(rule.getVariable());
Parameter parameter = document.getModel().getParameter(rule.getVariable());
if (species != null) {
unitDefVar = species.getDerivedUnitDefinition();
}
else if (compartment != null) {
unitDefVar = compartment.getDerivedUnitDefinition();
}
else {
unitDefVar = parameter.getDerivedUnitDefinition();
}
if (document.getModel().getUnitDefinition("time") != null) {
UnitDefinition timeUnitDef = document.getModel().getUnitDefinition("time");
for (int i = 0; i < timeUnitDef.getNumUnits(); i++) {
Unit timeUnit = timeUnitDef.getUnit(i);
Unit recTimeUnit = new Unit(timeUnit.getKind(), timeUnit.getExponent() * (-1), timeUnit
.getScale(), timeUnit.getMultiplier());
unitDefVar.addUnit(recTimeUnit);
}
}
else {
Unit unit = new Unit("second", -1, 0, 1.0);
unitDefVar.addUnit(unit);
}
if (!UnitDefinition.areEquivalent(unitDef, unitDefVar)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Units on the left and right-hand side of the rate rule do not agree.",
"Units Do Not Match", JOptionPane.ERROR_MESSAGE);
return true;
}
}
return false;
}
/**
* Check the units of an assignment rule
*/
public boolean checkAssignmentRuleUnits(Rule rule) {
document.getModel().populateListFormulaUnitsData();
if (rule.containsUndeclaredUnits()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Assignment rule contains literals numbers or parameters with undeclared units.\n"
+ "Therefore, it is not possible to completely verify the consistency of the units.",
"Contains Undeclared Units", JOptionPane.WARNING_MESSAGE);
return false;
}
else {
UnitDefinition unitDef = rule.getDerivedUnitDefinition();
UnitDefinition unitDefVar;
Species species = document.getModel().getSpecies(rule.getVariable());
Compartment compartment = document.getModel().getCompartment(rule.getVariable());
Parameter parameter = document.getModel().getParameter(rule.getVariable());
if (species != null) {
unitDefVar = species.getDerivedUnitDefinition();
}
else if (compartment != null) {
unitDefVar = compartment.getDerivedUnitDefinition();
}
else {
unitDefVar = parameter.getDerivedUnitDefinition();
}
if (!UnitDefinition.areEquivalent(unitDef, unitDefVar)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Units on the left and right-hand side of the assignment rule do not agree.",
"Units Do Not Match", JOptionPane.ERROR_MESSAGE);
return true;
}
}
return false;
}
/**
* Check the units of an initial assignment
*/
public boolean checkInitialAssignmentUnits(InitialAssignment init) {
document.getModel().populateListFormulaUnitsData();
if (init.containsUndeclaredUnits()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Initial assignment contains literals numbers or parameters with undeclared units.\n"
+ "Therefore, it is not possible to completely verify the consistency of the units.",
"Contains Undeclared Units", JOptionPane.WARNING_MESSAGE);
return false;
}
else {
UnitDefinition unitDef = init.getDerivedUnitDefinition();
UnitDefinition unitDefVar;
Species species = document.getModel().getSpecies(init.getSymbol());
Compartment compartment = document.getModel().getCompartment(init.getSymbol());
Parameter parameter = document.getModel().getParameter(init.getSymbol());
if (species != null) {
unitDefVar = species.getDerivedUnitDefinition();
}
else if (compartment != null) {
unitDefVar = compartment.getDerivedUnitDefinition();
}
else {
unitDefVar = parameter.getDerivedUnitDefinition();
}
if (!UnitDefinition.areEquivalent(unitDef, unitDefVar)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Units on the left and right-hand side of the initial assignment do not agree.",
"Units Do Not Match", JOptionPane.ERROR_MESSAGE);
return true;
}
// for (int i = 0; i < unitDef.getNumUnits(); i++) {
// Unit unit = unitDef.getUnit(i);
// System.out.println(unit.getKind() + " Exp = " + unit.getExponent() + "
// Mult = " + unit.getMultiplier() + " Scale = " + unit.getScale());
// }
// for (int i = 0; i < unitDefVar.getNumUnits(); i++) {
// Unit unit = unitDefVar.getUnit(i);
// System.out.println(unit.getKind() + " Exp = " + unit.getExponent() + "
// Mult = " + unit.getMultiplier() + " Scale = " + unit.getScale());
// }
}
return false;
}
/**
* Check the units of an event assignment
*/
public boolean checkEventAssignmentUnits(EventAssignment assign) {
document.getModel().populateListFormulaUnitsData();
if (assign.containsUndeclaredUnits()) {
JOptionPane.showMessageDialog(biosim.frame(), "Event assignment to " + assign.getVariable()
+ " contains literals numbers or parameters with undeclared units.\n"
+ "Therefore, it is not possible to completely verify the consistency of the units.",
"Contains Undeclared Units", JOptionPane.WARNING_MESSAGE);
return false;
}
else {
UnitDefinition unitDef = assign.getDerivedUnitDefinition();
UnitDefinition unitDefVar;
Species species = document.getModel().getSpecies(assign.getVariable());
Compartment compartment = document.getModel().getCompartment(assign.getVariable());
Parameter parameter = document.getModel().getParameter(assign.getVariable());
if (species != null) {
unitDefVar = species.getDerivedUnitDefinition();
}
else if (compartment != null) {
unitDefVar = compartment.getDerivedUnitDefinition();
}
else {
unitDefVar = parameter.getDerivedUnitDefinition();
}
if (!UnitDefinition.areEquivalent(unitDef, unitDefVar)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Units on the left and right-hand side for the event assignment "
+ assign.getVariable() + " do not agree.", "Units Do Not Match",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
return false;
}
/**
* Check the units of an event delay
*/
// public boolean checkEventDelayUnits(Delay delay) {
// document.getModel().populateListFormulaUnitsData();
// System.out.println(myFormulaToString(delay.getMath()));
// if (delay.containsUndeclaredUnits()) {
// JOptionPane.showMessageDialog(biosim.frame(), "Event assignment delay contains literals numbers or parameters with undeclared units.\n" +
// "Therefore, it is not possible to completely verify the consistency of the units.",
// "Contains Undeclared Units", JOptionPane.WARNING_MESSAGE);
// return false;
// } else {
// UnitDefinition unitDef = delay.getDerivedUnitDefinition();
// /* NEED TO CHECK IT AGAINST TIME HERE */
// }
// return false;
// }
/**
* Check the units of a kinetic law
*/
public boolean checkKineticLawUnits(KineticLaw law) {
document.getModel().populateListFormulaUnitsData();
if (law.containsUndeclaredUnits()) {
JOptionPane.showMessageDialog(biosim.frame(),
"Kinetic law contains literals numbers or parameters with undeclared units.\n"
+ "Therefore, it is not possible to completely verify the consistency of the units.",
"Contains Undeclared Units", JOptionPane.WARNING_MESSAGE);
return false;
}
else {
UnitDefinition unitDef = law.getDerivedUnitDefinition();
UnitDefinition unitDefLaw = new UnitDefinition();
if (document.getModel().getUnitDefinition("substance") != null) {
UnitDefinition subUnitDef = document.getModel().getUnitDefinition("substance");
for (int i = 0; i < subUnitDef.getNumUnits(); i++) {
Unit subUnit = subUnitDef.getUnit(i);
unitDefLaw.addUnit(subUnit);
}
}
else {
Unit unit = new Unit("mole", 1, 0, 1.0);
unitDefLaw.addUnit(unit);
}
if (document.getModel().getUnitDefinition("time") != null) {
UnitDefinition timeUnitDef = document.getModel().getUnitDefinition("time");
for (int i = 0; i < timeUnitDef.getNumUnits(); i++) {
Unit timeUnit = timeUnitDef.getUnit(i);
Unit recTimeUnit = new Unit(timeUnit.getKind(), timeUnit.getExponent() * (-1), timeUnit
.getScale(), timeUnit.getMultiplier());
unitDefLaw.addUnit(recTimeUnit);
}
}
else {
Unit unit = new Unit("second", -1, 0, 1.0);
unitDefLaw.addUnit(unit);
}
if (!UnitDefinition.areEquivalent(unitDef, unitDefLaw)) {
JOptionPane.showMessageDialog(biosim.frame(),
"Kinetic law units should be substance / time.", "Units Do Not Match",
JOptionPane.ERROR_MESSAGE);
return true;
}
}
return false;
}
}
| Added event support to ssa_with_user_update
Fixed compile bug in SBML_Editor.java
| gui/src/sbmleditor/SBML_Editor.java | Added event support to ssa_with_user_update Fixed compile bug in SBML_Editor.java |
|
Java | apache-2.0 | 3a9eb6678237fc0bf5ccb6cce2e1f211ac2231b5 | 0 | pousse-cafe/pousse-cafe,pousse-cafe/pousse-cafe | package poussecafe.process;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class DomainProcess extends TransactionAwareService {
protected Logger logger = LoggerFactory.getLogger(getClass());
}
| pousse-cafe-core/src/main/java/poussecafe/process/DomainProcess.java | package poussecafe.process;
public abstract class DomainProcess extends TransactionAwareService {
}
| Add default logger in DomainProcess. | pousse-cafe-core/src/main/java/poussecafe/process/DomainProcess.java | Add default logger in DomainProcess. |
|
Java | apache-2.0 | 22a10e2425d664d85a1299aac5b734f77c69a6e1 | 0 | dernasherbrezon/r2cloud,dernasherbrezon/r2cloud | package ru.r2cloud.it;
import static org.junit.Assert.assertEquals;
import java.io.File;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import ru.r2cloud.TestConfiguration;
import ru.r2cloud.TestUtil;
import ru.r2cloud.model.ObservationResult;
import ru.r2cloud.satellite.decoder.MeteorM22Decoder;
import ru.r2cloud.util.ProcessFactory;
public class MeteorM22DecoderIT {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
private TestConfiguration config;
private ProcessFactory factory;
@Test
public void testSuccess() throws Exception {
File file = TestUtil.setupClasspathResource(tempFolder, "data/meteor-m22-small.raw.gz");
MeteorM22Decoder decoder = new MeteorM22Decoder(config, factory);
ObservationResult result = decoder.decode(file, TestUtil.loadObservation("decodertests/MeteorM22DecoderTest.json").getReq());
assertEquals(3L, result.getNumberOfDecodedPackets().longValue());
}
@Before
public void start() throws Exception {
config = new TestConfiguration(tempFolder);
config.setProperty("satellites.meteor_demod.path", "meteor_demod");
config.setProperty("server.tmp.directory", tempFolder.getRoot().getAbsolutePath());
config.update();
factory = new ProcessFactory();
}
}
| src/test/java/ru/r2cloud/it/MeteorM22DecoderIT.java | package ru.r2cloud.it;
import static org.junit.Assert.assertEquals;
import java.io.File;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import ru.r2cloud.TestConfiguration;
import ru.r2cloud.TestUtil;
import ru.r2cloud.model.ObservationResult;
import ru.r2cloud.satellite.decoder.MeteorM22Decoder;
import ru.r2cloud.util.ProcessFactory;
public class MeteorM22DecoderIT {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
private TestConfiguration config;
private ProcessFactory factory;
@Test
public void testSuccess() throws Exception {
File file = TestUtil.setupClasspathResource(tempFolder, "data/meteor-m22-small.raw.gz");
MeteorM22Decoder decoder = new MeteorM22Decoder(config, factory);
ObservationResult result = decoder.decode(file, TestUtil.loadObservation("decodertests/MeteorM22DecoderTest.json").getReq());
assertEquals(2L, result.getNumberOfDecodedPackets().longValue());
}
@Before
public void start() throws Exception {
config = new TestConfiguration(tempFolder);
config.setProperty("satellites.meteor_demod.path", "meteor_demod");
config.setProperty("server.tmp.directory", tempFolder.getRoot().getAbsolutePath());
config.update();
factory = new ProcessFactory();
}
}
| fix test | src/test/java/ru/r2cloud/it/MeteorM22DecoderIT.java | fix test |
|
Java | mit | ffd13df6746369795568b0e11b7f27fd36bf9b80 | 0 | Jason0803/Cocoa-Note,Jason0803/Cocoa-Note,Jason0803/Cocoa-Note | package util;
import java.util.Calendar;
/*
* Date 관리용 커스텀 클래스.
* DB에서 Date 타입 컬럼 요청시 SELECT to_char(date, 'YYYYMMDDHH24MI') FROM table
* Constructor
* 1) String type의 YYYYMMDDHH24MI
* 2) int year, int month, int day
* 3) Calendar 객체
*
* 2017.10.17 / coding by K
*/
public class CocoaDate {
private int year;
private int month;
private int date;
private int startDay;
private int lastDate;
private int hour;
private int minute;
private Calendar originCal;
private Calendar renewCal;
public CocoaDate(Calendar cal) {
setDefault(cal.get(cal.YEAR), cal.get(cal.MONTH)+1, cal.get(cal.DATE), cal.get(cal.HOUR), cal.get(cal.MINUTE));
setRenewCal(cal);
}
public CocoaDate(int year, int month, int date) {
Calendar cal = Calendar.getInstance();
cal.set(year, month-1, date);
setDefault(cal.get(cal.YEAR), cal.get(cal.MONTH)+1, cal.get(cal.DATE), cal.get(cal.HOUR), cal.get(cal.MINUTE));
setRenewCal(cal);
}
public CocoaDate(String sql_date) {
//YYYYMMDDHHMM
//012345678901
int year = Integer.parseInt(sql_date.substring(0, 4));
int month = Integer.parseInt(sql_date.substring(4, 6));
int date = Integer.parseInt(sql_date.substring(6, 8));
int hour = Integer.parseInt(sql_date.substring(8, 10));
int minute = Integer.parseInt(sql_date.substring(10));
Calendar cal = Calendar.getInstance();
cal.set(year, month, date, hour, minute);
setDefault(year, month, date, hour, minute);
setRenewCal(cal);
}
private void setDefault(int year, int month, int date, int hour, int minute) {
this.year = year;
this.month = month;
this.date = date;
this.hour = hour;
this.minute = minute;
} // CocoaDate 객체 필드에 연월일분초를 할당하는 내부메소드
public Calendar getOriginCal() {
return originCal;
}
public void setOriginCal(Calendar originCal) {
this.originCal = originCal;
}
public Calendar getRenewCal() {
return renewCal;
}
public void setRenewCal(Calendar originCal) {
this.renewCal = originCal;
renewCal.set(Calendar.DATE, 1);
this.startDay = renewCal.get(renewCal.DAY_OF_WEEK);
this.lastDate = renewCal.getActualMaximum(renewCal.DATE);
} // Date연산용 temp Calendar 객체를 생성
public void setYear(int year) {
this.year = year;
}
public void setMonth(int month) {
this.month = month;
}
public void setDay(int day) {
this.date = day;
}
public void setStartDay(int startDay) {
this.startDay = startDay;
}
public void setEndDay(int endDay) {
this.lastDate = endDay;
}
public int getYear() {
return year;
}
public int getMonth() {
return month;
}
public int getDay() {
return date;
}
public int getStartDay() {
return startDay;
}
public int getEndDay() {
return lastDate;
}
}
| src/util/CocoaDate.java | package util;
import java.util.Calendar;
public class CocoaDate {
private int year;
private int month;
private int date;
private int startDay;
private int endDay;
private Calendar cal;
private Calendar cal2;
public CocoaDate(Calendar cal) {
this.year = cal.get(cal.YEAR);
this.month = cal.get(cal.MONTH)+1;
this.date = cal.get(cal.DATE);
this.cal2 = cal;
cal2.set(Calendar.DATE, 1);
this.startDay = cal2.get(cal2.DAY_OF_WEEK);
this.endDay = cal2.getActualMaximum(cal2.DAY_OF_MONTH);
}
public CocoaDate(int year, int month, int date) {
Calendar cal = Calendar.getInstance();
cal.set(year, month-1, date);
this.year = cal.get(cal.YEAR);
this.month = cal.get(cal.MONTH)+1;
this.date = cal.get(cal.DATE);
this.cal2 = cal;
cal2.set(Calendar.DATE, 1);
this.startDay = cal2.get(cal2.DAY_OF_WEEK);
this.endDay = cal2.getActualMaximum(cal2.DATE);
}
public Calendar getCal() {
return cal;
}
public void setCal(Calendar cal) {
this.cal = cal;
}
public Calendar getCal2() {
return cal2;
}
public void setCal2(Calendar cal2) {
this.cal2 = cal2;
}
public void setYear(int year) {
this.year = year;
}
public void setMonth(int month) {
this.month = month;
}
public void setDay(int day) {
this.date = day;
}
public void setStartDay(int startDay) {
this.startDay = startDay;
}
public void setEndDay(int endDay) {
this.endDay = endDay;
}
public int getYear() {
return year;
}
public int getMonth() {
return month;
}
public int getDay() {
return date;
}
public int getStartDay() {
return startDay;
}
public int getEndDay() {
return endDay;
}
}
| #00045 CocoaDate class modify
-시간, 분 필드 추가
-DB에서 받아온 날짜정보로 CocoaDate 객체를 생성할 수 있도록 생성자 추가
| src/util/CocoaDate.java | #00045 CocoaDate class modify |
|
Java | mit | bdf374e2640492105976b8625fa6bf2b2dbbb0ae | 0 | thest1/Android-VKontakte-SDK,romanbrandhall/MyApp | package com.perm.kate.api;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.zip.GZIPInputStream;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.perm.utils.Utils;
import com.perm.utils.WrongResponseCodeException;
import android.util.Log;
public class Api {
static final String TAG="Kate.Api";
public static final String BASE_URL="https://api.vk.com/method/";
public Api(String access_token, String api_id){
this.access_token=access_token;
this.api_id=api_id;
}
String access_token;
String api_id;
//TODO: it's not faster, even slower on slow devices. Maybe we should add an option to disable it. It's only good for paid internet connection.
static boolean enable_compression=true;
/*** utils methods***/
private void checkError(JSONObject root, String url) throws JSONException,KException {
if(!root.isNull("error")){
JSONObject error=root.getJSONObject("error");
int code=error.getInt("error_code");
String message=error.getString("error_msg");
KException e = new KException(code, message, url);
if (code==14) {
e.captcha_img = error.optString("captcha_img");
e.captcha_sid = error.optString("captcha_sid");
}
throw e;
}
}
private JSONObject sendRequest(Params params) throws IOException, MalformedURLException, JSONException, KException {
return sendRequest(params, false);
}
private final static int MAX_TRIES=3;
private JSONObject sendRequest(Params params, boolean is_post) throws IOException, MalformedURLException, JSONException, KException {
String url = getSignedUrl(params, is_post);
String body="";
if(is_post)
body=params.getParamsString(is_post);
Log.i(TAG, "url="+url);
if(body.length()!=0)
Log.i(TAG, "body="+body);
String response="";
for(int i=1;i<=MAX_TRIES;++i){
try{
if(i!=1)
Log.i(TAG, "try "+i);
response = sendRequestInternal(url, body, is_post);
break;
}catch(javax.net.ssl.SSLException ex){
processNetworkException(i, ex);
}catch(java.net.SocketException ex){
processNetworkException(i, ex);
}
}
Log.i(TAG, "response="+response);
JSONObject root=new JSONObject(response);
checkError(root, url);
return root;
}
private void processNetworkException(int i, IOException ex) throws IOException {
ex.printStackTrace();
if(i==MAX_TRIES)
throw ex;
}
private String sendRequestInternal(String url, String body, boolean is_post) throws IOException, MalformedURLException, WrongResponseCodeException {
HttpURLConnection connection=null;
try{
connection = (HttpURLConnection)new URL(url).openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setUseCaches(false);
connection.setDoOutput(is_post);
connection.setDoInput(true);
connection.setRequestMethod(is_post?"POST":"GET");
if(enable_compression)
connection.setRequestProperty("Accept-Encoding", "gzip");
if(is_post)
connection.getOutputStream().write(body.getBytes("UTF-8"));
int code=connection.getResponseCode();
Log.i(TAG, "code="+code);
//It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation
if (code==-1)
throw new WrongResponseCodeException("Network error");
//может стоит проверить на код 200
//on error can also read error stream from connection.
InputStream is = new BufferedInputStream(connection.getInputStream(), 8192);
String enc=connection.getHeaderField("Content-Encoding");
if(enc!=null && enc.equalsIgnoreCase("gzip"))
is = new GZIPInputStream(is);
String response=Utils.convertStreamToString(is);
return response;
}
finally{
if(connection!=null)
connection.disconnect();
}
}
private long getDefaultStartTime() {
long now = System.currentTimeMillis() / 1000L;//unixtime
return now-31*24*60*60;//month ago
}
private String getSignedUrl(Params params, boolean is_post) {
String args = "";
if(!is_post)
args=params.getParamsString(is_post);
//add access_token
if(args.length()!=0)
args+="&";
args+="access_token="+access_token;
return BASE_URL+params.method_name+"?"+args;
}
public static String unescape(String text){
if(text==null)
return null;
return text.replace("&", "&").replace(""", "\"").replace("<br>", "\n").replace(">", ">").replace("<", "<")
.replace("'", "'").replace("<br/>", "\n").replace("–","-").replace("!", "!").trim();
//возможно тут могут быть любые коды после &#, например были: 092 - backslash \
}
public static String unescapeWithSmiles(String text){
return unescape(text)
//May be useful to someone
//.replace("\uD83D\uDE0A", ":-)")
//.replace("\uD83D\uDE03", ":D")
//.replace("\uD83D\uDE09", ";-)")
//.replace("\uD83D\uDE06", "xD")
//.replace("\uD83D\uDE1C", ";P")
//.replace("\uD83D\uDE0B", ":p")
//.replace("\uD83D\uDE0D", "8)")
//.replace("\uD83D\uDE0E", "B)")
//
//.replace("\ud83d\ude12", ":(") //F0 9F 98 92
//.replace("\ud83d\ude0f", ":]") //F0 9F 98 8F
//.replace("\ud83d\ude14", "3(") //F0 9F 98 94
//.replace("\ud83d\ude22", ":'(") //F0 9F 98 A2
//.replace("\ud83d\ude2d", ":_(") //F0 9F 98 AD
//.replace("\ud83d\ude29", ":((") //F0 9F 98 A9
//.replace("\ud83d\ude28", ":o") //F0 9F 98 A8
//.replace("\ud83d\ude10", ":|") //F0 9F 98 90
//
//.replace("\ud83d\ude0c", "3)") //F0 9F 98 8C
//.replace("\ud83d\ude20", ">(") //F0 9F 98 A0
//.replace("\ud83d\ude21", ">((") //F0 9F 98 A1
//.replace("\ud83d\ude07", "O:)") //F0 9F 98 87
//.replace("\ud83d\ude30", ";o") //F0 9F 98 B0
//.replace("\ud83d\ude32", "8o") //F0 9F 98 B2
//.replace("\ud83d\ude33", "8|") //F0 9F 98 B3
//.replace("\ud83d\ude37", ":X") //F0 9F 98 B7
//
//.replace("\ud83d\ude1a", ":*") //F0 9F 98 9A
//.replace("\ud83d\ude08", "}:)") //F0 9F 98 88
//.replace("\u2764", "<3") //E2 9D A4
//.replace("\ud83d\udc4d", ":like:") //F0 9F 91 8D
//.replace("\ud83d\udc4e", ":dislike:") //F0 9F 91 8E
//.replace("\u261d", ":up:") //E2 98 9D
//.replace("\u270c", ":v:") //E2 9C 8C
//.replace("\ud83d\udc4c", ":ok:") //F0 9F 91 8C
;
}
/*** API methods ***/
//http://vk.com/developers.php?oid=-1&p=places.getCityById
public ArrayList<City> getCities(Collection<Long> cids) throws MalformedURLException, IOException, JSONException, KException {
if (cids == null || cids.size() == 0)
return null;
Params params = new Params("places.getCityById");
params.put("cids",arrayToString(cids));
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<City> cities=new ArrayList<City>();
if(array!=null){
for(int i=0; i<array.length(); i++){
JSONObject o = (JSONObject)array.get(i);
City c = City.parse(o);
cities.add(c);
}
}
return cities;
}
<T> String arrayToString(Collection<T> items) {
if(items==null)
return null;
String str_cids = "";
for (Object item:items){
if(str_cids.length()!=0)
str_cids+=',';
str_cids+=item;
}
return str_cids;
}
//http://vk.com/developers.php?oid=-1&p=places.getCountryById
public ArrayList<Country> getCountries(Collection<Long> cids) throws MalformedURLException, IOException, JSONException, KException {
if (cids == null || cids.size() == 0)
return null;
Params params = new Params("places.getCountryById");
String str_cids = arrayToString(cids);
params.put("cids",str_cids);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Country> countries=new ArrayList<Country>();
int category_count = array.length();
for(int i=0; i<category_count; i++){
JSONObject o = (JSONObject)array.get(i);
Country c = Country.parse(o);
countries.add(c);
}
return countries;
}
//*** methods for users ***//
//http://vk.com/developers.php?oid=-1&p=users.get
public ArrayList<User> getProfiles(Collection<Long> uids, Collection<String> domains, String fields, String name_case) throws MalformedURLException, IOException, JSONException, KException{
if (uids == null && domains == null)
return null;
if ((uids != null && uids.size() == 0) || (domains != null && domains.size() == 0))
return null;
Params params = new Params("users.get");
if (uids != null && uids.size() > 0)
params.put("uids",arrayToString(uids));
if (domains != null && domains.size() > 0)
params.put("uids",arrayToString(domains));
if (fields == null)
params.put("fields","uid,first_name,last_name,nickname,domain,sex,bdate,city,country,timezone,photo,photo_medium_rec,photo_big,has_mobile,rate,contacts,education,online");
else
params.put("fields",fields);
params.put("name_case",name_case);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
}
/*** methods for friends ***/
//http://vkontakte.ru/developers.php?o=-1&p=friends.get
public ArrayList<User> getFriends(Long user_id, String fields, Integer lid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.get");
if(fields==null)
fields="first_name,last_name,photo_medium,online";
params.put("fields",fields);
params.put("uid",user_id);
params.put("lid", lid);
//сортировка по популярности не даёт запросить друзей из списка
if(lid==null)
params.put("order","hints");
JSONObject root = sendRequest(params);
ArrayList<User> users=new ArrayList<User>();
JSONArray array=root.optJSONArray("response");
//if there are no friends "response" will not be array
if(array==null)
return users;
int category_count=array.length();
for(int i=0; i<category_count; ++i){
JSONObject o = (JSONObject)array.get(i);
User u = User.parse(o);
users.add(u);
}
return users;
}
//http://vkontakte.ru/developers.php?o=-1&p=friends.getOnline
public ArrayList<Long> getOnlineFriends(Long uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.getOnline");
params.put("uid",uid);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
//http://vkontakte.ru/developers.php?oid=-1&p=likes.getList
public ArrayList<Long> getLikeUsers(String item_type, long item_id, long owner_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.getList");
params.put("type",item_type);
params.put("owner_id",owner_id);
params.put("item_id",item_id);
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
JSONArray array=response.optJSONArray("users");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
//http://vkontakte.ru/developers.php?o=-1&p=friends.getMutual
public ArrayList<Long> getMutual(Long target_uid, Long source_uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.getMutual");
params.put("target_uid",target_uid);
params.put("source_uid",source_uid);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
/*** methods for photos ***/
//http://vkontakte.ru/developers.php?o=-1&p=photos.getAlbums
public ArrayList<Album> getAlbums(Long owner_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getAlbums");
if (owner_id > 0)
//user
params.put("uid",owner_id);
else
//group
params.put("gid",-owner_id);
JSONObject root = sendRequest(params);
ArrayList<Album> albums=new ArrayList<Album>();
JSONArray array=root.optJSONArray("response");
if(array==null)
return albums;
int category_count=array.length();
for(int i=0; i<category_count; ++i){
JSONObject o = (JSONObject)array.get(i);
Album a = Album.parse(o);
if(a.title.equals("DELETED"))
continue;
albums.add(a);
}
return albums;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.get
public ArrayList<Photo> getPhotos(Long uid, Long aid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.get");
if(uid>0)
params.put("uid", uid);
else
params.put("gid", -uid);
params.put("aid", aid);
params.put("extended", "1");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<Photo>();
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.getUserPhotos
public ArrayList<Photo> getUserPhotos(Long uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getUserPhotos");
params.put("uid", uid);
params.put("sort","0");
params.put("count","50");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<Photo>();
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.getAll
public ArrayList<Photo> getAllPhotos(Long owner_id, Long offset, Long count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getAll");
params.put("owner_id", owner_id);
params.put("offset", offset);
params.put("count", count);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos=new ArrayList<Photo>();
int category_count=array.length();
for(int i=1; i<category_count; ++i){
JSONObject o = (JSONObject)array.get(i);
Photo p = Photo.parse(o);
photos.add(p);
}
return photos;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.getUserPhotos
public ArrayList<Photo> getUserPhotos(Long owner_id, Long offset, Long count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getUserPhotos");
params.put("owner_id", owner_id);
params.put("offset", offset);
params.put("count", count);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos=new ArrayList<Photo>();
int category_count = array.length();
for(int i=1; i<category_count; ++i){
JSONObject o = (JSONObject)array.get(i);
Photo p = Photo.parse(o);
photos.add(p);
}
return photos;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.getComments
public CommentList getPhotoComments(Long pid, Long owner_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getComments");
params.put("pid", pid);
params.put("owner_id", owner_id);
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
params.put("sort", "asc");
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
CommentList commnets = new CommentList();
commnets.count=array.getInt(0);
int category_count = array.length();
for(int i = 1; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = (JSONObject)array.get(i);
Comment comment = Comment.parsePhotoComment(o);
commnets.comments.add(comment);
}
return commnets;
}
//http://vkontakte.ru/developers.php?o=-1&p=notes.getComments
public CommentList getNoteComments(Long nid, Long owner_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("notes.getComments");
params.put("nid", nid);
params.put("owner_id", owner_id);
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
CommentList commnets = new CommentList();
commnets.count=array.getInt(0);
int category_count = array.length();
for(int i = 1; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = (JSONObject)array.get(i);
Comment comment = Comment.parseNoteComment(o);
commnets.comments.add(comment);
}
return commnets;
}
//http://vkontakte.ru/developers.php?o=-1&p=video.getComments
public CommentList getVideoComments(long video_id, Long owner_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.getComments");
params.put("vid", video_id);
params.put("owner_id", owner_id);
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
CommentList commnets = new CommentList();
commnets.count=array.getInt(0);
int category_count = array.length();
for(int i = 1; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = (JSONObject)array.get(i);
Comment comment = Comment.parseVideoComment(o);
commnets.comments.add(comment);
}
return commnets;
}
//Not used for now
//http://vkontakte.ru/developers.php?o=-1&p=photos.getAllComments
public ArrayList<Comment> getAllPhotoComments(Long owner_id, Long album_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getAllComments");
params.put("owner_id", owner_id);
params.put("album_id", album_id);
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
ArrayList<Comment> commnets = new ArrayList<Comment>();
@SuppressWarnings("unused")
JSONObject root = sendRequest(params);
//здесь ещё приходит pid - photo_id
//вынести парсящий код чтобы не было дублирования
//JSONArray array = root.getJSONArray("response");
//int category_count = array.length();
//for(int i = 0; i<category_count; ++i) {
// JSONObject o = (JSONObject)array.get(i);
// Comment comment = new Comment();
// comment.cid = Long.parseLong(o.getString("cid"));
// comment.from_id = Long.parseLong(o.getString("from_id"));
// comment.date = Long.parseLong(o.getString("date"));
// comment.message = unescape(o.getString("message"));
// commnets.add(comment);
//}
return commnets;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.createComment
public long createPhotoComment(Long pid, Long owner_id, String message, Long reply_to_cid, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.createComment");
params.put("pid",pid);
params.put("owner_id",owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message",message);
params.put("reply_to_cid", reply_to_cid);
JSONObject root = sendRequest(params);
long message_id = root.optLong("response");
return message_id;
}
//http://vkontakte.ru/developers.php?o=-1&p=notes.createComment
public long createNoteComment(Long nid, Long owner_id, String message, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("notes.createComment");
params.put("nid",nid);
params.put("owner_id",owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message",message);
//if (reply_to != null && !reply_to.equals(""))
// params.put("reply_to", reply_to);
JSONObject root = sendRequest(params);
long message_id = root.optLong("response");
return message_id;
}
//http://vkontakte.ru/developers.php?o=-1&p=video.createComment
public long createVideoComment(Long video_id, Long owner_id, String message, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.createComment");
params.put("vid",video_id);
params.put("owner_id",owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message",message);
JSONObject root = sendRequest(params);
long message_id = root.optLong("response");
return message_id;
}
private void addCaptchaParams(String captcha_key, String captcha_sid, Params params) {
params.put("captcha_sid",captcha_sid);
params.put("captcha_key",captcha_key);
}
/*** methods for messages
* @throws KException ***/
//http://vkontakte.ru/developers.php?o=-1&p=messages.get
public ArrayList<Message> getMessages(long time_offset, boolean is_out, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.get");
if (is_out)
params.put("out","1");
if (time_offset!=0)
params.put("time_offset", time_offset);
if (count != 0)
params.put("count", count);
params.put("preview_length","0");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, false, 0, false, 0);
return messages;
}
//http://vkontakte.ru/developers.php?o=-1&p=messages.getHistory
public ArrayList<Message> getMessagesHistory(long uid, long chat_id, long me, Long offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getHistory");
if(chat_id<=0)
params.put("uid",uid);
else
params.put("chat_id",chat_id);
params.put("offset", offset);
if (count != 0)
params.put("count", count);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, chat_id<=0, uid, chat_id>0, me);
return messages;
}
//http://vkontakte.ru/developers.php?o=-1&p=messages.getDialogs
public ArrayList<Message> getMessagesDialogs(long offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getDialogs");
if (offset!=0)
params.put("offset", offset);
if (count != 0)
params.put("count", count);
params.put("preview_length","0");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, false, 0, false ,0);
return messages;
}
private ArrayList<Message> parseMessages(JSONArray array, boolean from_history, long history_uid, boolean from_chat, long me) throws JSONException {
ArrayList<Message> messages = new ArrayList<Message>();
if (array != null) {
int category_count = array.length();
for(int i = 1; i < category_count; ++i) {
JSONObject o = (JSONObject)array.get(i);
Message m = Message.parse(o, from_history, history_uid, from_chat, me);
messages.add(m);
}
}
return messages;
}
//http://vkontakte.ru/developers.php?o=-1&p=messages.send
public String sendMessage(Long uid, long chat_id, String message, String title, String type, Collection<String> attachments, ArrayList<Long> forward_messages, String lat, String lon, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.send");
if(chat_id<=0)
params.put("uid", uid);
else
params.put("chat_id", chat_id);
params.put("message", message);
params.put("title", title);
params.put("type", type);
params.put("attachment", arrayToString(attachments));
params.put("forward_messages", arrayToString(forward_messages));
params.put("lat", lat);
params.put("long", lon);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params, true);
Object message_id = root.opt("response");
if (message_id != null)
return String.valueOf(message_id);
return null;
}
//http://vkontakte.ru/developers.php?o=-1&p=messages.markAsNew
//http://vkontakte.ru/developers.php?o=-1&p=messages.markAsRead
public String markAsNewOrAsRead(ArrayList<Long> mids, boolean as_read) throws MalformedURLException, IOException, JSONException, KException{
if (mids == null || mids.size() == 0)
return null;
Params params;
if (as_read)
params = new Params("messages.markAsRead");
else
params = new Params("messages.markAsNew");
params.put("mids", arrayToString(mids));
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vkontakte.ru/developers.php?o=-1&p=messages.delete
public String deleteMessage(Long mid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.delete");
params.put("mid", mid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
/*** for status***/
//http://vk.com/developers.php?oid=-1&p=status.get
public VkStatus getStatus(Long uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("status.get");
params.put("uid", uid);
JSONObject root = sendRequest(params);
JSONObject obj = root.optJSONObject("response");
VkStatus status = new VkStatus();
if (obj != null) {
status.text = unescape(obj.getString("text"));
JSONObject jaudio = obj.optJSONObject("audio");
if (jaudio != null)
status.audio = Audio.parse(jaudio);
}
return status;
}
//http://vk.com/developers.php?o=-1&p=status.set
public String setStatus(String status_text, String audio) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("status.set");
params.put("text", status_text);
params.put("audio", audio); //oid_aid
JSONObject root = sendRequest(params);
Object response_id = root.opt("response");
if (response_id != null)
return String.valueOf(response_id);
return null;
}
/*** methods for wall
* @throws KException ***/
//http://vkontakte.ru/developers.php?o=-1&p=wall.get
public ArrayList<WallMessage> getWallMessages(Long owner_id, int count, int offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.get");
params.put("owner_id", owner_id);
if (count > 0)
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
ArrayList<WallMessage> wmessages = new ArrayList<WallMessage>();
int category_count = array.length();
for(int i = 1; i < category_count; ++i) {
JSONObject o = (JSONObject)array.get(i);
WallMessage wm = WallMessage.parse(o);
wmessages.add(wm);
}
return wmessages;
}
/*** methods for news
* @throws KException ***/
//http://vkontakte.ru/developers.php?o=-1&p=newsfeed.get
//always returns about 33-35 items
public Newsfeed getNews(long start_time, long count, long end_time) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("newsfeed.get");
params.put("filters","post,photo,photo_tag,friend,note");
params.put("start_time",(start_time==-1)?getDefaultStartTime():start_time);
if(end_time!=-1)
params.put("end_time",end_time);
if(count!=0)
params.put("count",count);
JSONObject root = sendRequest(params);
return Newsfeed.parse(root, false);
}
//Новости-Комментарии. Описания нет.
public Newsfeed getNewsComments() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("newsfeed.getComments");
params.put("last_comments","1");
params.put("count","50");
JSONObject root = sendRequest(params);
return Newsfeed.parse(root, true);
}
/*** for audio ***/
//http://vkontakte.ru/developers.php?o=-1&p=audio.get
public ArrayList<Audio> getAudio(Long uid, Long gid, Long album_id, Collection<Long> aids) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.get");
params.put("uid", uid);
params.put("gid", gid);
params.put("aids", arrayToString(aids));
params.put("album_id", album_id);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return parseAudioList(array, 0);
}
//http://vk.com/developers.php?oid=-1&p=audio.getById
public ArrayList<Audio> getAudioById(String audios) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.getById");
params.put("audios", audios);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return parseAudioList(array, 0);
}
public String getLyrics(Long id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.getLyrics");
params.put("lyrics_id", id);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return response.optString("text");
}
/*** for video ***/
//http://vkontakte.ru/developers.php?o=-1&p=video.get //width = 130,160,320
public ArrayList<Video> getVideo(String videos, Long owner_id, Long album_id, String width, Long count, Long offset, String access_key) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.get");
params.put("videos", videos);
if (owner_id != null){
if(owner_id>0)
params.put("uid", owner_id);
else
params.put("gid", -owner_id);
}
params.put("width", width);
params.put("count", count);
params.put("offset", offset);
params.put("aid", album_id);
params.put("access_key", access_key);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Video> videoss = new ArrayList<Video>();
if (array != null) {
for(int i = 1; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
Video video = Video.parse(o);
videoss.add(video);
}
}
return videoss;
}
//http://vkontakte.ru/developers.php?o=-1&p=video.getUserVideos
public ArrayList<Video> getUserVideo(Long user_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.getUserVideos");
params.put("uid", user_id);
params.put("count", "50");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Video> videos = new ArrayList<Video>();
if (array != null) {
for(int i = 1; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
videos.add(Video.parse(o));
}
}
return videos;
}
/*** for crate album ***/
//http://vkontakte.ru/developers.php?o=-1&p=photos.createAlbum
public Album createAlbum(String title, String privacy, String comment_privacy, String description) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.createAlbum");
params.put("title", title);
params.put("privacy", privacy);
params.put("comment_privacy", comment_privacy);
params.put("description", description);
JSONObject root = sendRequest(params);
JSONObject o = root.optJSONObject("response");
if (o == null)
return null;
return Album.parse(o);
}
//http://vk.com/developers.php?oid=-1&p=photos.editAlbum
public String editAlbum(long aid, String title, String privacy, String comment_privacy, String description) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.editAlbum");
params.put("aid", String.valueOf(aid));
params.put("title", title);
params.put("privacy", privacy);
params.put("comment_privacy", comment_privacy);
params.put("description", description);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
/*** for notes ***/
//http://vkontakte.ru/developers.php?o=-1&p=notes.get
public ArrayList<Note> getNotes(Long uid, Collection<Long> nids, String sort, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notes.get");
params.put("uid", uid);
params.put("nids", arrayToString(nids));
params.put("sort", sort);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Note> notes = new ArrayList<Note>();
if (array != null) {
for(int i = 1; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
Note note = Note.parse(o, true);
notes.add(note);
}
}
return notes;
}
//http://vk.com/developers.php?oid=-1&p=notes.delete
public String deleteNote(Long nid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("notes.delete");
params.put("nid", nid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.getUploadServer
public String photosGetUploadServer(long album_id, Long group_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.getUploadServer");
params.put("aid",album_id);
params.put("gid",group_id);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.getWallUploadServer
public String photosGetWallUploadServer(Long user_id, Long group_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.getWallUploadServer");
params.put("uid",user_id);
params.put("gid",group_id);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
//http://vkontakte.ru/developers.php?oid=-1&p=getAudioUploadServer
public String getAudioUploadServer() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("getAudioUploadServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
//http://vkontakte.ru/developers.php?oid=-1&p=photos.getMessagesUploadServer
public String photosGetMessagesUploadServer() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.getMessagesUploadServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.getProfileUploadServer
public String photosGetProfileUploadServer() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.getProfileUploadServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.save
public ArrayList<Photo> photosSave(String server, String photos_list, Long aid, Long group_id, String hash, String caption) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.save");
params.put("server",server);
params.put("photos_list",photos_list);
params.put("aid",aid);
params.put("gid",group_id);
params.put("hash",hash);
params.put("caption",caption);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.saveWallPhoto
public ArrayList<Photo> saveWallPhoto(String server, String photo, String hash, Long user_id, Long group_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.saveWallPhoto");
params.put("server",server);
params.put("photo",photo);
params.put("hash",hash);
params.put("uid",user_id);
params.put("gid",group_id);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
//http://vk.com/developers.php?oid=-1&p=audio.save
public Audio saveAudio(String server, String audio, String hash, String artist, String title) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("audio.save");
params.put("server",server);
params.put("audio",audio);
params.put("hash",hash);
params.put("artist",artist);
params.put("title",title);
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
return Audio.parse(response);
}
//http://vkontakte.ru/developers.php?oid=-1&p=photos.saveMessagesPhoto
public ArrayList<Photo> saveMessagesPhoto(String server, String photo, String hash) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.saveMessagesPhoto");
params.put("server",server);
params.put("photo",photo);
params.put("hash",hash);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.saveProfilePhoto
public String[] saveProfilePhoto(String server, String photo, String hash) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.saveProfilePhoto");
params.put("server",server);
params.put("photo",photo);
params.put("hash",hash);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
String src = response.optString("photo_src");
String hash1 = response.optString("photo_hash");
String[] res=new String[]{src, hash1};
return res;
}
private ArrayList<Photo> parsePhotos(JSONArray array) throws JSONException {
ArrayList<Photo> photos=new ArrayList<Photo>();
int category_count=array.length();
for(int i=0; i<category_count; ++i){
//in getUserPhotos first element is integer
if(array.get(i) instanceof JSONObject == false)
continue;
JSONObject o = (JSONObject)array.get(i);
Photo p = Photo.parse(o);
photos.add(p);
}
return photos;
}
/*public long createGraffitiComment(String gid, String owner_id, String message, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("graffiti.createComment");
params.put("gid",gid);
params.put("owner_id",owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message",message);
JSONObject root = sendRequest(params);
long message_id = root.optLong("response");
return message_id;
}*/
//http://vkontakte.ru/developers.php?o=-1&p=wall.addComment
public long createWallComment(Long owner_id, Long post_id, String text, Long reply_to_cid, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.addComment");
params.put("owner_id", owner_id);
params.put("post_id", post_id);
params.put("text", text);
params.put("reply_to_cid", reply_to_cid);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
long cid = response.optLong("cid");
return cid;
}
//http://vkontakte.ru/developers.php?o=-1&p=wall.post
public long createWallPost(long owner_id, String text, Collection<String> attachments, String export, boolean only_friends, boolean from_group, boolean signed, String lat, String lon, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.post");
params.put("owner_id", owner_id);
params.put("attachments", arrayToString(attachments));
params.put("lat", lat);
params.put("long", lon);
params.put("message", text);
if(export!=null && export.length()!=0)
params.put("services",export);
if (from_group)
params.put("from_group","1");
if (only_friends)
params.put("friends_only","1");
if (signed)
params.put("signed","1");
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params, true);
JSONObject response = root.getJSONObject("response");
long post_id = response.optLong("post_id");
return post_id;
}
//http://vkontakte.ru/developers.php?o=-1&p=wall.getComments
public CommentList getWallComments(Long owner_id, Long post_id, int offset, int count, String v) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.getComments");
params.put("post_id", post_id);
params.put("owner_id", owner_id);
/*
if (sort != null)
params.put("sort", sort);
//asc - хронологический
//desc - антихронологический
*/
if (offset > 0)
params.put("offset", offset);
if (count > 0)
params.put("count", count);
params.put("preview_length", "0");
params.put("need_likes", "1");
params.put("v", v);
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
CommentList commnets = new CommentList();
commnets.count=array.getInt(0);
int category_count = array.length();
for(int i = 1; i<category_count; ++i) //get(0) is integer, it is comments count
commnets.comments.add(Comment.parse((JSONObject)array.get(i)));
return commnets;
}
//http://vkontakte.ru/developers.php?o=-1&p=audio.search
public ArrayList<Audio> searchAudio(String q, String sort, String lyrics, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.search");
params.put("q", q);
params.put("sort", sort);
params.put("lyrics", lyrics);
params.put("count", count);
params.put("offset", offset);
params.put("auto_complete", "1");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return parseAudioList(array, 1);
}
private ArrayList<Audio> parseAudioList(JSONArray array, int type_array) //type_array must be 0 or 1
throws JSONException {
ArrayList<Audio> audios = new ArrayList<Audio>();
if (array != null) {
for(int i = type_array; i<array.length(); ++i) { //get(0) is integer, it is audio count
JSONObject o = (JSONObject)array.get(i);
audios.add(Audio.parse(o));
}
}
return audios;
}
//http://vkontakte.ru/developers.php?o=-1&p=audio.delete
public String deleteAudio(Long aid, Long oid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.delete");
params.put("aid", aid);
params.put("oid", oid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vkontakte.ru/developers.php?o=-1&p=audio.add
public String addAudio(Long aid, Long oid, Long gid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.add");
params.put("aid", aid);
params.put("oid", oid);
params.put("gid", gid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vkontakte.ru/developers.php?o=-1&p=wall.addLike
public Long wallAddLike(Long owner_id, Long post_id, boolean need_publish, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.addLike");
params.put("owner_id", owner_id);
params.put("post_id", post_id);
params.put("need_publish", need_publish?"1":"0");
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
long likes=response.optLong("likes", -1);
return likes;
}
//http://vkontakte.ru/developers.php?o=-1&p=wall.deleteLike
public Long wallDeleteLike(Long owner_id, Long post_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.deleteLike");
params.put("owner_id", owner_id);
params.put("post_id", post_id);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
long likes=response.optLong("likes", -1);
return likes;
}
//http://vk.com/developers.php?oid=-1&p=likes.add
public Long addLike(Long owner_id, Long item_id, String type, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.add");
params.put("owner_id", owner_id);
params.put("item_id", item_id);
params.put("type", type);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
long likes=response.optLong("likes", -1);
return likes;
}
//http://vk.com/developers.php?oid=-1&p=likes.delete
public Long deleteLike(Long owner_id, Long item_id, String type) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.delete");
params.put("owner_id", owner_id);
params.put("item_id", item_id);
params.put("type", type);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
long likes=response.optLong("likes", -1);
return likes;
}
//http://vkontakte.ru/developers.php?oid=-1&p=likes.add
public Long addLike(Long owner_id, String type, Long item_id, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.add");
params.put("owner_id", owner_id);
params.put("type", type);
params.put("item_id", item_id);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return response.optLong("likes", -1);
}
//http://vkontakte.ru/developers.php?oid=-1&p=likes.delete
public Long deleteLike(Long owner_id, String type, Long item_id, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.delete");
params.put("owner_id", owner_id);
params.put("type", type);
params.put("item_id", item_id);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return response.optLong("likes", -1);
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.getById
public ArrayList<Photo> getPhotosById(String photos) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getById");
params.put("photos", photos);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<Photo>();
ArrayList<Photo> photos1 = parsePhotos(array);
return photos1;
}
//http://vkontakte.ru/developers.php?oid=-1&p=groups.get
public ArrayList<Group> getUserGroups(Long user_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("groups.get");
params.put("extended","1");
params.put("uid",user_id);
JSONObject root = sendRequest(params);
ArrayList<Group> groups=new ArrayList<Group>();
JSONArray array=root.optJSONArray("response");
//if there are no groups "response" will not be array
if(array==null)
return groups;
groups = Group.parseGroups(array);
return groups;
}
//http://vkontakte.ru/developers.php?o=-1&p=wall.delete
public Boolean removeWallPost(Long post_id, long wall_owner_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("wall.delete");
params.put("owner_id", wall_owner_id);
params.put("post_id", post_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
//http://vkontakte.ru/developers.php?o=-1&p=wall.deleteComment
public Boolean deleteWallComment(Long wall_owner_id, long comment_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("wall.deleteComment");
params.put("owner_id", wall_owner_id);
params.put("cid", comment_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
//http://vkontakte.ru/developers.php?o=-1&p=notes.deleteComment
public Boolean deleteNoteComment(Long note_owner_id, long comment_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notes.deleteComment");
params.put("owner_id", note_owner_id);
params.put("cid", comment_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
//http://vkontakte.ru/developers.php?o=-1&p=video.deleteComment
public Boolean deleteVideoComment(Long video_owner_id, long comment_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.deleteComment");
params.put("owner_id", video_owner_id);
params.put("cid", comment_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.deleteComment
public Boolean deletePhotoComment(long photo_id, Long photo_owner_id, long comment_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.deleteComment");
params.put("owner_id", photo_owner_id);
params.put("cid", comment_id);
params.put("pid", photo_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
//http://vkontakte.ru/developers.php?o=-1&p=video.search
public ArrayList<Video> searchVideo(String q, String sort, String hd, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.search");
params.put("q", q);
params.put("sort", sort);
params.put("hd", hd);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Video> videoss = new ArrayList<Video>();
if (array != null) {
for(int i = 0; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
Video video = Video.parse(o);
videoss.add(video);
}
}
return videoss;
}
//no documentation
public ArrayList<User> searchUser(String q, String fields, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("users.search");
params.put("q", q);
params.put("count", count);
params.put("offset", offset);
params.put("fields", fields);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
}
//http://vkontakte.ru/developers.php?o=-1&p=video.delete
public String deleteVideo(Long vid, Long oid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.delete");
params.put("vid", vid);
params.put("oid", oid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vkontakte.ru/developers.php?o=-1&p=video.add
public String addVideo(Long vid, Long oid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.add");
params.put("vid", vid);
params.put("oid", oid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vkontakte.ru/developers.php?o=-1&p=notes.add
public long createNote(String title, String text) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("notes.add");
params.put("title", title);
params.put("text", text);
params.put("privacy", "0");
params.put("comment_privacy", "0");
JSONObject root = sendRequest(params, true);
JSONObject response = root.getJSONObject("response");
long note_id = response.optLong("nid");
return note_id;
}
//http://vkontakte.ru/developers.php?o=-1&p=messages.getLongPollServer
public Object[] getLongPollServer() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getLongPollServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
String key=response.getString("key");
String server=response.getString("server");
Long ts = response.getLong("ts");
return new Object[]{key, server, ts};
}
//не документирован
public void setOnline() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("activity.online");
sendRequest(params);
}
//http://vkontakte.ru/developers.php?oid=-1&p=friends.add
public long addFriend(Long uid, String text, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.add");
params.put("uid", uid);
params.put("text", text);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
return root.optLong("response");
}
//http://vkontakte.ru/developers.php?oid=-1&p=friends.delete
public long deleteFriend(Long uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.delete");
params.put("uid", uid);
JSONObject root = sendRequest(params);
return root.optLong("response");
}
//http://vkontakte.ru/developers.php?oid=-1&p=friends.getRequests
public ArrayList<Object[]> getRequestsFriends() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.getRequests");
params.put("need_messages", "1");
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<Object[]> users=new ArrayList<Object[]>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i) {
JSONObject item = array.optJSONObject(i);
if (item != null) {
Long id = item.optLong("uid", -1);
if (id!=-1) {
Object[] u = new Object[2];
u[0] = id;
u[1] = item.optString("message");
users.add(u);
}
}
}
}
return users;
}
//http://vkontakte.ru/developers.php?oid=-1&p=subscriptions.follow
public String followUser(Long uid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("subscriptions.follow");
params.put("uid", uid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vkontakte.ru/developers.php?oid=-1&p=subscriptions.unfollow
public String unfollowUser(Long uid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("subscriptions.unfollow");
params.put("uid", uid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vkontakte.ru/developers.php?oid=-1&p=subscriptions.get
public ArrayList<Long> getSubscriptions(Long uid, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("subscriptions.get");
params.put("uid", uid);
if (offset>0)
params.put("offset", offset);
if (count>0)
params.put("count", count);
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
JSONArray array=response.optJSONArray("users");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
//http://vkontakte.ru/developers.php?oid=-1&p=subscriptions.getFollowers
public ArrayList<Long> getFollowers(Long uid, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("subscriptions.getFollowers");
params.put("uid", uid);
if (offset>0)
params.put("offset", offset);
if (count>0)
params.put("count", count);
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
JSONArray array=response.optJSONArray("users");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
//http://vkontakte.ru/pages?oid=-1&p=messages.deleteDialog
public int deleteMessageThread(Long uid, Long chatId) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.deleteDialog");
params.put("uid", uid);
params.put("chat_id", chatId);
JSONObject root = sendRequest(params);
return root.getInt("response");
}
//http://vkontakte.ru/developers.php?oid=-1&p=execute
public void execute(String code) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("execute");
params.put("code", code);
sendRequest(params);
}
//http://vkontakte.ru/developers.php?oid=-1&p=photos.delete
public boolean deletePhoto(Long owner_id, Long photo_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.delete");
params.put("oid", owner_id);
params.put("pid", photo_id);
JSONObject root = sendRequest(params);
long response = root.optLong("response", -1);
return response==1;
}
//http://vkontakte.ru/developers.php?oid=-1&p=polls.getById
public VkPoll getPoll(long poll_id, long owner_id) throws JSONException, MalformedURLException, IOException, KException {
Params params = new Params("polls.getById");
params.put("owner_id", owner_id);
params.put("poll_id", poll_id);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return VkPoll.parse(response);
}
//http://vkontakte.ru/developers.php?oid=-1&p=polls.addVote
public int addPollVote(long poll_id, long answer_id, long owner_id) throws JSONException, MalformedURLException, IOException, KException {
Params params = new Params("polls.addVote");
params.put("owner_id", owner_id);
params.put("poll_id", poll_id);
params.put("answer_id", answer_id);
JSONObject root = sendRequest(params);
return root.getInt("response");
}
//http://vkontakte.ru/developers.php?oid=-1&p=polls.deleteVote
public int deletePollVote(long poll_id, long answer_id, long owner_id) throws JSONException, MalformedURLException, IOException, KException {
Params params = new Params("polls.deleteVote");
params.put("owner_id", owner_id);
params.put("poll_id", poll_id);
params.put("answer_id", answer_id);
JSONObject root = sendRequest(params);
return root.getInt("response");
}
//http://vkontakte.ru/developers.php?oid=-1&p=friends.getLists
public ArrayList<FriendsList> friendsLists() throws JSONException, MalformedURLException, IOException, KException {
Params params = new Params("friends.getLists");
JSONObject root = sendRequest(params);
ArrayList<FriendsList> result = new ArrayList<FriendsList>();
JSONArray list = root.optJSONArray("response");
if (list != null) {
for (int i=0; i<list.length(); ++i) {
JSONObject o = list.getJSONObject(i);
FriendsList fl = FriendsList.parse(o);
result.add(fl);
}
}
return result;
}
//http://vkontakte.ru/developers.php?oid=-1&p=video.save
public String saveVideo(String name, String description, Long gid, int privacy_view, int privacy_comment) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.save");
params.put("name", name);
params.put("description", description);
params.put("gid", gid);
if (privacy_view > 0)
params.put("privacy_view", privacy_view);
if (privacy_comment > 0)
params.put("privacy_comment", privacy_comment);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
//http://vkontakte.ru/developers.php?oid=-1&p=photos.deleteAlbum
public String deleteAlbum(Long aid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.deleteAlbum");
params.put("aid", aid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vk.com/developers.php?o=-1&p=photos.getTags
public ArrayList<PhotoTag> getPhotoTagsById(Long pid, Long owner_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getTags");
params.put("owner_id", owner_id);
params.put("pid", pid);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<PhotoTag>();
ArrayList<PhotoTag> photo_tags = parsePhotoTags(array, pid, owner_id);
return photo_tags;
}
private ArrayList<PhotoTag> parsePhotoTags(JSONArray array, Long pid, Long owner_id) throws JSONException {
ArrayList<PhotoTag> photo_tags=new ArrayList<PhotoTag>();
int category_count=array.length();
for(int i=0; i<category_count; ++i){
//in getUserPhotos first element is integer
if(array.get(i) instanceof JSONObject == false)
continue;
JSONObject o = (JSONObject)array.get(i);
PhotoTag p = PhotoTag.parse(o);
photo_tags.add(p);
if (pid != null)
p.pid = pid;
if (owner_id != null)
p.owner_id = owner_id;
}
return photo_tags;
}
//http://vk.com/developers.php?oid=-1&p=photos.putTag
public String putPhotoTag(PhotoTag ptag, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
if (ptag == null)
return null;
Params params = new Params("photos.putTag");
params.put("owner_id", ptag.owner_id);
params.put("pid", ptag.pid);
params.put("uid", ptag.uid);
params.putDouble("x", ptag.x);
params.putDouble("x2", ptag.x2);
params.putDouble("y", ptag.y);
params.putDouble("y2", ptag.y2);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
/*** topics region ***/
//http://kate1.unfuddle.com/a#/projects/2/tickets/by_number/340?cycle=true
public ArrayList<GroupTopic> getGroupTopics(long gid, int extended, int count, int offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.getTopics");
params.put("gid", gid);
if (extended == 1)
params.put("extended", "1"); //for profiles
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
JSONObject root = sendRequest(params);
ArrayList<GroupTopic> result = new ArrayList<GroupTopic>();
JSONObject response = root.optJSONObject("response");
if (response != null) {
JSONArray topics = response.optJSONArray("topics");
if (topics != null) {
for (int i=1; i<topics.length(); ++i) {
JSONObject o = topics.getJSONObject(i);
GroupTopic gt = GroupTopic.parse(o);
gt.gid = gid;
result.add(gt);
}
}
}
return result;
}
public CommentList getGroupTopicComments(long gid, long tid, int photo_sizes, int extended, int count, int offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("board.getComments");
params.put("gid", gid);
params.put("tid", tid);
if (photo_sizes == 1)
params.put("photo_sizes", "1");
if (extended == 1)
params.put("extended", "1");
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
CommentList result = new CommentList();
if (response != null) {
JSONArray comments = response.optJSONArray("comments");
int category_count = comments.length();
result.count=comments.getInt(0);
for (int i=1; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = comments.getJSONObject(i);
Comment c = Comment.parseTopicComment(o);
result.comments.add(c);
}
}
return result;
}
public long createGroupTopicComment(long gid, long tid, String text, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.addComment");
params.put("gid", gid);
params.put("tid", tid);
params.put("text", text);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
long message_id = root.optLong("response");
return message_id;
}
public Boolean deleteGroupTopicComment(long gid, long tid, long cid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.deleteComment");
params.put("gid", gid);
params.put("tid", tid);
params.put("cid", cid);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public long createGroupTopic(long gid, String title, String text, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.addTopic");
params.put("gid", gid);
params.put("title", title);
params.put("text", text);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
long topic_id = root.optLong("response");
return topic_id;
}
public Boolean deleteGroupTopic(long gid, long tid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.deleteTopic");
params.put("gid", gid);
params.put("tid", tid);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
/*** end topics region ***/
//http://vk.com/developers.php?oid=-1&p=groups.getById
public ArrayList<Group> getGroups(Collection<Long> uids, String domain, String fields) throws MalformedURLException, IOException, JSONException, KException{
if (uids == null && domain == null)
return null;
if (uids.size() == 0 && domain == null)
return null;
Params params = new Params("groups.getById");
String str_uids;
if (uids != null && uids.size() > 0)
str_uids=arrayToString(uids);
else
str_uids = domain;
params.put("gids", str_uids);
params.put("fields", fields); //Possible values: place,wiki_page,city,country,description,start_date,finish_date,site
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return Group.parseGroups(array);
}
//no documentation
public String joinGroup(long gid, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.join");
params.put("gid", gid);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//no documentation
public String leaveGroup(long gid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.leave");
params.put("gid", gid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//no documentation
public ArrayList<Group> searchGroup(String q, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.search");
params.put("q", q);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<Group> groups = new ArrayList<Group>();
//if there are no groups "response" will not be array
if (array==null)
return groups;
groups = Group.parseGroups(array);
return groups;
}
//http://vk.com/pages?oid=-1&p=account.registerDevice
public String registerDevice(String token, String device_model, String system_version, Integer no_text, String subscribe)
throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("account.registerDevice");
params.put("token", token);
params.put("device_model", device_model);
params.put("system_version", system_version);
params.put("no_text", no_text);
params.put("subscribe", subscribe);
JSONObject root = sendRequest(params);
return root.getString("response");
}
//http://vk.com/pages?oid=-1&p=account.unregisterDevice
public String unregisterDevice(String token) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("account.unregisterDevice");
params.put("token", token);
JSONObject root = sendRequest(params);
return root.getString("response");
}
//http://vk.com/developers.php?oid=-1&p=notifications.get
public Notifications getNotifications(String filters, Long start_time, Long end_time, Integer offset, Integer count) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notifications.get");
params.put("filters", filters);
params.put("start_time", start_time);
params.put("end_time", end_time);
params.put("offset", offset);
params.put("count", count);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return Notifications.parse(response);
}
//http://vk.com/developers.php?oid=-1&p=notifications.markAsViewed
public String resetUnreadNotifications() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notifications.markAsViewed");
JSONObject root = sendRequest(params);
return root.getString("response");
}
//http://vk.com/developers.php?oid=-1&p=messages.getById
public ArrayList<Message> getMessagesById(ArrayList<Long> message_ids) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getById");
params.put("mids", arrayToString(message_ids));
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, false, 0, false, 0);
return messages;
}
public Counters getCounters() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("getCounters");
JSONObject root = sendRequest(params);
JSONObject response=root.optJSONObject("response");
return Counters.parse(response);
}
/*** faves ***/
//http://vk.com/developers.php?oid=-1&p=fave.getUsers
public ArrayList<User> getFaveUsers(String fields, Integer count, Integer offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("fave.getUsers");
if(fields==null)
fields="photo_medium,online";
params.put("fields",fields);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
ArrayList<User> users=new ArrayList<User>();
JSONArray array=root.optJSONArray("response");
//if there are no friends "response" will not be array
if(array==null)
return users;
int category_count=array.length();
for(int i=0; i<category_count; ++i) {
if(array.get(i)==null || ((array.get(i) instanceof JSONObject)==false))
continue;
JSONObject o = (JSONObject)array.get(i);
User u = User.parseFromFave(o);
users.add(u);
}
return users;
}
//http://vk.com/developers.php?oid=-1&p=fave.getPhotos
public ArrayList<Photo> getFavePhotos(Integer count, Integer offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("fave.getPhotos");
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<Photo>();
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
//http://vk.com/developers.php?oid=-1&p=fave.getVideos
public ArrayList<Video> getFaveVideos(Integer count, Integer offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("fave.getVideos");
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Video> videos = new ArrayList<Video>();
if (array != null) {
for(int i = 1; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
Video video = Video.parse(o);
videos.add(video);
}
}
return videos;
}
//http://vk.com/developers.php?oid=-1&p=fave.getPosts
public ArrayList<WallMessage> getFavePosts(Integer count, Integer offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("fave.getPosts");
//params.put("extended", extended);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
//JSONArray array = response.optJSONArray("wall");
//JSONArray profiles_array = response.optJSONArray("profiles");
//JSONArray groups_array = response.optJSONArray("groups");
ArrayList<WallMessage> wmessages = new ArrayList<WallMessage>();
if (array == null)
return wmessages;
int category_count = array.length();
for(int i = 1; i < category_count; ++i) {
JSONObject o = (JSONObject)array.get(i);
WallMessage wm = WallMessage.parse(o);
wmessages.add(wm);
}
return wmessages;
}
//http://vk.com/developers.php?oid=-1&p=fave.getLinks
public ArrayList<Link> getFaveLinks(Integer count, Integer offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("fave.getLinks");
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
ArrayList<Link> groups=new ArrayList<Link>();
JSONArray array=root.optJSONArray("response");
//if there are no groups "response" will not be array
if(array==null)
return groups;
for(int i = 0; i < array.length(); i++) {
if(!(array.get(i) instanceof JSONObject))
continue;
JSONObject jlink = (JSONObject)array.get(i);
Link link = Link.parse(jlink);
groups.add(link);
}
return groups;
}
/*** end faves ***/
/*** chat methods ***/
//http://vk.com/pages?oid=-1&p=messages.createChat
public Long chatCreate(ArrayList<Long> uids, String title) throws MalformedURLException, IOException, JSONException, KException {
if (uids == null || uids.size() == 0)
return null;
Params params = new Params("messages.createChat");
String str_uids = String.valueOf(uids.get(0));
for (int i=1; i<uids.size(); i++)
str_uids += "," + String.valueOf(uids.get(i));
params.put("uids", str_uids);
params.put("title", title);
JSONObject root = sendRequest(params);
return root.optLong("response");
}
//http://vk.com/pages?oid=-1&p=messages.editChat
public Integer chatEdit(long chat_id, String title) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.editChat");
params.put("chat_id", chat_id);
params.put("title", title);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
//http://vk.com/pages?oid=-1&p=messages.getChatUsers
public ArrayList<User> getChatUsers(long chat_id, String fields) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.getChatUsers");
params.put("chat_id", chat_id);
params.put("fields", fields);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
}
//http://vk.com/pages?oid=-1&p=messages.addChatUser
public Integer addUserToChat(long chat_id, long uid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.addChatUser");
params.put("chat_id", chat_id);
params.put("uid", uid);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
//http://vk.com/pages?oid=-1&p=messages.removeChatUser
public Integer removeUserFromChat(long chat_id, long uid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.removeChatUser");
params.put("chat_id", chat_id);
params.put("uid", uid);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
/*** end chat methods ***/
//http://vk.com/pages?oid=-1&p=friends.getSuggestions
public ArrayList<User> getSuggestions(String filter, String fields) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("friends.getSuggestions");
params.put("filter", filter); //mutual, contacts, mutual_contacts
params.put("fields", fields);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
}
//http://vk.com/pages?oid=-1&p=account.importContacts
public Integer importContacts(Collection<String> contacts) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("account.importContacts");
params.put("contacts", arrayToString(contacts));
JSONObject root = sendRequest(params);
return root.optInt("response");
}
//http://vk.com/pages?oid=-1&p=friends.getByPhones
public ArrayList<User> getFriendsByPhones(ArrayList<String> phones, String fields) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("friends.getByPhones");
params.put("phones", arrayToString(phones));
params.put("fields", fields);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsersForGetByPhones(array);
}
/*** methods for messages search ***/
//http://vk.com/pages?oid=-1&p=messages.search
public ArrayList<Message> searchMessages(String q, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.search");
params.put("q", q);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, false, 0, false, 0);
return messages;
}
//http://vk.com/pages?oid=-1&p=messages.searchDialogs
public ArrayList<SearchDialogItem> searchDialogs(String q, String fields) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.searchDialogs");
params.put("q", q);
params.put("fields", fields);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return Message.parseSearchedDialogs(array);
}
//http://vk.com/pages?oid=-1&p=messages.getLastActivity
public LastActivity getLastActivity(long user_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getLastActivity");
params.put("uid", user_id);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return LastActivity.parse(response);
}
//http://vk.com/developers.php?oid=-1&p=groups.getMembers
public ArrayList<Long> getGroupsMembers(long gid, Integer count, Integer offset, String sort) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.getMembers");
params.put("gid", gid);
params.put("count", count);
params.put("offset", offset);
params.put("sort", sort); //id_asc, id_desc, time_asc, time_desc
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
JSONArray array=response.optJSONArray("users");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
//http://vk.com/developers.php?oid=-1&p=groups.getMembers
public Long getGroupsMembersCount(long gid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.getMembers");
params.put("gid", gid);
params.put("count", 10);
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
return response.optLong("count");
}
public ArrayList<User> getGroupsMembersWithExecute(long gid, Integer count, Integer offset, String sort, String fields) throws MalformedURLException, IOException, JSONException, KException {
//String code = "return API.getProfiles({\"uids\":API.groups.getMembers({\"gid\":" + String.valueOf(gid) + ",\"count\":" + String.valueOf(count) + ",\"offset\":" + String.valueOf(offset) + ",\"sort\":\"id_asc\"}),\"fields\":\"" + fields + "\"});";
String code = "var members=API.groups.getMembers({\"gid\":" + gid + "}); var u=members[1]; return API.getProfiles({\"uids\":u,\"fields\":\"" + fields + "\"});";
Params params = new Params("execute");
params.put("code", code);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
}
//http://vk.com/developers.php?oid=-1&p=getServerTime
public long getServerTime() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("getServerTime");
JSONObject root = sendRequest(params);
return root.getLong("response");
}
//http://vk.com/developers.php?oid=-1&p=audio.getAlbums
public ArrayList<AudioAlbum> getAudioAlbums(Long uid, Long gid, Integer offset, Integer count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.getAlbums");
params.put("uid", uid);
params.put("gid", gid);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<AudioAlbum> albums = AudioAlbum.parseAlbums(array);
return albums;
}
public ArrayList<Audio> getAudioRecommendations() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.getRecommendations");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return parseAudioList(array, 0);
}
//http://vk.com/developers.php?oid=-1&p=video.getAlbums
public ArrayList<AudioAlbum> getVideoAlbums(Long uid, Long gid, Integer offset, Integer count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.getAlbums");
params.put("uid", uid);
params.put("gid", gid);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<AudioAlbum> albums = AudioAlbum.parseAlbums(array);
return albums;
}
//http://vk.com/developers.php?oid=-1&p=messages.setActivity
public Integer setMessageActivity(long uid, long chat_id, boolean typing) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.setActivity");
params.put("uid", uid);
params.put("chat_id", chat_id);
if (typing)
params.put("type", "typing");
JSONObject root = sendRequest(params);
return root.optInt("response");
}
//http://vk.com/developers.php?oid=-1&p=wall.edit
public int editWallPost(long owner_id, long post_id, String text, Collection<String> attachments, String lat, String lon, long place_id, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.edit");
params.put("owner_id", owner_id);
params.put("post_id", post_id);
params.put("message", text);
params.put("attachments", arrayToString(attachments));
params.put("lat", lat);
params.put("long", lon);
params.put("place_id", place_id);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
//http://vk.com/developers.php?oid=-1&p=photos.edit
public Integer photoEdit(Long owner_id, long pid, String caption) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.edit");
params.put("owner_id", owner_id);
params.put("pid", pid);
params.put("caption", caption);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
//http://vk.com/developers.php?oid=-1&p=docs.get
public ArrayList<Document> getDocs(Long owner_id, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("docs.get");
params.put("oid", owner_id);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return Document.parseDocs(array);
}
//http://vk.com/developers.php?oid=-1&p=docs.getUploadServer
public String docsGetUploadServer() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("docs.getUploadServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
//http://vk.com/developers.php?oid=-1&p=docs.save
public Document saveDoc(String file) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("docs.save");
params.put("file", file);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Document> docs = Document.parseDocs(array);
return docs.get(0);
}
//http://vk.com/developers.php?oid=-1&p=docs.delete
public Boolean deleteDoc(Long doc_id, long owner_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("docs.delete");
params.put("oid", owner_id);
params.put("did", doc_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
//Помечает уведомления о новых ответах как прочитанные, документации нет
public Boolean markNotificationsAsViewed() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notifications.markAsViewed");
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
//http://vk.com/developers.php?oid=-1&p=newsfeed.getBanned
public BannArg getBanned(boolean is_extended, String fields) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("newsfeed.getBanned");
if (is_extended)
params.put("extended", "1");
params.put("fields", fields);
JSONObject root = sendRequest(params);
JSONObject object = root.optJSONObject("response");
return BannArg.parse(object);
}
//http://vk.com/developers.php?oid=-1&p=newsfeed.addBan
public Boolean addBan(Collection<Long> uids, Collection<Long> gids) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("newsfeed.addBan");
if (uids != null && uids.size() > 0)
params.put("uids",arrayToString(uids));
if (gids != null && gids.size() > 0)
params.put("gids",arrayToString(gids));
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
//http://vk.com/developers.php?oid=-1&p=newsfeed.deleteBan
public Boolean deleteBan(Collection<Long> uids, Collection<Long> gids) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("newsfeed.deleteBan");
if (uids != null && uids.size() > 0)
params.put("uids",arrayToString(uids));
if (gids != null && gids.size() > 0)
params.put("gids",arrayToString(gids));
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public boolean audioGetBroadcast() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("audio.getBroadcast");
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return response.optInt("enabled")==1;
}
} | AndroidVkSdk/src/com/perm/kate/api/Api.java | package com.perm.kate.api;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.zip.GZIPInputStream;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.perm.utils.Utils;
import com.perm.utils.WrongResponseCodeException;
import android.util.Log;
public class Api {
static final String TAG="Kate.Api";
public static final String BASE_URL="https://api.vk.com/method/";
public Api(String access_token, String api_id){
this.access_token=access_token;
this.api_id=api_id;
}
String access_token;
String api_id;
//TODO: it's not faster, even slower on slow devices. Maybe we should add an option to disable it. It's only good for paid internet connection.
static boolean enable_compression=true;
/*** utils methods***/
private void checkError(JSONObject root, String url) throws JSONException,KException {
if(!root.isNull("error")){
JSONObject error=root.getJSONObject("error");
int code=error.getInt("error_code");
String message=error.getString("error_msg");
KException e = new KException(code, message, url);
if (code==14) {
e.captcha_img = error.optString("captcha_img");
e.captcha_sid = error.optString("captcha_sid");
}
throw e;
}
}
private JSONObject sendRequest(Params params) throws IOException, MalformedURLException, JSONException, KException {
return sendRequest(params, false);
}
private final static int MAX_TRIES=3;
private JSONObject sendRequest(Params params, boolean is_post) throws IOException, MalformedURLException, JSONException, KException {
String url = getSignedUrl(params, is_post);
String body="";
if(is_post)
body=params.getParamsString(is_post);
Log.i(TAG, "url="+url);
if(body.length()!=0)
Log.i(TAG, "body="+body);
String response="";
for(int i=1;i<=MAX_TRIES;++i){
try{
if(i!=1)
Log.i(TAG, "try "+i);
response = sendRequestInternal(url, body, is_post);
break;
}catch(javax.net.ssl.SSLException ex){
processNetworkException(i, ex);
}catch(java.net.SocketException ex){
processNetworkException(i, ex);
}
}
Log.i(TAG, "response="+response);
JSONObject root=new JSONObject(response);
checkError(root, url);
return root;
}
private void processNetworkException(int i, IOException ex) throws IOException {
ex.printStackTrace();
if(i==MAX_TRIES)
throw ex;
}
private String sendRequestInternal(String url, String body, boolean is_post) throws IOException, MalformedURLException, WrongResponseCodeException {
HttpURLConnection connection=null;
try{
connection = (HttpURLConnection)new URL(url).openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setUseCaches(false);
connection.setDoOutput(is_post);
connection.setDoInput(true);
connection.setRequestMethod(is_post?"POST":"GET");
if(enable_compression)
connection.setRequestProperty("Accept-Encoding", "gzip");
if(is_post)
connection.getOutputStream().write(body.getBytes("UTF-8"));
int code=connection.getResponseCode();
Log.i(TAG, "code="+code);
//It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation
if (code==-1)
throw new WrongResponseCodeException("Network error");
//может стоит проверить на код 200
//on error can also read error stream from connection.
InputStream is = new BufferedInputStream(connection.getInputStream(), 8192);
String enc=connection.getHeaderField("Content-Encoding");
if(enc!=null && enc.equalsIgnoreCase("gzip"))
is = new GZIPInputStream(is);
String response=Utils.convertStreamToString(is);
return response;
}
finally{
if(connection!=null)
connection.disconnect();
}
}
private long getDefaultStartTime() {
long now = System.currentTimeMillis() / 1000L;//unixtime
return now-31*24*60*60;//month ago
}
private String getSignedUrl(Params params, boolean is_post) {
String args = "";
if(!is_post)
args=params.getParamsString(is_post);
//add access_token
if(args.length()!=0)
args+="&";
args+="access_token="+access_token;
return BASE_URL+params.method_name+"?"+args;
}
public static String unescape(String text){
if(text==null)
return null;
return text.replace("&", "&").replace(""", "\"").replace("<br>", "\n").replace(">", ">").replace("<", "<")
.replace("'", "'").replace("<br/>", "\n").replace("–","-").replace("!", "!").trim();
//возможно тут могут быть любые коды после &#, например были: 092 - backslash \
}
public static String unescapeWithSmiles(String text){
return unescape(text)
//May be useful to someone
//.replace("\uD83D\uDE0A", ":-)")
//.replace("\uD83D\uDE03", ":D")
//.replace("\uD83D\uDE09", ";-)")
//.replace("\uD83D\uDE06", "xD")
//.replace("\uD83D\uDE1C", ";P")
//.replace("\uD83D\uDE0B", ":p")
//.replace("\uD83D\uDE0D", "8)")
//.replace("\uD83D\uDE0E", "B)")
//
//.replace("\ud83d\ude12", ":(") //F0 9F 98 92
//.replace("\ud83d\ude0f", ":]") //F0 9F 98 8F
//.replace("\ud83d\ude14", "3(") //F0 9F 98 94
//.replace("\ud83d\ude22", ":'(") //F0 9F 98 A2
//.replace("\ud83d\ude2d", ":_(") //F0 9F 98 AD
//.replace("\ud83d\ude29", ":((") //F0 9F 98 A9
//.replace("\ud83d\ude28", ":o") //F0 9F 98 A8
//.replace("\ud83d\ude10", ":|") //F0 9F 98 90
//
//.replace("\ud83d\ude0c", "3)") //F0 9F 98 8C
//.replace("\ud83d\ude20", ">(") //F0 9F 98 A0
//.replace("\ud83d\ude21", ">((") //F0 9F 98 A1
//.replace("\ud83d\ude07", "O:)") //F0 9F 98 87
//.replace("\ud83d\ude30", ";o") //F0 9F 98 B0
//.replace("\ud83d\ude32", "8o") //F0 9F 98 B2
//.replace("\ud83d\ude33", "8|") //F0 9F 98 B3
//.replace("\ud83d\ude37", ":X") //F0 9F 98 B7
//
//.replace("\ud83d\ude1a", ":*") //F0 9F 98 9A
//.replace("\ud83d\ude08", "}:)") //F0 9F 98 88
//.replace("\u2764", "<3") //E2 9D A4
//.replace("\ud83d\udc4d", ":like:") //F0 9F 91 8D
//.replace("\ud83d\udc4e", ":dislike:") //F0 9F 91 8E
//.replace("\u261d", ":up:") //E2 98 9D
//.replace("\u270c", ":v:") //E2 9C 8C
//.replace("\ud83d\udc4c", ":ok:") //F0 9F 91 8C
;
}
/*** API methods ***/
//http://vk.com/developers.php?oid=-1&p=places.getCityById
public ArrayList<City> getCities(Collection<Long> cids) throws MalformedURLException, IOException, JSONException, KException {
if (cids == null || cids.size() == 0)
return null;
Params params = new Params("places.getCityById");
params.put("cids",arrayToString(cids));
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<City> cities=new ArrayList<City>();
if(array!=null){
for(int i=0; i<array.length(); i++){
JSONObject o = (JSONObject)array.get(i);
City c = City.parse(o);
cities.add(c);
}
}
return cities;
}
<T> String arrayToString(Collection<T> items) {
if(items==null)
return null;
String str_cids = "";
for (Object item:items){
if(str_cids.length()!=0)
str_cids+=',';
str_cids+=item;
}
return str_cids;
}
//http://vk.com/developers.php?oid=-1&p=places.getCountryById
public ArrayList<Country> getCountries(Collection<Long> cids) throws MalformedURLException, IOException, JSONException, KException {
if (cids == null || cids.size() == 0)
return null;
Params params = new Params("places.getCountryById");
String str_cids = arrayToString(cids);
params.put("cids",str_cids);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Country> countries=new ArrayList<Country>();
int category_count = array.length();
for(int i=0; i<category_count; i++){
JSONObject o = (JSONObject)array.get(i);
Country c = Country.parse(o);
countries.add(c);
}
return countries;
}
//*** methods for users ***//
//http://vk.com/developers.php?oid=-1&p=users.get
public ArrayList<User> getProfiles(Collection<Long> uids, Collection<String> domains, String fields, String name_case) throws MalformedURLException, IOException, JSONException, KException{
if (uids == null && domains == null)
return null;
if ((uids != null && uids.size() == 0) || (domains != null && domains.size() == 0))
return null;
Params params = new Params("users.get");
if (uids != null && uids.size() > 0)
params.put("uids",arrayToString(uids));
if (domains != null && domains.size() > 0)
params.put("uids",arrayToString(domains));
if (fields == null)
params.put("fields","uid,first_name,last_name,nickname,domain,sex,bdate,city,country,timezone,photo,photo_medium_rec,photo_big,has_mobile,rate,contacts,education,online");
else
params.put("fields",fields);
params.put("name_case",name_case);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
}
/*** methods for friends ***/
//http://vkontakte.ru/developers.php?o=-1&p=friends.get
public ArrayList<User> getFriends(Long user_id, String fields, Integer lid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.get");
if(fields==null)
fields="first_name,last_name,photo_medium,online";
params.put("fields",fields);
params.put("uid",user_id);
params.put("lid", lid);
//сортировка по популярности не даёт запросить друзей из списка
if(lid==null)
params.put("order","hints");
JSONObject root = sendRequest(params);
ArrayList<User> users=new ArrayList<User>();
JSONArray array=root.optJSONArray("response");
//if there are no friends "response" will not be array
if(array==null)
return users;
int category_count=array.length();
for(int i=0; i<category_count; ++i){
JSONObject o = (JSONObject)array.get(i);
User u = User.parse(o);
users.add(u);
}
return users;
}
//http://vkontakte.ru/developers.php?o=-1&p=friends.getOnline
public ArrayList<Long> getOnlineFriends(Long uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.getOnline");
params.put("uid",uid);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
//http://vkontakte.ru/developers.php?oid=-1&p=likes.getList
public ArrayList<Long> getLikeUsers(String item_type, long item_id, long owner_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.getList");
params.put("type",item_type);
params.put("owner_id",owner_id);
params.put("item_id",item_id);
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
JSONArray array=response.optJSONArray("users");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
//http://vkontakte.ru/developers.php?o=-1&p=friends.getMutual
public ArrayList<Long> getMutual(Long target_uid, Long source_uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.getMutual");
params.put("target_uid",target_uid);
params.put("source_uid",source_uid);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
/*** methods for photos ***/
//http://vkontakte.ru/developers.php?o=-1&p=photos.getAlbums
public ArrayList<Album> getAlbums(Long owner_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getAlbums");
if (owner_id > 0)
//user
params.put("uid",owner_id);
else
//group
params.put("gid",-owner_id);
JSONObject root = sendRequest(params);
ArrayList<Album> albums=new ArrayList<Album>();
JSONArray array=root.optJSONArray("response");
if(array==null)
return albums;
int category_count=array.length();
for(int i=0; i<category_count; ++i){
JSONObject o = (JSONObject)array.get(i);
Album a = Album.parse(o);
if(a.title.equals("DELETED"))
continue;
albums.add(a);
}
return albums;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.get
public ArrayList<Photo> getPhotos(Long uid, Long aid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.get");
if(uid>0)
params.put("uid", uid);
else
params.put("gid", -uid);
params.put("aid", aid);
params.put("extended", "1");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<Photo>();
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.getUserPhotos
public ArrayList<Photo> getUserPhotos(Long uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getUserPhotos");
params.put("uid", uid);
params.put("sort","0");
params.put("count","50");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<Photo>();
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.getAll
public ArrayList<Photo> getAllPhotos(Long owner_id, Long offset, Long count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getAll");
params.put("owner_id", owner_id);
params.put("offset", offset);
params.put("count", count);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos=new ArrayList<Photo>();
int category_count=array.length();
for(int i=1; i<category_count; ++i){
JSONObject o = (JSONObject)array.get(i);
Photo p = Photo.parse(o);
photos.add(p);
}
return photos;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.getUserPhotos
public ArrayList<Photo> getUserPhotos(Long owner_id, Long offset, Long count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getUserPhotos");
params.put("owner_id", owner_id);
params.put("offset", offset);
params.put("count", count);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos=new ArrayList<Photo>();
int category_count = array.length();
for(int i=1; i<category_count; ++i){
JSONObject o = (JSONObject)array.get(i);
Photo p = Photo.parse(o);
photos.add(p);
}
return photos;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.getComments
public CommentList getPhotoComments(Long pid, Long owner_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getComments");
params.put("pid", pid);
params.put("owner_id", owner_id);
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
params.put("sort", "asc");
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
CommentList commnets = new CommentList();
commnets.count=array.getInt(0);
int category_count = array.length();
for(int i = 1; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = (JSONObject)array.get(i);
Comment comment = Comment.parsePhotoComment(o);
commnets.comments.add(comment);
}
return commnets;
}
//http://vkontakte.ru/developers.php?o=-1&p=notes.getComments
public CommentList getNoteComments(Long nid, Long owner_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("notes.getComments");
params.put("nid", nid);
params.put("owner_id", owner_id);
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
CommentList commnets = new CommentList();
commnets.count=array.getInt(0);
int category_count = array.length();
for(int i = 1; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = (JSONObject)array.get(i);
Comment comment = Comment.parseNoteComment(o);
commnets.comments.add(comment);
}
return commnets;
}
//http://vkontakte.ru/developers.php?o=-1&p=video.getComments
public CommentList getVideoComments(long video_id, Long owner_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.getComments");
params.put("vid", video_id);
params.put("owner_id", owner_id);
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
CommentList commnets = new CommentList();
commnets.count=array.getInt(0);
int category_count = array.length();
for(int i = 1; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = (JSONObject)array.get(i);
Comment comment = Comment.parseVideoComment(o);
commnets.comments.add(comment);
}
return commnets;
}
//Not used for now
//http://vkontakte.ru/developers.php?o=-1&p=photos.getAllComments
public ArrayList<Comment> getAllPhotoComments(Long owner_id, Long album_id, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getAllComments");
params.put("owner_id", owner_id);
params.put("album_id", album_id);
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
ArrayList<Comment> commnets = new ArrayList<Comment>();
@SuppressWarnings("unused")
JSONObject root = sendRequest(params);
//здесь ещё приходит pid - photo_id
//вынести парсящий код чтобы не было дублирования
//JSONArray array = root.getJSONArray("response");
//int category_count = array.length();
//for(int i = 0; i<category_count; ++i) {
// JSONObject o = (JSONObject)array.get(i);
// Comment comment = new Comment();
// comment.cid = Long.parseLong(o.getString("cid"));
// comment.from_id = Long.parseLong(o.getString("from_id"));
// comment.date = Long.parseLong(o.getString("date"));
// comment.message = unescape(o.getString("message"));
// commnets.add(comment);
//}
return commnets;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.createComment
public long createPhotoComment(Long pid, Long owner_id, String message, Long reply_to_cid, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.createComment");
params.put("pid",pid);
params.put("owner_id",owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message",message);
params.put("reply_to_cid", reply_to_cid);
JSONObject root = sendRequest(params);
long message_id = root.optLong("response");
return message_id;
}
//http://vkontakte.ru/developers.php?o=-1&p=notes.createComment
public long createNoteComment(Long nid, Long owner_id, String message, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("notes.createComment");
params.put("nid",nid);
params.put("owner_id",owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message",message);
//if (reply_to != null && !reply_to.equals(""))
// params.put("reply_to", reply_to);
JSONObject root = sendRequest(params);
long message_id = root.optLong("response");
return message_id;
}
//http://vkontakte.ru/developers.php?o=-1&p=video.createComment
public long createVideoComment(Long video_id, Long owner_id, String message, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.createComment");
params.put("vid",video_id);
params.put("owner_id",owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message",message);
JSONObject root = sendRequest(params);
long message_id = root.optLong("response");
return message_id;
}
private void addCaptchaParams(String captcha_key, String captcha_sid, Params params) {
params.put("captcha_sid",captcha_sid);
params.put("captcha_key",captcha_key);
}
/*** methods for messages
* @throws KException ***/
//http://vkontakte.ru/developers.php?o=-1&p=messages.get
public ArrayList<Message> getMessages(long time_offset, boolean is_out, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.get");
if (is_out)
params.put("out","1");
if (time_offset!=0)
params.put("time_offset", time_offset);
if (count != 0)
params.put("count", count);
params.put("preview_length","0");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, false, 0, false, 0);
return messages;
}
//http://vkontakte.ru/developers.php?o=-1&p=messages.getHistory
public ArrayList<Message> getMessagesHistory(long uid, long chat_id, long me, Long offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getHistory");
if(chat_id<=0)
params.put("uid",uid);
else
params.put("chat_id",chat_id);
params.put("offset", offset);
if (count != 0)
params.put("count", count);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, chat_id<=0, uid, chat_id>0, me);
return messages;
}
//http://vkontakte.ru/developers.php?o=-1&p=messages.getDialogs
public ArrayList<Message> getMessagesDialogs(long offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getDialogs");
if (offset!=0)
params.put("offset", offset);
if (count != 0)
params.put("count", count);
params.put("preview_length","0");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, false, 0, false ,0);
return messages;
}
private ArrayList<Message> parseMessages(JSONArray array, boolean from_history, long history_uid, boolean from_chat, long me) throws JSONException {
ArrayList<Message> messages = new ArrayList<Message>();
if (array != null) {
int category_count = array.length();
for(int i = 1; i < category_count; ++i) {
JSONObject o = (JSONObject)array.get(i);
Message m = Message.parse(o, from_history, history_uid, from_chat, me);
messages.add(m);
}
}
return messages;
}
//http://vkontakte.ru/developers.php?o=-1&p=messages.send
public String sendMessage(Long uid, long chat_id, String message, String title, String type, Collection<String> attachments, ArrayList<Long> forward_messages, String lat, String lon, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.send");
if(chat_id<=0)
params.put("uid", uid);
else
params.put("chat_id", chat_id);
params.put("message", message);
params.put("title", title);
params.put("type", type);
params.put("attachment", arrayToString(attachments));
params.put("forward_messages", arrayToString(forward_messages));
params.put("lat", lat);
params.put("long", lon);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params, true);
Object message_id = root.opt("response");
if (message_id != null)
return String.valueOf(message_id);
return null;
}
//http://vkontakte.ru/developers.php?o=-1&p=messages.markAsNew
//http://vkontakte.ru/developers.php?o=-1&p=messages.markAsRead
public String markAsNewOrAsRead(ArrayList<Long> mids, boolean as_read) throws MalformedURLException, IOException, JSONException, KException{
if (mids == null || mids.size() == 0)
return null;
Params params;
if (as_read)
params = new Params("messages.markAsRead");
else
params = new Params("messages.markAsNew");
params.put("mids", arrayToString(mids));
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vkontakte.ru/developers.php?o=-1&p=messages.delete
public String deleteMessage(Long mid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.delete");
params.put("mid", mid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
/*** for status***/
//http://vk.com/developers.php?oid=-1&p=status.get
public VkStatus getStatus(Long uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("status.get");
params.put("uid", uid);
JSONObject root = sendRequest(params);
JSONObject obj = root.optJSONObject("response");
VkStatus status = new VkStatus();
if (obj != null) {
status.text = unescape(obj.getString("text"));
JSONObject jaudio = obj.optJSONObject("audio");
if (jaudio != null)
status.audio = Audio.parse(jaudio);
}
return status;
}
//http://vk.com/developers.php?o=-1&p=status.set
public String setStatus(String status_text, String audio) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("status.set");
params.put("text", status_text);
params.put("audio", audio); //oid_aid
JSONObject root = sendRequest(params);
Object response_id = root.opt("response");
if (response_id != null)
return String.valueOf(response_id);
return null;
}
/*** methods for wall
* @throws KException ***/
//http://vkontakte.ru/developers.php?o=-1&p=wall.get
public ArrayList<WallMessage> getWallMessages(Long owner_id, int count, int offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.get");
params.put("owner_id", owner_id);
if (count > 0)
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
ArrayList<WallMessage> wmessages = new ArrayList<WallMessage>();
int category_count = array.length();
for(int i = 1; i < category_count; ++i) {
JSONObject o = (JSONObject)array.get(i);
WallMessage wm = WallMessage.parse(o);
wmessages.add(wm);
}
return wmessages;
}
/*** methods for news
* @throws KException ***/
//http://vkontakte.ru/developers.php?o=-1&p=newsfeed.get
//always returns about 33-35 items
public Newsfeed getNews(long start_time, long count, long end_time) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("newsfeed.get");
params.put("filters","post,photo,photo_tag,friend,note");
params.put("start_time",(start_time==-1)?getDefaultStartTime():start_time);
if(end_time!=-1)
params.put("end_time",end_time);
if(count!=0)
params.put("count",count);
JSONObject root = sendRequest(params);
return Newsfeed.parse(root, false);
}
//Новости-Комментарии. Описания нет.
public Newsfeed getNewsComments() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("newsfeed.getComments");
params.put("last_comments","1");
params.put("count","50");
JSONObject root = sendRequest(params);
return Newsfeed.parse(root, true);
}
/*** for audio ***/
//http://vkontakte.ru/developers.php?o=-1&p=audio.get
public ArrayList<Audio> getAudio(Long uid, Long gid, Long album_id, Collection<Long> aids) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.get");
params.put("uid", uid);
params.put("gid", gid);
params.put("aids", arrayToString(aids));
params.put("album_id", album_id);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return parseAudioList(array, 0);
}
//http://vk.com/developers.php?oid=-1&p=audio.getById
public ArrayList<Audio> getAudioById(String audios) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.getById");
params.put("audios", audios);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return parseAudioList(array, 0);
}
public String getLyrics(Long id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.getLyrics");
params.put("lyrics_id", id);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return response.optString("text");
}
/*** for video ***/
//http://vkontakte.ru/developers.php?o=-1&p=video.get //width = 130,160,320
public ArrayList<Video> getVideo(String videos, Long owner_id, Long album_id, String width, Long count, Long offset, String access_key) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.get");
params.put("videos", videos);
if (owner_id != null){
if(owner_id>0)
params.put("uid", owner_id);
else
params.put("gid", -owner_id);
}
params.put("width", width);
params.put("count", count);
params.put("offset", offset);
params.put("aid", album_id);
params.put("access_key", access_key);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Video> videoss = new ArrayList<Video>();
if (array != null) {
for(int i = 1; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
Video video = Video.parse(o);
videoss.add(video);
}
}
return videoss;
}
//http://vkontakte.ru/developers.php?o=-1&p=video.getUserVideos
public ArrayList<Video> getUserVideo(Long user_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.getUserVideos");
params.put("uid", user_id);
params.put("count", "50");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Video> videos = new ArrayList<Video>();
if (array != null) {
for(int i = 1; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
videos.add(Video.parse(o));
}
}
return videos;
}
/*** for crate album ***/
//http://vkontakte.ru/developers.php?o=-1&p=photos.createAlbum
public Album createAlbum(String title, String privacy, String comment_privacy, String description) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.createAlbum");
params.put("title", title);
params.put("privacy", privacy);
params.put("comment_privacy", comment_privacy);
params.put("description", description);
JSONObject root = sendRequest(params);
JSONObject o = root.optJSONObject("response");
if (o == null)
return null;
return Album.parse(o);
}
//http://vk.com/developers.php?oid=-1&p=photos.editAlbum
public String editAlbum(long aid, String title, String privacy, String comment_privacy, String description) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.editAlbum");
params.put("aid", String.valueOf(aid));
params.put("title", title);
params.put("privacy", privacy);
params.put("comment_privacy", comment_privacy);
params.put("description", description);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
/*** for notes ***/
//http://vkontakte.ru/developers.php?o=-1&p=notes.get
public ArrayList<Note> getNotes(Long uid, Collection<Long> nids, String sort, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notes.get");
params.put("uid", uid);
params.put("nids", arrayToString(nids));
params.put("sort", sort);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Note> notes = new ArrayList<Note>();
if (array != null) {
for(int i = 1; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
Note note = Note.parse(o, true);
notes.add(note);
}
}
return notes;
}
//http://vk.com/developers.php?oid=-1&p=notes.delete
public String deleteNote(Long nid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("notes.delete");
params.put("nid", nid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.getUploadServer
public String photosGetUploadServer(long album_id, Long group_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.getUploadServer");
params.put("aid",album_id);
params.put("gid",group_id);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.getWallUploadServer
public String photosGetWallUploadServer(Long user_id, Long group_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.getWallUploadServer");
params.put("uid",user_id);
params.put("gid",group_id);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
//http://vkontakte.ru/developers.php?oid=-1&p=getAudioUploadServer
public String getAudioUploadServer() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("getAudioUploadServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
//http://vkontakte.ru/developers.php?oid=-1&p=photos.getMessagesUploadServer
public String photosGetMessagesUploadServer() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.getMessagesUploadServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.getProfileUploadServer
public String photosGetProfileUploadServer() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.getProfileUploadServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.save
public ArrayList<Photo> photosSave(String server, String photos_list, Long aid, Long group_id, String hash, String caption) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.save");
params.put("server",server);
params.put("photos_list",photos_list);
params.put("aid",aid);
params.put("gid",group_id);
params.put("hash",hash);
params.put("caption",caption);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.saveWallPhoto
public ArrayList<Photo> saveWallPhoto(String server, String photo, String hash, Long user_id, Long group_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.saveWallPhoto");
params.put("server",server);
params.put("photo",photo);
params.put("hash",hash);
params.put("uid",user_id);
params.put("gid",group_id);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
//http://vk.com/developers.php?oid=-1&p=audio.save
public Audio saveAudio(String server, String audio, String hash, String artist, String title) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("audio.save");
params.put("server",server);
params.put("audio",audio);
params.put("hash",hash);
params.put("artist",artist);
params.put("title",title);
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
return Audio.parse(response);
}
//http://vkontakte.ru/developers.php?oid=-1&p=photos.saveMessagesPhoto
public ArrayList<Photo> saveMessagesPhoto(String server, String photo, String hash) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.saveMessagesPhoto");
params.put("server",server);
params.put("photo",photo);
params.put("hash",hash);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.saveProfilePhoto
public String[] saveProfilePhoto(String server, String photo, String hash) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.saveProfilePhoto");
params.put("server",server);
params.put("photo",photo);
params.put("hash",hash);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
String src = response.optString("photo_src");
String hash1 = response.optString("photo_hash");
String[] res=new String[]{src, hash1};
return res;
}
private ArrayList<Photo> parsePhotos(JSONArray array) throws JSONException {
ArrayList<Photo> photos=new ArrayList<Photo>();
int category_count=array.length();
for(int i=0; i<category_count; ++i){
//in getUserPhotos first element is integer
if(array.get(i) instanceof JSONObject == false)
continue;
JSONObject o = (JSONObject)array.get(i);
Photo p = Photo.parse(o);
photos.add(p);
}
return photos;
}
/*public long createGraffitiComment(String gid, String owner_id, String message, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("graffiti.createComment");
params.put("gid",gid);
params.put("owner_id",owner_id);
addCaptchaParams(captcha_key, captcha_sid, params);
params.put("message",message);
JSONObject root = sendRequest(params);
long message_id = root.optLong("response");
return message_id;
}*/
//http://vkontakte.ru/developers.php?o=-1&p=wall.addComment
public long createWallComment(Long owner_id, Long post_id, String text, Long reply_to_cid, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.addComment");
params.put("owner_id", owner_id);
params.put("post_id", post_id);
params.put("text", text);
params.put("reply_to_cid", reply_to_cid);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
long cid = response.optLong("cid");
return cid;
}
//http://vkontakte.ru/developers.php?o=-1&p=wall.post
public long createWallPost(long owner_id, String text, Collection<String> attachments, String export, boolean only_friends, boolean from_group, boolean signed, String lat, String lon, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.post");
params.put("owner_id", owner_id);
params.put("attachments", arrayToString(attachments));
params.put("lat", lat);
params.put("long", lon);
params.put("message", text);
if(export!=null && export.length()!=0)
params.put("services",export);
if (from_group)
params.put("from_group","1");
if (only_friends)
params.put("friends_only","1");
if (signed)
params.put("signed","1");
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params, true);
JSONObject response = root.getJSONObject("response");
long post_id = response.optLong("post_id");
return post_id;
}
//http://vkontakte.ru/developers.php?o=-1&p=wall.getComments
public CommentList getWallComments(Long owner_id, Long post_id, int offset, int count, String v) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.getComments");
params.put("post_id", post_id);
params.put("owner_id", owner_id);
/*
if (sort != null)
params.put("sort", sort);
//asc - хронологический
//desc - антихронологический
*/
if (offset > 0)
params.put("offset", offset);
if (count > 0)
params.put("count", count);
params.put("preview_length", "0");
params.put("need_likes", "1");
params.put("v", v);
JSONObject root = sendRequest(params);
JSONArray array = root.getJSONArray("response");
CommentList commnets = new CommentList();
commnets.count=array.getInt(0);
int category_count = array.length();
for(int i = 1; i<category_count; ++i) //get(0) is integer, it is comments count
commnets.comments.add(Comment.parse((JSONObject)array.get(i)));
return commnets;
}
//http://vkontakte.ru/developers.php?o=-1&p=audio.search
public ArrayList<Audio> searchAudio(String q, String sort, String lyrics, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.search");
params.put("q", q);
params.put("sort", sort);
params.put("lyrics", lyrics);
params.put("count", count);
params.put("offset", offset);
params.put("auto_complete", "1");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return parseAudioList(array, 1);
}
private ArrayList<Audio> parseAudioList(JSONArray array, int type_array) //type_array must be 0 or 1
throws JSONException {
ArrayList<Audio> audios = new ArrayList<Audio>();
if (array != null) {
for(int i = type_array; i<array.length(); ++i) { //get(0) is integer, it is audio count
JSONObject o = (JSONObject)array.get(i);
audios.add(Audio.parse(o));
}
}
return audios;
}
//http://vkontakte.ru/developers.php?o=-1&p=audio.delete
public String deleteAudio(Long aid, Long oid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.delete");
params.put("aid", aid);
params.put("oid", oid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vkontakte.ru/developers.php?o=-1&p=audio.add
public String addAudio(Long aid, Long oid, Long gid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.add");
params.put("aid", aid);
params.put("oid", oid);
params.put("gid", gid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vkontakte.ru/developers.php?o=-1&p=wall.addLike
public Long wallAddLike(Long owner_id, Long post_id, boolean need_publish, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.addLike");
params.put("owner_id", owner_id);
params.put("post_id", post_id);
params.put("need_publish", need_publish?"1":"0");
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
long likes=response.optLong("likes", -1);
return likes;
}
//http://vkontakte.ru/developers.php?o=-1&p=wall.deleteLike
public Long wallDeleteLike(Long owner_id, Long post_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.deleteLike");
params.put("owner_id", owner_id);
params.put("post_id", post_id);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
long likes=response.optLong("likes", -1);
return likes;
}
//http://vk.com/developers.php?oid=-1&p=likes.add
public Long addLike(Long owner_id, Long item_id, String type, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.add");
params.put("owner_id", owner_id);
params.put("item_id", item_id);
params.put("type", type);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
long likes=response.optLong("likes", -1);
return likes;
}
//http://vk.com/developers.php?oid=-1&p=likes.delete
public Long deleteLike(Long owner_id, Long item_id, String type) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.delete");
params.put("owner_id", owner_id);
params.put("item_id", item_id);
params.put("type", type);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
long likes=response.optLong("likes", -1);
return likes;
}
//http://vkontakte.ru/developers.php?oid=-1&p=likes.add
public Long addLike(Long owner_id, String type, Long item_id, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.add");
params.put("owner_id", owner_id);
params.put("type", type);
params.put("item_id", item_id);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return response.optLong("likes", -1);
}
//http://vkontakte.ru/developers.php?oid=-1&p=likes.delete
public Long deleteLike(Long owner_id, String type, Long item_id, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("likes.delete");
params.put("owner_id", owner_id);
params.put("type", type);
params.put("item_id", item_id);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return response.optLong("likes", -1);
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.getById
public ArrayList<Photo> getPhotosById(String photos) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getById");
params.put("photos", photos);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<Photo>();
ArrayList<Photo> photos1 = parsePhotos(array);
return photos1;
}
//http://vkontakte.ru/developers.php?oid=-1&p=groups.get
public ArrayList<Group> getUserGroups(Long user_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("groups.get");
params.put("extended","1");
params.put("uid",user_id);
JSONObject root = sendRequest(params);
ArrayList<Group> groups=new ArrayList<Group>();
JSONArray array=root.optJSONArray("response");
//if there are no groups "response" will not be array
if(array==null)
return groups;
groups = Group.parseGroups(array);
return groups;
}
//http://vkontakte.ru/developers.php?o=-1&p=wall.delete
public Boolean removeWallPost(Long post_id, long wall_owner_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("wall.delete");
params.put("owner_id", wall_owner_id);
params.put("post_id", post_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
//http://vkontakte.ru/developers.php?o=-1&p=wall.deleteComment
public Boolean deleteWallComment(Long wall_owner_id, long comment_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("wall.deleteComment");
params.put("owner_id", wall_owner_id);
params.put("cid", comment_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
//http://vkontakte.ru/developers.php?o=-1&p=notes.deleteComment
public Boolean deleteNoteComment(Long note_owner_id, long comment_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notes.deleteComment");
params.put("owner_id", note_owner_id);
params.put("cid", comment_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
//http://vkontakte.ru/developers.php?o=-1&p=video.deleteComment
public Boolean deleteVideoComment(Long video_owner_id, long comment_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.deleteComment");
params.put("owner_id", video_owner_id);
params.put("cid", comment_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
//http://vkontakte.ru/developers.php?o=-1&p=photos.deleteComment
public Boolean deletePhotoComment(long photo_id, Long photo_owner_id, long comment_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.deleteComment");
params.put("owner_id", photo_owner_id);
params.put("cid", comment_id);
params.put("pid", photo_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
//http://vkontakte.ru/developers.php?o=-1&p=video.search
public ArrayList<Video> searchVideo(String q, String sort, String hd, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.search");
params.put("q", q);
params.put("sort", sort);
params.put("hd", hd);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Video> videoss = new ArrayList<Video>();
if (array != null) {
for(int i = 0; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
Video video = Video.parse(o);
videoss.add(video);
}
}
return videoss;
}
//no documentation
public ArrayList<User> searchUser(String q, String fields, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("users.search");
params.put("q", q);
params.put("count", count);
params.put("offset", offset);
params.put("fields", fields);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
}
//http://vkontakte.ru/developers.php?o=-1&p=video.delete
public String deleteVideo(Long vid, Long oid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.delete");
params.put("vid", vid);
params.put("oid", oid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vkontakte.ru/developers.php?o=-1&p=video.add
public String addVideo(Long vid, Long oid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.add");
params.put("vid", vid);
params.put("oid", oid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vkontakte.ru/developers.php?o=-1&p=notes.add
public long createNote(String title, String text) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("notes.add");
params.put("title", title);
params.put("text", text);
params.put("privacy", "0");
params.put("comment_privacy", "0");
JSONObject root = sendRequest(params, true);
JSONObject response = root.getJSONObject("response");
long note_id = response.optLong("nid");
return note_id;
}
//http://vkontakte.ru/developers.php?o=-1&p=messages.getLongPollServer
public Object[] getLongPollServer() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getLongPollServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
String key=response.getString("key");
String server=response.getString("server");
Long ts = response.getLong("ts");
return new Object[]{key, server, ts};
}
//не документирован
public void setOnline() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("activity.online");
sendRequest(params);
}
//http://vkontakte.ru/developers.php?oid=-1&p=friends.add
public long addFriend(Long uid, String text, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.add");
params.put("uid", uid);
params.put("text", text);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
return root.optLong("response");
}
//http://vkontakte.ru/developers.php?oid=-1&p=friends.delete
public long deleteFriend(Long uid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.delete");
params.put("uid", uid);
JSONObject root = sendRequest(params);
return root.optLong("response");
}
//http://vkontakte.ru/developers.php?oid=-1&p=friends.getRequests
public ArrayList<Object[]> getRequestsFriends() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("friends.getRequests");
params.put("need_messages", "1");
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<Object[]> users=new ArrayList<Object[]>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i) {
JSONObject item = array.optJSONObject(i);
if (item != null) {
Long id = item.optLong("uid", -1);
if (id!=-1) {
Object[] u = new Object[2];
u[0] = id;
u[1] = item.optString("message");
users.add(u);
}
}
}
}
return users;
}
//http://vkontakte.ru/developers.php?oid=-1&p=subscriptions.follow
public String followUser(Long uid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("subscriptions.follow");
params.put("uid", uid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vkontakte.ru/developers.php?oid=-1&p=subscriptions.unfollow
public String unfollowUser(Long uid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("subscriptions.unfollow");
params.put("uid", uid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vkontakte.ru/developers.php?oid=-1&p=subscriptions.get
public ArrayList<Long> getSubscriptions(Long uid, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("subscriptions.get");
params.put("uid", uid);
if (offset>0)
params.put("offset", offset);
if (count>0)
params.put("count", count);
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
JSONArray array=response.optJSONArray("users");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
//http://vkontakte.ru/developers.php?oid=-1&p=subscriptions.getFollowers
public ArrayList<Long> getFollowers(Long uid, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("subscriptions.getFollowers");
params.put("uid", uid);
if (offset>0)
params.put("offset", offset);
if (count>0)
params.put("count", count);
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
JSONArray array=response.optJSONArray("users");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
//http://vkontakte.ru/pages?oid=-1&p=messages.deleteDialog
public int deleteMessageThread(Long uid, Long chatId) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.deleteDialog");
params.put("uid", uid);
params.put("chat_id", chatId);
JSONObject root = sendRequest(params);
return root.getInt("response");
}
//http://vkontakte.ru/developers.php?oid=-1&p=execute
public void execute(String code) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("execute");
params.put("code", code);
sendRequest(params);
}
//http://vkontakte.ru/developers.php?oid=-1&p=photos.delete
public boolean deletePhoto(Long owner_id, Long photo_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.delete");
params.put("oid", owner_id);
params.put("pid", photo_id);
JSONObject root = sendRequest(params);
long response = root.optLong("response", -1);
return response==1;
}
//http://vkontakte.ru/developers.php?oid=-1&p=polls.getById
public VkPoll getPoll(long poll_id, long owner_id) throws JSONException, MalformedURLException, IOException, KException {
Params params = new Params("polls.getById");
params.put("owner_id", owner_id);
params.put("poll_id", poll_id);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return VkPoll.parse(response);
}
//http://vkontakte.ru/developers.php?oid=-1&p=polls.addVote
public int addPollVote(long poll_id, long answer_id, long owner_id) throws JSONException, MalformedURLException, IOException, KException {
Params params = new Params("polls.addVote");
params.put("owner_id", owner_id);
params.put("poll_id", poll_id);
params.put("answer_id", answer_id);
JSONObject root = sendRequest(params);
return root.getInt("response");
}
//http://vkontakte.ru/developers.php?oid=-1&p=polls.deleteVote
public int deletePollVote(long poll_id, long answer_id, long owner_id) throws JSONException, MalformedURLException, IOException, KException {
Params params = new Params("polls.deleteVote");
params.put("owner_id", owner_id);
params.put("poll_id", poll_id);
params.put("answer_id", answer_id);
JSONObject root = sendRequest(params);
return root.getInt("response");
}
//http://vkontakte.ru/developers.php?oid=-1&p=friends.getLists
public ArrayList<FriendsList> friendsLists() throws JSONException, MalformedURLException, IOException, KException {
Params params = new Params("friends.getLists");
JSONObject root = sendRequest(params);
ArrayList<FriendsList> result = new ArrayList<FriendsList>();
JSONArray list = root.optJSONArray("response");
if (list != null) {
for (int i=0; i<list.length(); ++i) {
JSONObject o = list.getJSONObject(i);
FriendsList fl = FriendsList.parse(o);
result.add(fl);
}
}
return result;
}
//http://vkontakte.ru/developers.php?oid=-1&p=video.save
public String saveVideo(String name, String description, Long gid, int privacy_view, int privacy_comment) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("video.save");
params.put("name", name);
params.put("description", description);
params.put("gid", gid);
if (privacy_view > 0)
params.put("privacy_view", privacy_view);
if (privacy_comment > 0)
params.put("privacy_comment", privacy_comment);
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
//http://vkontakte.ru/developers.php?oid=-1&p=photos.deleteAlbum
public String deleteAlbum(Long aid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.deleteAlbum");
params.put("aid", aid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//http://vk.com/developers.php?o=-1&p=photos.getTags
public ArrayList<PhotoTag> getPhotoTagsById(Long pid, Long owner_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("photos.getTags");
params.put("owner_id", owner_id);
params.put("pid", pid);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<PhotoTag>();
ArrayList<PhotoTag> photo_tags = parsePhotoTags(array, pid, owner_id);
return photo_tags;
}
private ArrayList<PhotoTag> parsePhotoTags(JSONArray array, Long pid, Long owner_id) throws JSONException {
ArrayList<PhotoTag> photo_tags=new ArrayList<PhotoTag>();
int category_count=array.length();
for(int i=0; i<category_count; ++i){
//in getUserPhotos first element is integer
if(array.get(i) instanceof JSONObject == false)
continue;
JSONObject o = (JSONObject)array.get(i);
PhotoTag p = PhotoTag.parse(o);
photo_tags.add(p);
if (pid != null)
p.pid = pid;
if (owner_id != null)
p.owner_id = owner_id;
}
return photo_tags;
}
//http://vk.com/developers.php?oid=-1&p=photos.putTag
public String putPhotoTag(PhotoTag ptag, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
if (ptag == null)
return null;
Params params = new Params("photos.putTag");
params.put("owner_id", ptag.owner_id);
params.put("pid", ptag.pid);
params.put("uid", ptag.uid);
params.putDouble("x", ptag.x);
params.putDouble("x2", ptag.x2);
params.putDouble("y", ptag.y);
params.putDouble("y2", ptag.y2);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
/*** topics region ***/
//http://kate1.unfuddle.com/a#/projects/2/tickets/by_number/340?cycle=true
public ArrayList<GroupTopic> getGroupTopics(long gid, int extended, int count, int offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.getTopics");
params.put("gid", gid);
if (extended == 1)
params.put("extended", "1"); //for profiles
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
JSONObject root = sendRequest(params);
ArrayList<GroupTopic> result = new ArrayList<GroupTopic>();
JSONObject response = root.optJSONObject("response");
if (response != null) {
JSONArray topics = response.optJSONArray("topics");
if (topics != null) {
for (int i=1; i<topics.length(); ++i) {
JSONObject o = topics.getJSONObject(i);
GroupTopic gt = GroupTopic.parse(o);
gt.gid = gid;
result.add(gt);
}
}
}
return result;
}
public CommentList getGroupTopicComments(long gid, long tid, int photo_sizes, int extended, int count, int offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("board.getComments");
params.put("gid", gid);
params.put("tid", tid);
if (photo_sizes == 1)
params.put("photo_sizes", "1");
if (extended == 1)
params.put("extended", "1");
if (count > 0)
params.put("count", count);
if (offset > 0)
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
CommentList result = new CommentList();
if (response != null) {
JSONArray comments = response.optJSONArray("comments");
int category_count = comments.length();
result.count=comments.getInt(0);
for (int i=1; i<category_count; ++i) { //get(0) is integer, it is comments count
JSONObject o = comments.getJSONObject(i);
Comment c = Comment.parseTopicComment(o);
result.comments.add(c);
}
}
return result;
}
public long createGroupTopicComment(long gid, long tid, String text, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.addComment");
params.put("gid", gid);
params.put("tid", tid);
params.put("text", text);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
long message_id = root.optLong("response");
return message_id;
}
public Boolean deleteGroupTopicComment(long gid, long tid, long cid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.deleteComment");
params.put("gid", gid);
params.put("tid", tid);
params.put("cid", cid);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
public long createGroupTopic(long gid, String title, String text, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.addTopic");
params.put("gid", gid);
params.put("title", title);
params.put("text", text);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
long topic_id = root.optLong("response");
return topic_id;
}
public Boolean deleteGroupTopic(long gid, long tid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("board.deleteTopic");
params.put("gid", gid);
params.put("tid", tid);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
/*** end topics region ***/
//http://vk.com/developers.php?oid=-1&p=groups.getById
public ArrayList<Group> getGroups(Collection<Long> uids, String domain, String fields) throws MalformedURLException, IOException, JSONException, KException{
if (uids == null && domain == null)
return null;
if (uids.size() == 0 && domain == null)
return null;
Params params = new Params("groups.getById");
String str_uids;
if (uids != null && uids.size() > 0)
str_uids=arrayToString(uids);
else
str_uids = domain;
params.put("gids", str_uids);
params.put("fields", fields); //Possible values: place,wiki_page,city,country,description,start_date,finish_date,site
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return Group.parseGroups(array);
}
//no documentation
public String joinGroup(long gid, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.join");
params.put("gid", gid);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//no documentation
public String leaveGroup(long gid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.leave");
params.put("gid", gid);
JSONObject root = sendRequest(params);
Object response_code = root.opt("response");
if (response_code != null)
return String.valueOf(response_code);
return null;
}
//no documentation
public ArrayList<Group> searchGroup(String q, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.search");
params.put("q", q);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
ArrayList<Group> groups = new ArrayList<Group>();
//if there are no groups "response" will not be array
if (array==null)
return groups;
groups = Group.parseGroups(array);
return groups;
}
//http://vk.com/pages?oid=-1&p=account.registerDevice
public String registerDevice(String token, String device_model, String system_version, Integer no_text, String subscribe)
throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("account.registerDevice");
params.put("token", token);
params.put("device_model", device_model);
params.put("system_version", system_version);
params.put("no_text", no_text);
params.put("subscribe", subscribe);
JSONObject root = sendRequest(params);
return root.getString("response");
}
//http://vk.com/pages?oid=-1&p=account.unregisterDevice
public String unregisterDevice(String token) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("account.unregisterDevice");
params.put("token", token);
JSONObject root = sendRequest(params);
return root.getString("response");
}
//http://vk.com/developers.php?oid=-1&p=notifications.get
public Notifications getNotifications(String filters, Long start_time, Long end_time, Integer offset, Integer count) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notifications.get");
params.put("filters", filters);
params.put("start_time", start_time);
params.put("end_time", end_time);
params.put("offset", offset);
params.put("count", count);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return Notifications.parse(response);
}
//http://vk.com/developers.php?oid=-1&p=notifications.markAsViewed
public String resetUnreadNotifications() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notifications.markAsViewed");
JSONObject root = sendRequest(params);
return root.getString("response");
}
//http://vk.com/developers.php?oid=-1&p=messages.getById
public ArrayList<Message> getMessagesById(ArrayList<Long> message_ids) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getById");
params.put("mids", arrayToString(message_ids));
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, false, 0, false, 0);
return messages;
}
public Counters getCounters() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("getCounters");
JSONObject root = sendRequest(params);
JSONObject response=root.optJSONObject("response");
return Counters.parse(response);
}
/*** faves ***/
//http://vk.com/developers.php?oid=-1&p=fave.getUsers
public ArrayList<User> getFaveUsers(String fields, Integer count, Integer offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("fave.getUsers");
if(fields==null)
fields="photo_medium,online";
params.put("fields",fields);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
ArrayList<User> users=new ArrayList<User>();
JSONArray array=root.optJSONArray("response");
//if there are no friends "response" will not be array
if(array==null)
return users;
int category_count=array.length();
for(int i=0; i<category_count; ++i) {
if(array.get(i)==null || ((array.get(i) instanceof JSONObject)==false))
continue;
JSONObject o = (JSONObject)array.get(i);
User u = User.parseFromFave(o);
users.add(u);
}
return users;
}
//http://vk.com/developers.php?oid=-1&p=fave.getPhotos
public ArrayList<Photo> getFavePhotos(Integer count, Integer offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("fave.getPhotos");
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
if (array == null)
return new ArrayList<Photo>();
ArrayList<Photo> photos = parsePhotos(array);
return photos;
}
//http://vk.com/developers.php?oid=-1&p=fave.getVideos
public ArrayList<Video> getFaveVideos(Integer count, Integer offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("fave.getVideos");
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Video> videos = new ArrayList<Video>();
if (array != null) {
for(int i = 1; i<array.length(); ++i) {
JSONObject o = (JSONObject)array.get(i);
Video video = Video.parse(o);
videos.add(video);
}
}
return videos;
}
//http://vk.com/developers.php?oid=-1&p=fave.getPosts
public ArrayList<WallMessage> getFavePosts(Integer count, Integer offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("fave.getPosts");
//params.put("extended", extended);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
//JSONArray array = response.optJSONArray("wall");
//JSONArray profiles_array = response.optJSONArray("profiles");
//JSONArray groups_array = response.optJSONArray("groups");
ArrayList<WallMessage> wmessages = new ArrayList<WallMessage>();
if (array == null)
return wmessages;
int category_count = array.length();
for(int i = 1; i < category_count; ++i) {
JSONObject o = (JSONObject)array.get(i);
WallMessage wm = WallMessage.parse(o);
wmessages.add(wm);
}
return wmessages;
}
//http://vk.com/developers.php?oid=-1&p=fave.getLinks
public ArrayList<Link> getFaveLinks(Integer count, Integer offset) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("fave.getLinks");
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
ArrayList<Link> groups=new ArrayList<Link>();
JSONArray array=root.optJSONArray("response");
//if there are no groups "response" will not be array
if(array==null)
return groups;
for(int i = 0; i < array.length(); i++) {
if(!(array.get(i) instanceof JSONObject))
continue;
JSONObject jlink = (JSONObject)array.get(i);
Link link = Link.parse(jlink);
groups.add(link);
}
return groups;
}
/*** end faves ***/
/*** chat methods ***/
//http://vk.com/pages?oid=-1&p=messages.createChat
public Long chatCreate(ArrayList<Long> uids, String title) throws MalformedURLException, IOException, JSONException, KException {
if (uids == null || uids.size() == 0)
return null;
Params params = new Params("messages.createChat");
String str_uids = String.valueOf(uids.get(0));
for (int i=1; i<uids.size(); i++)
str_uids += "," + String.valueOf(uids.get(i));
params.put("uids", str_uids);
params.put("title", title);
JSONObject root = sendRequest(params);
return root.optLong("response");
}
//http://vk.com/pages?oid=-1&p=messages.editChat
public Integer chatEdit(long chat_id, String title) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.editChat");
params.put("chat_id", chat_id);
params.put("title", title);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
//http://vk.com/pages?oid=-1&p=messages.getChatUsers
public ArrayList<User> getChatUsers(long chat_id, String fields) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.getChatUsers");
params.put("chat_id", chat_id);
params.put("fields", fields);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
}
//http://vk.com/pages?oid=-1&p=messages.addChatUser
public Integer addUserToChat(long chat_id, long uid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.addChatUser");
params.put("chat_id", chat_id);
params.put("uid", uid);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
//http://vk.com/pages?oid=-1&p=messages.removeChatUser
public Integer removeUserFromChat(long chat_id, long uid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.removeChatUser");
params.put("chat_id", chat_id);
params.put("uid", uid);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
/*** end chat methods ***/
//http://vk.com/pages?oid=-1&p=friends.getSuggestions
public ArrayList<User> getSuggestions(String filter, String fields) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("friends.getSuggestions");
params.put("filter", filter); //mutual, contacts, mutual_contacts
params.put("fields", fields);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
}
//http://vk.com/pages?oid=-1&p=account.importContacts
public Integer importContacts(Collection<String> contacts) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("account.importContacts");
params.put("contacts", arrayToString(contacts));
JSONObject root = sendRequest(params);
return root.optInt("response");
}
//http://vk.com/pages?oid=-1&p=friends.getByPhones
public ArrayList<User> getFriendsByPhones(ArrayList<String> phones, String fields) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("friends.getByPhones");
params.put("phones", arrayToString(phones));
params.put("fields", fields);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsersForGetByPhones(array);
}
/*** methods for messages search ***/
//http://vk.com/pages?oid=-1&p=messages.search
public ArrayList<Message> searchMessages(String q, int offset, int count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.search");
params.put("q", q);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<Message> messages = parseMessages(array, false, 0, false, 0);
return messages;
}
//http://vk.com/pages?oid=-1&p=messages.searchDialogs
public ArrayList<SearchDialogItem> searchDialogs(String q, String fields) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.searchDialogs");
params.put("q", q);
params.put("fields", fields);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return Message.parseSearchedDialogs(array);
}
//http://vk.com/pages?oid=-1&p=messages.getLastActivity
public LastActivity getLastActivity(long user_id) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("messages.getLastActivity");
params.put("uid", user_id);
JSONObject root = sendRequest(params);
JSONObject response = root.optJSONObject("response");
return LastActivity.parse(response);
}
//http://vk.com/developers.php?oid=-1&p=groups.getMembers
public ArrayList<Long> getGroupsMembers(long gid, Integer count, Integer offset, String sort) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.getMembers");
params.put("gid", gid);
params.put("count", count);
params.put("offset", offset);
params.put("sort", sort); //id_asc, id_desc, time_asc, time_desc
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
JSONArray array=response.optJSONArray("users");
ArrayList<Long> users=new ArrayList<Long>();
if (array != null) {
int category_count=array.length();
for(int i=0; i<category_count; ++i){
Long id = array.optLong(i, -1);
if(id!=-1)
users.add(id);
}
}
return users;
}
//http://vk.com/developers.php?oid=-1&p=groups.getMembers
public Long getGroupsMembersCount(long gid) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("groups.getMembers");
params.put("gid", gid);
params.put("count", 10);
JSONObject root = sendRequest(params);
JSONObject response=root.getJSONObject("response");
return response.optLong("count");
}
public ArrayList<User> getGroupsMembersWithExecute(long gid, Integer count, Integer offset, String sort, String fields) throws MalformedURLException, IOException, JSONException, KException {
//String code = "return API.getProfiles({\"uids\":API.groups.getMembers({\"gid\":" + String.valueOf(gid) + ",\"count\":" + String.valueOf(count) + ",\"offset\":" + String.valueOf(offset) + ",\"sort\":\"id_asc\"}),\"fields\":\"" + fields + "\"});";
String code = "var members=API.groups.getMembers({\"gid\":" + gid + "}); var u=members[1]; return API.getProfiles({\"uids\":u,\"fields\":\"" + fields + "\"});";
Params params = new Params("execute");
params.put("code", code);
JSONObject root = sendRequest(params);
JSONArray array=root.optJSONArray("response");
return User.parseUsers(array);
}
//http://vk.com/developers.php?oid=-1&p=getServerTime
public long getServerTime() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("getServerTime");
JSONObject root = sendRequest(params);
return root.getLong("response");
}
//http://vk.com/developers.php?oid=-1&p=audio.getAlbums
public ArrayList<AudioAlbum> getAudioAlbums(Long uid, Long gid, Integer offset, Integer count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.getAlbums");
params.put("uid", uid);
params.put("gid", gid);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<AudioAlbum> albums = AudioAlbum.parseAlbums(array);
return albums;
}
public ArrayList<Audio> getAudioRecommendations() throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("audio.getRecommendations");
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return parseAudioList(array, 0);
}
//http://vk.com/developers.php?oid=-1&p=video.getAlbums
public ArrayList<AudioAlbum> getVideoAlbums(Long uid, Long gid, Integer offset, Integer count) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("video.getAlbums");
params.put("uid", uid);
params.put("gid", gid);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
ArrayList<AudioAlbum> albums = AudioAlbum.parseAlbums(array);
return albums;
}
//http://vk.com/developers.php?oid=-1&p=messages.setActivity
public Integer setMessageActivity(long uid, long chat_id, boolean typing) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("messages.setActivity");
params.put("uid", uid);
params.put("chat_id", chat_id);
if (typing)
params.put("type", "typing");
JSONObject root = sendRequest(params);
return root.optInt("response");
}
//http://vk.com/developers.php?oid=-1&p=wall.edit
public int editWallPost(long owner_id, long post_id, String text, Collection<String> attachments, String lat, String lon, long place_id, String captcha_key, String captcha_sid) throws MalformedURLException, IOException, JSONException, KException{
Params params = new Params("wall.edit");
params.put("owner_id", owner_id);
params.put("post_id", post_id);
params.put("message", text);
params.put("attachments", arrayToString(attachments));
params.put("lat", lat);
params.put("long", lon);
params.put("place_id", place_id);
addCaptchaParams(captcha_key, captcha_sid, params);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
//http://vk.com/developers.php?oid=-1&p=photos.edit
public Integer photoEdit(Long owner_id, long pid, String caption) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("photos.edit");
params.put("owner_id", owner_id);
params.put("pid", pid);
params.put("caption", caption);
JSONObject root = sendRequest(params);
return root.optInt("response");
}
//http://vk.com/developers.php?oid=-1&p=docs.get
public ArrayList<Document> getDocs(Long owner_id, Long count, Long offset) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("docs.get");
params.put("oid", owner_id);
params.put("count", count);
params.put("offset", offset);
JSONObject root = sendRequest(params);
JSONArray array = root.optJSONArray("response");
return Document.parseDocs(array);
}
//http://vk.com/developers.php?oid=-1&p=docs.getUploadServer
public String docsGetUploadServer() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("docs.getUploadServer");
JSONObject root = sendRequest(params);
JSONObject response = root.getJSONObject("response");
return response.getString("upload_url");
}
//http://vk.com/developers.php?oid=-1&p=docs.save
public Document saveDoc(String file) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("docs.save");
params.put("file", file);
JSONObject root = sendRequest(params);
JSONArray array=root.getJSONArray("response");
ArrayList<Document> docs = Document.parseDocs(array);
return docs.get(0);
}
//http://vk.com/developers.php?oid=-1&p=docs.delete
public Boolean deleteDoc(Long doc_id, long owner_id) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("docs.delete");
params.put("oid", owner_id);
params.put("did", doc_id);
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
//Помечает уведомления о новых ответах как прочитанные, документации нет
public Boolean markNotificationsAsViewed() throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("notifications.markAsViewed");
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
//http://vk.com/developers.php?oid=-1&p=newsfeed.getBanned
public BannArg getBanned(boolean is_extended, String fields) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("newsfeed.getBanned");
if (is_extended)
params.put("extended", "1");
params.put("fields", fields);
JSONObject root = sendRequest(params);
JSONObject object = root.optJSONObject("response");
return BannArg.parse(object);
}
//http://vk.com/developers.php?oid=-1&p=newsfeed.addBan
public Boolean addBan(Collection<Long> uids, Collection<Long> gids) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("newsfeed.addBan");
if (uids != null && uids.size() > 0)
params.put("uids",arrayToString(uids));
if (gids != null && gids.size() > 0)
params.put("gids",arrayToString(gids));
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
//http://vk.com/developers.php?oid=-1&p=newsfeed.deleteBan
public Boolean deleteBan(Collection<Long> uids, Collection<Long> gids) throws MalformedURLException, IOException, JSONException, KException {
Params params = new Params("newsfeed.deleteBan");
if (uids != null && uids.size() > 0)
params.put("uids",arrayToString(uids));
if (gids != null && gids.size() > 0)
params.put("gids",arrayToString(gids));
JSONObject root = sendRequest(params);
int response = root.optInt("response");
return response==1;
}
} | audioGetBroadcast() method
| AndroidVkSdk/src/com/perm/kate/api/Api.java | audioGetBroadcast() method |
|
Java | mit | 52eee45e1052a0716591dff9fa67466175510aaa | 0 | homelinen/ld23-Tiny-World | package com.calumgilchrist.ld23.tinyworld.core;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.World;
public class Planetoid {
private Sprite sprite;
private Body pBody;
private Vec2 pos;
public Planetoid(Vec2 startPos, Sprite s, BodyDef bodyDef, World world){
//TODO: Need an initial mass
this.pos = startPos;
this.sprite = s;
this.pBody = world.createBody(bodyDef);
}
/**
* Apply force to the center of the planetoid
* @param force
*/
public void applyThrust(Vec2 force) {
force = force.mul(1/Constants.PHYS_RATIO);
this.getBody().applyForce(force, this.getBody().getWorldCenter());
}
public Sprite getSprite(){
return sprite;
}
public Vec2 getPos() {
return pos;
}
public void setPos(Vec2 pos) {
this.pos = pos;
}
public Body getBody() {
return this.pBody;
}
}
| core/src/main/java/com/calumgilchrist/ld23/tinyworld/core/Planetoid.java | package com.calumgilchrist.ld23.tinyworld.core;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.World;
public class Planetoid {
private Sprite sprite;
private Body pBody;
private Vec2 pos;
public Planetoid(Vec2 startPos, Sprite s, BodyDef bodyDef, World world){
//TODO: Need an initial mass
this.pos = startPos;
this.sprite = s;
this.pBody = world.createBody(bodyDef);
}
public Sprite getSprite(){
return sprite;
}
public Vec2 getPos() {
return pos;
}
public void setPos(Vec2 pos) {
this.pos = pos;
}
public Body getBody() {
return this.pBody;
}
}
| Moved Apply Thrust from Player to Planetoid
| core/src/main/java/com/calumgilchrist/ld23/tinyworld/core/Planetoid.java | Moved Apply Thrust from Player to Planetoid |
|
Java | epl-1.0 | c86411cf1dd02c93ab31ccdce7bd3c74039adebf | 0 | lastnpe/eclipse-external-annotations-m2e-plugin | package ch.sla.eeaplugin.core.configurator;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Plugin;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.m2e.core.project.IMavenProjectFacade;
import org.eclipse.m2e.core.project.MavenProjectChangedEvent;
import org.eclipse.m2e.core.project.configurator.AbstractProjectConfigurator;
import org.eclipse.m2e.core.project.configurator.ProjectConfigurationRequest;
import org.eclipse.m2e.jdt.IClasspathDescriptor;
import org.eclipse.m2e.jdt.IClasspathEntryDescriptor;
import org.eclipse.m2e.jdt.IJavaProjectConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* M2E Project configurator to set external null annotations.
*
* @author Sylvain LAURENT - original impl: Single EEA for all containers
* @author Michael Vorburger - support multiple individual EEA JARs, per M2E
* entry and JRE; plus set compiler properties from POM
*/
public class ClasspathConfigurator extends AbstractProjectConfigurator implements IJavaProjectConfigurator {
private static final Pattern NEWLINE_REGEXP = Pattern.compile("\\n");
private static final String JRE_CONTAINER = "org.eclipse.jdt.launching.JRE_CONTAINER";
private static final MavenGAV JAVA_GAV = MavenGAV.of("java", "java");
private static final String EEA_FOR_GAV_FILENAME = "eea-for-gav";
private static final String M2E_JDT_ANNOTATIONPATH = "m2e.jdt.annotationpath";
private final static Logger LOGGER = LoggerFactory.getLogger(ClasspathConfigurator.class);
@Override
public void configureClasspath(IMavenProjectFacade mavenProjectFacade, IClasspathDescriptor classpath,
IProgressMonitor monitor) throws CoreException {
List<IPath> classpathEntryPaths = classpath.getEntryDescriptors().stream().map(cpEntry -> cpEntry.getPath()).collect(Collectors.toList());
Map<MavenGAV, IPath> mapping = getExternalAnnotationMapping(classpathEntryPaths);
for (IClasspathEntryDescriptor cpEntry : classpath.getEntryDescriptors()) {
mapping.entrySet().stream()
.filter(e -> e.getKey().matches(cpEntry.getArtifactKey())).findFirst()
.ifPresent(e -> {
setExternalAnnotationsPath(cpEntry, e.getValue().toString());
});
}
// Do *NOT* configure the JRE's EEA here, but in configureRawClasspath(),
// because it's the wrong time for M2E (and will break project import,
// when the IProject doesn't fully exist in JDT yet at this stage).
}
private void setExternalAnnotationsPath(IClasspathEntryDescriptor cpEntry, String path) {
cpEntry.setClasspathAttribute("annotationpath", path);
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Setting External Annotations of {} to {}", toString(cpEntry), path);
}
}
private Map<MavenGAV, IPath> getExternalAnnotationMapping(List<IPath> classpathEntryPaths) {
Map<MavenGAV, IPath> mapping = new HashMap<>();
for (IPath cpEntryPath : classpathEntryPaths) {
Optional<File> optionalFileOrDirectory = toFile(cpEntryPath);
optionalFileOrDirectory.ifPresent(fileOrDirectory -> {
getExternalAnnotationMapping(fileOrDirectory).forEach(gav -> mapping.put(gav, cpEntryPath));
});
}
return mapping;
}
private List<MavenGAV> getExternalAnnotationMapping(File dependency) {
List<String> gavLines = readLines(dependency, EEA_FOR_GAV_FILENAME);
List<MavenGAV> result = new ArrayList<>(gavLines.size());
gavLines.forEach(line -> {
try {
MavenGAV gav = MavenGAV.parse(line);
LOGGER.info("Found EEA for {} in {}", gav, dependency);
result.add(gav);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Bad line in " + EEA_FOR_GAV_FILENAME + " of " + dependency + ": " + line, e);
}
});
return result;
}
private List<String> readLines(File fileOrDirectory, String fileName) {
Optional<String> fileContent = read(fileOrDirectory, fileName);
if (fileContent.isPresent()) {
return readLines(fileContent.get());
} else {
return Collections.emptyList();
}
}
private Optional<File> toFile(IPath iPath) {
// iPath.toFile() is NOT what we want..
// https://wiki.eclipse.org/FAQ_What_is_the_difference_between_a_path_and_a_location%3F
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
IResource resource = root.findMember(iPath);
if (resource != null) {
IPath location = resource.getLocation();
return Optional.ofNullable(location.toFile());
} else {
// In this case iPath likely was an absolute FS / non-WS path to being with (or a closed project), so try:
return Optional.ofNullable(iPath.toFile());
}
}
/**
* Reads content of a name file from either inside a JAR or a directory
* @param fileOrDirectory either a ZIP/JAR file, or a directory
* @param fileName file to look for in that ZIP/JAR file or directory
* @return content of file, if any
*/
private Optional<String> read(File fileOrDirectory, String fileName) {
if (!fileOrDirectory.exists()) {
LOGGER.error("File does not exist: {}", fileOrDirectory);
return Optional.empty();
}
if (fileOrDirectory.isDirectory()) {
File file = new File(fileOrDirectory, fileName);
return readFile(file.toPath());
} else if (fileOrDirectory.isFile()) {
Path jarFilePath = Paths.get(fileOrDirectory.toURI());
URI jarEntryURI = URI.create("jar:file:" + jarFilePath.toUri().getPath() + "!/" + fileName);
try (FileSystem zipfs = FileSystems.newFileSystem(jarEntryURI, Collections.emptyMap())) {
Path jarEntryPath = Paths.get(jarEntryURI);
return readFile(jarEntryPath);
} catch (IOException e) {
LOGGER.error("IOException from ZipFileSystemProvider for: {}", jarEntryURI, e);
return Optional.empty();
}
} else {
LOGGER.error("File is neither a directory nor a file: {}", fileOrDirectory);
return Optional.empty();
}
}
private Optional<String> readFile(Path path) {
try {
if (Files.exists(path)) {
return Optional.of(new String(Files.readAllBytes(path), Charset.forName("UTF-8")));
} else {
return Optional.empty();
}
} catch (IOException e) {
LOGGER.error("IOException from Files.readAllBytes for: {}", path, e);
return Optional.empty();
}
}
private List<String> readLines(String string) {
return NEWLINE_REGEXP.splitAsStream(string)
.map(t -> t.trim())
.filter(t -> !t.isEmpty())
.filter(t -> !t.startsWith("#"))
.collect(Collectors.toList());
}
@Override
public void configureRawClasspath(ProjectConfigurationRequest request, IClasspathDescriptor classpath,
IProgressMonitor monitor) throws CoreException {
String annotationPath = getSingleProjectWideAnnotationPath(request.getMavenProjectFacade());
if (annotationPath != null && !annotationPath.isEmpty()) {
setContainerClasspathExternalAnnotationsPath(classpath, annotationPath, false);
} else {
// Find the JRE's EEA among the dependencies to set it....
// Note that at this stage of M2E we have to use the Maven project dependencies,
// and cannot rely on the dependencies already being on the IClasspathDescriptor
// (that happens in configureClasspath() not here in configureRawClasspath())
//
final MavenProject mavenProject = request.getMavenProject();
for (Dependency dependency : mavenProject.getDependencies()) {
// Filter by "*-eea" artifactId naming convention, just for performance
if (!dependency.getArtifactId().endsWith("-eea")) {
continue;
}
Artifact artifact = maven.resolve(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(),
dependency.getType(), dependency.getClassifier(), mavenProject.getRemoteArtifactRepositories(),
monitor);
if (artifact != null && artifact.isResolved()) {
final File eeaProjectOrJarFile = artifact.getFile();
if (getExternalAnnotationMapping(eeaProjectOrJarFile).contains(JAVA_GAV)) {
setContainerClasspathExternalAnnotationsPath(classpath, eeaProjectOrJarFile.toString(), true);
return;
}
}
}
}
}
private void setContainerClasspathExternalAnnotationsPath(IClasspathDescriptor classpath, String annotationPath, boolean onlyJRE) {
for (IClasspathEntryDescriptor cpEntry : classpath.getEntryDescriptors()) {
if (cpEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
if (onlyJRE && !cpEntry.getPath().toString().startsWith(JRE_CONTAINER)) {
continue;
}
setExternalAnnotationsPath(cpEntry, annotationPath);
}
}
}
private String getSingleProjectWideAnnotationPath(IMavenProjectFacade mavenProjectFacade) {
if (mavenProjectFacade == null) {
return null;
}
MavenProject mavenProject = mavenProjectFacade.getMavenProject();
if (mavenProject == null) {
return null;
}
Properties properties = mavenProject.getProperties();
if (properties == null) {
return null;
}
String property = properties.getProperty(M2E_JDT_ANNOTATIONPATH);
if (property == null) {
return null;
} else {
return property.trim();
}
}
/**
* Configure Project's JDT Compiler Properties. First attempts to read
* a file named "org.eclipse.jdt.core.prefs" stored in a dependency of the
* maven-compiler-plugin. If none found, copy the properties read from the
* maven-compiler-plugin configuration compilerArguments properties.
*
* <p>The reason we support (and give preference to) a dependency over the
* properties from the compilerArguments configuration is that the latter
* requires the file to be at the given location, which it may not (yet) be;
* for the build this is typically based e.g. on a maven-dependency-plugin
* unpack - which may not have run, yet.
*/
@Override
public void configure(ProjectConfigurationRequest projectConfigurationRequest, IProgressMonitor monitor) throws CoreException {
final MavenProject mavenProject = projectConfigurationRequest.getMavenProject();
final Plugin plugin = mavenProject.getPlugin("org.apache.maven.plugins:maven-compiler-plugin");
if (plugin == null) {
return;
}
for (Dependency dependency : plugin.getDependencies()) {
if ("tycho-compiler-jdt".equals(dependency.getArtifactId())) {
continue;
}
Artifact artifact = maven.resolve(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(),
dependency.getType(), dependency.getClassifier(), mavenProject.getRemoteArtifactRepositories(),
monitor);
if (artifact != null && artifact.isResolved()) {
Optional<String> optionalPropertiesAsText = read(artifact.getFile(), "org.eclipse.jdt.core.prefs");
optionalPropertiesAsText.ifPresent(propertiesAsText -> {
Properties configurationCompilerArgumentsProperties = new Properties();
try {
configurationCompilerArgumentsProperties.load(new StringReader(propertiesAsText));
configureProjectFromProperties(projectConfigurationRequest.getProject(), configurationCompilerArgumentsProperties);
return;
} catch (IOException e) {
LOGGER.error("IOException while reading properties: {}", propertiesAsText, e);
}
});
}
}
if (!(plugin.getConfiguration() instanceof Xpp3Dom)) {
return;
}
Xpp3Dom configurationDom = (Xpp3Dom) plugin.getConfiguration();
if (configurationDom == null) {
return;
}
Xpp3Dom compilerArgumentsDom = configurationDom.getChild("compilerArguments");
if (compilerArgumentsDom == null) {
return;
}
Xpp3Dom propertiesDom = compilerArgumentsDom.getChild("properties");
String configurationCompilerArgumentsPropertiesPath = propertiesDom.getValue();
if (configurationCompilerArgumentsPropertiesPath == null) {
return;
}
File configurationCompilerArgumentsFile = new File(configurationCompilerArgumentsPropertiesPath);
if (!configurationCompilerArgumentsFile.exists()) {
return;
}
if (configurationCompilerArgumentsFile.getPath().replace('\\', '/').contains("/.settings/")) {
return;
}
try (FileInputStream inputStream = new FileInputStream(configurationCompilerArgumentsFile)) {
Properties configurationCompilerArgumentsProperties = new Properties();
configurationCompilerArgumentsProperties.load(inputStream);
configureProjectFromProperties(projectConfigurationRequest.getProject(), configurationCompilerArgumentsProperties);
return;
} catch (IOException e) {
LOGGER.error("IOException while reading file: {}", configurationCompilerArgumentsFile, e);
}
}
private void configureProjectFromProperties(IProject project, Properties configurationCompilerArgumentsProperties) {
if (configurationCompilerArgumentsProperties.isEmpty()) {
return;
}
IJavaProject javaProject = JavaCore.create(project);
if (javaProject == null) {
return;
}
javaProject.setOptions(fromProperties(configurationCompilerArgumentsProperties));
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private Map<String, String> fromProperties(Properties properties) {
Map configurationCompilerArgumentsPropertiesAsMap = properties;
Map<String, String> map = new HashMap<String, String>(configurationCompilerArgumentsPropertiesAsMap);
return map;
}
@Override
public void mavenProjectChanged(MavenProjectChangedEvent event, IProgressMonitor monitor) throws CoreException {
String newAnnotationpath = getSingleProjectWideAnnotationPath(event.getMavenProject());
String oldAnnotationpath = getSingleProjectWideAnnotationPath(event.getOldMavenProject());
if (newAnnotationpath == oldAnnotationpath
|| newAnnotationpath != null && newAnnotationpath.equals(oldAnnotationpath)) {
return;
}
// TODO : warn the user that the config should be updated in full
}
private String toString(IClasspathEntryDescriptor entry) {
StringBuilder sb = new StringBuilder("IClasspathEntryDescriptor[");
if (entry.getArtifactKey() != null) {
sb.append(entry.getArtifactKey().toString()).append(" - ");
}
sb.append(entry.getEntryKind());
sb.append(": ");
sb.append(entry.getPath());
sb.append("]");
return sb.toString();
}
}
| eclipse-external-annotations-m2e-plugin.core/src/ch/sla/eeaplugin/core/configurator/ClasspathConfigurator.java | package ch.sla.eeaplugin.core.configurator;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Plugin;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.m2e.core.project.IMavenProjectFacade;
import org.eclipse.m2e.core.project.MavenProjectChangedEvent;
import org.eclipse.m2e.core.project.configurator.AbstractProjectConfigurator;
import org.eclipse.m2e.core.project.configurator.ProjectConfigurationRequest;
import org.eclipse.m2e.jdt.IClasspathDescriptor;
import org.eclipse.m2e.jdt.IClasspathEntryDescriptor;
import org.eclipse.m2e.jdt.IJavaProjectConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* M2E Project configurator to set external null annotations.
*
* @author Sylvain LAURENT - original impl: Single EEA for all containers
* @author Michael Vorburger - support multiple individual EEA JARs, per M2E
* entry and JRE; plus set compiler properties from POM
*/
public class ClasspathConfigurator extends AbstractProjectConfigurator implements IJavaProjectConfigurator {
/**
*
*/
private static final Pattern NEWLINE_REGEXP = Pattern.compile("\\n");
private static final MavenGAV JAVA_GAV = MavenGAV.of("java", "java");
private static final String EEA_FOR_GAV_FILENAME = "eea-for-gav";
private static final String M2E_JDT_ANNOTATIONPATH = "m2e.jdt.annotationpath";
private final static Logger LOGGER = LoggerFactory.getLogger(ClasspathConfigurator.class);
@Override
public void configureClasspath(IMavenProjectFacade mavenProjectFacade, IClasspathDescriptor classpath,
IProgressMonitor monitor) throws CoreException {
dump("configureClasspath", classpath);
List<IPath> classpathEntryPaths = classpath.getEntryDescriptors().stream().map(cpEntry -> cpEntry.getPath()).collect(Collectors.toList());
Map<MavenGAV, IPath> mapping = getExternalAnnotationMapping(classpathEntryPaths);
for (IClasspathEntryDescriptor cpEntry : classpath.getEntryDescriptors()) {
mapping.entrySet().stream()
.filter(e -> e.getKey().matches(cpEntry.getArtifactKey())).findFirst()
.ifPresent(e -> {
setExternalAnnotationsPath(cpEntry, e.getValue().toString());
});
}
setJREsEEA(mapping, mavenProjectFacade.getProject());
}
private void setJREsEEA(Map<MavenGAV, IPath> mapping, IProject project) throws CoreException {
IPath javaEEAPath = mapping.get(JAVA_GAV);
if (javaEEAPath != null) {
// TODO This does not actually work (because RuntimeClasspathEntry.updateClasspathEntry() does nothing for container, only Archive & Variable
JavaRuntime.computeJREEntry(JavaCore.create(project)).setExternalAnnotationsPath(javaEEAPath);
LOGGER.info("Setting External Annotations of JRE to {}", javaEEAPath);
}
}
private void setExternalAnnotationsPath(IClasspathEntryDescriptor cpEntry, String path) {
cpEntry.setClasspathAttribute("annotationpath", path);
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Setting External Annotations of {} to {}", toString(cpEntry), path);
}
}
private Map<MavenGAV, IPath> getExternalAnnotationMapping(List<IPath> classpathEntryPaths) {
Map<MavenGAV, IPath> mapping = new HashMap<>();
for (IPath cpEntryPath : classpathEntryPaths) {
List<String> gavLines = getPath(cpEntryPath, EEA_FOR_GAV_FILENAME);
gavLines.forEach(line -> {
try {
MavenGAV gav = MavenGAV.parse(line);
LOGGER.info("Found EEA for {} in {}", gav, cpEntryPath);
mapping.put(gav, cpEntryPath);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Bad line in " + EEA_FOR_GAV_FILENAME + " of " + cpEntryPath + ": " + line, e);
}
});
}
return mapping;
}
private List<String> getPath(IPath iPath, String fileName) {
Optional<File> optionalFileOrDirectory = toFile(iPath);
if (!optionalFileOrDirectory.isPresent()) {
return Collections.emptyList();
}
File fileOrDirectory = optionalFileOrDirectory.get();
Optional<String> fileContent = read(fileOrDirectory, fileName);
if (fileContent.isPresent()) {
return readFileLines(fileContent.get());
} else {
return Collections.emptyList();
}
}
private Optional<File> toFile(IPath iPath) {
// iPath.toFile() is NOT what we want..
// https://wiki.eclipse.org/FAQ_What_is_the_difference_between_a_path_and_a_location%3F
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
IResource resource = root.findMember(iPath);
if (resource != null) {
IPath location = resource.getLocation();
return Optional.ofNullable(location.toFile());
} else {
// In this case iPath likely was an absolute FS / non-WS path to being with (or a closed project), so try:
return Optional.ofNullable(iPath.toFile());
}
}
/**
* Reads content of a name file from either inside a JAR or a directory
* @param fileOrDirectory either a ZIP/JAR file, or a directory
* @param fileName file to look for in that ZIP/JAR file or directory
* @return content of file, if any
*/
private Optional<String> read(File fileOrDirectory, String fileName) {
if (!fileOrDirectory.exists()) {
LOGGER.error("File does not exist: {}", fileOrDirectory);
return Optional.empty();
}
if (fileOrDirectory.isDirectory()) {
File file = new File(fileOrDirectory, fileName);
return readFile(file.toPath());
} else if (fileOrDirectory.isFile()) {
Path jarFilePath = Paths.get(fileOrDirectory.toURI());
URI jarEntryURI = URI.create("jar:file:" + jarFilePath.toUri().getPath() + "!/" + fileName);
try (FileSystem zipfs = FileSystems.newFileSystem(jarEntryURI, Collections.emptyMap())) {
Path jarEntryPath = Paths.get(jarEntryURI);
return readFile(jarEntryPath);
} catch (IOException e) {
LOGGER.error("IOException from ZipFileSystemProvider for: {}", jarEntryURI, e);
return Optional.empty();
}
} else {
LOGGER.error("File is neither a directory nor a file: {}", fileOrDirectory);
return Optional.empty();
}
}
private Optional<String> readFile(Path path) {
try {
if (Files.exists(path)) {
return Optional.of(new String(Files.readAllBytes(path), Charset.forName("UTF-8")));
} else {
return Optional.empty();
}
} catch (IOException e) {
LOGGER.error("IOException from Files.readAllBytes for: {}", path, e);
return Optional.empty();
}
}
private List<String> readFileLines(String string) {
return NEWLINE_REGEXP.splitAsStream(string)
.map(t -> t.trim())
.filter(t -> !t.isEmpty())
.filter(t -> !t.startsWith("#"))
.collect(Collectors.toList());
}
@Override
public void configureRawClasspath(ProjectConfigurationRequest request, IClasspathDescriptor classpath,
IProgressMonitor monitor) throws CoreException {
dump("configureRawClasspath", classpath);
String annotationPath = getAnnotationPath(request.getMavenProjectFacade());
if (annotationPath != null && !annotationPath.isEmpty()) {
for (IClasspathEntryDescriptor cpEntry : classpath.getEntryDescriptors()) {
if (cpEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
setExternalAnnotationsPath(cpEntry, annotationPath);
}
}
} else {
IProject iProject = request.getProject();
// Note that we must use computeDefaultRuntimeClassPath() instead of
// classpath.getEntryDescriptors() here, because in this configureRawClasspath(),
// contrary to configureClasspath(), we get the JRE & M2E Container, not entries
// (but to have the java:java EEA we need all entries)
List<IRuntimeClasspathEntry> allEntries = computeDefaultRuntimeClassPath(iProject);
List<IPath> classpathEntryPaths = allEntries.stream().map(cpEntry -> cpEntry.getPath()).collect(Collectors.toList());
Map<MavenGAV, IPath> mapping = getExternalAnnotationMapping(classpathEntryPaths);
// TODO if setJREsEEA worked we could do:
// setJREsEEA(mapping, iProject);
// but for now let's just:
IPath javaEEAPath = mapping.get(JAVA_GAV);
if (javaEEAPath != null) {
for (IClasspathEntryDescriptor cpEntry : classpath.getEntryDescriptors()) {
if (cpEntry.getPath().toString().startsWith("org.eclipse.jdt.launching.JRE_CONTAINER")) {
setExternalAnnotationsPath(cpEntry, javaEEAPath.toString());
}
}
}
}
}
private List<IRuntimeClasspathEntry> computeDefaultRuntimeClassPath(IProject project) throws CoreException {
IJavaProject jProject = JavaCore.create(project);
if (jProject == null) {
Collections.emptyList();
}
// strongly inspired by org.eclipse.jdt.launching.JavaRuntime.computeDefaultRuntimeClassPath(IJavaProject)
IRuntimeClasspathEntry[] unresolved = JavaRuntime.computeUnresolvedRuntimeClasspath(jProject);
List<IRuntimeClasspathEntry> resolved = new ArrayList<>(unresolved.length);
for (IRuntimeClasspathEntry entry : unresolved) {
if (entry.getClasspathProperty() == IRuntimeClasspathEntry.USER_CLASSES) {
IRuntimeClasspathEntry[] entries = JavaRuntime.resolveRuntimeClasspathEntry(entry, jProject);
for (IRuntimeClasspathEntry entrie : entries) {
resolved.add(entrie);
}
}
}
return resolved;
}
private String getAnnotationPath(IMavenProjectFacade mavenProjectFacade) {
if (mavenProjectFacade == null) {
return null;
}
MavenProject mavenProject = mavenProjectFacade.getMavenProject();
if (mavenProject == null) {
return null;
}
Properties properties = mavenProject.getProperties();
if (properties == null) {
return null;
}
String property = properties.getProperty(M2E_JDT_ANNOTATIONPATH);
if (property == null) {
return null;
} else {
return property.trim();
}
}
/**
* Configure Project's JDT Compiler Properties. First attempts to read
* a file named "org.eclipse.jdt.core.prefs" stored in a dependency of the
* maven-compiler-plugin. If none found, copy the properties read from the
* maven-compiler-plugin configuration compilerArguments properties.
*
* <p>The reason we support (and give preference to) a dependency over the
* properties from the compilerArguments configuration is that the latter
* requires the file to be at the given location, which it may not (yet) be;
* for the build this is typically based e.g. on a maven-dependency-plugin
* unpack - which may not have run, yet.
*/
@Override
public void configure(ProjectConfigurationRequest projectConfigurationRequest, IProgressMonitor monitor) throws CoreException {
final MavenProject mavenProject = projectConfigurationRequest.getMavenProject();
final Plugin plugin = mavenProject.getPlugin("org.apache.maven.plugins:maven-compiler-plugin");
if (plugin == null) {
return;
}
for (Dependency dependency : plugin.getDependencies()) {
if ("tycho-compiler-jdt".equals(dependency.getArtifactId())) {
continue;
}
Artifact artifact = maven.resolve(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(),
dependency.getType(), dependency.getClassifier(), mavenProject.getRemoteArtifactRepositories(),
monitor);
if (artifact != null && artifact.isResolved()) {
Optional<String> optionalPropertiesAsText = read(artifact.getFile(), "org.eclipse.jdt.core.prefs");
optionalPropertiesAsText.ifPresent(propertiesAsText -> {
Properties configurationCompilerArgumentsProperties = new Properties();
try {
configurationCompilerArgumentsProperties.load(new StringReader(propertiesAsText));
configureProjectFromProperties(projectConfigurationRequest.getProject(), configurationCompilerArgumentsProperties);
return;
} catch (IOException e) {
LOGGER.error("IOException while reading properties: {}", propertiesAsText, e);
}
});
}
}
if (!(plugin.getConfiguration() instanceof Xpp3Dom)) {
return;
}
Xpp3Dom configurationDom = (Xpp3Dom) plugin.getConfiguration();
if (configurationDom == null) {
return;
}
Xpp3Dom compilerArgumentsDom = configurationDom.getChild("compilerArguments");
if (compilerArgumentsDom == null) {
return;
}
Xpp3Dom propertiesDom = compilerArgumentsDom.getChild("properties");
String configurationCompilerArgumentsPropertiesPath = propertiesDom.getValue();
if (configurationCompilerArgumentsPropertiesPath == null) {
return;
}
File configurationCompilerArgumentsFile = new File(configurationCompilerArgumentsPropertiesPath);
if (!configurationCompilerArgumentsFile.exists()) {
return;
}
if (configurationCompilerArgumentsFile.getPath().replace('\\', '/').contains("/.settings/")) {
return;
}
try (FileInputStream inputStream = new FileInputStream(configurationCompilerArgumentsFile)) {
Properties configurationCompilerArgumentsProperties = new Properties();
configurationCompilerArgumentsProperties.load(inputStream);
configureProjectFromProperties(projectConfigurationRequest.getProject(), configurationCompilerArgumentsProperties);
return;
} catch (IOException e) {
LOGGER.error("IOException while reading file: {}", configurationCompilerArgumentsFile, e);
}
}
private void configureProjectFromProperties(IProject project, Properties configurationCompilerArgumentsProperties) {
if (configurationCompilerArgumentsProperties.isEmpty()) {
return;
}
IJavaProject javaProject = JavaCore.create(project);
if (javaProject == null) {
return;
}
javaProject.setOptions(fromProperties(configurationCompilerArgumentsProperties));
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private Map<String, String> fromProperties(Properties properties) {
Map configurationCompilerArgumentsPropertiesAsMap = properties;
Map<String, String> map = new HashMap<String, String>(configurationCompilerArgumentsPropertiesAsMap);
return map;
}
@Override
public void mavenProjectChanged(MavenProjectChangedEvent event, IProgressMonitor monitor) throws CoreException {
String newAnnotationpath = getAnnotationPath(event.getMavenProject());
String oldAnnotationpath = getAnnotationPath(event.getOldMavenProject());
if (newAnnotationpath == oldAnnotationpath
|| newAnnotationpath != null && newAnnotationpath.equals(oldAnnotationpath)) {
return;
}
// TODO : warn the user that the config should be updated in full
}
private void dump(String methodName, IClasspathDescriptor classpath) {
if (LOGGER.isDebugEnabled()) {
for (IClasspathEntryDescriptor entry : classpath.getEntryDescriptors()) {
LOGGER.debug("{}: {} ", methodName, toString(entry));
}
}
}
private String toString(IClasspathEntryDescriptor entry) {
StringBuilder sb = new StringBuilder("IClasspathEntryDescriptor[");
if (entry.getArtifactKey() != null) {
sb.append(entry.getArtifactKey().toString()).append(" - ");
}
sb.append(entry.getEntryKind());
sb.append(": ");
sb.append(entry.getPath());
sb.append("]");
return sb.toString();
}
}
| Major bug fix, big refactoring.. JRE EEA works well now!
Signed-off-by: Michael Vorburger <[email protected]> | eclipse-external-annotations-m2e-plugin.core/src/ch/sla/eeaplugin/core/configurator/ClasspathConfigurator.java | Major bug fix, big refactoring.. JRE EEA works well now! |
|
Java | epl-1.0 | b3224b1372be2906b2332c329123adfaeadda854 | 0 | dbadia/openhab,kuijp/openhab,druciak/openhab,mvolaart/openhab,gerrieg/openhab,TheOriginalAndrobot/openhab,coolweb/openhab,idserda/openhab,TheOriginalAndrobot/openhab,rmayr/openhab,netwolfuk/openhab,evansj/openhab,idserda/openhab,robnielsen/openhab,dbadia/openhab,openhab/openhab,dominicdesu/openhab,LaurensVanAcker/openhab,svenschreier/openhab,ivanfmartinez/openhab,querdenker2k/openhab,seebag/openhab,hemantsangwan/openhab,lewie/openhab,coolweb/openhab,rmayr/openhab,Mixajlo/openhab,joek/openhab1-addons,steintore/openhab,berndpfrommer/openhab,revenz/openhab,docbender/openhab,RafalLukawiecki/openhab1-addons,CrackerStealth/openhab,docbender/openhab,ivanfmartinez/openhab,ssalonen/openhab,dvanherbergen/openhab,aruder77/openhab,hmerk/openhab,RafalLukawiecki/openhab1-addons,revenz/openhab,openhab/openhab,svenschaefer74/openhab,steintore/openhab,druciak/openhab,wuellueb/openhab,cdjackson/openhab,coolweb/openhab,mvolaart/openhab,doubled-ca/openhab1-addons,seebag/openhab,TheOriginalAndrobot/openhab,netwolfuk/openhab,dvanherbergen/openhab,sibbi77/openhab,ssalonen/openhab,berndpfrommer/openhab,andreasgebauer/openhab,TheNetStriker/openhab,wep4you/openhab,dominicdesu/openhab,gerrieg/openhab,wep4you/openhab,TheNetStriker/openhab,savageautomate/openhab,savageautomate/openhab,dominicdesu/openhab,sibbi77/openhab,RafalLukawiecki/openhab1-addons,computergeek1507/openhab,cdjackson/openhab,basriram/openhab,docbender/openhab,bbesser/openhab1-addons,watou/openhab,sedstef/openhab,TheOriginalAndrobot/openhab,computergeek1507/openhab,aruder77/openhab,svenschaefer74/openhab,dvanherbergen/openhab,querdenker2k/openhab,dominicdesu/openhab,sytone/openhab,svenschreier/openhab,basriram/openhab,hemantsangwan/openhab,dominicdesu/openhab,netwolfuk/openhab,svenschreier/openhab,vgoldman/openhab,juri8/openhab,juri8/openhab,robnielsen/openhab,vgoldman/openhab,CrackerStealth/openhab,bbesser/openhab1-addons,QuailAutomation/openhab,sedstef/openhab,TheOriginalAndrobot/openhab,lewie/openhab,sumnerboy12/openhab,tomtrath/openhab,netwolfuk/openhab,seebag/openhab,beowulfe/openhab,druciak/openhab,cvanorman/openhab,tomtrath/openhab,andreasgebauer/openhab,ivanfmartinez/openhab,dbadia/openhab,Snickermicker/openhab,sytone/openhab,Snickermicker/openhab,wuellueb/openhab,theoweiss/openhab,beowulfe/openhab,LaurensVanAcker/openhab,QuailAutomation/openhab,theoweiss/openhab,kaikreuzer/openhab,mvolaart/openhab,bbesser/openhab1-addons,revenz/openhab,idserda/openhab,ivanfmartinez/openhab,lewie/openhab,tomtrath/openhab,dbadia/openhab,savageautomate/openhab,beowulfe/openhab,jowiho/openhab,frami/openhab,kaikreuzer/openhab,bbesser/openhab1-addons,Mixajlo/openhab,doubled-ca/openhab1-addons,tomtrath/openhab,svenschreier/openhab,evansj/openhab,kuijp/openhab,savageautomate/openhab,basriram/openhab,berndpfrommer/openhab,hemantsangwan/openhab,svenschaefer74/openhab,revenz/openhab,mvolaart/openhab,coolweb/openhab,querdenker2k/openhab,netwolfuk/openhab,rmayr/openhab,kreutpet/openhab,kuijp/openhab,openhab/openhab,TheNetStriker/openhab,hemantsangwan/openhab,robnielsen/openhab,dmize/openhab,lewie/openhab,LaurensVanAcker/openhab,juri8/openhab,aruder77/openhab,tomtrath/openhab,evansj/openhab,sytone/openhab,computergeek1507/openhab,TheNetStriker/openhab,querdenker2k/openhab,ssalonen/openhab,juri8/openhab,QuailAutomation/openhab,dmize/openhab,aschor/openhab,watou/openhab,aschor/openhab,Mixajlo/openhab,beowulfe/openhab,lewie/openhab,TheNetStriker/openhab,berndpfrommer/openhab,joek/openhab1-addons,sedstef/openhab,rmayr/openhab,kuijp/openhab,ivanfmartinez/openhab,gerrieg/openhab,aschor/openhab,LaurensVanAcker/openhab,docbender/openhab,seebag/openhab,Snickermicker/openhab,Mixajlo/openhab,berndpfrommer/openhab,steintore/openhab,CrackerStealth/openhab,dvanherbergen/openhab,lewie/openhab,hmerk/openhab,CrackerStealth/openhab,sumnerboy12/openhab,QuailAutomation/openhab,dmize/openhab,tomtrath/openhab,jowiho/openhab,andreasgebauer/openhab,juri8/openhab,aruder77/openhab,computergeek1507/openhab,andreasgebauer/openhab,dmize/openhab,idserda/openhab,andreasgebauer/openhab,docbender/openhab,RafalLukawiecki/openhab1-addons,ollie-dev/openhab,steintore/openhab,vgoldman/openhab,ollie-dev/openhab,mvolaart/openhab,watou/openhab,wep4you/openhab,svenschaefer74/openhab,aschor/openhab,falkena/openhab,TheNetStriker/openhab,cdjackson/openhab,revenz/openhab,bbesser/openhab1-addons,Snickermicker/openhab,kaikreuzer/openhab,CrackerStealth/openhab,joek/openhab1-addons,hmerk/openhab,doubled-ca/openhab1-addons,falkena/openhab,druciak/openhab,seebag/openhab,cvanorman/openhab,ssalonen/openhab,evansj/openhab,bbesser/openhab1-addons,kuijp/openhab,mvolaart/openhab,rmayr/openhab,wuellueb/openhab,Mixajlo/openhab,dbadia/openhab,openhab/openhab,frami/openhab,doubled-ca/openhab1-addons,aruder77/openhab,vgoldman/openhab,sumnerboy12/openhab,cdjackson/openhab,sumnerboy12/openhab,robnielsen/openhab,theoweiss/openhab,jowiho/openhab,wep4you/openhab,beowulfe/openhab,dominicdesu/openhab,doubled-ca/openhab1-addons,RafalLukawiecki/openhab1-addons,sumnerboy12/openhab,cvanorman/openhab,dvanherbergen/openhab,sibbi77/openhab,falkena/openhab,kreutpet/openhab,joek/openhab1-addons,robnielsen/openhab,hemantsangwan/openhab,beowulfe/openhab,docbender/openhab,rmayr/openhab,hmerk/openhab,ssalonen/openhab,dvanherbergen/openhab,robnielsen/openhab,wuellueb/openhab,joek/openhab1-addons,revenz/openhab,cdjackson/openhab,gerrieg/openhab,kreutpet/openhab,hemantsangwan/openhab,RafalLukawiecki/openhab1-addons,netwolfuk/openhab,jowiho/openhab,falkena/openhab,savageautomate/openhab,revenz/openhab,coolweb/openhab,sumnerboy12/openhab,watou/openhab,vgoldman/openhab,falkena/openhab,sibbi77/openhab,sedstef/openhab,computergeek1507/openhab,cvanorman/openhab,druciak/openhab,gerrieg/openhab,svenschaefer74/openhab,andreasgebauer/openhab,openhab/openhab,svenschaefer74/openhab,basriram/openhab,doubled-ca/openhab1-addons,coolweb/openhab,idserda/openhab,aruder77/openhab,evansj/openhab,theoweiss/openhab,basriram/openhab,frami/openhab,kaikreuzer/openhab,coolweb/openhab,hmerk/openhab,theoweiss/openhab,cvanorman/openhab,steintore/openhab,hemantsangwan/openhab,ollie-dev/openhab,QuailAutomation/openhab,falkena/openhab,basriram/openhab,kreutpet/openhab,TheNetStriker/openhab,kuijp/openhab,ssalonen/openhab,jowiho/openhab,tomtrath/openhab,gerrieg/openhab,sytone/openhab,kreutpet/openhab,frami/openhab,watou/openhab,aschor/openhab,kaikreuzer/openhab,jowiho/openhab,idserda/openhab,cvanorman/openhab,savageautomate/openhab,falkena/openhab,aschor/openhab,evansj/openhab,vgoldman/openhab,andreasgebauer/openhab,querdenker2k/openhab,frami/openhab,Snickermicker/openhab,ollie-dev/openhab,cdjackson/openhab,watou/openhab,LaurensVanAcker/openhab,svenschreier/openhab,sibbi77/openhab,docbender/openhab,ollie-dev/openhab,lewie/openhab,juri8/openhab,seebag/openhab,berndpfrommer/openhab,hmerk/openhab,LaurensVanAcker/openhab,wep4you/openhab,svenschreier/openhab,watou/openhab,querdenker2k/openhab,frami/openhab,dbadia/openhab,kreutpet/openhab,druciak/openhab,sytone/openhab,tomtrath/openhab,sedstef/openhab,QuailAutomation/openhab,ivanfmartinez/openhab,TheOriginalAndrobot/openhab,theoweiss/openhab,wuellueb/openhab,steintore/openhab,wep4you/openhab,joek/openhab1-addons,computergeek1507/openhab,dmize/openhab,sibbi77/openhab,sedstef/openhab,wuellueb/openhab,Mixajlo/openhab,openhab/openhab,Snickermicker/openhab,ollie-dev/openhab,CrackerStealth/openhab,juri8/openhab,dmize/openhab,kaikreuzer/openhab,sytone/openhab | /**
* Copyright (c) 2010-2016, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.ecobee.internal;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.prefs.Preferences;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.openhab.binding.ecobee.EcobeeActionProvider;
import org.openhab.binding.ecobee.EcobeeBindingProvider;
import org.openhab.binding.ecobee.messages.AbstractFunction;
import org.openhab.binding.ecobee.messages.AbstractRequest;
import org.openhab.binding.ecobee.messages.ApiResponse;
import org.openhab.binding.ecobee.messages.AuthorizeRequest;
import org.openhab.binding.ecobee.messages.AuthorizeResponse;
import org.openhab.binding.ecobee.messages.RefreshTokenRequest;
import org.openhab.binding.ecobee.messages.Request;
import org.openhab.binding.ecobee.messages.Selection;
import org.openhab.binding.ecobee.messages.Selection.SelectionType;
import org.openhab.binding.ecobee.messages.Status;
import org.openhab.binding.ecobee.messages.Temperature;
import org.openhab.binding.ecobee.messages.Thermostat;
import org.openhab.binding.ecobee.messages.Thermostat.HvacMode;
import org.openhab.binding.ecobee.messages.Thermostat.VentilatorMode;
import org.openhab.binding.ecobee.messages.ThermostatRequest;
import org.openhab.binding.ecobee.messages.ThermostatResponse;
import org.openhab.binding.ecobee.messages.ThermostatSummaryRequest;
import org.openhab.binding.ecobee.messages.ThermostatSummaryResponse;
import org.openhab.binding.ecobee.messages.ThermostatSummaryResponse.Revision;
import org.openhab.binding.ecobee.messages.TokenRequest;
import org.openhab.binding.ecobee.messages.TokenResponse;
import org.openhab.binding.ecobee.messages.UpdateThermostatRequest;
import org.openhab.core.binding.AbstractActiveBinding;
import org.openhab.core.binding.BindingProvider;
import org.openhab.core.library.types.DateTimeType;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.openhab.core.types.UnDefType;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Binding that retrieves information about thermostats we're interested in every few minutes, and sends updates and
* commands to Ecobee as they are made. Reviewed lots of other binding implementations, particularly Netatmo and XBMC.
*
* @author John Cocula
* @since 1.7.0
*/
public class EcobeeBinding extends AbstractActiveBinding<EcobeeBindingProvider>
implements ManagedService, EcobeeActionProvider {
private static final String DEFAULT_USER_ID = "DEFAULT_USER";
private static final long DEFAULT_GRANULARITY = 5000;
private static final long DEFAULT_REFRESH = 180000;
private static final long DEFAULT_QUICKPOLL = 6000;
private static final Logger logger = LoggerFactory.getLogger(EcobeeBinding.class);
protected static final String CONFIG_GRANULARITY = "granularity";
protected static final String CONFIG_REFRESH = "refresh";
protected static final String CONFIG_QUICKPOLL = "quickpoll";
protected static final String CONFIG_TIMEOUT = "timeout";
protected static final String CONFIG_APP_KEY = "appkey";
protected static final String CONFIG_SCOPE = "scope";
protected static final String CONFIG_TEMP_SCALE = "tempscale";
static {
// Register bean type converters
ConvertUtils.register(new Converter() {
@SuppressWarnings("rawtypes")
@Override
public Object convert(Class type, Object value) {
if (value instanceof DecimalType) {
return Temperature.fromLocalTemperature(((DecimalType) value).toBigDecimal());
} else {
return null;
}
}
}, Temperature.class);
ConvertUtils.register(new Converter() {
@SuppressWarnings("rawtypes")
@Override
public Object convert(Class type, Object value) {
if (value instanceof StringType) {
return HvacMode.forValue(value.toString());
} else {
return null;
}
}
}, HvacMode.class);
ConvertUtils.register(new Converter() {
@SuppressWarnings("rawtypes")
@Override
public Object convert(Class type, Object value) {
if (value instanceof DecimalType) {
return ((DecimalType) value).intValue();
} else {
return null;
}
}
}, Integer.class);
ConvertUtils.register(new Converter() {
@SuppressWarnings("rawtypes")
@Override
public Object convert(Class type, Object value) {
if (value instanceof StringType) {
return VentilatorMode.forValue(value.toString());
} else {
return null;
}
}
}, VentilatorMode.class);
ConvertUtils.register(new Converter() {
@SuppressWarnings("rawtypes")
@Override
public Object convert(Class type, Object value) {
if (value instanceof OnOffType) {
return ((OnOffType) value) == OnOffType.ON;
} else {
return null;
}
}
}, Boolean.class);
ConvertUtils.register(new Converter() {
@SuppressWarnings("rawtypes")
@Override
public Object convert(Class type, Object value) {
return value.toString();
}
}, String.class);
}
/**
* the interval which is used to call the execute() method
*/
private long granularity = DEFAULT_GRANULARITY;
/**
* the normal refresh interval which is used to poll values from the Ecobee server
*/
private long refreshInterval = DEFAULT_REFRESH;
/**
* the quick refresh interval which is used to poll values from the Ecobee server after a command was sent, a state
* was updated or an action was called
*/
private long quickPollInterval = DEFAULT_QUICKPOLL;
/**
* A map of userids from the openhab.cfg file to OAuth credentials used to communicate with each app instance.
*/
private Map<String, OAuthCredentials> credentialsCache = new HashMap<String, OAuthCredentials>();
/**
* used to store events that we have sent ourselves; we need to remember them for not reacting to them
*/
private static class Update {
private String itemName;
private State state;
Update(final String itemName, final State state) {
this.itemName = itemName;
this.state = state;
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof Update)) {
return false;
}
return (this.itemName == null ? ((Update) o).itemName == null : this.itemName.equals(((Update) o).itemName))
&& (this.state == null ? ((Update) o).state == null : this.state.equals(((Update) o).state));
}
@Override
public int hashCode() {
return (this.itemName == null ? 0 : this.itemName.hashCode())
^ (this.state == null ? 0 : this.state.hashCode());
}
}
private List<Update> ignoreEventList = Collections.synchronizedList(new ArrayList<Update>());
public EcobeeBinding() {
}
/**
* {@inheritDoc}
*/
@Override
public void activate() {
super.activate();
}
/**
* {@inheritDoc}
*/
@Override
public void deactivate() {
// deallocate resources here that are no longer needed and
// should be reset when activating this binding again
}
/**
* {@inheritDoc}
*/
@Override
protected long getRefreshInterval() {
return granularity;
}
/**
* {@inheritDoc}
*/
@Override
protected String getName() {
return "Ecobee Refresh Service";
}
/**
* {@inheritDoc}
*/
@Override
protected void execute() {
try {
for (String userid : credentialsCache.keySet()) {
OAuthCredentials oauthCredentials = getOAuthCredentials(userid);
if (oauthCredentials.pollTimeExpired()) {
// schedule the next poll at the standard refresh interval
oauthCredentials.schedulePoll(this.refreshInterval);
logger.trace("Querying Ecobee API for instance {}", oauthCredentials.userid);
Selection selection = createSelection(oauthCredentials);
if (selection == null) {
logger.debug("Nothing to retrieve for '{}'; skipping thermostat retrieval.",
oauthCredentials.userid);
continue;
}
if (oauthCredentials.noAccessToken()) {
if (!oauthCredentials.refreshTokens()) {
logger.warn("Periodic poll skipped for '{}'.", oauthCredentials.userid);
continue;
}
}
readEcobee(oauthCredentials, selection);
}
}
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.warn("Exception reading from Ecobee:", e);
} else {
logger.warn("Exception reading from Ecobee: {}", e.getMessage());
}
}
}
/**
* Given the credentials to use and what to select from the Ecobee API, read any changed information from Ecobee and
* update the affected items.
*
* @param oauthCredentials
* the credentials to use
* @param selection
* the selection of data to retrieve
*/
private void readEcobee(OAuthCredentials oauthCredentials, Selection selection) throws Exception {
logger.debug("Requesting summaries for {}", selection);
ThermostatSummaryRequest request = new ThermostatSummaryRequest(oauthCredentials.accessToken, selection);
ThermostatSummaryResponse response = request.execute();
if (response.isError()) {
final Status status = response.getStatus();
if (status.isAccessTokenExpired()) {
logger.debug("Access token has expired: {}", status);
if (oauthCredentials.refreshTokens()) {
readEcobee(oauthCredentials, selection);
}
} else {
logger.error(status.getMessage());
}
return; // abort processing
}
logger.debug("Retrieved summaries for {} thermostat(s).", response.getRevisionList().size());
// Identify which thermostats have changed since the last fetch
Map<String, Revision> newRevisionMap = new HashMap<String, Revision>();
for (Revision r : response.getRevisionList()) {
newRevisionMap.put(r.getThermostatIdentifier(), r);
}
// Accumulate the thermostat IDs for thermostats that have updated
// since the last fetch.
Set<String> thermostatIdentifiers = new HashSet<String>();
for (Revision newRevision : newRevisionMap.values()) {
Revision lastRevision = oauthCredentials.getLastRevisionMap().get(newRevision.getThermostatIdentifier());
// If this thermostat's values have changed,
// add it to the list for full retrieval
/*
* NOTE: The following tests may be more eager than they should be, because we may have a settings binding
* for one thermostat and not another, and a runtime binding for another thermostat but not this one, but we
* will now retrieve both thermostats. A small sin. If the Ecobee binding is only working with a single
* thermostat, these tests will be perfectly accurate.
*/
boolean changed = false;
changed = changed || (newRevision.hasRuntimeChanged(lastRevision) && (selection.includeRuntime()
|| selection.includeExtendedRuntime() || selection.includeSensors()));
changed = changed || (newRevision.hasThermostatChanged(lastRevision)
&& (selection.includeSettings() || selection.includeProgram()));
if (changed) {
thermostatIdentifiers.add(newRevision.getThermostatIdentifier());
}
}
// Remember the new revisions for the next execute() call.
oauthCredentials.setLastRevisionMap(newRevisionMap);
if (0 == thermostatIdentifiers.size()) {
logger.debug("No changes detected.");
return;
}
logger.debug("Requesting full retrieval for {} thermostat(s).", thermostatIdentifiers.size());
// Potentially decrease the number of thermostats for the full
// retrieval.
selection.setSelectionMatch(thermostatIdentifiers);
// TODO loop through possibly multiple pages (@watou)
ThermostatRequest treq = new ThermostatRequest(oauthCredentials.accessToken, selection, null);
ThermostatResponse tres = treq.execute();
if (tres.isError()) {
logger.error("Error retrieving thermostats: {}", tres.getStatus());
return;
}
// Create a ID-based map of the thermostats we retrieved.
Map<String, Thermostat> thermostats = new HashMap<String, Thermostat>();
for (Thermostat t : tres.getThermostatList()) {
thermostats.put(t.getIdentifier(), t);
}
// Iterate through bindings and update all inbound values.
for (final EcobeeBindingProvider provider : this.providers) {
for (final String itemName : provider.getItemNames()) {
if (provider.isInBound(itemName) && credentialsMatch(provider, itemName, oauthCredentials)
&& thermostats.containsKey(provider.getThermostatIdentifier(itemName))) {
final State newState = getState(provider, thermostats, itemName);
logger.debug("readEcobee: Updating itemName '{}' with newState '{}'", itemName, newState);
/*
* we need to make sure that we won't send out this event to Ecobee again, when receiving it on the
* openHAB bus
*/
ignoreEventList.add(new Update(itemName, newState));
logger.trace("Added event (item='{}', newState='{}') to the ignore event list (size={})", itemName,
newState, ignoreEventList.size());
this.eventPublisher.postUpdate(itemName, newState);
}
}
}
}
/**
* Give a binding provider, a map of thermostats, and an item name, return the corresponding state object.
*
* @param provider
* the Ecobee binding provider
* @param thermostats
* a map of thermostat identifiers to {@link Thermostat} objects
* @param itemName
* the item name from the items file.
* @return the State object for the named item
*/
private State getState(EcobeeBindingProvider provider, Map<String, Thermostat> thermostats, String itemName) {
final String thermostatIdentifier = provider.getThermostatIdentifier(itemName);
final String property = provider.getProperty(itemName);
final Thermostat thermostat = thermostats.get(thermostatIdentifier);
if (thermostat == null) {
logger.error("Did not receive thermostat '{}' for item '{}'; skipping.", thermostatIdentifier, itemName);
} else {
try {
return createState(thermostat.getProperty(property));
} catch (Exception e) {
logger.debug("Unable to get state from thermostat", e);
}
}
return UnDefType.NULL;
}
/**
* Creates an openHAB {@link State} in accordance to the class of the given {@code propertyValue}. Currently
* {@link Date}, {@link BigDecimal}, {@link Temperature} and {@link Boolean} are handled explicitly. All other
* {@code dataTypes} are mapped to {@link StringType}.
* <p>
* If {@code propertyValue} is {@code null}, {@link UnDefType#NULL} will be returned.
*
* Copied/adapted from the Koubachi binding.
*
* @param propertyValue
*
* @return the new {@link State} in accordance with {@code dataType}. Will never be {@code null}.
*/
private State createState(Object propertyValue) {
if (propertyValue == null) {
return UnDefType.NULL;
}
Class<?> dataType = propertyValue.getClass();
if (Date.class.isAssignableFrom(dataType)) {
Calendar calendar = Calendar.getInstance();
calendar.setTime((Date) propertyValue);
return new DateTimeType(calendar);
} else if (Integer.class.isAssignableFrom(dataType)) {
return new DecimalType((Integer) propertyValue);
} else if (BigDecimal.class.isAssignableFrom(dataType)) {
return new DecimalType((BigDecimal) propertyValue);
} else if (Boolean.class.isAssignableFrom(dataType)) {
if ((Boolean) propertyValue) {
return OnOffType.ON;
} else {
return OnOffType.OFF;
}
} else if (Temperature.class.isAssignableFrom(dataType)) {
return new DecimalType(((Temperature) propertyValue).toLocalTemperature());
} else if (State.class.isAssignableFrom(dataType)) {
return (State) propertyValue;
} else {
return new StringType(propertyValue.toString());
}
}
/**
* {@inheritDoc}
*/
@Override
protected void internalReceiveCommand(String itemName, Command command) {
logger.trace("internalReceiveCommand(item='{}', command='{}')", itemName, command);
commandEcobee(itemName, command);
}
/**
* {@inheritDoc}
*/
@Override
protected void internalReceiveUpdate(final String itemName, final State newState) {
logger.trace("Received update (item='{}', state='{}')", itemName, newState.toString());
if (!isEcho(itemName, newState)) {
updateEcobee(itemName, newState);
}
}
/**
* Perform the given {@code command} against all targets referenced in {@code itemName}.
*
* @param command
* the command to execute
* @param the
* target(s) against which to execute this command
*/
private void commandEcobee(final String itemName, final Command command) {
if (command instanceof State) {
updateEcobee(itemName, (State) command);
}
}
private boolean isEcho(String itemName, State state) {
if (ignoreEventList.remove(new Update(itemName, state))) {
logger.trace(
"We received this event (item='{}', state='{}') from Ecobee, so we don't send it back again -> ignore!",
itemName, state.toString());
return true;
} else {
return false;
}
}
/**
* Send the {@code newState} for the given {@code itemName} to Ecobee.
*
* @param itemName
* @param newState
*/
private void updateEcobee(final String itemName, final State newState) {
// Find the first binding provider for this itemName.
EcobeeBindingProvider provider = null;
String selectionMatch = null;
for (EcobeeBindingProvider p : this.providers) {
selectionMatch = p.getThermostatIdentifier(itemName);
if (selectionMatch != null) {
provider = p;
break;
}
}
if (provider == null) {
logger.warn("no matching binding provider found [itemName={}, newState={}]", itemName, newState);
return;
}
if (!provider.isOutBound(itemName)) {
logger.debug("attempt to update non-outbound item skipped [itemName={}, newState={}]", itemName, newState);
return;
}
final Selection selection = new Selection(selectionMatch);
List<AbstractFunction> functions = null;
logger.trace("Selection for update: {}", selection);
String property = provider.getProperty(itemName);
try {
final Thermostat thermostat = new Thermostat(null);
logger.debug("About to set property '{}' to '{}'", property, newState);
thermostat.setProperty(property, newState);
logger.trace("Thermostat for update: {}", thermostat);
OAuthCredentials oauthCredentials = getOAuthCredentials(provider.getUserid(itemName));
if (oauthCredentials == null) {
logger.warn("Unable to locate credentials for item {}; aborting update.", itemName);
return;
}
if (oauthCredentials.noAccessToken()) {
if (!oauthCredentials.refreshTokens()) {
logger.warn("Sending update skipped.");
return;
}
}
UpdateThermostatRequest request = new UpdateThermostatRequest(oauthCredentials.accessToken, selection,
functions, thermostat);
ApiResponse response = request.execute();
if (response.isError()) {
final Status status = response.getStatus();
if (status.isAccessTokenExpired()) {
if (oauthCredentials.refreshTokens()) {
updateEcobee(itemName, newState);
}
} else {
logger.error("Error updating thermostat(s): {}", response);
}
} else {
// schedule the next poll to happen quickly
oauthCredentials.schedulePoll(this.quickPollInterval);
}
} catch (Exception e) {
logger.error("Unable to update thermostat(s)", e);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean callEcobee(final String itemName, final AbstractFunction function) {
// Find the first binding provider for this itemName.
EcobeeBindingProvider provider = null;
String selectionMatch = null;
for (EcobeeBindingProvider p : this.providers) {
selectionMatch = p.getThermostatIdentifier(itemName);
if (selectionMatch != null) {
provider = p;
break;
}
}
if (provider == null) {
logger.warn("no matching binding provider found [itemName={}, function={}]", itemName, function);
return false;
}
final Selection selection = new Selection(selectionMatch);
logger.trace("Selection for function: {}", selection);
try {
logger.trace("Function to call: {}", function);
OAuthCredentials oauthCredentials = getOAuthCredentials(provider.getUserid(itemName));
if (oauthCredentials == null) {
logger.warn("Unable to locate credentials for item {}; aborting function call.", itemName);
return false;
}
if (oauthCredentials.noAccessToken()) {
if (!oauthCredentials.refreshTokens()) {
logger.warn("Calling function skipped.");
return false;
}
}
List<AbstractFunction> functions = new ArrayList<AbstractFunction>(1);
functions.add(function);
UpdateThermostatRequest request = new UpdateThermostatRequest(oauthCredentials.accessToken, selection,
functions, null);
ApiResponse response = request.execute();
if (response.isError()) {
final Status status = response.getStatus();
if (status.isAccessTokenExpired()) {
if (oauthCredentials.refreshTokens()) {
return callEcobee(itemName, function);
}
} else {
logger.error("Error calling function: {}", response);
}
return false;
} else {
// schedule the next poll to happen quickly
oauthCredentials.schedulePoll(this.quickPollInterval);
return true;
}
} catch (Exception e) {
logger.error("Unable to call function", e);
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public void bindingChanged(BindingProvider provider, String itemName) {
// Forget prior revisions because we may be concerned with
// different thermostats or properties than before.
if (provider instanceof EcobeeBindingProvider) {
String userid = ((EcobeeBindingProvider) provider).getUserid(itemName);
if (userid != null) {
getOAuthCredentials(userid).getLastRevisionMap().clear();
}
}
super.bindingChanged(provider, itemName);
}
/**
* {@inheritDoc}
*/
@Override
public void allBindingsChanged(BindingProvider provider) {
// Forget prior revisions because we may be concerned with
// different thermostats or properties than before.
if (provider instanceof EcobeeBindingProvider) {
for (String userid : this.credentialsCache.keySet()) {
getOAuthCredentials(userid).getLastRevisionMap().clear();
}
}
super.allBindingsChanged(provider);
}
/**
* Returns the cached {@link OAuthCredentials} for the given {@code userid}. If their is no such cached
* {@link OAuthCredentials} element, the cache is searched with the {@code DEFAULT_USER}. If there is still no
* cached element found {@code NULL} is returned.
*
* @param userid
* the userid to find the {@link OAuthCredentials}
* @return the cached {@link OAuthCredentials} or {@code NULL}
*/
private OAuthCredentials getOAuthCredentials(String userid) {
if (credentialsCache.containsKey(userid)) {
return credentialsCache.get(userid);
} else {
return credentialsCache.get(DEFAULT_USER_ID);
}
}
protected void addBindingProvider(EcobeeBindingProvider bindingProvider) {
super.addBindingProvider(bindingProvider);
}
protected void removeBindingProvider(EcobeeBindingProvider bindingProvider) {
super.removeBindingProvider(bindingProvider);
}
/**
* {@inheritDoc}
*/
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
if (config != null) {
// to override the default granularity one has to add a
// parameter to openhab.cfg like ecobee:granularity=2000
String granularityString = (String) config.get(CONFIG_GRANULARITY);
granularity = isNotBlank(granularityString) ? Long.parseLong(granularityString) : DEFAULT_GRANULARITY;
// to override the default refresh interval one has to add a
// parameter to openhab.cfg like ecobee:refresh=240000
String refreshIntervalString = (String) config.get(CONFIG_REFRESH);
refreshInterval = isNotBlank(refreshIntervalString) ? Long.parseLong(refreshIntervalString)
: DEFAULT_REFRESH;
// to override the default quickPoll interval one has to add a
// parameter to openhab.cfg like ecobee:quickpoll=4000
String quickPollIntervalString = (String) config.get(CONFIG_QUICKPOLL);
quickPollInterval = isNotBlank(quickPollIntervalString) ? Long.parseLong(quickPollIntervalString)
: DEFAULT_QUICKPOLL;
// to override the default HTTP timeout one has to add a
// parameter to openhab.cfg like ecobee:timeout=20000
String timeoutString = (String) config.get(CONFIG_TIMEOUT);
if (isNotBlank(timeoutString)) {
AbstractRequest.setHttpRequestTimeout(Integer.parseInt(timeoutString));
}
// to override the default usage of Fahrenheit one has to add a
// parameter to openhab.cfg, as in ecobee:tempscale=C
String tempScaleString = (String) config.get(CONFIG_TEMP_SCALE);
if (isNotBlank(tempScaleString)) {
try {
Temperature.setLocalScale(Temperature.Scale.forValue(tempScaleString));
} catch (IllegalArgumentException iae) {
throw new ConfigurationException(CONFIG_TEMP_SCALE,
"Unsupported temperature scale '" + tempScaleString + "'.");
}
}
Enumeration<String> configKeys = config.keys();
while (configKeys.hasMoreElements()) {
String configKey = configKeys.nextElement();
// the config-key enumeration contains additional keys that we
// don't want to process here ...
if (CONFIG_GRANULARITY.equals(configKey) || CONFIG_REFRESH.equals(configKey)
|| CONFIG_QUICKPOLL.equals(configKey) || CONFIG_TIMEOUT.equals(configKey)
|| CONFIG_TEMP_SCALE.equals(configKey) || "service.pid".equals(configKey)) {
continue;
}
String userid;
String configKeyTail;
if (configKey.contains(".")) {
String[] keyElements = configKey.split("\\.");
userid = keyElements[0];
configKeyTail = keyElements[1];
} else {
userid = DEFAULT_USER_ID;
configKeyTail = configKey;
}
OAuthCredentials credentials = credentialsCache.get(userid);
if (credentials == null) {
credentials = new OAuthCredentials(userid);
credentialsCache.put(userid, credentials);
}
String value = (String) config.get(configKey);
if (CONFIG_APP_KEY.equals(configKeyTail)) {
credentials.appKey = value;
} else if (CONFIG_SCOPE.equals(configKeyTail)) {
credentials.scope = value;
} else {
throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown");
}
}
// Verify the completeness of each OAuthCredentials entry
// to make sure we can get started.
boolean properlyConfigured = true;
for (String userid : credentialsCache.keySet()) {
OAuthCredentials oauthCredentials = getOAuthCredentials(userid);
String userString = (DEFAULT_USER_ID.equals(userid)) ? "" : (userid + ".");
if (oauthCredentials.appKey == null) {
logger.error("Required ecobee:{}{} is missing.", userString, CONFIG_APP_KEY);
properlyConfigured = false;
break;
}
if (oauthCredentials.scope == null) {
logger.error("Required ecobee:{}{} is missing.", userString, CONFIG_SCOPE);
properlyConfigured = false;
break;
}
// Knowing this OAuthCredentials object is complete, load its tokens from persistent storage.
oauthCredentials.load();
}
setProperlyConfigured(properlyConfigured);
}
}
/**
* Return true if the given itemName pertains to the given OAuthCredentials. Since there is a single userid-based
* mapping of credential objects for the binding, if the credentials object is the same object as the one in the
* userid-based map, then we know that this item pertains to these credentials.
*
* @param provider
* the binding provider
* @param itemName
* the item name
* @param oauthCredentials
* the OAuthCredentials to compare
* @return true if the given itemName pertains to the given OAuthCredentials.
*/
private boolean credentialsMatch(EcobeeBindingProvider provider, String itemName,
OAuthCredentials oauthCredentials) {
return oauthCredentials == getOAuthCredentials(provider.getUserid(itemName));
}
/**
* Creates the necessary {@link Selection} object to request all information required from the Ecobee API for all
* thermostats and sub-objects that have a binding, per set of credentials configured in openhab.cfg. One
* {@link ThermostatRequest} can then query all information in one go.
*
* @param oauthCredentials
* constrain the resulting Selection object to only select the thermostats which the configuration
* indicates can be reached using these credentials.
* @returns the Selection object, or <code>null</code> if only an unsuitable Selection is possible.
*/
private Selection createSelection(OAuthCredentials oauthCredentials) {
final Selection selection = new Selection(SelectionType.THERMOSTATS, null);
final Set<String> thermostatIdentifiers = new HashSet<String>();
for (final EcobeeBindingProvider provider : this.providers) {
for (final String itemName : provider.getItemNames()) {
final String thermostatIdentifier = provider.getThermostatIdentifier(itemName);
final String property = provider.getProperty(itemName);
/*
* We are only concerned with inbound items, so there would be no point to including the criteria for
* this item.
*
* We are also only concerned with items that can be reached by the given credentials.
*/
if (!provider.isInBound(itemName) || !credentialsMatch(provider, itemName, oauthCredentials)) {
continue;
}
thermostatIdentifiers.add(thermostatIdentifier);
if (property.startsWith("settings")) {
selection.setIncludeSettings(true);
} else if (property.startsWith("runtime")) {
selection.setIncludeRuntime(true);
} else if (property.startsWith("extendedRuntime")) {
selection.setIncludeExtendedRuntime(true);
} else if (property.startsWith("electricity")) {
selection.setIncludeElectricity(true);
} else if (property.startsWith("devices")) {
selection.setIncludeDevice(true);
} else if (property.startsWith("electricity")) {
selection.setIncludeElectricity(true);
} else if (property.startsWith("location")) {
selection.setIncludeLocation(true);
} else if (property.startsWith("technician")) {
selection.setIncludeTechnician(true);
} else if (property.startsWith("utility")) {
selection.setIncludeUtility(true);
} else if (property.startsWith("management")) {
selection.setIncludeManagement(true);
} else if (property.startsWith("weather")) {
selection.setIncludeWeather(true);
} else if (property.startsWith("events") || property.startsWith("runningEvent")) {
selection.setIncludeEvents(true);
} else if (property.startsWith("program")) {
selection.setIncludeProgram(true);
} else if (property.startsWith("houseDetails")) {
selection.setIncludeHouseDetails(true);
} else if (property.startsWith("oemCfg")) {
selection.setIncludeOemCfg(true);
} else if (property.startsWith("equipmentStatus")) {
selection.setIncludeEquipmentStatus(true);
} else if (property.startsWith("notificationSettings")) {
selection.setIncludeNotificationSettings(true);
} else if (property.startsWith("privacy")) {
selection.setIncludePrivacy(true);
} else if (property.startsWith("version")) {
selection.setIncludeVersion(true);
} else if (property.startsWith("remoteSensors")) {
selection.setIncludeSensors(true);
}
}
}
if (thermostatIdentifiers.isEmpty()) {
logger.info("No Ecobee in-bindings have been found for selection.");
return null;
}
// include all the thermostats we found in the bindings
selection.setSelectionMatch(thermostatIdentifiers);
return selection;
}
/**
* This internal class holds the different credentials necessary for the OAuth2 flow to work. It also provides basic
* methods to refresh the tokens.
*
* <p>
* OAuth States
* <table>
* <thead>
* <tr>
* <th>authToken</th>
* <th>refreshToken</th>
* <th>accessToken</th>
* <th>State</th>
* </tr>
* <thead> <tbody>
* <tr>
* <td>null</td>
* <td></td>
* <td></td>
* <td>authorize</td>
* </tr>
* <tr>
* <td>non-null</td>
* <td>null</td>
* <td></td>
* <td>request tokens</td>
* </tr>
* <tr>
* <td>non-null</td>
* <td>non-null</td>
* <td>null</td>
* <td>refresh tokens</td>
* </tr>
* <tr>
* <td>non-null</td>
* <td>non-null</td>
* <td>non-null</td>
* <td>if expired, refresh if any error, authorize</td>
* </tr>
* </tbody>
* </table>
*
* @author John Cocula
* @since 1.7.0
*/
static class OAuthCredentials {
private static final String APP_KEY = "appKey";
private static final String AUTH_TOKEN = "authToken";
private static final String REFRESH_TOKEN = "refreshToken";
private static final String ACCESS_TOKEN = "accessToken";
private String userid;
/**
* The private app key needed in order to interact with the Ecobee API. This must be provided in the
* <code>openhab.cfg</code> file.
*/
private String appKey;
/**
* The scope needed when authorizing this client to the Ecobee API.
*
* @see AuthorizeRequest
*/
private String scope;
/**
* The authorization token needed to request the refresh and access tokens. Obtained and persisted when
* {@code authorize()} is called.
*
* @see AuthorizeRequest
* @see #authorize()
*/
private String authToken;
/**
* The refresh token to access the Ecobee API. Initial token is received using the <code>authToken</code>,
* periodically refreshed using the previous refreshToken, and saved in persistent storage so it can be used
* across activations.
*
* @see TokenRequest
* @see RefreshTokenRequest
*/
private String refreshToken;
/**
* The access token to access the Ecobee API. Automatically renewed from the API using the refresh token and
* persisted for use across activations.
*
* @see #refreshTokens()
*/
private String accessToken;
/**
* The next time to poll this instance. Initially 0 so pollTimeExpired() initially returns true.
*/
private final AtomicLong pollTime = new AtomicLong(0);
/**
* The most recently received list of revisions, or an empty Map if none have been retrieved yet.
*/
private Map<String, Revision> lastRevisionMap = new HashMap<String, Revision>();
public OAuthCredentials(String userid) {
this.userid = userid;
}
public Map<String, Revision> getLastRevisionMap() {
return this.lastRevisionMap;
}
public void setLastRevisionMap(final Map<String, Revision> lastRevisionMap) {
this.lastRevisionMap = lastRevisionMap;
}
private Preferences getPrefsNode() {
return Preferences.userRoot().node("org.openhab.ecobee." + userid);
}
private void load() {
Preferences prefs = getPrefsNode();
/*
* Only load the tokens if they were not saved with the app key used to create them (backwards
* compatibility), or if the saved app key matches the current app key specified in openhab.cfg. This
* properly ignores saved tokens when the app key has been changed.
*/
final String savedAppKey = prefs.get(APP_KEY, null);
if (savedAppKey == null || savedAppKey.equals(this.appKey)) {
this.authToken = prefs.get(AUTH_TOKEN, null);
this.refreshToken = prefs.get(REFRESH_TOKEN, null);
this.accessToken = prefs.get(ACCESS_TOKEN, null);
}
}
private void save() {
Preferences prefs = getPrefsNode();
prefs.put(APP_KEY, this.appKey);
if (this.authToken != null) {
prefs.put(AUTH_TOKEN, this.authToken);
} else {
prefs.remove(AUTH_TOKEN);
}
if (this.refreshToken != null) {
prefs.put(REFRESH_TOKEN, this.refreshToken);
} else {
prefs.remove(REFRESH_TOKEN);
}
if (this.accessToken != null) {
prefs.put(ACCESS_TOKEN, this.accessToken);
} else {
prefs.remove(ACCESS_TOKEN);
}
}
public boolean noAccessToken() {
return this.accessToken == null;
}
public void authorize() {
logger.trace("Authorizing this binding with the Ecobee API.");
final AuthorizeRequest request = new AuthorizeRequest(this.appKey, this.scope);
logger.trace("Request: {}", request);
final AuthorizeResponse response = request.execute();
logger.trace("Response: {}", response);
this.authToken = response.getAuthToken();
this.refreshToken = null;
this.accessToken = null;
save();
logger.info("#########################################################################################");
logger.info("# Ecobee-Integration: U S E R I N T E R A C T I O N R E Q U I R E D !!");
logger.info("# 1. Login to www.ecobee.com using your '{}' account", this.userid);
logger.info("# 2. Enter the PIN '{}' in My Apps within the next {} seconds.", response.getEcobeePin(),
response.getExpiresIn());
logger.info("# NOTE: Any API attempts will fail in the meantime.");
logger.info("#########################################################################################");
}
/**
* This method attempts to advance the authorization process by retrieving the tokens needed to use the API. It
* returns <code>true</code> if there is reason to believe that an immediately subsequent API call would
* succeed.
* <p>
* This method requests access and refresh tokens to use the Ecobee API. If there is a <code>refreshToken</code>
* , it will be used to obtain the tokens, but if there is only an <code>authToken</code>, that will be used
* instead.
*
* @return <code>true</code> if there is reason to believe that an immediately subsequent API call would
* succeed.
*/
public boolean refreshTokens() {
if (this.authToken == null) {
authorize();
return false;
} else {
logger.trace("Refreshing tokens.");
Request request;
if (this.refreshToken == null) {
request = new TokenRequest(this.authToken, this.appKey);
} else {
request = new RefreshTokenRequest(this.refreshToken, this.appKey);
}
logger.trace("Request: {}", request);
final TokenResponse response = (TokenResponse) request.execute();
logger.trace("Response: {}", response);
if (response.isError()) {
logger.error("Error retrieving tokens: {}", response.getError());
if ("authorization_expired".equals(response.getError())) {
this.refreshToken = null;
this.accessToken = null;
if (request instanceof TokenRequest) {
this.authToken = null;
}
save();
}
return false;
} else {
this.refreshToken = response.getRefreshToken();
this.accessToken = response.getAccessToken();
save();
return true;
}
}
}
/**
* Return true if this instance is at or past the time to poll.
*
* @return if this instance is at or past the time to poll.
*/
private boolean pollTimeExpired() {
return System.currentTimeMillis() >= this.pollTime.get();
}
/**
* Record the earliest time in the future at which we are allowed to poll this instance.
*
* @param future
* the number of milliseconds in the future
*/
private void schedulePoll(long future) {
this.pollTime.set(System.currentTimeMillis() + future);
}
}
}
| bundles/binding/org.openhab.binding.ecobee/src/main/java/org/openhab/binding/ecobee/internal/EcobeeBinding.java | /**
* Copyright (c) 2010-2016, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.ecobee.internal;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.prefs.Preferences;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.openhab.binding.ecobee.EcobeeActionProvider;
import org.openhab.binding.ecobee.EcobeeBindingProvider;
import org.openhab.binding.ecobee.messages.AbstractFunction;
import org.openhab.binding.ecobee.messages.AbstractRequest;
import org.openhab.binding.ecobee.messages.ApiResponse;
import org.openhab.binding.ecobee.messages.AuthorizeRequest;
import org.openhab.binding.ecobee.messages.AuthorizeResponse;
import org.openhab.binding.ecobee.messages.RefreshTokenRequest;
import org.openhab.binding.ecobee.messages.Request;
import org.openhab.binding.ecobee.messages.Selection;
import org.openhab.binding.ecobee.messages.Selection.SelectionType;
import org.openhab.binding.ecobee.messages.Status;
import org.openhab.binding.ecobee.messages.Temperature;
import org.openhab.binding.ecobee.messages.Thermostat;
import org.openhab.binding.ecobee.messages.Thermostat.HvacMode;
import org.openhab.binding.ecobee.messages.Thermostat.VentilatorMode;
import org.openhab.binding.ecobee.messages.ThermostatRequest;
import org.openhab.binding.ecobee.messages.ThermostatResponse;
import org.openhab.binding.ecobee.messages.ThermostatSummaryRequest;
import org.openhab.binding.ecobee.messages.ThermostatSummaryResponse;
import org.openhab.binding.ecobee.messages.ThermostatSummaryResponse.Revision;
import org.openhab.binding.ecobee.messages.TokenRequest;
import org.openhab.binding.ecobee.messages.TokenResponse;
import org.openhab.binding.ecobee.messages.UpdateThermostatRequest;
import org.openhab.core.binding.AbstractActiveBinding;
import org.openhab.core.binding.BindingProvider;
import org.openhab.core.library.types.DateTimeType;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.openhab.core.types.UnDefType;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Binding that retrieves information about thermostats we're interested in every few minutes, and sends updates and
* commands to Ecobee as they are made. Reviewed lots of other binding implementations, particularly Netatmo and XBMC.
*
* @author John Cocula
* @since 1.7.0
*/
public class EcobeeBinding extends AbstractActiveBinding<EcobeeBindingProvider>
implements ManagedService, EcobeeActionProvider {
private static final String DEFAULT_USER_ID = "DEFAULT_USER";
private static final long DEFAULT_GRANULARITY = 5000;
private static final long DEFAULT_REFRESH = 180000;
private static final long DEFAULT_QUICKPOLL = 6000;
private static final Logger logger = LoggerFactory.getLogger(EcobeeBinding.class);
protected static final String CONFIG_GRANULARITY = "granularity";
protected static final String CONFIG_REFRESH = "refresh";
protected static final String CONFIG_QUICKPOLL = "quickpoll";
protected static final String CONFIG_TIMEOUT = "timeout";
protected static final String CONFIG_APP_KEY = "appkey";
protected static final String CONFIG_SCOPE = "scope";
protected static final String CONFIG_TEMP_SCALE = "tempscale";
static {
// Register bean type converters
ConvertUtils.register(new Converter() {
@SuppressWarnings("rawtypes")
@Override
public Object convert(Class type, Object value) {
if (value instanceof DecimalType) {
return Temperature.fromLocalTemperature(((DecimalType) value).toBigDecimal());
} else {
return null;
}
}
}, Temperature.class);
ConvertUtils.register(new Converter() {
@SuppressWarnings("rawtypes")
@Override
public Object convert(Class type, Object value) {
if (value instanceof StringType) {
return HvacMode.forValue(value.toString());
} else {
return null;
}
}
}, HvacMode.class);
ConvertUtils.register(new Converter() {
@SuppressWarnings("rawtypes")
@Override
public Object convert(Class type, Object value) {
if (value instanceof DecimalType) {
return ((DecimalType) value).intValue();
} else {
return null;
}
}
}, Integer.class);
ConvertUtils.register(new Converter() {
@SuppressWarnings("rawtypes")
@Override
public Object convert(Class type, Object value) {
if (value instanceof StringType) {
return VentilatorMode.forValue(value.toString());
} else {
return null;
}
}
}, VentilatorMode.class);
ConvertUtils.register(new Converter() {
@SuppressWarnings("rawtypes")
@Override
public Object convert(Class type, Object value) {
if (value instanceof OnOffType) {
return ((OnOffType) value) == OnOffType.ON;
} else {
return null;
}
}
}, Boolean.class);
ConvertUtils.register(new Converter() {
@SuppressWarnings("rawtypes")
@Override
public Object convert(Class type, Object value) {
return value.toString();
}
}, String.class);
}
/**
* the interval which is used to call the execute() method
*/
private long granularity = DEFAULT_GRANULARITY;
/**
* the normal refresh interval which is used to poll values from the Ecobee server
*/
private long refreshInterval = DEFAULT_REFRESH;
/**
* the quick refresh interval which is used to poll values from the Ecobee server after a command was sent, a state
* was updated or an action was called
*/
private long quickPollInterval = DEFAULT_QUICKPOLL;
/**
* A map of userids from the openhab.cfg file to OAuth credentials used to communicate with each app instance.
*/
private Map<String, OAuthCredentials> credentialsCache = new HashMap<String, OAuthCredentials>();
/**
* used to store events that we have sent ourselves; we need to remember them for not reacting to them
*/
private static class Update {
private String itemName;
private State state;
Update(final String itemName, final State state) {
this.itemName = itemName;
this.state = state;
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof Update)) {
return false;
}
return (this.itemName == null ? ((Update) o).itemName == null : this.itemName.equals(((Update) o).itemName))
&& (this.state == null ? ((Update) o).state == null : this.state.equals(((Update) o).state));
}
@Override
public int hashCode() {
return (this.itemName == null ? 0 : this.itemName.hashCode())
^ (this.state == null ? 0 : this.state.hashCode());
}
}
private List<Update> ignoreEventList = Collections.synchronizedList(new ArrayList<Update>());
public EcobeeBinding() {
}
/**
* {@inheritDoc}
*/
@Override
public void activate() {
super.activate();
}
/**
* {@inheritDoc}
*/
@Override
public void deactivate() {
// deallocate resources here that are no longer needed and
// should be reset when activating this binding again
}
/**
* {@inheritDoc}
*/
@Override
protected long getRefreshInterval() {
return granularity;
}
/**
* {@inheritDoc}
*/
@Override
protected String getName() {
return "Ecobee Refresh Service";
}
/**
* {@inheritDoc}
*/
@Override
protected void execute() {
try {
for (String userid : credentialsCache.keySet()) {
OAuthCredentials oauthCredentials = getOAuthCredentials(userid);
if (oauthCredentials.pollTimeExpired()) {
// schedule the next poll at the standard refresh interval
oauthCredentials.schedulePoll(this.refreshInterval);
logger.trace("Querying Ecobee API for instance {}", oauthCredentials.userid);
Selection selection = createSelection(oauthCredentials);
if (selection == null) {
logger.debug("Nothing to retrieve for '{}'; skipping thermostat retrieval.",
oauthCredentials.userid);
continue;
}
if (oauthCredentials.noAccessToken()) {
if (!oauthCredentials.refreshTokens()) {
logger.warn("Periodic poll skipped for '{}'.", oauthCredentials.userid);
continue;
}
}
readEcobee(oauthCredentials, selection);
}
}
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.warn("Exception reading from Ecobee:", e);
} else {
logger.warn("Exception reading from Ecobee: {}", e.getMessage());
}
}
}
/**
* Given the credentials to use and what to select from the Ecobee API, read any changed information from Ecobee and
* update the affected items.
*
* @param oauthCredentials
* the credentials to use
* @param selection
* the selection of data to retrieve
*/
private void readEcobee(OAuthCredentials oauthCredentials, Selection selection) throws Exception {
logger.debug("Requesting summaries for {}", selection);
ThermostatSummaryRequest request = new ThermostatSummaryRequest(oauthCredentials.accessToken, selection);
ThermostatSummaryResponse response = request.execute();
if (response.isError()) {
final Status status = response.getStatus();
if (status.isAccessTokenExpired()) {
logger.debug("Access token has expired: {}", status);
if (oauthCredentials.refreshTokens()) {
readEcobee(oauthCredentials, selection);
}
} else {
logger.error(status.getMessage());
}
return; // abort processing
}
logger.debug("Retrieved summaries for {} thermostat(s).", response.getRevisionList().size());
// Identify which thermostats have changed since the last fetch
Map<String, Revision> newRevisionMap = new HashMap<String, Revision>();
for (Revision r : response.getRevisionList()) {
newRevisionMap.put(r.getThermostatIdentifier(), r);
}
// Accumulate the thermostat IDs for thermostats that have updated
// since the last fetch.
Set<String> thermostatIdentifiers = new HashSet<String>();
for (Revision newRevision : newRevisionMap.values()) {
Revision lastRevision = oauthCredentials.getLastRevisionMap().get(newRevision.getThermostatIdentifier());
// If this thermostat's values have changed,
// add it to the list for full retrieval
/*
* NOTE: The following tests may be more eager than they should be, because we may have a settings binding
* for one thermostat and not another, and a runtime binding for another thermostat but not this one, but we
* will now retrieve both thermostats. A small sin. If the Ecobee binding is only working with a single
* thermostat, these tests will be perfectly accurate.
*/
boolean changed = false;
changed = changed || (newRevision.hasRuntimeChanged(lastRevision) && (selection.includeRuntime()
|| selection.includeExtendedRuntime() || selection.includeSensors()));
changed = changed || (newRevision.hasThermostatChanged(lastRevision)
&& (selection.includeSettings() || selection.includeProgram()));
if (changed) {
thermostatIdentifiers.add(newRevision.getThermostatIdentifier());
}
}
// Remember the new revisions for the next execute() call.
oauthCredentials.setLastRevisionMap(newRevisionMap);
if (0 == thermostatIdentifiers.size()) {
logger.debug("No changes detected.");
return;
}
logger.debug("Requesting full retrieval for {} thermostat(s).", thermostatIdentifiers.size());
// Potentially decrease the number of thermostats for the full
// retrieval.
selection.setSelectionMatch(thermostatIdentifiers);
// TODO loop through possibly multiple pages (@watou)
ThermostatRequest treq = new ThermostatRequest(oauthCredentials.accessToken, selection, null);
ThermostatResponse tres = treq.execute();
if (tres.isError()) {
logger.error("Error retrieving thermostats: {}", tres.getStatus());
return;
}
// Create a ID-based map of the thermostats we retrieved.
Map<String, Thermostat> thermostats = new HashMap<String, Thermostat>();
for (Thermostat t : tres.getThermostatList()) {
thermostats.put(t.getIdentifier(), t);
}
// Iterate through bindings and update all inbound values.
for (final EcobeeBindingProvider provider : this.providers) {
for (final String itemName : provider.getItemNames()) {
if (provider.isInBound(itemName) && credentialsMatch(provider, itemName, oauthCredentials)
&& thermostats.containsKey(provider.getThermostatIdentifier(itemName))) {
final State newState = getState(provider, thermostats, itemName);
logger.debug("readEcobee: Updating itemName '{}' with newState '{}'", itemName, newState);
/*
* we need to make sure that we won't send out this event to Ecobee again, when receiving it on the
* openHAB bus
*/
ignoreEventList.add(new Update(itemName, newState));
logger.trace("Added event (item='{}', newState='{}') to the ignore event list (size={})", itemName,
newState, ignoreEventList.size());
this.eventPublisher.postUpdate(itemName, newState);
}
}
}
}
/**
* Give a binding provider, a map of thermostats, and an item name, return the corresponding state object.
*
* @param provider
* the Ecobee binding provider
* @param thermostats
* a map of thermostat identifiers to {@link Thermostat} objects
* @param itemName
* the item name from the items file.
* @return the State object for the named item
*/
private State getState(EcobeeBindingProvider provider, Map<String, Thermostat> thermostats, String itemName) {
final String thermostatIdentifier = provider.getThermostatIdentifier(itemName);
final String property = provider.getProperty(itemName);
final Thermostat thermostat = thermostats.get(thermostatIdentifier);
if (thermostat == null) {
logger.error("Did not receive thermostat '{}' for item '{}'; skipping.", thermostatIdentifier, itemName);
} else {
try {
return createState(thermostat.getProperty(property));
} catch (Exception e) {
logger.debug("Unable to get state from thermostat", e);
}
}
return UnDefType.NULL;
}
/**
* Creates an openHAB {@link State} in accordance to the class of the given {@code propertyValue}. Currently
* {@link Date}, {@link BigDecimal}, {@link Temperature} and {@link Boolean} are handled explicitly. All other
* {@code dataTypes} are mapped to {@link StringType}.
* <p>
* If {@code propertyValue} is {@code null}, {@link UnDefType#NULL} will be returned.
*
* Copied/adapted from the Koubachi binding.
*
* @param propertyValue
*
* @return the new {@link State} in accordance with {@code dataType}. Will never be {@code null}.
*/
private State createState(Object propertyValue) {
if (propertyValue == null) {
return UnDefType.NULL;
}
Class<?> dataType = propertyValue.getClass();
if (Date.class.isAssignableFrom(dataType)) {
Calendar calendar = Calendar.getInstance();
calendar.setTime((Date) propertyValue);
return new DateTimeType(calendar);
} else if (Integer.class.isAssignableFrom(dataType)) {
return new DecimalType((Integer) propertyValue);
} else if (BigDecimal.class.isAssignableFrom(dataType)) {
return new DecimalType((BigDecimal) propertyValue);
} else if (Boolean.class.isAssignableFrom(dataType)) {
if ((Boolean) propertyValue) {
return OnOffType.ON;
} else {
return OnOffType.OFF;
}
} else if (Temperature.class.isAssignableFrom(dataType)) {
return new DecimalType(((Temperature) propertyValue).toLocalTemperature());
} else if (State.class.isAssignableFrom(dataType)) {
return (State) propertyValue;
} else {
return new StringType(propertyValue.toString());
}
}
/**
* {@inheritDoc}
*/
@Override
protected void internalReceiveCommand(String itemName, Command command) {
logger.trace("internalReceiveCommand(item='{}', command='{}')", itemName, command);
commandEcobee(itemName, command);
}
/**
* {@inheritDoc}
*/
@Override
protected void internalReceiveUpdate(final String itemName, final State newState) {
logger.trace("Received update (item='{}', state='{}')", itemName, newState.toString());
if (!isEcho(itemName, newState)) {
updateEcobee(itemName, newState);
}
}
/**
* Perform the given {@code command} against all targets referenced in {@code itemName}.
*
* @param command
* the command to execute
* @param the
* target(s) against which to execute this command
*/
private void commandEcobee(final String itemName, final Command command) {
if (command instanceof State) {
updateEcobee(itemName, (State) command);
}
}
private boolean isEcho(String itemName, State state) {
if (ignoreEventList.remove(new Update(itemName, state))) {
logger.trace(
"We received this event (item='{}', state='{}') from Ecobee, so we don't send it back again -> ignore!",
itemName, state.toString());
return true;
} else {
return false;
}
}
/**
* Send the {@code newState} for the given {@code itemName} to Ecobee.
*
* @param itemName
* @param newState
*/
private void updateEcobee(final String itemName, final State newState) {
// Find the first binding provider for this itemName.
EcobeeBindingProvider provider = null;
String selectionMatch = null;
for (EcobeeBindingProvider p : this.providers) {
selectionMatch = p.getThermostatIdentifier(itemName);
if (selectionMatch != null) {
provider = p;
break;
}
}
if (provider == null) {
logger.warn("no matching binding provider found [itemName={}, newState={}]", itemName, newState);
return;
}
if (!provider.isOutBound(itemName)) {
logger.debug("attempt to update non-outbound item skipped [itemName={}, newState={}]", itemName, newState);
return;
}
final Selection selection = new Selection(selectionMatch);
List<AbstractFunction> functions = null;
logger.trace("Selection for update: {}", selection);
String property = provider.getProperty(itemName);
try {
final Thermostat thermostat = new Thermostat(null);
logger.debug("About to set property '{}' to '{}'", property, newState);
thermostat.setProperty(property, newState);
logger.trace("Thermostat for update: {}", thermostat);
OAuthCredentials oauthCredentials = getOAuthCredentials(provider.getUserid(itemName));
if (oauthCredentials == null) {
logger.warn("Unable to locate credentials for item {}; aborting update.", itemName);
return;
}
if (oauthCredentials.noAccessToken()) {
if (!oauthCredentials.refreshTokens()) {
logger.warn("Sending update skipped.");
return;
}
}
UpdateThermostatRequest request = new UpdateThermostatRequest(oauthCredentials.accessToken, selection,
functions, thermostat);
ApiResponse response = request.execute();
if (response.isError()) {
final Status status = response.getStatus();
if (status.isAccessTokenExpired()) {
if (oauthCredentials.refreshTokens()) {
updateEcobee(itemName, newState);
}
} else {
logger.error("Error updating thermostat(s): {}", response);
}
} else {
// schedule the next poll to happen quickly
oauthCredentials.schedulePoll(this.quickPollInterval);
}
} catch (Exception e) {
logger.error("Unable to update thermostat(s)", e);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean callEcobee(final String itemName, final AbstractFunction function) {
// Find the first binding provider for this itemName.
EcobeeBindingProvider provider = null;
String selectionMatch = null;
for (EcobeeBindingProvider p : this.providers) {
selectionMatch = p.getThermostatIdentifier(itemName);
if (selectionMatch != null) {
provider = p;
break;
}
}
if (provider == null) {
logger.warn("no matching binding provider found [itemName={}, function={}]", itemName, function);
return false;
}
final Selection selection = new Selection(selectionMatch);
logger.trace("Selection for function: {}", selection);
try {
logger.trace("Function to call: {}", function);
OAuthCredentials oauthCredentials = getOAuthCredentials(provider.getUserid(itemName));
if (oauthCredentials == null) {
logger.warn("Unable to locate credentials for item {}; aborting function call.", itemName);
return false;
}
if (oauthCredentials.noAccessToken()) {
if (!oauthCredentials.refreshTokens()) {
logger.warn("Calling function skipped.");
return false;
}
}
List<AbstractFunction> functions = new ArrayList<AbstractFunction>(1);
functions.add(function);
UpdateThermostatRequest request = new UpdateThermostatRequest(oauthCredentials.accessToken, selection,
functions, null);
ApiResponse response = request.execute();
if (response.isError()) {
final Status status = response.getStatus();
if (status.isAccessTokenExpired()) {
if (oauthCredentials.refreshTokens()) {
return callEcobee(itemName, function);
}
} else {
logger.error("Error calling function: {}", response);
}
return false;
} else {
// schedule the next poll to happen quickly
oauthCredentials.schedulePoll(this.quickPollInterval);
return true;
}
} catch (Exception e) {
logger.error("Unable to call function", e);
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public void bindingChanged(BindingProvider provider, String itemName) {
// Forget prior revisions because we may be concerned with
// different thermostats or properties than before.
if (provider instanceof EcobeeBindingProvider) {
String userid = ((EcobeeBindingProvider) provider).getUserid(itemName);
if (userid != null) {
getOAuthCredentials(userid).getLastRevisionMap().clear();
}
}
super.bindingChanged(provider, itemName);
}
/**
* {@inheritDoc}
*/
@Override
public void allBindingsChanged(BindingProvider provider) {
// Forget prior revisions because we may be concerned with
// different thermostats or properties than before.
if (provider instanceof EcobeeBindingProvider) {
for (String userid : this.credentialsCache.keySet()) {
getOAuthCredentials(userid).getLastRevisionMap().clear();
}
}
super.allBindingsChanged(provider);
}
/**
* Returns the cached {@link OAuthCredentials} for the given {@code userid}. If their is no such cached
* {@link OAuthCredentials} element, the cache is searched with the {@code DEFAULT_USER}. If there is still no
* cached element found {@code NULL} is returned.
*
* @param userid
* the userid to find the {@link OAuthCredentials}
* @return the cached {@link OAuthCredentials} or {@code NULL}
*/
private OAuthCredentials getOAuthCredentials(String userid) {
if (credentialsCache.containsKey(userid)) {
return credentialsCache.get(userid);
} else {
return credentialsCache.get(DEFAULT_USER_ID);
}
}
/**
* {@inheritDoc}
*/
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
if (config != null) {
// to override the default granularity one has to add a
// parameter to openhab.cfg like ecobee:granularity=2000
String granularityString = (String) config.get(CONFIG_GRANULARITY);
granularity = isNotBlank(granularityString) ? Long.parseLong(granularityString) : DEFAULT_GRANULARITY;
// to override the default refresh interval one has to add a
// parameter to openhab.cfg like ecobee:refresh=240000
String refreshIntervalString = (String) config.get(CONFIG_REFRESH);
refreshInterval = isNotBlank(refreshIntervalString) ? Long.parseLong(refreshIntervalString)
: DEFAULT_REFRESH;
// to override the default quickPoll interval one has to add a
// parameter to openhab.cfg like ecobee:quickpoll=4000
String quickPollIntervalString = (String) config.get(CONFIG_QUICKPOLL);
quickPollInterval = isNotBlank(quickPollIntervalString) ? Long.parseLong(quickPollIntervalString)
: DEFAULT_QUICKPOLL;
// to override the default HTTP timeout one has to add a
// parameter to openhab.cfg like ecobee:timeout=20000
String timeoutString = (String) config.get(CONFIG_TIMEOUT);
if (isNotBlank(timeoutString)) {
AbstractRequest.setHttpRequestTimeout(Integer.parseInt(timeoutString));
}
// to override the default usage of Fahrenheit one has to add a
// parameter to openhab.cfg, as in ecobee:tempscale=C
String tempScaleString = (String) config.get(CONFIG_TEMP_SCALE);
if (isNotBlank(tempScaleString)) {
try {
Temperature.setLocalScale(Temperature.Scale.forValue(tempScaleString));
} catch (IllegalArgumentException iae) {
throw new ConfigurationException(CONFIG_TEMP_SCALE,
"Unsupported temperature scale '" + tempScaleString + "'.");
}
}
Enumeration<String> configKeys = config.keys();
while (configKeys.hasMoreElements()) {
String configKey = configKeys.nextElement();
// the config-key enumeration contains additional keys that we
// don't want to process here ...
if (CONFIG_GRANULARITY.equals(configKey) || CONFIG_REFRESH.equals(configKey)
|| CONFIG_QUICKPOLL.equals(configKey) || CONFIG_TIMEOUT.equals(configKey)
|| CONFIG_TEMP_SCALE.equals(configKey) || "service.pid".equals(configKey)) {
continue;
}
String userid;
String configKeyTail;
if (configKey.contains(".")) {
String[] keyElements = configKey.split("\\.");
userid = keyElements[0];
configKeyTail = keyElements[1];
} else {
userid = DEFAULT_USER_ID;
configKeyTail = configKey;
}
OAuthCredentials credentials = credentialsCache.get(userid);
if (credentials == null) {
credentials = new OAuthCredentials(userid);
credentialsCache.put(userid, credentials);
}
String value = (String) config.get(configKey);
if (CONFIG_APP_KEY.equals(configKeyTail)) {
credentials.appKey = value;
} else if (CONFIG_SCOPE.equals(configKeyTail)) {
credentials.scope = value;
} else {
throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown");
}
}
// Verify the completeness of each OAuthCredentials entry
// to make sure we can get started.
boolean properlyConfigured = true;
for (String userid : credentialsCache.keySet()) {
OAuthCredentials oauthCredentials = getOAuthCredentials(userid);
String userString = (DEFAULT_USER_ID.equals(userid)) ? "" : (userid + ".");
if (oauthCredentials.appKey == null) {
logger.error("Required ecobee:{}{} is missing.", userString, CONFIG_APP_KEY);
properlyConfigured = false;
break;
}
if (oauthCredentials.scope == null) {
logger.error("Required ecobee:{}{} is missing.", userString, CONFIG_SCOPE);
properlyConfigured = false;
break;
}
// Knowing this OAuthCredentials object is complete, load its tokens from persistent storage.
oauthCredentials.load();
}
setProperlyConfigured(properlyConfigured);
}
}
/**
* Return true if the given itemName pertains to the given OAuthCredentials. Since there is a single userid-based
* mapping of credential objects for the binding, if the credentials object is the same object as the one in the
* userid-based map, then we know that this item pertains to these credentials.
*
* @param provider
* the binding provider
* @param itemName
* the item name
* @param oauthCredentials
* the OAuthCredentials to compare
* @return true if the given itemName pertains to the given OAuthCredentials.
*/
private boolean credentialsMatch(EcobeeBindingProvider provider, String itemName,
OAuthCredentials oauthCredentials) {
return oauthCredentials == getOAuthCredentials(provider.getUserid(itemName));
}
/**
* Creates the necessary {@link Selection} object to request all information required from the Ecobee API for all
* thermostats and sub-objects that have a binding, per set of credentials configured in openhab.cfg. One
* {@link ThermostatRequest} can then query all information in one go.
*
* @param oauthCredentials
* constrain the resulting Selection object to only select the thermostats which the configuration
* indicates can be reached using these credentials.
* @returns the Selection object, or <code>null</code> if only an unsuitable Selection is possible.
*/
private Selection createSelection(OAuthCredentials oauthCredentials) {
final Selection selection = new Selection(SelectionType.THERMOSTATS, null);
final Set<String> thermostatIdentifiers = new HashSet<String>();
for (final EcobeeBindingProvider provider : this.providers) {
for (final String itemName : provider.getItemNames()) {
final String thermostatIdentifier = provider.getThermostatIdentifier(itemName);
final String property = provider.getProperty(itemName);
/*
* We are only concerned with inbound items, so there would be no point to including the criteria for
* this item.
*
* We are also only concerned with items that can be reached by the given credentials.
*/
if (!provider.isInBound(itemName) || !credentialsMatch(provider, itemName, oauthCredentials)) {
continue;
}
thermostatIdentifiers.add(thermostatIdentifier);
if (property.startsWith("settings")) {
selection.setIncludeSettings(true);
} else if (property.startsWith("runtime")) {
selection.setIncludeRuntime(true);
} else if (property.startsWith("extendedRuntime")) {
selection.setIncludeExtendedRuntime(true);
} else if (property.startsWith("electricity")) {
selection.setIncludeElectricity(true);
} else if (property.startsWith("devices")) {
selection.setIncludeDevice(true);
} else if (property.startsWith("electricity")) {
selection.setIncludeElectricity(true);
} else if (property.startsWith("location")) {
selection.setIncludeLocation(true);
} else if (property.startsWith("technician")) {
selection.setIncludeTechnician(true);
} else if (property.startsWith("utility")) {
selection.setIncludeUtility(true);
} else if (property.startsWith("management")) {
selection.setIncludeManagement(true);
} else if (property.startsWith("weather")) {
selection.setIncludeWeather(true);
} else if (property.startsWith("events") || property.startsWith("runningEvent")) {
selection.setIncludeEvents(true);
} else if (property.startsWith("program")) {
selection.setIncludeProgram(true);
} else if (property.startsWith("houseDetails")) {
selection.setIncludeHouseDetails(true);
} else if (property.startsWith("oemCfg")) {
selection.setIncludeOemCfg(true);
} else if (property.startsWith("equipmentStatus")) {
selection.setIncludeEquipmentStatus(true);
} else if (property.startsWith("notificationSettings")) {
selection.setIncludeNotificationSettings(true);
} else if (property.startsWith("privacy")) {
selection.setIncludePrivacy(true);
} else if (property.startsWith("version")) {
selection.setIncludeVersion(true);
} else if (property.startsWith("remoteSensors")) {
selection.setIncludeSensors(true);
}
}
}
if (thermostatIdentifiers.isEmpty()) {
logger.info("No Ecobee in-bindings have been found for selection.");
return null;
}
// include all the thermostats we found in the bindings
selection.setSelectionMatch(thermostatIdentifiers);
return selection;
}
/**
* This internal class holds the different credentials necessary for the OAuth2 flow to work. It also provides basic
* methods to refresh the tokens.
*
* <p>
* OAuth States
* <table>
* <thead>
* <tr>
* <th>authToken</th>
* <th>refreshToken</th>
* <th>accessToken</th>
* <th>State</th>
* </tr>
* <thead> <tbody>
* <tr>
* <td>null</td>
* <td></td>
* <td></td>
* <td>authorize</td>
* </tr>
* <tr>
* <td>non-null</td>
* <td>null</td>
* <td></td>
* <td>request tokens</td>
* </tr>
* <tr>
* <td>non-null</td>
* <td>non-null</td>
* <td>null</td>
* <td>refresh tokens</td>
* </tr>
* <tr>
* <td>non-null</td>
* <td>non-null</td>
* <td>non-null</td>
* <td>if expired, refresh if any error, authorize</td>
* </tr>
* </tbody>
* </table>
*
* @author John Cocula
* @since 1.7.0
*/
static class OAuthCredentials {
private static final String APP_KEY = "appKey";
private static final String AUTH_TOKEN = "authToken";
private static final String REFRESH_TOKEN = "refreshToken";
private static final String ACCESS_TOKEN = "accessToken";
private String userid;
/**
* The private app key needed in order to interact with the Ecobee API. This must be provided in the
* <code>openhab.cfg</code> file.
*/
private String appKey;
/**
* The scope needed when authorizing this client to the Ecobee API.
*
* @see AuthorizeRequest
*/
private String scope;
/**
* The authorization token needed to request the refresh and access tokens. Obtained and persisted when
* {@code authorize()} is called.
*
* @see AuthorizeRequest
* @see #authorize()
*/
private String authToken;
/**
* The refresh token to access the Ecobee API. Initial token is received using the <code>authToken</code>,
* periodically refreshed using the previous refreshToken, and saved in persistent storage so it can be used
* across activations.
*
* @see TokenRequest
* @see RefreshTokenRequest
*/
private String refreshToken;
/**
* The access token to access the Ecobee API. Automatically renewed from the API using the refresh token and
* persisted for use across activations.
*
* @see #refreshTokens()
*/
private String accessToken;
/**
* The next time to poll this instance. Initially 0 so pollTimeExpired() initially returns true.
*/
private final AtomicLong pollTime = new AtomicLong(0);
/**
* The most recently received list of revisions, or an empty Map if none have been retrieved yet.
*/
private Map<String, Revision> lastRevisionMap = new HashMap<String, Revision>();
public OAuthCredentials(String userid) {
this.userid = userid;
}
public Map<String, Revision> getLastRevisionMap() {
return this.lastRevisionMap;
}
public void setLastRevisionMap(final Map<String, Revision> lastRevisionMap) {
this.lastRevisionMap = lastRevisionMap;
}
private Preferences getPrefsNode() {
return Preferences.userRoot().node("org.openhab.ecobee." + userid);
}
private void load() {
Preferences prefs = getPrefsNode();
/*
* Only load the tokens if they were not saved with the app key used to create them (backwards
* compatibility), or if the saved app key matches the current app key specified in openhab.cfg. This
* properly ignores saved tokens when the app key has been changed.
*/
final String savedAppKey = prefs.get(APP_KEY, null);
if (savedAppKey == null || savedAppKey.equals(this.appKey)) {
this.authToken = prefs.get(AUTH_TOKEN, null);
this.refreshToken = prefs.get(REFRESH_TOKEN, null);
this.accessToken = prefs.get(ACCESS_TOKEN, null);
}
}
private void save() {
Preferences prefs = getPrefsNode();
prefs.put(APP_KEY, this.appKey);
if (this.authToken != null) {
prefs.put(AUTH_TOKEN, this.authToken);
} else {
prefs.remove(AUTH_TOKEN);
}
if (this.refreshToken != null) {
prefs.put(REFRESH_TOKEN, this.refreshToken);
} else {
prefs.remove(REFRESH_TOKEN);
}
if (this.accessToken != null) {
prefs.put(ACCESS_TOKEN, this.accessToken);
} else {
prefs.remove(ACCESS_TOKEN);
}
}
public boolean noAccessToken() {
return this.accessToken == null;
}
public void authorize() {
logger.trace("Authorizing this binding with the Ecobee API.");
final AuthorizeRequest request = new AuthorizeRequest(this.appKey, this.scope);
logger.trace("Request: {}", request);
final AuthorizeResponse response = request.execute();
logger.trace("Response: {}", response);
this.authToken = response.getAuthToken();
this.refreshToken = null;
this.accessToken = null;
save();
logger.info("#########################################################################################");
logger.info("# Ecobee-Integration: U S E R I N T E R A C T I O N R E Q U I R E D !!");
logger.info("# 1. Login to www.ecobee.com using your '{}' account", this.userid);
logger.info("# 2. Enter the PIN '{}' in My Apps within the next {} seconds.", response.getEcobeePin(),
response.getExpiresIn());
logger.info("# NOTE: Any API attempts will fail in the meantime.");
logger.info("#########################################################################################");
}
/**
* This method attempts to advance the authorization process by retrieving the tokens needed to use the API. It
* returns <code>true</code> if there is reason to believe that an immediately subsequent API call would
* succeed.
* <p>
* This method requests access and refresh tokens to use the Ecobee API. If there is a <code>refreshToken</code>
* , it will be used to obtain the tokens, but if there is only an <code>authToken</code>, that will be used
* instead.
*
* @return <code>true</code> if there is reason to believe that an immediately subsequent API call would
* succeed.
*/
public boolean refreshTokens() {
if (this.authToken == null) {
authorize();
return false;
} else {
logger.trace("Refreshing tokens.");
Request request;
if (this.refreshToken == null) {
request = new TokenRequest(this.authToken, this.appKey);
} else {
request = new RefreshTokenRequest(this.refreshToken, this.appKey);
}
logger.trace("Request: {}", request);
final TokenResponse response = (TokenResponse) request.execute();
logger.trace("Response: {}", response);
if (response.isError()) {
logger.error("Error retrieving tokens: {}", response.getError());
if ("authorization_expired".equals(response.getError())) {
this.refreshToken = null;
this.accessToken = null;
if (request instanceof TokenRequest) {
this.authToken = null;
}
save();
}
return false;
} else {
this.refreshToken = response.getRefreshToken();
this.accessToken = response.getAccessToken();
save();
return true;
}
}
}
/**
* Return true if this instance is at or past the time to poll.
*
* @return if this instance is at or past the time to poll.
*/
private boolean pollTimeExpired() {
return System.currentTimeMillis() >= this.pollTime.get();
}
/**
* Record the earliest time in the future at which we are allowed to poll this instance.
*
* @param future
* the number of milliseconds in the future
*/
private void schedulePoll(long future) {
this.pollTime.set(System.currentTimeMillis() + future);
}
}
}
| ecobee
| bundles/binding/org.openhab.binding.ecobee/src/main/java/org/openhab/binding/ecobee/internal/EcobeeBinding.java | ecobee |
|
Java | epl-1.0 | 3504b5477a054c07f52079f6bac045e10a3c22c6 | 0 | sbrannen/junit-lambda,junit-team/junit-lambda | /*
* Copyright 2015-2016 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.junit.gen5.engine.junit5.discoveryNEW;
import static java.lang.String.format;
import static org.junit.gen5.commons.util.ReflectionUtils.*;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.junit.gen5.commons.util.ReflectionUtils;
import org.junit.gen5.commons.util.StringUtils;
import org.junit.gen5.engine.TestDescriptor;
import org.junit.gen5.engine.UniqueId;
import org.junit.gen5.engine.junit5.descriptor.ClassTestDescriptor;
import org.junit.gen5.engine.junit5.discovery.IsNonStaticInnerClass;
public class JavaElementsResolver {
private static final Logger LOG = Logger.getLogger(JavaElementsResolver.class.getName());
private final TestDescriptor engineDescriptor;
private final Set<ElementResolver> resolvers;
public JavaElementsResolver(TestDescriptor engineDescriptor, Set<ElementResolver> resolvers) {
this.engineDescriptor = engineDescriptor;
this.resolvers = resolvers;
}
public void resolveClass(Class<?> testClass) {
Set<TestDescriptor> resolvedDescriptors = resolveContainerWithParents(testClass);
resolvedDescriptors.forEach(this::resolveChildren);
if (resolvedDescriptors.isEmpty()) {
LOG.warning(() -> {
String classDescription = testClass.getName();
return format("Class '%s' could not be resolved", classDescription);
});
}
}
public void resolveMethod(Class<?> testClass, Method testMethod) {
Set<TestDescriptor> potentialParents = resolveContainerWithParents(testClass);
Set<TestDescriptor> resolvedDescriptors = resolveForAllParents(testMethod, potentialParents);
if (resolvedDescriptors.isEmpty()) {
LOG.warning(() -> {
String methodId = String.format("%s(%s)", testMethod.getName(),
StringUtils.nullSafeToString(testMethod.getParameterTypes()));
String methodDescription = testMethod.getDeclaringClass().getName() + "#" + methodId;
return format("Method '%s' could not be resolved", methodDescription);
});
}
}
private Set<TestDescriptor> resolveContainerWithParents(Class<?> testClass) {
if (new IsNonStaticInnerClass().test(testClass)) {
Set<TestDescriptor> potentialParents = resolveContainerWithParents(testClass.getDeclaringClass());
return resolveForAllParents(testClass, potentialParents);
}
else {
return resolveForAllParents(testClass, Collections.singleton(engineDescriptor));
}
}
public void resolveUniqueId(UniqueId uniqueId) {
List<UniqueId.Segment> segments = uniqueId.getSegments();
segments.remove(0); // Ignore engine unique ID
if (!resolveUniqueId(engineDescriptor, segments))
LOG.warning(() -> {
return format("Unique ID '%s' could not be resolved", uniqueId.getUniqueString());
});
}
/**
* Return true if all segments of unique ID could be resolved
*/
private boolean resolveUniqueId(TestDescriptor parent, List<UniqueId.Segment> remainingSegments) {
if (remainingSegments.isEmpty()) {
resolveChildren(parent);
return true;
}
UniqueId.Segment head = remainingSegments.remove(0);
for (ElementResolver resolver : resolvers) {
Optional<TestDescriptor> resolvedDescriptor = resolver.resolve(head, parent);
if (!resolvedDescriptor.isPresent())
continue;
Optional<TestDescriptor> foundTestDescriptor = findTestDescriptorByUniqueId(
resolvedDescriptor.get().getUniqueId());
TestDescriptor descriptor = foundTestDescriptor.orElseGet(() -> {
TestDescriptor newDescriptor = resolvedDescriptor.get();
parent.addChild(newDescriptor);
return newDescriptor;
});
return resolveUniqueId(descriptor, new ArrayList<>(remainingSegments));
}
return false;
}
private Set<TestDescriptor> resolveContainerWithChildren(Class<?> containerClass,
Set<TestDescriptor> potentialParents) {
Set<TestDescriptor> resolvedDescriptors = resolveForAllParents(containerClass, potentialParents);
resolvedDescriptors.forEach(this::resolveChildren);
return resolvedDescriptors;
}
private Set<TestDescriptor> resolveForAllParents(AnnotatedElement element, Set<TestDescriptor> potentialParents) {
Set<TestDescriptor> resolvedDescriptors = new HashSet<>();
potentialParents.forEach(parent -> {
resolvedDescriptors.addAll(resolve(element, parent));
});
return resolvedDescriptors;
}
private void resolveChildren(TestDescriptor descriptor) {
if (descriptor instanceof ClassTestDescriptor) {
Class<?> testClass = ((ClassTestDescriptor) descriptor).getTestClass();
resolveContainedMethods(descriptor, testClass);
resolveContainedNestedClasses(descriptor, testClass);
}
}
private void resolveContainedNestedClasses(TestDescriptor containerDescriptor, Class<?> clazz) {
List<Class<?>> nestedClassesCandidates = findNestedClasses(clazz, new IsNonStaticInnerClass());
nestedClassesCandidates.forEach(
nestedClass -> resolveContainerWithChildren(nestedClass, Collections.singleton(containerDescriptor)));
}
private void resolveContainedMethods(TestDescriptor containerDescriptor, Class<?> testClass) {
List<Method> testMethodCandidates = findMethods(testClass, method -> !ReflectionUtils.isPrivate(method),
ReflectionUtils.MethodSortOrder.HierarchyDown);
testMethodCandidates.forEach(method -> resolve(method, containerDescriptor));
}
private Set<TestDescriptor> resolve(AnnotatedElement element, TestDescriptor parent) {
return resolvers.stream() //
.map(resolver -> tryToResolveWithResolver(element, parent, resolver)) //
.filter(testDescriptors -> !testDescriptors.isEmpty()) //
.flatMap(Collection::stream) //
.collect(Collectors.toSet());
}
private Set<TestDescriptor> tryToResolveWithResolver(AnnotatedElement element, TestDescriptor parent,
ElementResolver resolver) {
Set<TestDescriptor> resolvedDescriptors = resolver.resolve(element, parent);
resolvedDescriptors.forEach(testDescriptor -> {
Optional<TestDescriptor> existingTestDescriptor = findTestDescriptorByUniqueId(
testDescriptor.getUniqueId());
if (!existingTestDescriptor.isPresent()) {
parent.addChild(testDescriptor);
}
});
return resolvedDescriptors;
}
@SuppressWarnings("unchecked")
private Optional<TestDescriptor> findTestDescriptorByUniqueId(UniqueId uniqueId) {
return (Optional<TestDescriptor>) engineDescriptor.findByUniqueId(uniqueId);
}
}
| junit5-engine/src/main/java/org/junit/gen5/engine/junit5/discoveryNEW/JavaElementsResolver.java | /*
* Copyright 2015-2016 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.junit.gen5.engine.junit5.discoveryNEW;
import static java.lang.String.format;
import static org.junit.gen5.commons.util.ReflectionUtils.*;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.junit.gen5.commons.util.ReflectionUtils;
import org.junit.gen5.commons.util.StringUtils;
import org.junit.gen5.engine.TestDescriptor;
import org.junit.gen5.engine.UniqueId;
import org.junit.gen5.engine.junit5.descriptor.ClassTestDescriptor;
import org.junit.gen5.engine.junit5.discovery.IsNonStaticInnerClass;
public class JavaElementsResolver {
private static final Logger LOG = Logger.getLogger(JavaElementsResolver.class.getName());
private final TestDescriptor engineDescriptor;
private final Set<ElementResolver> resolvers;
public JavaElementsResolver(TestDescriptor engineDescriptor, Set<ElementResolver> resolvers) {
this.engineDescriptor = engineDescriptor;
this.resolvers = resolvers;
}
public void resolveClass(Class<?> testClass) {
Set<TestDescriptor> potentialParents = new HashSet<>();
if (new IsNonStaticInnerClass().test(testClass)) {
potentialParents.addAll(resolveContainerWithParents(testClass.getDeclaringClass()));
}
else {
potentialParents.add(engineDescriptor);
}
if (resolveElementWithChildren(testClass, potentialParents).isEmpty()) {
LOG.warning(() -> {
String classDescription = testClass.getName();
return format("Class '%s' could not be resolved", classDescription);
});
}
}
public void resolveMethod(Class<?> testClass, Method testMethod) {
Set<TestDescriptor> potentialParents = resolveContainerWithParents(testClass);
if (resolveElementWithChildren(testMethod, potentialParents).isEmpty()) {
LOG.warning(() -> {
String methodId = String.format("%s(%s)", testMethod.getName(),
StringUtils.nullSafeToString(testMethod.getParameterTypes()));
String methodDescription = testMethod.getDeclaringClass().getName() + "#" + methodId;
return format("Method '%s' could not be resolved", methodDescription);
});
}
}
private Set<TestDescriptor> resolveContainerWithParents(Class<?> testClass) {
Set<TestDescriptor> resolvedParents = new HashSet<>();
if (new IsNonStaticInnerClass().test(testClass)) {
Set<TestDescriptor> potentialParents = resolveContainerWithParents(testClass.getDeclaringClass());
potentialParents.forEach(parent -> {
resolvedParents.addAll(resolve(testClass, parent));
});
}
else {
resolvedParents.addAll(resolve(testClass, engineDescriptor));
}
return resolvedParents;
}
public void resolveUniqueId(UniqueId uniqueId) {
List<UniqueId.Segment> segments = uniqueId.getSegments();
segments.remove(0); // Ignore engine unique ID
if (!resolveUniqueId(engineDescriptor, segments))
LOG.warning(() -> {
return format("Unique ID '%s' could not be resolved", uniqueId.getUniqueString());
});
}
/**
* Return true if all segments of unique ID could be resolved
*/
private boolean resolveUniqueId(TestDescriptor parent, List<UniqueId.Segment> remainingSegments) {
if (remainingSegments.isEmpty()) {
resolveChildren(parent);
return true;
}
UniqueId.Segment head = remainingSegments.remove(0);
for (ElementResolver resolver : resolvers) {
Optional<TestDescriptor> resolvedDescriptor = resolver.resolve(head, parent);
if (!resolvedDescriptor.isPresent())
continue;
Optional<TestDescriptor> foundTestDescriptor = findTestDescriptorByUniqueId(
resolvedDescriptor.get().getUniqueId());
TestDescriptor descriptor = foundTestDescriptor.orElseGet(() -> {
TestDescriptor newDescriptor = resolvedDescriptor.get();
parent.addChild(newDescriptor);
return newDescriptor;
});
return resolveUniqueId(descriptor, new ArrayList<>(remainingSegments));
}
return false;
}
private Set<TestDescriptor> resolveElementWithChildren(AnnotatedElement element,
Set<TestDescriptor> potentialParents) {
Set<TestDescriptor> resolvedDescriptors = new HashSet<>();
potentialParents.forEach(parent -> {
resolvedDescriptors.addAll(resolve(element, parent));
});
resolvedDescriptors.forEach(this::resolveChildren);
return resolvedDescriptors;
}
private void resolveChildren(TestDescriptor descriptor) {
if (descriptor instanceof ClassTestDescriptor) {
Class<?> testClass = ((ClassTestDescriptor) descriptor).getTestClass();
resolveContainedMethods(descriptor, testClass);
resolveContainedNestedClasses(descriptor, testClass);
}
}
private void resolveContainedNestedClasses(TestDescriptor containerDescriptor, Class<?> clazz) {
List<Class<?>> nestedClassesCandidates = findNestedClasses(clazz, new IsNonStaticInnerClass());
nestedClassesCandidates.forEach(
nestedClass -> resolveElementWithChildren(nestedClass, Collections.singleton(containerDescriptor)));
}
private void resolveContainedMethods(TestDescriptor containerDescriptor, Class<?> testClass) {
List<Method> testMethodCandidates = findMethods(testClass, method -> !ReflectionUtils.isPrivate(method),
ReflectionUtils.MethodSortOrder.HierarchyDown);
testMethodCandidates.forEach(
method -> resolveElementWithChildren(method, Collections.singleton(containerDescriptor)));
}
private Set<TestDescriptor> resolve(AnnotatedElement element, TestDescriptor parent) {
return resolvers.stream() //
.map(resolver -> tryToResolveWithResolver(element, parent, resolver)) //
.filter(testDescriptors -> !testDescriptors.isEmpty()) //
.flatMap(Collection::stream) //
.collect(Collectors.toSet());
}
private Set<TestDescriptor> tryToResolveWithResolver(AnnotatedElement element, TestDescriptor parent,
ElementResolver resolver) {
Set<TestDescriptor> resolvedDescriptors = resolver.resolve(element, parent);
resolvedDescriptors.forEach(testDescriptor -> {
Optional<TestDescriptor> existingTestDescriptor = findTestDescriptorByUniqueId(
testDescriptor.getUniqueId());
if (!existingTestDescriptor.isPresent()) {
parent.addChild(testDescriptor);
}
});
return resolvedDescriptors;
}
@SuppressWarnings("unchecked")
private Optional<TestDescriptor> findTestDescriptorByUniqueId(UniqueId uniqueId) {
return (Optional<TestDescriptor>) engineDescriptor.findByUniqueId(uniqueId);
}
}
| Some refactoring in JavaElementsResolver
| junit5-engine/src/main/java/org/junit/gen5/engine/junit5/discoveryNEW/JavaElementsResolver.java | Some refactoring in JavaElementsResolver |
|
Java | mpl-2.0 | ca910942601346fb2fece2d287f61bbb4e0c2e15 | 0 | etomica/etomica,etomica/etomica,etomica/etomica | package etomica.virial.simulations.KnottedPolymer;
import etomica.action.IAction;
import etomica.action.activity.ActivityIntegrate;
import etomica.atom.AtomType;
import etomica.atom.DiameterHashByType;
import etomica.atom.IAtom;
import etomica.atom.iterator.ApiIndexList;
import etomica.box.Box;
import etomica.data.*;
import etomica.data.history.HistoryCollapsingAverage;
import etomica.data.meter.MeterPotentialEnergy;
import etomica.data.meter.MeterRadiusGyration;
import etomica.graphics.DisplayBox;
import etomica.graphics.DisplayPlot;
import etomica.graphics.SimulationGraphic;
import etomica.integrator.IntegratorListenerAction;
import etomica.integrator.IntegratorMC;
import etomica.integrator.mcmove.MCMoveAtom;
import etomica.integrator.mcmove.MCMoveStepTracker;
import etomica.nbr.CriterionInterMolecular;
import etomica.nbr.NeighborCriterion;
import etomica.nbr.PotentialMasterNbr;
import etomica.nbr.cell.PotentialMasterCell;
import etomica.potential.P2Fene;
import etomica.potential.P2WCA;
import etomica.potential.PotentialGroup;
import etomica.potential.PotentialMaster;
import etomica.simulation.Simulation;
import etomica.space.BoundaryRectangularNonperiodic;
import etomica.space3d.Space3D;
import etomica.space3d.Vector3D;
import etomica.species.ISpecies;
import etomica.util.ParameterBase;
import etomica.util.ParseArgs;
import java.util.ArrayList;
public class StarPolymerMC extends Simulation {
public Box box;
public int f, l;
public SpeciesPolymerMono species;
public IntegratorMC integratorMC;
public final ActivityIntegrate ai;
public P2Fene potentialFene;
public P2WCA potentialWCA;
public PotentialMaster potentialMaster;
public StarPolymerMC(int f, int l, double temperature, double tStep, boolean fromFile) {
super(Space3D.getInstance());
this.f = f;
this.l = l;
species = new SpeciesPolymerMono(this, getSpace(), f, l);
species.setIsDynamic(true);
addSpecies(species);
box = this.makeBox(new BoundaryRectangularNonperiodic(space));
box.getBoundary().setBoxSize(new Vector3D(1.5 * l * 2, 1.5 * l * 2, 1.5 * l * 2));
box.setNMolecules(species, 1);
if (fromFile) {
ConformationStarPolymerAll conf = new ConformationStarPolymerAll(this.getSpace(), "./resource/f5L40.xyz", 0);
conf.initializePositions(box.getMoleculeList().get(0).getChildList());
}
ArrayList<ArrayList<int[]>> pairArray = getPairArray(f, l);
int[][] boundedPairs = pairArray.get(0).toArray(new int[0][0]);
int[][] nonBoundedPairs = pairArray.get(1).toArray(new int[0][0]);
boolean useNbrs = false;
if (l < 30) useNbrs = false;
if (useNbrs) {
potentialMaster = new PotentialMasterCell(this, Math.sqrt(2), space);
} else {
potentialMaster = new PotentialMaster();
}
integratorMC = new IntegratorMC(this, potentialMaster, box);
if (fromFile) {
MCMoveUpdateConformation moveConformation = new MCMoveUpdateConformation(this, space, "./resource/f5L40.xyz");
integratorMC.getMoveManager().addMCMove(moveConformation);
} else {
MCMoveAtom atomMove = new MCMoveAtom(random, potentialMaster, space);
// integratorMC.getMoveManager().addMCMove(atomMove);
((MCMoveStepTracker) atomMove.getTracker()).setNoisyAdjustment(true);
MCMoveWiggle wiggleMove = new MCMoveWiggle(potentialMaster, random, 1, l, space);
// integratorMC.getMoveManager().addMCMove(wiggleMove);
((MCMoveStepTracker) wiggleMove.getTracker()).setNoisyAdjustment(true);
MCMoveRotateArm rotateArmMove = new MCMoveRotateArm(potentialMaster, random, 1, l, space);
integratorMC.getMoveManager().addMCMove(rotateArmMove);
((MCMoveStepTracker) rotateArmMove.getTracker()).setNoisyAdjustment(true);
MCMoveBondLength bondMove = new MCMoveBondLength(potentialMaster, random, 1, l, space);
integratorMC.getMoveManager().addMCMove(bondMove);
((MCMoveStepTracker) bondMove.getTracker()).setNoisyAdjustment(true);
}
ai = new ActivityIntegrate(integratorMC);
getController().addAction(ai);
potentialFene = new P2Fene(space);
potentialWCA = new P2WCA(space);
PotentialGroup potentialGroup = potentialMaster.makePotentialGroup(1);
ApiIndexList boundedIndexList = new ApiIndexList(boundedPairs);
ApiIndexList nonBoundedIndexList = new ApiIndexList(nonBoundedPairs);
potentialGroup.addPotential(potentialFene, boundedIndexList);
AtomType type = species.getAtomType(0);
potentialMaster.addPotential(potentialGroup, new ISpecies[]{species});
if (useNbrs) {
potentialMaster.addPotential(potentialWCA, new AtomType[]{type, type});
CriterionInterMolecular criterion = (CriterionInterMolecular) ((PotentialMasterNbr) potentialMaster).getCriterion(type, type);
//CriterionSimple criterion2 = (CriterionSimple)((CriterionAdapter)criterion.getWrappedCriterion();
// System.out.println(criterion2);
criterion.setIntraMolecularCriterion(new NeighborCriterion() {
@Override
public boolean accept(IAtom atom1, IAtom atom2) {
// int idx1 = atom1.getIndex();
// int idx2 = atom2.getIndex();
// if (idx1 > idx2) {
// int temp = idx1;
// idx1 = idx2;
// idx2 = temp;
// }
// if (idx1 == 0 && idx2 % l == 1) return false;
// if (idx2 - 1 == idx1 && idx1 % l != 0) return false;
return true;
}
@Override
public boolean needUpdate(IAtom atom) {
return criterion.needUpdate(atom);
}
@Override
public void setBox(Box box) {
criterion.setBox(box);
}
@Override
public boolean unsafe() {
return criterion.unsafe();
}
@Override
public void reset(IAtom atom) {
criterion.reset(atom);
}
});
criterion.setIntraMolecularOnly(true);
((PotentialMasterCell) potentialMaster).getNbrCellManager(box).assignCellAll();
integratorMC.getMoveEventManager().addListener(((PotentialMasterCell) potentialMaster).getNbrCellManager(box).makeMCMoveListener());
} else {
potentialGroup.addPotential(potentialWCA, nonBoundedIndexList);
potentialGroup.addPotential(potentialWCA, boundedIndexList);
}
}
public static void main(String[] args) {
StarPolymerMC.PolymerParam params = new StarPolymerMC.PolymerParam();
if (args.length > 0) {
ParseArgs.doParseArgs(params, args);
} else {
params.fp = "./resource/rg.dat";
params.numSteps = 1000000L;
params.fv = 6;
params.lv = 80;
params.xsteps = 1000000L;
}
String fp = params.fp;
long steps = params.numSteps;
int f = params.fv;
int l = params.lv;
long xsteps = params.xsteps;
double temperature = 1.0;
final int dataInterval = 100;
boolean graphics = true;
double tStep = 0.005;
boolean fromFile = false;
final StarPolymerMC sim = new StarPolymerMC(f, l, temperature, tStep, fromFile);
final MeterPotentialEnergy meterPE = new MeterPotentialEnergy(sim.potentialMaster, sim.box);
double u = meterPE.getDataAsScalar();
System.out.println("Initial Potential energy: " + u);
DataFork forkPE = new DataFork();
AccumulatorAverageCollapsing accPE = new AccumulatorAverageCollapsing();
AccumulatorHistory histPE = new AccumulatorHistory(new HistoryCollapsingAverage());
forkPE.addDataSink(accPE);
forkPE.addDataSink(histPE);
DataPumpListener pumpPF = new DataPumpListener(meterPE, forkPE, dataInterval);
sim.integratorMC.getEventManager().addListener(pumpPF);
sim.integratorMC.reset();
MeterRadiusGyration meterRG = new MeterRadiusGyration(sim.getSpace());
meterRG.setBox(sim.getBox(0));
System.out.println(String.format("Squared Radius of Gyration: %.8f\n", meterRG.getDataAsScalar()));
DataFork rgFork = new DataFork();
AccumulatorAverageCollapsing accRG = new AccumulatorAverageCollapsing();
AccumulatorHistory histRG = new AccumulatorHistory(new HistoryCollapsingAverage());
rgFork.addDataSink(accRG);
rgFork.addDataSink(histRG);
DataPumpListener rgPump = new DataPumpListener(meterRG, rgFork, dataInterval);
sim.integratorMC.getEventManager().addListener(rgPump);
sim.integratorMC.reset();
MeterBondLength meterBL = new MeterBondLength(sim.box, f, l);
if (graphics) {
final String APP_NAME = "StarPolymer-MD";
// sim.getBox(0).getBoundary().setBoxSize(Vector.of(new double[]{50, 50, 50}));
final SimulationGraphic simGraphic = new SimulationGraphic(sim, SimulationGraphic.TABBED_PANE, APP_NAME, 1);
DisplayBox displayBox = simGraphic.getDisplayBox(sim.getBox(0));
displayBox.setShowBoundary(false);
simGraphic.getController().getReinitButton().setPostAction(simGraphic.getPaintAction(sim.box));
simGraphic.makeAndDisplayFrame(APP_NAME);
DiameterHashByType dh = (DiameterHashByType) simGraphic.getDisplayBox(sim.box).getDiameterHash();
dh.setDiameter(sim.species.getAtomType(0), 1.0);
// sim.ai.setMaxSteps(1);
DisplayPlot pePlot = new DisplayPlot();
histPE.addDataSink(pePlot.getDataSet().makeDataSink());
pePlot.setLabel("PE");
simGraphic.add(pePlot);
sim.integratorMC.getEventManager().addListener(new IntegratorListenerAction(meterBL, dataInterval));
DisplayPlot blPlot = new DisplayPlot();
blPlot.getPlot().setYLog(true);
DataPumpListener blPump = new DataPumpListener(meterBL, blPlot.getDataSet().makeDataSink(), dataInterval);
sim.integratorMC.getEventManager().addListener(blPump);
blPlot.setLabel("bond length");
simGraphic.add(blPlot);
DisplayPlot rgPlot = new DisplayPlot();
histRG.addDataSink(rgPlot.getDataSet().makeDataSink());
rgPlot.setLabel("Radius of Gyration^2");
simGraphic.add(rgPlot);
simGraphic.getController().getDataStreamPumps().add(pumpPF);
simGraphic.getController().getDataStreamPumps().add(rgPump);
simGraphic.getController().getResetAveragesButton().setPostAction(new IAction() {
@Override
public void actionPerformed() {
meterBL.reset();
}
});
return;
}
System.out.println("MD starts...");
long t1 = System.currentTimeMillis();
sim.ai.setMaxSteps(steps);
sim.getController().actionPerformed();
long t2 = System.currentTimeMillis();
System.out.println("MD finished! ");
System.out.println("time : " + (t2 - t1) / 1000.0);
if (true) {
System.out.println();
System.out.println("MD begin for dumping rg^2 ");
int interval = 1000;
DataLogger dataLogger = new DataLogger();
DataPumpListener rgPumpListener = new DataPumpListener(meterRG, dataLogger, interval);
sim.integratorMC.getEventManager().addListener(rgPumpListener);
dataLogger.setFileName(fp);
dataLogger.setAppending(false);
DataArrayWriter writer = new DataArrayWriter();
writer.setIncludeHeader(false);
dataLogger.setDataSink(writer);
sim.getController().getEventManager().addListener(dataLogger);
long t3 = System.currentTimeMillis();
sim.getController().reset();
sim.ai.setMaxSteps(xsteps);
sim.getController().actionPerformed();
System.out.println("Dumping finished! ");
System.out.println("time: " + (t3 - t1) / 1000.0);
}
System.out.println();
System.out.println("Final Potential energy: " + meterPE.getDataAsScalar());
System.out.println(String.format("Final rg^2 : %.8f\n", meterRG.getDataAsScalar()));
}
private ArrayList<ArrayList<int[]>> getPairArray(int f, int l) {
ArrayList<ArrayList<int[]>> pairArray = new ArrayList<>(2);
ArrayList<int[]> boundedPairArray = new ArrayList<>();
ArrayList<int[]> nonBoundedPariArray = new ArrayList<>();
for (int k = 1; k < f * l + 1; k++) {
int[] temp = new int[]{0, k};
if (k % l == 1 || l == 1) {
boundedPairArray.add(temp);
} else {
nonBoundedPariArray.add(temp);
}
}
for (int i = 1; i < f * l + 1; i++) {
for (int j = i + 1; j < f * l + 1; j++) {
int[] temp = new int[]{i, j};
if (j != i + 1 | i % l == 0) {
nonBoundedPariArray.add(temp);
} else {
boundedPairArray.add(temp);
}
}
}
pairArray.add(boundedPairArray);
pairArray.add(nonBoundedPariArray);
return pairArray;
}
public static class PolymerParam extends ParameterBase {
public long numSteps = 1000000;
public String fp = null;
public int fv = 5;
public int lv = 40;
public int size = 1000;
public int interval = 1000;
public long xsteps = 1000000;
}
}
| etomica-apps/src/main/java/etomica/virial/simulations/KnottedPolymer/StarPolymerMC.java | package etomica.virial.simulations.KnottedPolymer;
import etomica.action.IAction;
import etomica.action.activity.ActivityIntegrate;
import etomica.atom.AtomType;
import etomica.atom.DiameterHashByType;
import etomica.atom.IAtom;
import etomica.atom.iterator.ApiIndexList;
import etomica.box.Box;
import etomica.data.*;
import etomica.data.history.HistoryCollapsingAverage;
import etomica.data.meter.MeterPotentialEnergy;
import etomica.data.meter.MeterRadiusGyration;
import etomica.graphics.DisplayBox;
import etomica.graphics.DisplayPlot;
import etomica.graphics.SimulationGraphic;
import etomica.integrator.IntegratorListenerAction;
import etomica.integrator.IntegratorMC;
import etomica.integrator.mcmove.MCMoveAtom;
import etomica.integrator.mcmove.MCMoveStepTracker;
import etomica.nbr.CriterionInterMolecular;
import etomica.nbr.NeighborCriterion;
import etomica.nbr.PotentialMasterNbr;
import etomica.nbr.cell.PotentialMasterCell;
import etomica.potential.P2Fene;
import etomica.potential.P2WCA;
import etomica.potential.PotentialGroup;
import etomica.potential.PotentialMaster;
import etomica.simulation.Simulation;
import etomica.space.BoundaryRectangularNonperiodic;
import etomica.space3d.Space3D;
import etomica.space3d.Vector3D;
import etomica.species.ISpecies;
import etomica.util.ParameterBase;
import etomica.util.ParseArgs;
import java.util.ArrayList;
public class StarPolymerMC extends Simulation {
public Box box;
public int f, l;
public SpeciesPolymerMono species;
public IntegratorMC integratorMC;
public final ActivityIntegrate ai;
public P2Fene potentialFene;
public P2WCA potentialWCA;
public PotentialMaster potentialMaster;
public StarPolymerMC(int f, int l, double temperature, double tStep, boolean fromFile) {
super(Space3D.getInstance());
this.f = f;
this.l = l;
species = new SpeciesPolymerMono(this, getSpace(), f, l);
species.setIsDynamic(true);
addSpecies(species);
box = this.makeBox(new BoundaryRectangularNonperiodic(space));
box.getBoundary().setBoxSize(new Vector3D(1.5 * l * 2, 1.5 * l * 2, 1.5 * l * 2));
box.setNMolecules(species, 1);
if (false) {
ConformationStarPolymerAll conf = new ConformationStarPolymerAll(this.getSpace(), "./resource/f5L40.xyz", 0);
conf.initializePositions(box.getMoleculeList().get(0).getChildList());
}
ArrayList<ArrayList<int[]>> pairArray = getPairArray(f, l);
int[][] boundedPairs = pairArray.get(0).toArray(new int[0][0]);
int[][] nonBoundedPairs = pairArray.get(1).toArray(new int[0][0]);
boolean useNbrs = false;
if (l < 30) useNbrs = false;
if (useNbrs) {
potentialMaster = new PotentialMasterCell(this, Math.sqrt(2), space);
} else {
potentialMaster = new PotentialMaster();
}
integratorMC = new IntegratorMC(this, potentialMaster, box);
if (fromFile) {
MCMoveUpdateConformation moveConformation = new MCMoveUpdateConformation(this, space, "./resource/f5L40.xyz");
integratorMC.getMoveManager().addMCMove(moveConformation);
} else {
MCMoveAtom atomMove = new MCMoveAtom(random, potentialMaster, space);
// integratorMC.getMoveManager().addMCMove(atomMove);
((MCMoveStepTracker) atomMove.getTracker()).setNoisyAdjustment(true);
MCMoveWiggle wiggleMove = new MCMoveWiggle(potentialMaster, random, 1, l, space);
// integratorMC.getMoveManager().addMCMove(wiggleMove);
((MCMoveStepTracker) wiggleMove.getTracker()).setNoisyAdjustment(true);
MCMoveRotateArm rotateArmMove = new MCMoveRotateArm(potentialMaster, random, 1, l, space);
integratorMC.getMoveManager().addMCMove(rotateArmMove);
((MCMoveStepTracker) rotateArmMove.getTracker()).setNoisyAdjustment(true);
MCMoveBondLength bondMove = new MCMoveBondLength(potentialMaster, random, 1, l, space);
integratorMC.getMoveManager().addMCMove(bondMove);
((MCMoveStepTracker) bondMove.getTracker()).setNoisyAdjustment(true);
}
ai = new ActivityIntegrate(integratorMC);
getController().addAction(ai);
potentialFene = new P2Fene(space);
potentialWCA = new P2WCA(space);
PotentialGroup potentialGroup = potentialMaster.makePotentialGroup(1);
ApiIndexList boundedIndexList = new ApiIndexList(boundedPairs);
ApiIndexList nonBoundedIndexList = new ApiIndexList(nonBoundedPairs);
potentialGroup.addPotential(potentialFene, boundedIndexList);
AtomType type = species.getAtomType(0);
potentialMaster.addPotential(potentialGroup, new ISpecies[]{species});
if (useNbrs) {
potentialMaster.addPotential(potentialWCA, new AtomType[]{type, type});
CriterionInterMolecular criterion = (CriterionInterMolecular) ((PotentialMasterNbr) potentialMaster).getCriterion(type, type);
//CriterionSimple criterion2 = (CriterionSimple)((CriterionAdapter)criterion.getWrappedCriterion();
// System.out.println(criterion2);
criterion.setIntraMolecularCriterion(new NeighborCriterion() {
@Override
public boolean accept(IAtom atom1, IAtom atom2) {
// int idx1 = atom1.getIndex();
// int idx2 = atom2.getIndex();
// if (idx1 > idx2) {
// int temp = idx1;
// idx1 = idx2;
// idx2 = temp;
// }
// if (idx1 == 0 && idx2 % l == 1) return false;
// if (idx2 - 1 == idx1 && idx1 % l != 0) return false;
return true;
}
@Override
public boolean needUpdate(IAtom atom) {
return criterion.needUpdate(atom);
}
@Override
public void setBox(Box box) {
criterion.setBox(box);
}
@Override
public boolean unsafe() {
return criterion.unsafe();
}
@Override
public void reset(IAtom atom) {
criterion.reset(atom);
}
});
criterion.setIntraMolecularOnly(true);
((PotentialMasterCell) potentialMaster).getNbrCellManager(box).assignCellAll();
integratorMC.getMoveEventManager().addListener(((PotentialMasterCell) potentialMaster).getNbrCellManager(box).makeMCMoveListener());
} else {
potentialGroup.addPotential(potentialWCA, nonBoundedIndexList);
potentialGroup.addPotential(potentialWCA, boundedIndexList);
}
}
public static void main(String[] args) {
StarPolymerMC.PolymerParam params = new StarPolymerMC.PolymerParam();
if (args.length > 0) {
ParseArgs.doParseArgs(params, args);
} else {
params.fp = "./resource/rg.dat";
params.numSteps = 1000000L;
params.fv = 6;
params.lv = 80;
params.xsteps = 1000000L;
}
String fp = params.fp;
long steps = params.numSteps;
int f = params.fv;
int l = params.lv;
long xsteps = params.xsteps;
double temperature = 1.0;
final int dataInterval = 100;
boolean graphics = true;
double tStep = 0.005;
boolean fromFile = false;
final StarPolymerMC sim = new StarPolymerMC(f, l, temperature, tStep, fromFile);
final MeterPotentialEnergy meterPE = new MeterPotentialEnergy(sim.potentialMaster, sim.box);
double u = meterPE.getDataAsScalar();
System.out.println("Initial Potential energy: " + u);
DataFork forkPE = new DataFork();
AccumulatorAverageCollapsing accPE = new AccumulatorAverageCollapsing();
AccumulatorHistory histPE = new AccumulatorHistory(new HistoryCollapsingAverage());
forkPE.addDataSink(accPE);
forkPE.addDataSink(histPE);
DataPumpListener pumpPF = new DataPumpListener(meterPE, forkPE, dataInterval);
sim.integratorMC.getEventManager().addListener(pumpPF);
sim.integratorMC.reset();
MeterRadiusGyration meterRG = new MeterRadiusGyration(sim.getSpace());
meterRG.setBox(sim.getBox(0));
System.out.println(String.format("Squared Radius of Gyration: %.8f\n", meterRG.getDataAsScalar()));
DataFork rgFork = new DataFork();
AccumulatorAverageCollapsing accRG = new AccumulatorAverageCollapsing();
AccumulatorHistory histRG = new AccumulatorHistory(new HistoryCollapsingAverage());
rgFork.addDataSink(accRG);
rgFork.addDataSink(histRG);
DataPumpListener rgPump = new DataPumpListener(meterRG, rgFork, dataInterval);
sim.integratorMC.getEventManager().addListener(rgPump);
sim.integratorMC.reset();
MeterBondLength meterBL = new MeterBondLength(sim.box, f, l);
if (graphics) {
final String APP_NAME = "StarPolymer-MD";
// sim.getBox(0).getBoundary().setBoxSize(Vector.of(new double[]{50, 50, 50}));
final SimulationGraphic simGraphic = new SimulationGraphic(sim, SimulationGraphic.TABBED_PANE, APP_NAME, 1);
DisplayBox displayBox = simGraphic.getDisplayBox(sim.getBox(0));
displayBox.setShowBoundary(false);
simGraphic.getController().getReinitButton().setPostAction(simGraphic.getPaintAction(sim.box));
simGraphic.makeAndDisplayFrame(APP_NAME);
DiameterHashByType dh = (DiameterHashByType) simGraphic.getDisplayBox(sim.box).getDiameterHash();
dh.setDiameter(sim.species.getAtomType(0), 1.0);
// sim.ai.setMaxSteps(1);
DisplayPlot pePlot = new DisplayPlot();
histPE.addDataSink(pePlot.getDataSet().makeDataSink());
pePlot.setLabel("PE");
simGraphic.add(pePlot);
sim.integratorMC.getEventManager().addListener(new IntegratorListenerAction(meterBL, dataInterval));
DisplayPlot blPlot = new DisplayPlot();
blPlot.getPlot().setYLog(true);
DataPumpListener blPump = new DataPumpListener(meterBL, blPlot.getDataSet().makeDataSink(), dataInterval);
sim.integratorMC.getEventManager().addListener(blPump);
blPlot.setLabel("bond length");
simGraphic.add(blPlot);
DisplayPlot rgPlot = new DisplayPlot();
histRG.addDataSink(rgPlot.getDataSet().makeDataSink());
rgPlot.setLabel("Radius of Gyration^2");
simGraphic.add(rgPlot);
simGraphic.getController().getDataStreamPumps().add(pumpPF);
simGraphic.getController().getDataStreamPumps().add(rgPump);
simGraphic.getController().getResetAveragesButton().setPostAction(new IAction() {
@Override
public void actionPerformed() {
meterBL.reset();
}
});
return;
}
System.out.println("MD starts...");
long t1 = System.currentTimeMillis();
sim.ai.setMaxSteps(steps);
sim.getController().actionPerformed();
long t2 = System.currentTimeMillis();
System.out.println("MD finished! ");
System.out.println("time : " + (t2 - t1) / 1000.0);
if (true) {
System.out.println();
System.out.println("MD begin for dumping rg^2 ");
int interval = 1000;
DataLogger dataLogger = new DataLogger();
DataPumpListener rgPumpListener = new DataPumpListener(meterRG, dataLogger, interval);
sim.integratorMC.getEventManager().addListener(rgPumpListener);
dataLogger.setFileName(fp);
dataLogger.setAppending(false);
DataArrayWriter writer = new DataArrayWriter();
writer.setIncludeHeader(false);
dataLogger.setDataSink(writer);
sim.getController().getEventManager().addListener(dataLogger);
long t3 = System.currentTimeMillis();
sim.getController().reset();
sim.ai.setMaxSteps(xsteps);
sim.getController().actionPerformed();
System.out.println("Dumping finished! ");
System.out.println("time: " + (t3 - t1) / 1000.0);
}
System.out.println();
System.out.println("Final Potential energy: " + meterPE.getDataAsScalar());
System.out.println(String.format("Final rg^2 : %.8f\n", meterRG.getDataAsScalar()));
}
private ArrayList<ArrayList<int[]>> getPairArray(int f, int l) {
ArrayList<ArrayList<int[]>> pairArray = new ArrayList<>(2);
ArrayList<int[]> boundedPairArray = new ArrayList<>();
ArrayList<int[]> nonBoundedPariArray = new ArrayList<>();
for (int k = 1; k < f * l + 1; k++) {
int[] temp = new int[]{0, k};
if (k % l == 1) {
boundedPairArray.add(temp);
} else {
nonBoundedPariArray.add(temp);
}
}
for (int i = 1; i < f * l + 1; i++) {
for (int j = i + 1; j < f * l + 1; j++) {
int[] temp = new int[]{i, j};
if (j != i + 1 | i % l == 0) {
nonBoundedPariArray.add(temp);
} else {
boundedPairArray.add(temp);
}
}
}
pairArray.add(boundedPairArray);
pairArray.add(nonBoundedPariArray);
return pairArray;
}
public static class PolymerParam extends ParameterBase {
public long numSteps = 1000000;
public String fp = null;
public int fv = 5;
public int lv = 40;
public int size = 1000;
public int interval = 1000;
public long xsteps = 1000000;
}
}
| Handle l=1
| etomica-apps/src/main/java/etomica/virial/simulations/KnottedPolymer/StarPolymerMC.java | Handle l=1 |
|
Java | agpl-3.0 | 12e27c275d58459240c1ec6b07aabaa6c62035e7 | 0 | PaulKh/scale-proactive,jrochas/scale-proactive,paraita/programming,ow2-proactive/programming,PaulKh/scale-proactive,acontes/programming,jrochas/scale-proactive,acontes/programming,mnip91/programming-multiactivities,mnip91/programming-multiactivities,mnip91/programming-multiactivities,lpellegr/programming,mnip91/programming-multiactivities,acontes/scheduling,acontes/scheduling,paraita/programming,acontes/scheduling,mnip91/proactive-component-monitoring,acontes/scheduling,lpellegr/programming,PaulKh/scale-proactive,fviale/programming,acontes/programming,mnip91/proactive-component-monitoring,acontes/programming,jrochas/scale-proactive,PaulKh/scale-proactive,fviale/programming,ow2-proactive/programming,paraita/programming,acontes/programming,PaulKh/scale-proactive,paraita/programming,jrochas/scale-proactive,ow2-proactive/programming,acontes/scheduling,lpellegr/programming,mnip91/programming-multiactivities,fviale/programming,ow2-proactive/programming,mnip91/proactive-component-monitoring,ow2-proactive/programming,acontes/scheduling,PaulKh/scale-proactive,acontes/scheduling,paraita/programming,jrochas/scale-proactive,ow2-proactive/programming,jrochas/scale-proactive,mnip91/proactive-component-monitoring,fviale/programming,mnip91/proactive-component-monitoring,paraita/programming,acontes/programming,acontes/programming,mnip91/programming-multiactivities,lpellegr/programming,lpellegr/programming,jrochas/scale-proactive,mnip91/proactive-component-monitoring,fviale/programming,fviale/programming,PaulKh/scale-proactive,lpellegr/programming | /*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis
* Contact: [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* Initial developer(s): The ProActive Team
* http://www.inria.fr/oasis/ProActive/contacts.html
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.core.runtime.ibis;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import org.objectweb.proactive.Body;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.body.UniversalBody;
import org.objectweb.proactive.core.body.ft.checkpointing.Checkpoint;
import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor;
import org.objectweb.proactive.core.descriptor.data.VirtualNode;
import org.objectweb.proactive.core.mop.ConstructorCall;
import org.objectweb.proactive.core.mop.ConstructorCallExecutionFailedException;
import org.objectweb.proactive.core.node.NodeException;
import org.objectweb.proactive.core.process.UniversalProcess;
import org.objectweb.proactive.core.runtime.ProActiveRuntime;
import org.objectweb.proactive.core.runtime.ProActiveRuntimeImpl;
import org.objectweb.proactive.core.runtime.VMInformation;
import org.objectweb.proactive.core.util.UrlBuilder;
import org.objectweb.proactive.ext.security.PolicyServer;
import org.objectweb.proactive.ext.security.SecurityContext;
import org.objectweb.proactive.ext.security.exceptions.SecurityNotAvailableException;
import ibis.rmi.AlreadyBoundException;
import ibis.rmi.Naming;
import ibis.rmi.NotBoundException;
import ibis.rmi.RemoteException;
import ibis.rmi.server.UnicastRemoteObject;
/**
* An adapter for a ProActiveRuntime to be able to receive remote calls. This helps isolate Ibis-specific
* code into a small set of specific classes, thus enabling reuse if we one day decide to switch
* to anothe remote objects library.
* @see <a href="http://www.javaworld.com/javaworld/jw-05-1999/jw-05-networked_p.html">Adapter Pattern</a>
*/
public class IbisProActiveRuntimeImpl extends UnicastRemoteObject
implements IbisProActiveRuntime {
protected transient ProActiveRuntime proActiveRuntime;
protected String proActiveRuntimeURL;
// stores nodes urls to be able to unregister nodes
protected ArrayList nodesArray;
//store vn urls to be able to unregister vns
protected ArrayList vnNodesArray;
//
// -- CONSTRUCTORS -----------------------------------------------
//
public IbisProActiveRuntimeImpl()
throws RemoteException, AlreadyBoundException {
//System.out.println("toto");
this.proActiveRuntime = ProActiveRuntimeImpl.getProActiveRuntime();
this.nodesArray = new java.util.ArrayList();
this.vnNodesArray = new java.util.ArrayList();
this.proActiveRuntimeURL = buildRuntimeURL();
register(proActiveRuntimeURL, false);
}
//
// -- PUBLIC METHODS -----------------------------------------------
//
public String createLocalNode(String nodeName,
boolean replacePreviousBinding, PolicyServer ps, String vnname,
String jobId) throws RemoteException, NodeException {
String nodeURL = null;
//Node node;
try {
//first we build a well-formed url
nodeURL = buildNodeURL(nodeName);
//then take the name of the node
String name = UrlBuilder.getNameFromUrl(nodeURL);
//register the url in rmi registry
register(nodeURL, replacePreviousBinding);
proActiveRuntime.createLocalNode(name, replacePreviousBinding, ps,
vnname, jobId);
} catch (java.net.UnknownHostException e) {
throw new RemoteException("Host unknown in " + nodeURL, e);
}
nodesArray.add(nodeURL);
return nodeURL;
}
public void killAllNodes() throws RemoteException, ProActiveException {
for (int i = 0; i < nodesArray.size(); i++) {
String url = (String) nodesArray.get(i);
killNode(url);
}
proActiveRuntime.killAllNodes();
}
public void killNode(String nodeName)
throws RemoteException, ProActiveException {
String nodeUrl = null;
String name = null;
try {
nodeUrl = buildNodeURL(nodeName);
name = UrlBuilder.getNameFromUrl(nodeUrl);
unregister(nodeUrl);
} catch (UnknownHostException e) {
throw new RemoteException("Host unknown in " + nodeUrl, e);
}
proActiveRuntime.killNode(name);
}
public void createVM(UniversalProcess remoteProcess)
throws IOException, ProActiveException {
proActiveRuntime.createVM(remoteProcess);
}
public String[] getLocalNodeNames()
throws RemoteException, ProActiveException {
return proActiveRuntime.getLocalNodeNames();
}
public VMInformation getVMInformation() {
// we can cast because for sure the runtime is a runtimeImpl
// and we avoid throwing an exception
return ((ProActiveRuntimeImpl) proActiveRuntime).getVMInformation();
}
public void register(ProActiveRuntime proActiveRuntimeDist,
String proActiveRuntimeName, String creatorID, String creationProtocol,
String vmName) throws RemoteException, ProActiveException {
proActiveRuntime.register(proActiveRuntimeDist, proActiveRuntimeName,
creatorID, creationProtocol, vmName);
}
/**
* @throws ProActiveException
* @see org.objectweb.proactive.core.runtime.ibis.RemoteProActiveRuntime#unregister(org.objectweb.proactive.core.runtime.ProActiveRuntime, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public void unregister(ProActiveRuntime proActiveRuntimeDist,
String proActiveRuntimeName, String creatorID, String creationProtocol,
String vmName) throws RemoteException, ProActiveException {
this.proActiveRuntime.unregister(proActiveRuntimeDist,
proActiveRuntimeURL, creatorID, creationProtocol, vmName);
}
public ProActiveRuntime[] getProActiveRuntimes()
throws RemoteException, ProActiveException {
return proActiveRuntime.getProActiveRuntimes();
}
public ProActiveRuntime getProActiveRuntime(String proActiveRuntimeName)
throws RemoteException, ProActiveException {
return proActiveRuntime.getProActiveRuntime(proActiveRuntimeName);
}
public void addAcquaintance(String proActiveRuntimeName)
throws RemoteException, ProActiveException {
proActiveRuntime.addAcquaintance(proActiveRuntimeName);
}
public String[] getAcquaintances()
throws RemoteException, ProActiveException {
return proActiveRuntime.getAcquaintances();
}
public void rmAcquaintance(String proActiveRuntimeName)
throws RemoteException, ProActiveException {
proActiveRuntime.rmAcquaintance(proActiveRuntimeName);
}
public void killRT(boolean softly) throws Exception {
killAllNodes();
unregisterAllVirtualNodes();
unregister(proActiveRuntimeURL);
proActiveRuntime.killRT(false);
}
public String getURL() {
return proActiveRuntimeURL;
}
public ArrayList getActiveObjects(String nodeName)
throws RemoteException, ProActiveException {
return proActiveRuntime.getActiveObjects(nodeName);
}
public ArrayList getActiveObjects(String nodeName, String objectName)
throws RemoteException, ProActiveException {
return proActiveRuntime.getActiveObjects(nodeName, objectName);
}
public VirtualNode getVirtualNode(String virtualNodeName)
throws RemoteException, ProActiveException {
return proActiveRuntime.getVirtualNode(virtualNodeName);
}
public void registerVirtualNode(String virtualNodeName,
boolean replacePreviousBinding) throws IOException {
String virtualNodeURL = null;
try {
//first we build a well-formed url
virtualNodeURL = buildNodeURL(virtualNodeName);
//register it with the url
register(virtualNodeURL, replacePreviousBinding);
} catch (java.net.UnknownHostException e) {
throw new RemoteException("Host unknown in " + virtualNodeURL, e);
}
vnNodesArray.add(virtualNodeURL);
}
public void unregisterVirtualNode(String virtualnodeName)
throws RemoteException, ProActiveException {
String virtualNodeURL = null;
proActiveRuntime.unregisterVirtualNode(UrlBuilder.removeVnSuffix(
virtualnodeName));
try {
//first we build a well-formed url
virtualNodeURL = buildNodeURL(virtualnodeName);
unregister(virtualNodeURL);
} catch (java.net.UnknownHostException e) {
throw new RemoteException("Host unknown in " + virtualNodeURL, e);
}
vnNodesArray.remove(virtualNodeURL);
}
public void unregisterAllVirtualNodes()
throws RemoteException, ProActiveException {
for (int i = 0; i < vnNodesArray.size(); i++) {
String url = (String) vnNodesArray.get(i);
unregisterVirtualNode(url);
}
}
public UniversalBody createBody(String nodeName,
ConstructorCall bodyConstructorCall, boolean isNodeLocal)
throws RemoteException, ConstructorCallExecutionFailedException,
ProActiveException, InvocationTargetException {
return proActiveRuntime.createBody(nodeName, bodyConstructorCall,
isNodeLocal);
}
public UniversalBody receiveBody(String nodeName, Body body)
throws RemoteException, ProActiveException {
return proActiveRuntime.receiveBody(nodeName, body);
}
public UniversalBody receiveCheckpoint(String nodeName, Checkpoint ckpt,
int inc) throws RemoteException, ProActiveException {
return proActiveRuntime.receiveCheckpoint(nodeName, ckpt, inc);
}
// SECURITY
/**
* @return policy server
* @throws ProActiveException
*/
public PolicyServer getPolicyServer()
throws RemoteException, ProActiveException {
return proActiveRuntime.getPolicyServer();
}
public String getVNName(String nodename)
throws RemoteException, ProActiveException {
return proActiveRuntime.getVNName(nodename);
}
/**
* @param nodeName
* @return returns all entities associated to the node
* @throws ProActiveException
*/
public ArrayList getEntities(String nodeName)
throws RemoteException, ProActiveException {
return proActiveRuntime.getEntities(nodeName);
}
/**
* @return returns all entities associated to this runtime
* @throws SecurityNotAvailableException
* @throws ProActiveException
*/
public SecurityContext getPolicy(SecurityContext sc)
throws RemoteException, ProActiveException,
SecurityNotAvailableException {
return proActiveRuntime.getPolicy(sc);
}
// -----------------------------------------
// Security: methods not used
//-----------------------------------------
// /* (non-Javadoc)
// * @see org.objectweb.proactive.core.runtime.rmi.RemoteProActiveRuntime#getCreatorCertificate()
// */
// public X509Certificate getCreatorCertificate() throws RemoteException {
// return proActiveRuntime.getCreatorCertificate();
// }
//
//
//
// public void setProActiveSecurityManager(ProActiveSecurityManager ps)
// throws RemoteException {
// proActiveRuntime.setProActiveSecurityManager(ps);
// }
//
// /* (non-Javadoc)
// * @see org.objectweb.proactive.core.runtime.rmi.RemoteProActiveRuntime#setDefaultNodeVirtualNodeNAme(java.lang.String)
// */
// public void setDefaultNodeVirtualNodeName(String s)
// throws RemoteException {
// proActiveRuntime.setDefaultNodeVirtualNodeName(s);
// }
//
// /* (non-Javadoc)
// * @see org.objectweb.proactive.core.runtime.rmi.RemoteProActiveRuntime#updateLocalNodeVirtualName()
// */
// public void updateLocalNodeVirtualName() throws RemoteException {
// // proActiveRuntime.updateLocalNodeVirtualName();
// }
//
// /* (non-Javadoc)
// * @see org.objectweb.proactive.core.runtime.ibis.RemoteProActiveRuntime#getNodePolicyServer(java.lang.String)
// */
// public PolicyServer getNodePolicyServer(String nodeName)
// throws RemoteException {
// return null;
// }
//
// /* (non-Javadoc)
// * @see org.objectweb.proactive.core.runtime.ibis.RemoteProActiveRuntime#enableSecurityIfNeeded()
// */
// public void enableSecurityIfNeeded() throws RemoteException {
// // TODOremove this function
// }
//
// /* (non-Javadoc)
// * @see org.objectweb.proactive.core.runtime.ibis.RemoteProActiveRuntime#getNodeCertificate(java.lang.String)
// */
// public X509Certificate getNodeCertificate(String nodeName)
// throws RemoteException {
// return proActiveRuntime.getNodeCertificate(nodeName);
// }
//
//
//
// /**
// * @param uBody
// * @return returns all entities associated to the node
// */
// public ArrayList getEntities(UniversalBody uBody) throws RemoteException {
// return proActiveRuntime.getEntities(uBody);
// }
//
// /**
// * @return returns all entities associated to this runtime
// */
// public ArrayList getEntities() throws RemoteException {
// return proActiveRuntime.getEntities();
// }
/**
* @throws ProActiveException
* @see org.objectweb.proactive.core.runtime.ibis.RemoteProActiveRuntime#getJobID(java.lang.String)
*/
public String getJobID(String nodeUrl)
throws RemoteException, ProActiveException {
return proActiveRuntime.getJobID(nodeUrl);
}
public byte[] getClassDataFromParentRuntime(String className)
throws IOException, ProActiveException {
try {
return proActiveRuntime.getClassDataFromParentRuntime(className);
} catch (ProActiveException e) {
throw new ProActiveException("class not found : " + className, e);
}
}
public byte[] getClassDataFromThisRuntime(String className)
throws IOException, ProActiveException {
return proActiveRuntime.getClassDataFromThisRuntime(className);
}
/**
* @see org.objectweb.proactive.Job#getJobID()
*/
public String getJobID() {
return proActiveRuntime.getJobID();
}
public void launchMain(String className, String[] parameters)
throws IOException, ClassNotFoundException, NoSuchMethodException,
ProActiveException {
proActiveRuntime.launchMain(className, parameters);
}
public void newRemote(String className)
throws IOException, ClassNotFoundException, ProActiveException {
proActiveRuntime.newRemote(className);
}
public ProActiveDescriptor getDescriptor(String url,
boolean isHierarchicalSearch) throws IOException, ProActiveException {
return proActiveRuntime.getDescriptor(url, isHierarchicalSearch);
}
//
// ---PRIVATE METHODS--------------------------------------
//
private void register(String url, boolean replacePreviousBinding)
throws RemoteException {
try {
if (replacePreviousBinding) {
Naming.rebind(UrlBuilder.removeProtocol(url, "ibis:"), this);
} else {
Naming.bind(UrlBuilder.removeProtocol(url, "ibis:"), this);
}
if (url.indexOf("PA_JVM") < 0) {
runtimeLogger.info(url + " successfully bound in registry at " +
url);
}
} catch (AlreadyBoundException e) {
runtimeLogger.warn("WARNING " + url + " already bound in registry",
e);
} catch (java.net.MalformedURLException e) {
throw new RemoteException("cannot bind in registry at " + url, e);
}
}
private void unregister(String url) throws RemoteException {
try {
Naming.unbind(UrlBuilder.removeProtocol(url, "ibis:"));
if (url.indexOf("PA_JVM") < 0) {
runtimeLogger.info(url + " unbound in registry");
}
} catch (java.net.MalformedURLException e) {
throw new RemoteException("cannot unbind in registry at " + url, e);
} catch (NotBoundException e) {
// No need to throw an exception if an object is already unregistered
runtimeLogger.info("WARNING " + url +
" is not bound in the registry ");
}
}
private String buildRuntimeURL() {
int port = IbisRuntimeFactory.getRegistryHelper().getRegistryPortNumber();
String host = UrlBuilder.getHostNameorIP(getVMInformation()
.getInetAddress());
String name = getVMInformation().getName();
return UrlBuilder.buildUrl(host, name, "ibis:", port);
}
private String buildNodeURL(String url)
throws java.net.UnknownHostException {
int i = url.indexOf('/');
if (i == -1) {
//it is an url given by a descriptor
String host = UrlBuilder.getHostNameorIP(getVMInformation()
.getInetAddress());
int port = IbisRuntimeFactory.getRegistryHelper()
.getRegistryPortNumber();
return UrlBuilder.buildUrl(host, url, "ibis:", port);
} else {
return UrlBuilder.checkUrl(url);
}
}
}
| src/org/objectweb/proactive/core/runtime/ibis/IbisProActiveRuntimeImpl.java | /*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2002 INRIA/University of Nice-Sophia Antipolis
* Contact: [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* Initial developer(s): The ProActive Team
* http://www.inria.fr/oasis/ProActive/contacts.html
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.core.runtime.ibis;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import org.objectweb.proactive.Body;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.body.UniversalBody;
import org.objectweb.proactive.core.body.ft.checkpointing.Checkpoint;
import org.objectweb.proactive.core.descriptor.data.VirtualNode;
import org.objectweb.proactive.core.mop.ConstructorCall;
import org.objectweb.proactive.core.mop.ConstructorCallExecutionFailedException;
import org.objectweb.proactive.core.node.NodeException;
import org.objectweb.proactive.core.process.UniversalProcess;
import org.objectweb.proactive.core.runtime.ProActiveRuntime;
import org.objectweb.proactive.core.runtime.ProActiveRuntimeImpl;
import org.objectweb.proactive.core.runtime.VMInformation;
import org.objectweb.proactive.core.util.UrlBuilder;
import org.objectweb.proactive.ext.security.PolicyServer;
import org.objectweb.proactive.ext.security.SecurityContext;
import org.objectweb.proactive.ext.security.exceptions.SecurityNotAvailableException;
import ibis.rmi.AlreadyBoundException;
import ibis.rmi.Naming;
import ibis.rmi.NotBoundException;
import ibis.rmi.RemoteException;
import ibis.rmi.server.UnicastRemoteObject;
/**
* An adapter for a ProActiveRuntime to be able to receive remote calls. This helps isolate Ibis-specific
* code into a small set of specific classes, thus enabling reuse if we one day decide to switch
* to anothe remote objects library.
* @see <a href="http://www.javaworld.com/javaworld/jw-05-1999/jw-05-networked_p.html">Adapter Pattern</a>
*/
public class IbisProActiveRuntimeImpl extends UnicastRemoteObject
implements IbisProActiveRuntime {
protected transient ProActiveRuntime proActiveRuntime;
protected String proActiveRuntimeURL;
// stores nodes urls to be able to unregister nodes
protected ArrayList nodesArray;
//store vn urls to be able to unregister vns
protected ArrayList vnNodesArray;
//
// -- CONSTRUCTORS -----------------------------------------------
//
public IbisProActiveRuntimeImpl()
throws RemoteException, AlreadyBoundException {
//System.out.println("toto");
this.proActiveRuntime = ProActiveRuntimeImpl.getProActiveRuntime();
this.nodesArray = new java.util.ArrayList();
this.vnNodesArray = new java.util.ArrayList();
this.proActiveRuntimeURL = buildRuntimeURL();
register(proActiveRuntimeURL, false);
}
//
// -- PUBLIC METHODS -----------------------------------------------
//
public String createLocalNode(String nodeName,
boolean replacePreviousBinding, PolicyServer ps, String vnname,
String jobId) throws RemoteException, NodeException {
String nodeURL = null;
//Node node;
try {
//first we build a well-formed url
nodeURL = buildNodeURL(nodeName);
//then take the name of the node
String name = UrlBuilder.getNameFromUrl(nodeURL);
//register the url in rmi registry
register(nodeURL, replacePreviousBinding);
proActiveRuntime.createLocalNode(name, replacePreviousBinding, ps,
vnname, jobId);
} catch (java.net.UnknownHostException e) {
throw new RemoteException("Host unknown in " + nodeURL, e);
}
nodesArray.add(nodeURL);
return nodeURL;
}
public void killAllNodes() throws RemoteException, ProActiveException {
for (int i = 0; i < nodesArray.size(); i++) {
String url = (String) nodesArray.get(i);
killNode(url);
}
proActiveRuntime.killAllNodes();
}
public void killNode(String nodeName)
throws RemoteException, ProActiveException {
String nodeUrl = null;
String name = null;
try {
nodeUrl = buildNodeURL(nodeName);
name = UrlBuilder.getNameFromUrl(nodeUrl);
unregister(nodeUrl);
} catch (UnknownHostException e) {
throw new RemoteException("Host unknown in " + nodeUrl, e);
}
proActiveRuntime.killNode(name);
}
public void createVM(UniversalProcess remoteProcess)
throws IOException, ProActiveException {
proActiveRuntime.createVM(remoteProcess);
}
public String[] getLocalNodeNames()
throws RemoteException, ProActiveException {
return proActiveRuntime.getLocalNodeNames();
}
public VMInformation getVMInformation() {
// we can cast because for sure the runtime is a runtimeImpl
// and we avoid throwing an exception
return ((ProActiveRuntimeImpl) proActiveRuntime).getVMInformation();
}
public void register(ProActiveRuntime proActiveRuntimeDist,
String proActiveRuntimeName, String creatorID, String creationProtocol,
String vmName) throws RemoteException, ProActiveException {
proActiveRuntime.register(proActiveRuntimeDist, proActiveRuntimeName,
creatorID, creationProtocol, vmName);
}
/**
* @throws ProActiveException
* @see org.objectweb.proactive.core.runtime.ibis.RemoteProActiveRuntime#unregister(org.objectweb.proactive.core.runtime.ProActiveRuntime, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public void unregister(ProActiveRuntime proActiveRuntimeDist,
String proActiveRuntimeName, String creatorID, String creationProtocol,
String vmName) throws RemoteException, ProActiveException {
this.proActiveRuntime.unregister(proActiveRuntimeDist,
proActiveRuntimeURL, creatorID, creationProtocol, vmName);
}
public ProActiveRuntime[] getProActiveRuntimes()
throws RemoteException, ProActiveException {
return proActiveRuntime.getProActiveRuntimes();
}
public ProActiveRuntime getProActiveRuntime(String proActiveRuntimeName)
throws RemoteException, ProActiveException {
return proActiveRuntime.getProActiveRuntime(proActiveRuntimeName);
}
public void addAcquaintance(String proActiveRuntimeName)
throws RemoteException, ProActiveException {
proActiveRuntime.addAcquaintance(proActiveRuntimeName);
}
public String[] getAcquaintances()
throws RemoteException, ProActiveException {
return proActiveRuntime.getAcquaintances();
}
public void rmAcquaintance(String proActiveRuntimeName)
throws RemoteException, ProActiveException {
proActiveRuntime.rmAcquaintance(proActiveRuntimeName);
}
public void killRT(boolean softly) throws Exception {
killAllNodes();
unregisterAllVirtualNodes();
unregister(proActiveRuntimeURL);
proActiveRuntime.killRT(false);
}
public String getURL() {
return proActiveRuntimeURL;
}
public ArrayList getActiveObjects(String nodeName)
throws RemoteException, ProActiveException {
return proActiveRuntime.getActiveObjects(nodeName);
}
public ArrayList getActiveObjects(String nodeName, String objectName)
throws RemoteException, ProActiveException {
return proActiveRuntime.getActiveObjects(nodeName, objectName);
}
public VirtualNode getVirtualNode(String virtualNodeName)
throws RemoteException, ProActiveException {
return proActiveRuntime.getVirtualNode(virtualNodeName);
}
public void registerVirtualNode(String virtualNodeName,
boolean replacePreviousBinding) throws IOException {
String virtualNodeURL = null;
try {
//first we build a well-formed url
virtualNodeURL = buildNodeURL(virtualNodeName);
//register it with the url
register(virtualNodeURL, replacePreviousBinding);
} catch (java.net.UnknownHostException e) {
throw new RemoteException("Host unknown in " + virtualNodeURL, e);
}
vnNodesArray.add(virtualNodeURL);
}
public void unregisterVirtualNode(String virtualnodeName)
throws RemoteException, ProActiveException {
String virtualNodeURL = null;
proActiveRuntime.unregisterVirtualNode(UrlBuilder.removeVnSuffix(
virtualnodeName));
try {
//first we build a well-formed url
virtualNodeURL = buildNodeURL(virtualnodeName);
unregister(virtualNodeURL);
} catch (java.net.UnknownHostException e) {
throw new RemoteException("Host unknown in " + virtualNodeURL, e);
}
vnNodesArray.remove(virtualNodeURL);
}
public void unregisterAllVirtualNodes()
throws RemoteException, ProActiveException {
for (int i = 0; i < vnNodesArray.size(); i++) {
String url = (String) vnNodesArray.get(i);
unregisterVirtualNode(url);
}
}
public UniversalBody createBody(String nodeName,
ConstructorCall bodyConstructorCall, boolean isNodeLocal)
throws RemoteException, ConstructorCallExecutionFailedException,
ProActiveException, InvocationTargetException {
return proActiveRuntime.createBody(nodeName, bodyConstructorCall,
isNodeLocal);
}
public UniversalBody receiveBody(String nodeName, Body body)
throws RemoteException, ProActiveException {
return proActiveRuntime.receiveBody(nodeName, body);
}
public UniversalBody receiveCheckpoint(String nodeName, Checkpoint ckpt,
int inc) throws RemoteException, ProActiveException {
return proActiveRuntime.receiveCheckpoint(nodeName, ckpt, inc);
}
// SECURITY
/**
* @return policy server
* @throws ProActiveException
*/
public PolicyServer getPolicyServer()
throws RemoteException, ProActiveException {
return proActiveRuntime.getPolicyServer();
}
public String getVNName(String nodename)
throws RemoteException, ProActiveException {
return proActiveRuntime.getVNName(nodename);
}
/**
* @param nodeName
* @return returns all entities associated to the node
* @throws ProActiveException
*/
public ArrayList getEntities(String nodeName)
throws RemoteException, ProActiveException {
return proActiveRuntime.getEntities(nodeName);
}
/**
* @return returns all entities associated to this runtime
* @throws SecurityNotAvailableException
* @throws ProActiveException
*/
public SecurityContext getPolicy(SecurityContext sc)
throws RemoteException, ProActiveException,
SecurityNotAvailableException {
return proActiveRuntime.getPolicy(sc);
}
// -----------------------------------------
// Security: methods not used
//-----------------------------------------
// /* (non-Javadoc)
// * @see org.objectweb.proactive.core.runtime.rmi.RemoteProActiveRuntime#getCreatorCertificate()
// */
// public X509Certificate getCreatorCertificate() throws RemoteException {
// return proActiveRuntime.getCreatorCertificate();
// }
//
//
//
// public void setProActiveSecurityManager(ProActiveSecurityManager ps)
// throws RemoteException {
// proActiveRuntime.setProActiveSecurityManager(ps);
// }
//
// /* (non-Javadoc)
// * @see org.objectweb.proactive.core.runtime.rmi.RemoteProActiveRuntime#setDefaultNodeVirtualNodeNAme(java.lang.String)
// */
// public void setDefaultNodeVirtualNodeName(String s)
// throws RemoteException {
// proActiveRuntime.setDefaultNodeVirtualNodeName(s);
// }
//
// /* (non-Javadoc)
// * @see org.objectweb.proactive.core.runtime.rmi.RemoteProActiveRuntime#updateLocalNodeVirtualName()
// */
// public void updateLocalNodeVirtualName() throws RemoteException {
// // proActiveRuntime.updateLocalNodeVirtualName();
// }
//
// /* (non-Javadoc)
// * @see org.objectweb.proactive.core.runtime.ibis.RemoteProActiveRuntime#getNodePolicyServer(java.lang.String)
// */
// public PolicyServer getNodePolicyServer(String nodeName)
// throws RemoteException {
// return null;
// }
//
// /* (non-Javadoc)
// * @see org.objectweb.proactive.core.runtime.ibis.RemoteProActiveRuntime#enableSecurityIfNeeded()
// */
// public void enableSecurityIfNeeded() throws RemoteException {
// // TODOremove this function
// }
//
// /* (non-Javadoc)
// * @see org.objectweb.proactive.core.runtime.ibis.RemoteProActiveRuntime#getNodeCertificate(java.lang.String)
// */
// public X509Certificate getNodeCertificate(String nodeName)
// throws RemoteException {
// return proActiveRuntime.getNodeCertificate(nodeName);
// }
//
//
//
// /**
// * @param uBody
// * @return returns all entities associated to the node
// */
// public ArrayList getEntities(UniversalBody uBody) throws RemoteException {
// return proActiveRuntime.getEntities(uBody);
// }
//
// /**
// * @return returns all entities associated to this runtime
// */
// public ArrayList getEntities() throws RemoteException {
// return proActiveRuntime.getEntities();
// }
/**
* @throws ProActiveException
* @see org.objectweb.proactive.core.runtime.ibis.RemoteProActiveRuntime#getJobID(java.lang.String)
*/
public String getJobID(String nodeUrl)
throws RemoteException, ProActiveException {
return proActiveRuntime.getJobID(nodeUrl);
}
public byte[] getClassDataFromParentRuntime(String className)
throws IOException, ProActiveException {
try {
return proActiveRuntime.getClassDataFromParentRuntime(className);
} catch (ProActiveException e) {
throw new ProActiveException("class not found : " + className, e);
}
}
public byte[] getClassDataFromThisRuntime(String className)
throws IOException, ProActiveException {
return proActiveRuntime.getClassDataFromThisRuntime(className);
}
/**
* @see org.objectweb.proactive.Job#getJobID()
*/
public String getJobID() {
return proActiveRuntime.getJobID();
}
//
// ---PRIVATE METHODS--------------------------------------
//
private void register(String url, boolean replacePreviousBinding)
throws RemoteException {
try {
if (replacePreviousBinding) {
Naming.rebind(UrlBuilder.removeProtocol(url, "ibis:"), this);
} else {
Naming.bind(UrlBuilder.removeProtocol(url, "ibis:"), this);
}
if (url.indexOf("PA_JVM") < 0) {
runtimeLogger.info(url + " successfully bound in registry at " +
url);
}
} catch (AlreadyBoundException e) {
runtimeLogger.warn("WARNING " + url + " already bound in registry",
e);
} catch (java.net.MalformedURLException e) {
throw new RemoteException("cannot bind in registry at " + url, e);
}
}
private void unregister(String url) throws RemoteException {
try {
Naming.unbind(UrlBuilder.removeProtocol(url, "ibis:"));
if (url.indexOf("PA_JVM") < 0) {
runtimeLogger.info(url + " unbound in registry");
}
} catch (java.net.MalformedURLException e) {
throw new RemoteException("cannot unbind in registry at " + url, e);
} catch (NotBoundException e) {
// No need to throw an exception if an object is already unregistered
runtimeLogger.info("WARNING " + url +
" is not bound in the registry ");
}
}
private String buildRuntimeURL() {
int port = IbisRuntimeFactory.getRegistryHelper().getRegistryPortNumber();
String host = UrlBuilder.getHostNameorIP(getVMInformation()
.getInetAddress());
String name = getVMInformation().getName();
return UrlBuilder.buildUrl(host, name, "ibis:", port);
}
private String buildNodeURL(String url)
throws java.net.UnknownHostException {
int i = url.indexOf('/');
if (i == -1) {
//it is an url given by a descriptor
String host = UrlBuilder.getHostNameorIP(getVMInformation()
.getInetAddress());
int port = IbisRuntimeFactory.getRegistryHelper()
.getRegistryPortNumber();
return UrlBuilder.buildUrl(host, url, "ibis:", port);
} else {
return UrlBuilder.checkUrl(url);
}
}
}
| methods implementation for ibis
git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@2560 28e8926c-6b08-0410-baaa-805c5e19b8d6
| src/org/objectweb/proactive/core/runtime/ibis/IbisProActiveRuntimeImpl.java | methods implementation for ibis |
|
Java | agpl-3.0 | 8be6c1d16032e992e68202d451b54b4a86c8ec18 | 0 | ua-eas/kfs,quikkian-ua-devops/kfs,smith750/kfs,UniversityOfHawaii/kfs,kuali/kfs,bhutchinson/kfs,UniversityOfHawaii/kfs,smith750/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,kuali/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,smith750/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,smith750/kfs,quikkian-ua-devops/will-financials,kkronenb/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,kuali/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,kkronenb/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,kuali/kfs,quikkian-ua-devops/will-financials,bhutchinson/kfs,quikkian-ua-devops/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,quikkian-ua-devops/kfs,kkronenb/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,ua-eas/kfs-devops-automation-fork,kkronenb/kfs,quikkian-ua-devops/will-financials,bhutchinson/kfs,bhutchinson/kfs | /*
* Copyright 2010 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.module.endow.batch.service.impl;
import static org.kuali.kfs.sys.fixture.UserNameFixture.khuntley;
import java.util.Date;
import org.kuali.kfs.module.endow.EndowParameterKeyConstants;
import org.kuali.kfs.module.endow.batch.service.RollProcessDateService;
import org.kuali.kfs.module.endow.document.service.KEMService;
import org.kuali.kfs.sys.ConfigureContext;
import org.kuali.kfs.sys.context.KualiTestBase;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.rice.kns.bo.Parameter;
import org.kuali.rice.kns.service.ParameterService;
@ConfigureContext(session = khuntley)
public class RollProcessDateServiceImplTest extends KualiTestBase {
protected ParameterService parameterService;
protected KEMService kemService;
protected RollProcessDateService rollProcessDateService;
/**
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
// Initialize service objects.
rollProcessDateService = SpringContext.getBean(RollProcessDateService.class);
kemService = SpringContext.getBean(KEMService.class);
parameterService = SpringContext.getBean(ParameterService.class);
super.setUp();
}
/**
*
* @see junit.framework.TestCase#tearDown()
*/
@Override
protected void tearDown() throws Exception {
rollProcessDateService = null;
kemService = null;
parameterService = null;
super.tearDown();
}
/**
* checks rollProcessDateService#rollDate
* But this batch does not anything because it
*/
public void testProcessDate() {
// rollProcessDateService.rollDate();
}
}
| test/unit/src/org/kuali/kfs/module/endow/batch/service/impl/RollProcessDateServiceImplTest.java | /*
* Copyright 2010 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.module.endow.batch.service.impl;
import static org.kuali.kfs.sys.fixture.UserNameFixture.khuntley;
import java.util.Date;
import org.kuali.kfs.module.endow.EndowParameterKeyConstants;
import org.kuali.kfs.module.endow.batch.service.RollProcessDateService;
import org.kuali.kfs.module.endow.document.service.KEMService;
import org.kuali.kfs.sys.ConfigureContext;
import org.kuali.kfs.sys.context.KualiTestBase;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.rice.kns.bo.Parameter;
import org.kuali.rice.kns.service.ParameterService;
@ConfigureContext(session = khuntley)
public class RollProcessDateServiceImplTest extends KualiTestBase {
protected ParameterService parameterService;
protected KEMService kemService;
protected RollProcessDateService rollProcessDateService;
/**
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
// Initialize service objects.
rollProcessDateService = SpringContext.getBean(RollProcessDateService.class);
kemService = SpringContext.getBean(KEMService.class);
parameterService = SpringContext.getBean(ParameterService.class);
super.setUp();
}
/**
*
* @see junit.framework.TestCase#tearDown()
*/
@Override
protected void tearDown() throws Exception {
rollProcessDateService = null;
kemService = null;
parameterService = null;
super.tearDown();
}
public void testProcessDate() {
Date currentProcessDate = kemService.getCurrentDate();
System.out.println(currentProcessDate.toString());
rollProcessDateService.rollDate();
}
}
| KFSMI-6271: commented out rollProcessDateService.rollDate()
| test/unit/src/org/kuali/kfs/module/endow/batch/service/impl/RollProcessDateServiceImplTest.java | KFSMI-6271: commented out rollProcessDateService.rollDate() |
|
Java | lgpl-2.1 | c4b53b5cbc9607e4525633325efe3e9e362475f4 | 0 | Mrdigs/Bootstrap.jsp,Mrdigs/Bootstrap.jsp,Mrdigs/Bootstrap.jsp | /*
* Copyright (c) 2014 Darren Scott - All Rights Reserved
*
* This program is distributed under LGPL Version 2.1 in the hope that
* it will be useful, but WITHOUT ANY WARRANTY.
*/
package org.bootstrapjsp.support;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspTag;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import org.bootstrapjsp.util.Config;
public abstract class NestedTagSupport extends SimpleTagSupport implements BaseTag {
public static final int BEFORE_BODY = -1;
public static final int AROUND_BODY = 0;
public static final int AFTER_BODY = 1;
private final List<Class<? extends BaseTag>> parents = new ArrayList<Class<? extends BaseTag>>();
private final List<BaseTag> beforeChildren = new ArrayList<BaseTag>();
private final List<BaseTag> aroundChildren = new ArrayList<BaseTag>();
private final List<BaseTag> afterChildren = new ArrayList<BaseTag>();
private JspTag parent;
@Override
public void doTag() throws JspException, IOException {
this.doBeforeBody();
if (this.aroundChildren.size() > 0) {
BaseTag aroundChild = this.aroundChildren.get(0);
aroundChild.setJspContext(this.getJspContext());
aroundChild.setJspBody(this.getJspBody());
aroundChild.doTag();
} else if (this.getJspBody() != null) {
this.getJspBody().invoke(null);
}
this.doAfterBody();
}
protected void doBeforeBody() throws JspException, IOException {
this.renderChildren(this.beforeChildren);
}
protected void doAfterBody() throws JspException, IOException {
this.renderChildren(this.afterChildren);
}
@Override
public void setParent(JspTag parent) {
if (parent != null && this.parents.size() > 0) {
if (!this.parents.contains(parent.getClass())) {
final StringBuilder error = new StringBuilder("Invalid parent for ");
error.append(this).append(": ").append(parent);
throw new IllegalArgumentException(error.toString());
}
}
this.parent = parent;
super.setParent(parent);
}
public JspTag getParent() {
return this.parent;
}
public void appendChild(BaseTag child) {
this.appendChild(child, AROUND_BODY);
}
public void appendChild(BaseTag child, int position) {
if (position == BEFORE_BODY) {
this.beforeChildren.add(child);
child.setParent(this);
return;
} else if (position == AROUND_BODY) {
this.aroundChildren.add(child);
child.setParent(this);
return;
} else if (position == AFTER_BODY) {
this.afterChildren.add(child);
child.setParent(this);
return;
}
final StringBuilder message = new StringBuilder();
message.append("Position ").append(position).append(" not recognized");
throw new IllegalArgumentException(message.toString());
}
public void setValidParents(Class<? extends BaseTag>... parents) {
if (Config.validateParents()) {
this.parents.addAll(Arrays.asList(parents));
}
}
@SuppressWarnings("unchecked")
protected <T> T findAncestor(Class<? extends BaseTag> clazz) {
return (T) SimpleTagSupport.findAncestorWithClass(this, clazz);
}
protected void renderChildren(List<BaseTag> children) throws JspException, IOException {
for (final BaseTag child : children) {
child.setJspContext(this.getJspContext());
child.doTag();
}
}
protected void wrapIn(NestedTagSupport wrapper) throws JspException, IOException {
wrapper.appendChild(this);
wrapper.setJspContext(super.getJspContext());
wrapper.setJspBody(super.getJspBody());
wrapper.doTag();
}
}
| src/org/bootstrapjsp/support/NestedTagSupport.java | /*
* Copyright (c) 2014 Darren Scott - All Rights Reserved
*
* This program is distributed under LGPL Version 2.1 in the hope that
* it will be useful, but WITHOUT ANY WARRANTY.
*/
package org.bootstrapjsp.support;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspTag;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import org.bootstrapjsp.util.Config;
public abstract class NestedTagSupport extends SimpleTagSupport implements BaseTag {
public static final int BEFORE_BODY = -1;
public static final int AROUND_BODY = 0;
public static final int AFTER_BODY = 1;
private final List<Class<? extends BaseTag>> parents = new ArrayList<Class<? extends BaseTag>>();
private final List<BaseTag> beforeChildren = new ArrayList<BaseTag>();
private final List<BaseTag> aroundChildren = new ArrayList<BaseTag>();
private final List<BaseTag> afterChildren = new ArrayList<BaseTag>();
private JspTag parent;
@Override
public void doTag() throws JspException, IOException {
this.doBeforeBody();
if (this.aroundChildren.size() > 0) {
BaseTag aroundChild = this.aroundChildren.get(0);
aroundChild.setJspContext(this.getJspContext());
aroundChild.setJspBody(this.getJspBody());
aroundChild.doTag();
} else if (this.getJspBody() != null) {
this.getJspBody().invoke(null);
}
this.doAfterBody();
}
protected void doBeforeBody() throws JspException, IOException {
this.renderChildren(this.beforeChildren);
}
protected void doAfterBody() throws JspException, IOException {
this.renderChildren(this.afterChildren);
}
@Override
public void setParent(JspTag parent) {
if (parent != null && this.parents.size() > 0) {
if (!this.parents.contains(parent.getClass())) {
final StringBuilder error = new StringBuilder("Invalid parent for ");
error.append(this).append(": ").append(parent);
throw new IllegalArgumentException(error.toString());
}
}
this.parent = parent;
super.setParent(parent);
}
public JspTag getParent() {
return this.parent;
}
public void appendChild(BaseTag child) {
this.appendChild(child, AROUND_BODY);
}
public void appendChild(BaseTag child, int position) {
if (position == BEFORE_BODY) {
this.beforeChildren.add(child);
child.setParent(this);
return;
} else if (position == AROUND_BODY) {
this.aroundChildren.add(child);
child.setParent(this);
return;
} else if (position == AFTER_BODY) {
this.afterChildren.add(child);
child.setParent(this);
return;
}
final StringBuilder message = new StringBuilder();
message.append("Position ").append(position).append(" not recognized");
throw new IllegalArgumentException(message.toString());
}
public void setValidParents(Class<? extends BaseTag>... parents) {
if (Config.validateParents()) {
this.parents.addAll(Arrays.asList(parents));
}
}
@SuppressWarnings("unchecked")
protected <T> T findAncestor(Class<? extends BaseTag> clazz) {
return (T) SimpleTagSupport.findAncestorWithClass(this, clazz);
}
protected void renderChildren(List<BaseTag> children) throws JspException, IOException {
for (final BaseTag child : children) {
child.setJspContext(this.getJspContext());
child.doTag();
}
}
protected void wrapIn(NestedTagSupport wrapper) throws JspException, IOException {
wrapper.appendChild(this);
wrapper.setJspContext(super.getJspContext());
wrapper.doTag();
}
}
| Fixed an issue with wrapIn() that prevented the body of the wrapped component from outputting | src/org/bootstrapjsp/support/NestedTagSupport.java | Fixed an issue with wrapIn() that prevented the body of the wrapped component from outputting |
|
Java | apache-2.0 | aab29f1ed7f8d217e8c099f2bba9ba4a7a9b2def | 0 | opensingular/singular-server,opensingular/singular-server,opensingular/singular-server | /*
*
* * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.opensingular.requirement.commons.wicket;
import javax.inject.Inject;
import net.vidageek.mirror.dsl.Mirror;
import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.IModel;
import org.junit.Test;
import org.opensingular.flow.core.TaskInstance;
import org.opensingular.form.SFormUtil;
import org.opensingular.form.SInstance;
import org.opensingular.form.document.RefType;
import org.opensingular.form.persistence.FormKey;
import org.opensingular.form.service.FormService;
import org.opensingular.form.spring.SpringSDocumentFactory;
import org.opensingular.form.util.transformer.Value;
import org.opensingular.form.wicket.component.SingularButton;
import org.opensingular.form.wicket.helpers.AssertionsWComponent;
import org.opensingular.form.wicket.helpers.SingularWicketTester;
import org.opensingular.lib.commons.lambda.IConsumer;
import org.opensingular.lib.wicket.util.ajax.ActionAjaxLink;
import org.opensingular.lib.wicket.util.bootstrap.layout.TemplatePanel;
import org.opensingular.requirement.commons.CommonsApplicationMock;
import org.opensingular.requirement.commons.SingularCommonsBaseTest;
import org.opensingular.requirement.module.form.FormAction;
import org.opensingular.requirement.module.service.RequirementInstance;
import org.opensingular.requirement.module.service.RequirementService;
import org.opensingular.requirement.module.test.SingularServletContextTestExecutionListener;
import org.opensingular.requirement.module.wicket.error.Page500;
import org.opensingular.requirement.module.wicket.view.form.FormPage;
import org.opensingular.requirement.module.wicket.view.form.SimpleMessageFlowConfirmModal;
import org.opensingular.requirement.module.wicket.view.util.ActionContext;
import org.opensingular.singular.pet.module.foobar.stuff.SPackageFoo;
import org.opensingular.singular.pet.module.foobar.stuff.STypeFoo;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.context.TestExecutionListeners;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Date;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@TestExecutionListeners(listeners = {SingularServletContextTestExecutionListener.class}, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS)
public class FormPageTest extends SingularCommonsBaseTest {
public static final String SUPER_TESTE_STRING = "SuperTeste";
@Inject
CommonsApplicationMock singularApplication;
@Inject
FormService formService;
@Inject
RequirementService requirementService;
@Inject
SpringSDocumentFactory documentFactory;
private SingularWicketTester tester;
@WithUserDetails("vinicius.nunes")
@Test
public void testFormPageRendering() {
tester = new SingularWicketTester(singularApplication);
ActionContext context = new ActionContext();
context.setFormName(SFormUtil.getTypeName(STypeFoo.class));
context.setFormAction(FormAction.FORM_FILL);
context.setRequirementDefinitionKey("FOO_REQ");
FormPage p = new FormPage(context);
tester.startPage(p);
tester.assertRenderedPage(FormPage.class);
}
@WithUserDetails("vinicius.nunes")
@Test
public void testSaveForm() {
tester = new SingularWicketTester(singularApplication);
saveDraft();
SInstance fooInstance = tester.getAssertionsInstance().getTarget();
FormKey formKey = FormKey.from(fooInstance);
assertNotNull(requirementService.getFormFlowInstanceEntity(fooInstance));
assertNotNull(formService.loadFormEntity(formKey));
SInstance si = formService.loadSInstance(formKey, RefType.of(STypeFoo.class), documentFactory);
assertEquals(SUPER_TESTE_STRING, Value.of(si, STypeFoo.FIELD_NOME));
}
private FormPage saveDraft() {
ActionContext context = new ActionContext();
context.setFormName(SFormUtil.getTypeName(STypeFoo.class));
context.setFormAction(FormAction.FORM_FILL);
context.setRequirementDefinitionKey(getRequirementDefinitionKey());
FormPage p = new FormPage(context);
tester.startPage(p);
tester.assertRenderedPage(FormPage.class);
TextField<String> t = (TextField<String>) new AssertionsWComponent(p).getSubComponents(TextField.class).first().getTarget();
t.getModel().setObject(SUPER_TESTE_STRING);
tester.executeAjaxEvent(new AssertionsWComponent(p).getSubComponentWithId("save-btn").getTarget(), "click");
return p;
}
public FormPage sendRequirement(SingularWicketTester tester, String formName, IConsumer<Page> formFiller) {
ActionContext context = new ActionContext();
context.setFormName(formName);
context.setFormAction(FormAction.FORM_FILL);
context.setRequirementDefinitionKey(getRequirementDefinitionKey());
FormPage p = new FormPage(context);
tester.startPage(p);
tester.assertRenderedPage(FormPage.class);
formFiller.accept(p);
tester.executeAjaxEvent(new AssertionsWComponent(p).getSubComponentWithId("send-btn").getTarget(), "click");
tester.executeAjaxEvent(new AssertionsWComponent(p).getSubComponentWithId("confirm-btn").getTarget(), "click");
return p;
}
@WithUserDetails("vinicius.nunes")
@Test
public void testSendForm() {
tester = new SingularWicketTester(singularApplication);
FormPage p = sendRequirement(tester, SFormUtil.getTypeName(STypeFoo.class), this::fillForm);
RequirementInstance requirement = getRequirementFrom(p);
assertNotNull(requirement.getFlowInstance());
}
private void fillForm(Page page) {
TextField<String> t = (TextField<String>) new AssertionsWComponent(page).getSubComponents(TextField.class).first().getTarget();
t.getModel().setObject(SUPER_TESTE_STRING);
}
@WithUserDetails("vinicius.nunes")
@Test
public void testLoadDraft() {
tester = new SingularWicketTester(singularApplication);
FormPage p = saveDraft();
RequirementInstance requirement = getRequirementFrom(p);
ActionContext context = new ActionContext();
context.setFormName(SFormUtil.getTypeName(STypeFoo.class));
context.setFormAction(FormAction.FORM_FILL);
context.setRequirementId(requirement.getCod());
FormPage p2 = new FormPage(context);
tester.startPage(p2);
tester.assertRenderedPage(FormPage.class);
TextField<String> t2 = (TextField<String>) new AssertionsWComponent(p2).getSubComponents(TextField.class).first().getTarget();
assertEquals(SUPER_TESTE_STRING, t2.getDefaultModelObject());
}
public RequirementInstance getRequirementFrom(FormPage p) {
return (RequirementInstance) ((IModel) new Mirror().on(p).invoke().method("getRequirementModel").withoutArgs()).getObject();
}
@WithUserDetails("vinicius.nunes")
@Test
public void testExecuteTransition() {
tester = new SingularWicketTester(singularApplication);
FormPage p = sendRequirement(tester, SFormUtil.getTypeName(STypeFoo.class), this::fillForm);
RequirementInstance requirement = getRequirementFrom(p);
ActionContext context = new ActionContext();
context.setFormName(SFormUtil.getTypeName(STypeFoo.class));
context.setFormAction(FormAction.FORM_ANALYSIS);
context.setRequirementId(requirement.getCod());
FormPage p2 = new FormPage(context);
tester.startPage(p2);
tester.assertRenderedPage(FormPage.class);
Component transitionButton = new AssertionsWComponent(p2)
.getSubComponentWithId("custom-buttons")
.getSubComponents(SingularButton.class)
.first()
.getTarget();
tester.executeAjaxEvent(transitionButton, "click");
Component confirmationButton = new AssertionsWComponent(p2)
.getSubComponentWithId("modals")
.getSubComponents(SimpleMessageFlowConfirmModal.class)
.first()
.getSubComponents(SingularButton.class)
.first()
.getTarget();
tester.executeAjaxEvent(confirmationButton, "click");
RequirementInstance requirementFrom = getRequirementFrom(p2);
TaskInstance currentTask = requirementFrom.getCurrentTaskOrException();
assertEquals("Transition bar", currentTask.getName());
}
@WithUserDetails("vinicius.nunes")
@Test
public void testFormPageWithoutContext() {
tester = new SingularWicketTester(singularApplication);
ActionContext context = new ActionContext();
context.setFormName(SFormUtil.getTypeName(STypeFoo.class));
FormPage p = new FormPage(context);
tester.startPage(p);
tester.assertRenderedPage(Page500.class);
}
@WithUserDetails("vinicius.nunes")
@Test
public void testOpenAnnotationAfterOpeningModal() {
tester = new SingularWicketTester(singularApplication);
ActionContext context = new ActionContext();
context.setFormName(SPackageFoo.STypeFOOModal.FULL_NAME);
context.setFormAction(FormAction.FORM_FILL_WITH_ANALYSIS_FILL);
context.setRequirementDefinitionKey(getRequirementDefinitionKey());
FormPage p = new FormPage(context);
tester.startPage(p);
tester.assertRenderedPage(FormPage.class);
Form f = (Form) new AssertionsWComponent(p).getSubComponents(Form.class).first().getTarget();
f.setMultiPart(false);
Component addPessoa = p.get("save-form:singular-panel:generated:_:1:_:1:_:1:_:1:_:2:_:1:_:3:_:1:_:1:panel:form:footer:addButton");
tester.executeAjaxEvent(addPessoa, "click");
Component linkAnnotation = tester.getAssertionsPage().getSubComponents(ActionAjaxLink.class).first().getTarget();
tester.executeAjaxEvent(linkAnnotation, "click");
Component justificativa = tester.getAssertionsPage().getSubComponents(TextArea.class).first().getTarget();
assertEquals(justificativa.getId(), "justificativa");
assertTrue(justificativa.isVisibleInHierarchy());
}
}
| requirement/requirement-module/src/test/java/org/opensingular/requirement/commons/wicket/FormPageTest.java | /*
*
* * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package org.opensingular.requirement.commons.wicket;
import javax.inject.Inject;
import net.vidageek.mirror.dsl.Mirror;
import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.IModel;
import org.junit.Test;
import org.opensingular.flow.core.TaskInstance;
import org.opensingular.form.SFormUtil;
import org.opensingular.form.SInstance;
import org.opensingular.form.document.RefType;
import org.opensingular.form.persistence.FormKey;
import org.opensingular.form.service.FormService;
import org.opensingular.form.spring.SpringSDocumentFactory;
import org.opensingular.form.util.transformer.Value;
import org.opensingular.form.wicket.component.SingularButton;
import org.opensingular.form.wicket.helpers.AssertionsWComponent;
import org.opensingular.form.wicket.helpers.SingularWicketTester;
import org.opensingular.lib.commons.lambda.IConsumer;
import org.opensingular.lib.wicket.util.ajax.ActionAjaxLink;
import org.opensingular.lib.wicket.util.bootstrap.layout.TemplatePanel;
import org.opensingular.requirement.commons.CommonsApplicationMock;
import org.opensingular.requirement.commons.SingularCommonsBaseTest;
import org.opensingular.requirement.module.form.FormAction;
import org.opensingular.requirement.module.service.RequirementInstance;
import org.opensingular.requirement.module.service.RequirementService;
import org.opensingular.requirement.module.test.SingularServletContextTestExecutionListener;
import org.opensingular.requirement.module.wicket.error.Page500;
import org.opensingular.requirement.module.wicket.view.form.FormPage;
import org.opensingular.requirement.module.wicket.view.util.ActionContext;
import org.opensingular.singular.pet.module.foobar.stuff.SPackageFoo;
import org.opensingular.singular.pet.module.foobar.stuff.STypeFoo;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.context.TestExecutionListeners;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Date;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@TestExecutionListeners(listeners = {SingularServletContextTestExecutionListener.class}, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS)
public class FormPageTest extends SingularCommonsBaseTest {
public static final String SUPER_TESTE_STRING = "SuperTeste";
@Inject
CommonsApplicationMock singularApplication;
@Inject
FormService formService;
@Inject
RequirementService requirementService;
@Inject
SpringSDocumentFactory documentFactory;
private SingularWicketTester tester;
@WithUserDetails("vinicius.nunes")
@Test
public void testFormPageRendering() {
tester = new SingularWicketTester(singularApplication);
ActionContext context = new ActionContext();
context.setFormName(SFormUtil.getTypeName(STypeFoo.class));
context.setFormAction(FormAction.FORM_FILL);
context.setRequirementDefinitionKey("FOO_REQ");
FormPage p = new FormPage(context);
tester.startPage(p);
tester.assertRenderedPage(FormPage.class);
}
@WithUserDetails("vinicius.nunes")
@Test
public void testSaveForm() {
tester = new SingularWicketTester(singularApplication);
saveDraft();
SInstance fooInstance = tester.getAssertionsInstance().getTarget();
FormKey formKey = FormKey.from(fooInstance);
assertNotNull(requirementService.getFormFlowInstanceEntity(fooInstance));
assertNotNull(formService.loadFormEntity(formKey));
SInstance si = formService.loadSInstance(formKey, RefType.of(STypeFoo.class), documentFactory);
assertEquals(SUPER_TESTE_STRING, Value.of(si, STypeFoo.FIELD_NOME));
}
private FormPage saveDraft() {
ActionContext context = new ActionContext();
context.setFormName(SFormUtil.getTypeName(STypeFoo.class));
context.setFormAction(FormAction.FORM_FILL);
context.setRequirementDefinitionKey(getRequirementDefinitionKey());
FormPage p = new FormPage(context);
tester.startPage(p);
tester.assertRenderedPage(FormPage.class);
TextField<String> t = (TextField<String>) new AssertionsWComponent(p).getSubComponents(TextField.class).first().getTarget();
t.getModel().setObject(SUPER_TESTE_STRING);
tester.executeAjaxEvent(new AssertionsWComponent(p).getSubComponentWithId("save-btn").getTarget(), "click");
return p;
}
public FormPage sendRequirement(SingularWicketTester tester, String formName, IConsumer<Page> formFiller) {
ActionContext context = new ActionContext();
context.setFormName(formName);
context.setFormAction(FormAction.FORM_FILL);
context.setRequirementDefinitionKey(getRequirementDefinitionKey());
FormPage p = new FormPage(context);
tester.startPage(p);
tester.assertRenderedPage(FormPage.class);
formFiller.accept(p);
tester.executeAjaxEvent(new AssertionsWComponent(p).getSubComponentWithId("send-btn").getTarget(), "click");
tester.executeAjaxEvent(new AssertionsWComponent(p).getSubComponentWithId("confirm-btn").getTarget(), "click");
return p;
}
@WithUserDetails("vinicius.nunes")
@Test
public void testSendForm() {
tester = new SingularWicketTester(singularApplication);
FormPage p = sendRequirement(tester, SFormUtil.getTypeName(STypeFoo.class), this::fillForm);
RequirementInstance requirement = getRequirementFrom(p);
assertNotNull(requirement.getFlowInstance());
}
private void fillForm(Page page) {
TextField<String> t = (TextField<String>) new AssertionsWComponent(page).getSubComponents(TextField.class).first().getTarget();
t.getModel().setObject(SUPER_TESTE_STRING);
}
@WithUserDetails("vinicius.nunes")
@Test
public void testLoadDraft() {
tester = new SingularWicketTester(singularApplication);
FormPage p = saveDraft();
RequirementInstance requirement = getRequirementFrom(p);
ActionContext context = new ActionContext();
context.setFormName(SFormUtil.getTypeName(STypeFoo.class));
context.setFormAction(FormAction.FORM_FILL);
context.setRequirementId(requirement.getCod());
FormPage p2 = new FormPage(context);
tester.startPage(p2);
tester.assertRenderedPage(FormPage.class);
TextField<String> t2 = (TextField<String>) new AssertionsWComponent(p2).getSubComponents(TextField.class).first().getTarget();
assertEquals(SUPER_TESTE_STRING, t2.getDefaultModelObject());
}
public RequirementInstance getRequirementFrom(FormPage p) {
return (RequirementInstance) ((IModel) new Mirror().on(p).invoke().method("getRequirementModel").withoutArgs()).getObject();
}
@WithUserDetails("vinicius.nunes")
@Test
public void testExecuteTransition() {
tester = new SingularWicketTester(singularApplication);
FormPage p = sendRequirement(tester, SFormUtil.getTypeName(STypeFoo.class), this::fillForm);
RequirementInstance requirement = getRequirementFrom(p);
ActionContext context = new ActionContext();
context.setFormName(SFormUtil.getTypeName(STypeFoo.class));
context.setFormAction(FormAction.FORM_ANALYSIS);
context.setRequirementId(requirement.getCod());
FormPage p2 = new FormPage(context);
tester.startPage(p2);
tester.assertRenderedPage(FormPage.class);
Component transitionButton = new AssertionsWComponent(p2)
.getSubComponentWithId("custom-buttons")
.getSubComponents(SingularButton.class)
.first()
.getTarget();
tester.executeAjaxEvent(transitionButton, "click");
Component confirmationButton = new AssertionsWComponent(p2)
.getSubComponentWithId("modals")
.getSubComponents(TemplatePanel.class)
.last()
.getSubComponents(SingularButton.class)
.first()
.getTarget();
tester.executeAjaxEvent(confirmationButton, "click");
RequirementInstance requirementFrom = getRequirementFrom(p2);
TaskInstance currentTask = requirementFrom.getCurrentTaskOrException();
assertEquals("No more bar", currentTask.getName());
}
@WithUserDetails("vinicius.nunes")
@Test
public void testFormPageWithoutContext() {
tester = new SingularWicketTester(singularApplication);
ActionContext context = new ActionContext();
context.setFormName(SFormUtil.getTypeName(STypeFoo.class));
FormPage p = new FormPage(context);
tester.startPage(p);
tester.assertRenderedPage(Page500.class);
}
@WithUserDetails("vinicius.nunes")
@Test
public void testOpenAnnotationAfterOpeningModal() {
tester = new SingularWicketTester(singularApplication);
ActionContext context = new ActionContext();
context.setFormName(SPackageFoo.STypeFOOModal.FULL_NAME);
context.setFormAction(FormAction.FORM_FILL_WITH_ANALYSIS_FILL);
context.setRequirementDefinitionKey(getRequirementDefinitionKey());
FormPage p = new FormPage(context);
tester.startPage(p);
tester.assertRenderedPage(FormPage.class);
Form f = (Form) new AssertionsWComponent(p).getSubComponents(Form.class).first().getTarget();
f.setMultiPart(false);
Component addPessoa = p.get("save-form:singular-panel:generated:_:1:_:1:_:1:_:1:_:2:_:1:_:3:_:1:_:1:panel:form:footer:addButton");
tester.executeAjaxEvent(addPessoa, "click");
Component linkAnnotation = tester.getAssertionsPage().getSubComponents(ActionAjaxLink.class).first().getTarget();
tester.executeAjaxEvent(linkAnnotation, "click");
Component justificativa = tester.getAssertionsPage().getSubComponents(TextArea.class).first().getTarget();
assertEquals(justificativa.getId(), "justificativa");
assertTrue(justificativa.isVisibleInHierarchy());
}
}
| [SGL-751] fixing unit test
| requirement/requirement-module/src/test/java/org/opensingular/requirement/commons/wicket/FormPageTest.java | [SGL-751] fixing unit test |
|
Java | apache-2.0 | dfec812c030974b6dad20d755b7edf299d81b383 | 0 | bkirschn/sakai,frasese/sakai,noondaysun/sakai,tl-its-umich-edu/sakai,Fudan-University/sakai,introp-software/sakai,conder/sakai,willkara/sakai,bzhouduke123/sakai,lorenamgUMU/sakai,ouit0408/sakai,whumph/sakai,conder/sakai,OpenCollabZA/sakai,joserabal/sakai,tl-its-umich-edu/sakai,puramshetty/sakai,introp-software/sakai,surya-janani/sakai,OpenCollabZA/sakai,colczr/sakai,kingmook/sakai,zqian/sakai,joserabal/sakai,conder/sakai,liubo404/sakai,colczr/sakai,clhedrick/sakai,zqian/sakai,lorenamgUMU/sakai,zqian/sakai,buckett/sakai-gitflow,conder/sakai,clhedrick/sakai,rodriguezdevera/sakai,noondaysun/sakai,rodriguezdevera/sakai,willkara/sakai,bkirschn/sakai,wfuedu/sakai,willkara/sakai,zqian/sakai,Fudan-University/sakai,OpenCollabZA/sakai,kingmook/sakai,zqian/sakai,hackbuteer59/sakai,frasese/sakai,tl-its-umich-edu/sakai,introp-software/sakai,wfuedu/sakai,tl-its-umich-edu/sakai,kwedoff1/sakai,joserabal/sakai,bzhouduke123/sakai,whumph/sakai,kingmook/sakai,bkirschn/sakai,surya-janani/sakai,surya-janani/sakai,frasese/sakai,surya-janani/sakai,kwedoff1/sakai,joserabal/sakai,buckett/sakai-gitflow,bzhouduke123/sakai,wfuedu/sakai,noondaysun/sakai,pushyamig/sakai,duke-compsci290-spring2016/sakai,tl-its-umich-edu/sakai,bzhouduke123/sakai,kwedoff1/sakai,ouit0408/sakai,hackbuteer59/sakai,bkirschn/sakai,wfuedu/sakai,lorenamgUMU/sakai,duke-compsci290-spring2016/sakai,ktakacs/sakai,clhedrick/sakai,bkirschn/sakai,udayg/sakai,Fudan-University/sakai,kwedoff1/sakai,liubo404/sakai,noondaysun/sakai,liubo404/sakai,ouit0408/sakai,rodriguezdevera/sakai,bkirschn/sakai,colczr/sakai,buckett/sakai-gitflow,noondaysun/sakai,zqian/sakai,wfuedu/sakai,puramshetty/sakai,whumph/sakai,conder/sakai,pushyamig/sakai,tl-its-umich-edu/sakai,clhedrick/sakai,joserabal/sakai,bzhouduke123/sakai,duke-compsci290-spring2016/sakai,willkara/sakai,surya-janani/sakai,ouit0408/sakai,hackbuteer59/sakai,kingmook/sakai,pushyamig/sakai,colczr/sakai,buckett/sakai-gitflow,puramshetty/sakai,introp-software/sakai,buckett/sakai-gitflow,puramshetty/sakai,colczr/sakai,udayg/sakai,Fudan-University/sakai,buckett/sakai-gitflow,wfuedu/sakai,hackbuteer59/sakai,bkirschn/sakai,ktakacs/sakai,hackbuteer59/sakai,bkirschn/sakai,wfuedu/sakai,wfuedu/sakai,bzhouduke123/sakai,pushyamig/sakai,noondaysun/sakai,OpenCollabZA/sakai,frasese/sakai,hackbuteer59/sakai,liubo404/sakai,kwedoff1/sakai,Fudan-University/sakai,frasese/sakai,clhedrick/sakai,kingmook/sakai,pushyamig/sakai,colczr/sakai,introp-software/sakai,introp-software/sakai,frasese/sakai,willkara/sakai,hackbuteer59/sakai,Fudan-University/sakai,ktakacs/sakai,ktakacs/sakai,rodriguezdevera/sakai,clhedrick/sakai,whumph/sakai,OpenCollabZA/sakai,pushyamig/sakai,liubo404/sakai,zqian/sakai,ktakacs/sakai,udayg/sakai,Fudan-University/sakai,rodriguezdevera/sakai,surya-janani/sakai,willkara/sakai,frasese/sakai,puramshetty/sakai,colczr/sakai,duke-compsci290-spring2016/sakai,kingmook/sakai,kingmook/sakai,noondaysun/sakai,noondaysun/sakai,clhedrick/sakai,joserabal/sakai,kwedoff1/sakai,whumph/sakai,buckett/sakai-gitflow,liubo404/sakai,surya-janani/sakai,frasese/sakai,tl-its-umich-edu/sakai,kingmook/sakai,bzhouduke123/sakai,rodriguezdevera/sakai,whumph/sakai,OpenCollabZA/sakai,conder/sakai,rodriguezdevera/sakai,udayg/sakai,introp-software/sakai,whumph/sakai,buckett/sakai-gitflow,colczr/sakai,lorenamgUMU/sakai,udayg/sakai,bzhouduke123/sakai,lorenamgUMU/sakai,lorenamgUMU/sakai,udayg/sakai,introp-software/sakai,liubo404/sakai,pushyamig/sakai,surya-janani/sakai,lorenamgUMU/sakai,ktakacs/sakai,puramshetty/sakai,conder/sakai,puramshetty/sakai,tl-its-umich-edu/sakai,hackbuteer59/sakai,ouit0408/sakai,conder/sakai,willkara/sakai,ouit0408/sakai,duke-compsci290-spring2016/sakai,clhedrick/sakai,puramshetty/sakai,OpenCollabZA/sakai,joserabal/sakai,pushyamig/sakai,udayg/sakai,duke-compsci290-spring2016/sakai,ouit0408/sakai,Fudan-University/sakai,kwedoff1/sakai,rodriguezdevera/sakai,liubo404/sakai,kwedoff1/sakai,ouit0408/sakai,lorenamgUMU/sakai,duke-compsci290-spring2016/sakai,willkara/sakai,joserabal/sakai,zqian/sakai,duke-compsci290-spring2016/sakai,ktakacs/sakai,udayg/sakai,ktakacs/sakai,OpenCollabZA/sakai,whumph/sakai | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2006, 2007, 2008, 2009 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.citation.tool;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.io.input.BOMInputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.antivirus.api.VirusFoundException;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.VelocityPortletPaneledAction;
import org.sakaiproject.citation.api.ActiveSearch;
import org.sakaiproject.citation.api.Citation;
import org.sakaiproject.citation.api.CitationCollection;
import org.sakaiproject.citation.api.CitationHelper;
import org.sakaiproject.citation.api.CitationIterator;
import org.sakaiproject.citation.api.CitationService;
import org.sakaiproject.citation.api.ConfigurationService;
import org.sakaiproject.citation.api.Schema;
import org.sakaiproject.citation.api.Schema.Field;
import org.sakaiproject.citation.api.SearchCategory;
import org.sakaiproject.citation.api.SearchDatabaseHierarchy;
import org.sakaiproject.citation.api.SearchManager;
import org.sakaiproject.citation.util.api.SearchCancelException;
import org.sakaiproject.citation.util.api.SearchException;
import org.sakaiproject.citation.util.api.SearchQuery;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.content.api.ContentCollection;
import org.sakaiproject.content.api.ContentEntity;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.content.api.GroupAwareEntity.AccessMode;
import org.sakaiproject.content.api.ResourceToolAction;
import org.sakaiproject.content.api.ResourceToolActionPipe;
import org.sakaiproject.content.api.ResourceType;
import org.sakaiproject.entity.api.EntityManager;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdLengthException;
import org.sakaiproject.exception.IdUniquenessException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.InconsistentException;
import org.sakaiproject.exception.OverQuotaException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.ServerOverloadException;
import org.sakaiproject.exception.TypeException;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.api.ToolException;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.util.FileItem;
import org.sakaiproject.util.ParameterParser;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.Validator;
import org.sakaiproject.util.api.FormattedText;
/**
*
*/
public class CitationHelperAction extends VelocityPortletPaneledAction
{
/**
* This class contains constants and utility methods to maintain state of
* the advanced search form UI and process submitted data
*
* @author gbhatnag
*/
protected static class AdvancedSearchHelper
{
/* ids for fields */
public static final String KEYWORD_ID = "keyword";
public static final String AUTHOR_ID = "author";
public static final String TITLE_ID = "title";
public static final String SUBJECT_ID = "subject";
public static final String YEAR_ID = "year";
/* keys to hold state information */
public static final String STATE_FIELD1 = CitationHelper.CITATION_PREFIX + "advField1";
public static final String STATE_FIELD2 = CitationHelper.CITATION_PREFIX + "advField2";
public static final String STATE_FIELD3 = CitationHelper.CITATION_PREFIX + "advField3";
public static final String STATE_FIELD4 = CitationHelper.CITATION_PREFIX + "advField4";
public static final String STATE_FIELD5 = CitationHelper.CITATION_PREFIX + "advField5";
public static final String STATE_CRITERIA1 = CitationHelper.CITATION_PREFIX + "advCriteria1";
public static final String STATE_CRITERIA2 = CitationHelper.CITATION_PREFIX + "advCriteria2";
public static final String STATE_CRITERIA3 = CitationHelper.CITATION_PREFIX + "advCriteria3";
public static final String STATE_CRITERIA4 = CitationHelper.CITATION_PREFIX + "advCriteria4";
public static final String STATE_CRITERIA5 = CitationHelper.CITATION_PREFIX + "advCriteria5";
/**
* Puts field selections stored in session state (using setFieldSelections())
* into the given context
*
* @param context context to put field selections into
* @param state SessionState to pull field selections from
*/
public static void putFieldSelections( Context context, SessionState state )
{
/*
context.put( "advField1", ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD1 ) );
context.put( "advField2", ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD2 ) );
context.put( "advField3", ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD3 ) );
context.put( "advField4", ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD4 ) );
context.put( "advField5", ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD5 ) );
*/
String advField1 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD1 );
String advField2 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD2 );
String advField3 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD3 );
String advField4 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD4 );
String advField5 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD5 );
if( advField1 != null && !advField1.trim().equals("") )
{
context.put( "advField1", advField1 );
}
else
{
context.put( "advField1", KEYWORD_ID );
}
if( advField2 != null && !advField2.trim().equals("") )
{
context.put( "advField2", advField2 );
}
else
{
context.put( "advField2", AUTHOR_ID );
}
if( advField3 != null && !advField3.trim().equals("") )
{
context.put( "advField3", advField3 );
}
else
{
context.put( "advField3", TITLE_ID );
}
if( advField4 != null && !advField4.trim().equals("") )
{
context.put( "advField4", advField4 );
}
else
{
context.put( "advField4", SUBJECT_ID );
}
if( advField5 != null && !advField5.trim().equals("") )
{
context.put( "advField5", advField5 );
}
else
{
context.put( "advField5", YEAR_ID );
}
}
/**
* Puts field criteria stored in session state (using setFieldCriteria())
* into the given context
*
* @param context context to put field criteria into
* @param state SessionState to pull field criteria from
*/
public static void putFieldCriteria( Context context, SessionState state )
{
context.put( "advCriteria1", ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA1 ) );
context.put( "advCriteria2", ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA2 ) );
context.put( "advCriteria3", ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA3 ) );
context.put( "advCriteria4", ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA4 ) );
context.put( "advCriteria5", ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA5 ) );
}
/**
* Sets user-selected fields in session state from request parameters
*
* @param params request parameters from doBeginSearch
* @param state SessionState to store field selections
*/
public static void setFieldSelections( ParameterParser params, SessionState state )
{
String advField1 = params.getString( "advField1" );
if( advField1 != null && !advField1.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_FIELD1, advField1 );
}
String advField2 = params.getString( "advField2" );
if( advField2 != null && !advField2.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_FIELD2, advField2 );
}
String advField3 = params.getString( "advField3" );
if( advField3 != null && !advField3.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_FIELD3, advField3 );
}
String advField4 = params.getString( "advField4" );
if( advField4 != null && !advField4.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_FIELD4, advField4 );
}
String advField5 = params.getString( "advField5" );
if( advField5 != null && !advField5.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_FIELD5, advField5 );
}
}
/**
* Sets user-entered search field criteria in session state
* from request parameters
*
* @param params request parameters from doBeginSearch
* @param state SessionState to store field criteria
*/
public static void setFieldCriteria( ParameterParser params, SessionState state )
{
String advCriteria1 = params.getString( "advCriteria1" );
if( advCriteria1 != null && !advCriteria1.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_CRITERIA1, advCriteria1 );
}
String advCriteria2 = params.getString( "advCriteria2" );
if( advCriteria2 != null && !advCriteria2.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_CRITERIA2, advCriteria2 );
}
String advCriteria3 = params.getString( "advCriteria3" );
if( advCriteria3 != null && !advCriteria3.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_CRITERIA3, advCriteria3 );
}
String advCriteria4 = params.getString( "advCriteria4" );
if( advCriteria4 != null && !advCriteria4.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_CRITERIA4, advCriteria4 );
}
String advCriteria5 = params.getString( "advCriteria5" );
if( advCriteria5 != null && !advCriteria5.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_CRITERIA5, advCriteria5 );
}
}
public static SearchQuery getAdvancedCriteria( SessionState state )
{
String advField1 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD1 );
String advField2 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD2 );
String advField3 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD3 );
String advField4 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD4 );
String advField5 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD5 );
String advCriteria1 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA1 );
String advCriteria2 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA2 );
String advCriteria3 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA3 );
String advCriteria4 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA4 );
String advCriteria5 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA5 );
SearchQuery searchQuery = new org.sakaiproject.citation.util.impl.SearchQuery();
/*
* put fielded, non-null criteria into the searchQuery
*/
if( advField1 != null && advCriteria1 != null )
{
if( advField1.equalsIgnoreCase( KEYWORD_ID ) )
{
searchQuery.addKeywords( advCriteria1 );
}
else if( advField1.equalsIgnoreCase( AUTHOR_ID ) )
{
searchQuery.addAuthor( advCriteria1 );
}
else if( advField1.equalsIgnoreCase( TITLE_ID ) )
{
searchQuery.addTitle( advCriteria1 );
}
else if( advField1.equalsIgnoreCase( SUBJECT_ID ) )
{
searchQuery.addSubject( advCriteria1 );
}
else if( advField1.equalsIgnoreCase( YEAR_ID ) )
{
searchQuery.addYear( advCriteria1 );
}
}
if( advField2 != null && advCriteria2 != null )
{
if( advField2.equalsIgnoreCase( KEYWORD_ID ) )
{
searchQuery.addKeywords( advCriteria2 );
}
else if( advField2.equalsIgnoreCase( AUTHOR_ID ) )
{
searchQuery.addAuthor( advCriteria2 );
}
else if( advField2.equalsIgnoreCase( TITLE_ID ) )
{
searchQuery.addTitle( advCriteria2 );
}
else if( advField2.equalsIgnoreCase( SUBJECT_ID ) )
{
searchQuery.addSubject( advCriteria2 );
}
else if( advField2.equalsIgnoreCase( YEAR_ID ) )
{
searchQuery.addYear( advCriteria2 );
}
}
if( advField3 != null && advCriteria3 != null )
{
if( advField3.equalsIgnoreCase( KEYWORD_ID ) )
{
searchQuery.addKeywords( advCriteria3 );
}
else if( advField3.equalsIgnoreCase( AUTHOR_ID ) )
{
searchQuery.addAuthor( advCriteria3 );
}
else if( advField3.equalsIgnoreCase( TITLE_ID ) )
{
searchQuery.addTitle( advCriteria3 );
}
else if( advField3.equalsIgnoreCase( SUBJECT_ID ) )
{
searchQuery.addSubject( advCriteria3 );
}
else if( advField3.equalsIgnoreCase( YEAR_ID ) )
{
searchQuery.addYear( advCriteria3 );
}
}
if( advField4 != null && advCriteria4 != null )
{
if( advField4.equalsIgnoreCase( KEYWORD_ID ) )
{
searchQuery.addKeywords( advCriteria4 );
}
else if( advField4.equalsIgnoreCase( AUTHOR_ID ) )
{
searchQuery.addAuthor( advCriteria4 );
}
else if( advField4.equalsIgnoreCase( TITLE_ID ) )
{
searchQuery.addTitle( advCriteria4 );
}
else if( advField4.equalsIgnoreCase( SUBJECT_ID ) )
{
searchQuery.addSubject( advCriteria4 );
}
else if( advField4.equalsIgnoreCase( YEAR_ID ) )
{
searchQuery.addYear( advCriteria4 );
}
}
if( advField5 != null && advCriteria5 != null )
{
if( advField5.equalsIgnoreCase( KEYWORD_ID ) )
{
searchQuery.addKeywords( advCriteria5 );
}
else if( advField5.equalsIgnoreCase( AUTHOR_ID ) )
{
searchQuery.addAuthor( advCriteria5 );
}
else if( advField5.equalsIgnoreCase( TITLE_ID ) )
{
searchQuery.addTitle( advCriteria5 );
}
else if( advField5.equalsIgnoreCase( SUBJECT_ID ) )
{
searchQuery.addSubject( advCriteria5 );
}
else if( advField5.equalsIgnoreCase( YEAR_ID ) )
{
searchQuery.addYear( advCriteria5 );
}
}
return searchQuery;
}
public static void clearAdvancedFormState( SessionState state )
{
state.removeAttribute( AdvancedSearchHelper.STATE_FIELD1 );
state.removeAttribute( AdvancedSearchHelper.STATE_FIELD2 );
state.removeAttribute( AdvancedSearchHelper.STATE_FIELD3 );
state.removeAttribute( AdvancedSearchHelper.STATE_FIELD4 );
state.removeAttribute( AdvancedSearchHelper.STATE_FIELD5 );
state.removeAttribute( AdvancedSearchHelper.STATE_CRITERIA1 );
state.removeAttribute( AdvancedSearchHelper.STATE_CRITERIA2 );
state.removeAttribute( AdvancedSearchHelper.STATE_CRITERIA3 );
state.removeAttribute( AdvancedSearchHelper.STATE_CRITERIA4 );
state.removeAttribute( AdvancedSearchHelper.STATE_CRITERIA5 );
}
}
protected final static Log logger = LogFactory.getLog(CitationHelperAction.class);
public static ResourceLoader rb = new ResourceLoader("citations");
protected CitationService citationService;
protected ConfigurationService configurationService;
protected SearchManager searchManager;
protected ContentHostingService contentService;
protected EntityManager entityManager;
protected SessionManager sessionManager;
protected static FormattedText formattedText;
protected static ToolManager toolManager;
public static final Integer DEFAULT_RESULTS_PAGE_SIZE = new Integer(10);
public static final Integer DEFAULT_LIST_PAGE_SIZE = new Integer(50);
public static Integer defaultListPageSize = DEFAULT_LIST_PAGE_SIZE;
protected static final String ELEMENT_ID_CREATE_FORM = "createForm";
protected static final String ELEMENT_ID_EDIT_FORM = "editForm";
protected static final String ELEMENT_ID_LIST_FORM = "listForm";
protected static final String ELEMENT_ID_SEARCH_FORM = "searchForm";
protected static final String ELEMENT_ID_RESULTS_FORM = "resultsForm";
protected static final String ELEMENT_ID_VIEW_FORM = "viewForm";
/**
* The calling application reflects the nature of our caller
*/
public final static String CITATIONS_HELPER_CALLER = "citations_helper_caller";
public enum Caller
{
RESOURCE_TOOL,
EDITOR_INTEGRATION;
}
/**
* Mode defines a complete set of values describing the user's navigation intentions
*/
public enum Mode
{
NEW_RESOURCE,
DATABASE,
CREATE,
EDIT,
ERROR,
ERROR_FATAL,
LIST,
REORDER,
ADD_CITATIONS,
IMPORT_CITATIONS,
MESSAGE,
SEARCH,
RESULTS,
VIEW;
}
/*
* define a set of "fake" Modes (asynchronous calls) to maintain proper
* back-button stack state
*/
protected static Set<Mode> ignoreModes = new java.util.HashSet<Mode>();
static {
ignoreModes.add( Mode.DATABASE );
ignoreModes.add( Mode.MESSAGE );
}
protected static final String PARAM_FORM_NAME = "FORM_NAME";
protected static final String STATE_RESOURCES_ADD = CitationHelper.CITATION_PREFIX + "resources_add";
protected static final String STATE_CURRENT_DATABASES = CitationHelper.CITATION_PREFIX + "current_databases";
protected static final String STATE_CANCEL_PAGE = CitationHelper.CITATION_PREFIX + "cancel_page";
protected static final String STATE_CITATION_COLLECTION_ID = CitationHelper.CITATION_PREFIX + "citation_collection_id";
protected static final String STATE_CITATION_COLLECTION = CitationHelper.CITATION_PREFIX + "citation_collection";
protected static final String STATE_CITATION_ID = CitationHelper.CITATION_PREFIX + "citation_id";
protected static final String STATE_COLLECTION_TITLE = CitationHelper.CITATION_PREFIX + "collection_name";
protected static final String STATE_CURRENT_REPOSITORY = CitationHelper.CITATION_PREFIX + "current_repository";
protected static final String STATE_CURRENT_RESULTS = CitationHelper.CITATION_PREFIX + "current_results";
protected static final String STATE_LIST_ITERATOR = CitationHelper.CITATION_PREFIX + "list_iterator";
protected static final String STATE_LIST_PAGE = CitationHelper.CITATION_PREFIX + "list_page";
protected static final String STATE_LIST_PAGE_SIZE = CitationHelper.CITATION_PREFIX + "list_page_size";
protected static final String STATE_LIST_NO_SCROLL = CitationHelper.CITATION_PREFIX + "list_no_scroll";
protected static final String STATE_NO_KEYWORDS = CitationHelper.CITATION_PREFIX + "no_search_criteria";
protected static final String STATE_NO_DATABASES = CitationHelper.CITATION_PREFIX + "no_databases";
protected static final String STATE_NO_RESULTS = CitationHelper.CITATION_PREFIX + "no_results";
protected static final String STATE_SEARCH_HIERARCHY = CitationHelper.CITATION_PREFIX + "search_hierarchy";
protected static final String STATE_SELECTED_CATEGORY = CitationHelper.CITATION_PREFIX + "selected_category";
protected static final String STATE_DEFAULT_CATEGORY = CitationHelper.CITATION_PREFIX + "default_category";
protected static final String STATE_UNAUTHORIZED_DB = CitationHelper.CITATION_PREFIX + "unauthorized_database";
protected static final String STATE_REPOSITORY_MAP = CitationHelper.CITATION_PREFIX + "repository_map";
protected static final String STATE_RESULTS_PAGE_SIZE = CitationHelper.CITATION_PREFIX + "results_page_size";
protected static final String STATE_KEYWORDS = CitationHelper.CITATION_PREFIX + "search_criteria";
protected static final String STATE_SEARCH_INFO = CitationHelper.CITATION_PREFIX + "search_info";
protected static final String STATE_BASIC_SEARCH = CitationHelper.CITATION_PREFIX + "basic_search";
protected static final String STATE_SEARCH_RESULTS = CitationHelper.CITATION_PREFIX + "search_results";
protected static final String STATE_RESOURCE_ENTITY_PROPERTIES = CitationHelper.CITATION_PREFIX + "citationList_properties";
protected static final String STATE_SORT = CitationHelper.CITATION_PREFIX + "sort";
protected static final String TEMPLATE_NEW_RESOURCE = "citation/new_resource";
protected static final String TEMPLATE_CREATE = "citation/create";
protected static final String TEMPLATE_EDIT = "citation/edit";
protected static final String TEMPLATE_ERROR = "citation/error";
protected static final String TEMPLATE_ERROR_FATAL = "citation/error_fatal";
protected static final String TEMPLATE_LIST = "citation/list";
protected static final String TEMPLATE_REORDER = "citation/reorder";
protected static final String TEMPLATE_ADD_CITATIONS = "citation/add_citations";
protected static final String TEMPLATE_IMPORT_CITATIONS = "citation/import_citations";
protected static final String TEMPLATE_MESSAGE = "citation/_message";
protected static final String TEMPLATE_SEARCH = "citation/search";
protected static final String TEMPLATE_RESULTS = "citation/results";
protected static final String TEMPLATE_VIEW = "citation/view";
protected static final String TEMPLATE_DATABASE = "citation/_databases";
protected static final String PROP_ACCESS_MODE = "accessMode";
protected static final String PROP_IS_COLLECTION = "isCollection";
protected static final String PROP_IS_DROPBOX = "isDropbox";
protected static final String PROP_IS_GROUP_INHERITED = "isGroupInherited";
protected static final String PROP_IS_GROUP_POSSIBLE = "isGroupPossible";
protected static final String PROP_IS_HIDDEN = "isHidden";
protected static final String PROP_IS_PUBVIEW = "isPubview";
protected static final String PROP_IS_PUBVIEW_INHERITED = "isPubviewInherited";
protected static final String PROP_IS_PUBVIEW_POSSIBLE = "isPubviewPossible";
protected static final String PROP_IS_SINGLE_GROUP_INHERITED = "isSingleGroupInherited";
protected static final String PROP_IS_SITE_COLLECTION = "isSiteCollection";
protected static final String PROP_IS_SITE_ONLY = "isSiteOnly";
protected static final String PROP_IS_USER_SITE = "isUserSite";
protected static final String PROP_POSSIBLE_GROUPS = "possibleGroups";
protected static final String PROP_RELEASE_DATE = "releaseDate";
protected static final String PROP_RELEASE_DATE_STR = "releaseDateStr";
protected static final String PROP_RETRACT_DATE = "retractDate";
protected static final String PROP_RETRACT_DATE_STR = "retractDateStr";
protected static final String PROP_USE_RELEASE_DATE = "useReleaseDate";
protected static final String PROP_USE_RETRACT_DATE = "useRetractDate";
public static final String CITATION_ACTION = "citation_action";
public static final String UPDATE_RESOURCE = "update_resource";
public static final String CREATE_RESOURCE = "create_resource";
public static final String IMPORT_CITATIONS = "import_citations";
public static final String UPDATE_SAVED_SORT = "update_saved_sort";
public static final String CHECK_FOR_UPDATES = "check_for_updates";
public static final String MIMETYPE_JSON = "application/json";
public static final String MIMETYPE_HTML = "text/html";
public static final String REQUESTED_MIMETYPE = "requested_mimetype";
public static final String CHARSET_UTF8 = "UTF-8";
/** A long representing the number of milliseconds in one week. Used for date calculations */
public static final long ONE_DAY = 24L * 60L * 60L * 1000L;
/** A long representing the number of milliseconds in one week. Used for date calculations */
public static final long ONE_WEEK = 7L * ONE_DAY;
public void init() throws ServletException {
ServerConfigurationService scs
= (ServerConfigurationService) ComponentManager.get(ServerConfigurationService.class);
if(scs != null) {
defaultListPageSize = scs.getInt("citations.default.list.page.size", DEFAULT_LIST_PAGE_SIZE);
} else {
logger.warn("Failed to get default list page size as ServerConfigurationService is null. Defaulting to " + DEFAULT_LIST_PAGE_SIZE);
defaultListPageSize = DEFAULT_LIST_PAGE_SIZE;
}
}
/**
* Check for the helper-done case locally and handle it before letting the VPPA.toolModeDispatch() handle the actual dispatch.
* @see org.sakaiproject.cheftool.VelocityPortletPaneledAction#toolModeDispatch(java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void toolModeDispatch(String methodBase, String methodExt, HttpServletRequest req, HttpServletResponse res)
throws ToolException
{
logger.debug("toolModeDispatch()");
//SessionState sstate = getState(req);
ToolSession toolSession = getSessionManager().getCurrentToolSession();
//String mode = (String) sstate.getAttribute(ResourceToolAction.STATE_MODE);
//Object started = toolSession.getAttribute(ResourceToolAction.STARTED);
Object done = toolSession.getAttribute(ResourceToolAction.DONE);
// if we're done or not properly initialized, redirect to Resources
if ( done != null || !initHelper( getState(req) ) )
{
toolSession.removeAttribute(ResourceToolAction.STARTED);
Tool tool = getToolManager().getCurrentTool();
String url = (String) toolSession.getAttribute(tool.getId() + Tool.HELPER_DONE_URL);
toolSession.removeAttribute(tool.getId() + Tool.HELPER_DONE_URL);
try
{
res.sendRedirect(url); // TODO
}
catch (IOException e)
{
logger.warn("IOException", e);
// Log.warn("chef", this + " : ", e);
}
return;
}
super.toolModeDispatch(methodBase, methodExt, req, res);
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException {
logger.info("doGet()");
String isAjaxRequest = req.getParameter("ajaxRequest");
if(isAjaxRequest != null && isAjaxRequest.trim().equalsIgnoreCase(Boolean.toString(true))) {
ParameterParser params = (ParameterParser) req.getAttribute(ATTR_PARAMS);
if(params == null) {
params = new ParameterParser(req);
}
SessionState state = getState(req);
// Check whether this is an AJAX request expecting a JSON response and if it is
// dispatch the request to the buildJsonResponse() method, avoiding VPPA's
// html rendering. Other options might be HTML-fragment, XML, etc.
//String requestedMimetype = (String) toolSession.getAttribute(REQUESTED_MIMETYPE);
String requestedMimetype = params.getString(REQUESTED_MIMETYPE);
logger.info("doGet() requestedMimetype == " + requestedMimetype);
if(requestedMimetype != null && requestedMimetype.equals(MIMETYPE_JSON)) {
doGetJsonResponse(params, state, req, res);
} else if(requestedMimetype != null && requestedMimetype.equals(MIMETYPE_HTML)) {
doGetHtmlFragmentResponse(params, state, req, res);
} else {
// throw something
}
return;
}
super.doGet(req, res);
}
protected void doGetHtmlFragmentResponse(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
}
protected void doGetJsonResponse(ParameterParser params, SessionState state,
HttpServletRequest req, HttpServletResponse res) {
res.setCharacterEncoding(CHARSET_UTF8);
res.setContentType(MIMETYPE_JSON);
Map<String,Object> jsonMap = new HashMap<String,Object>();
String sakai_csrf_token = params.getString("sakai_csrf_token");
if(sakai_csrf_token != null && ! sakai_csrf_token.trim().equals("")) {
jsonMap.put("sakai_csrf_token", sakai_csrf_token);
}
jsonMap.put("timestamp", Long.toString(System.currentTimeMillis()));
String citation_action = params.getString("citation_action");
if(citation_action != null && citation_action.trim().equals(CHECK_FOR_UPDATES)) {
Map<String,Object> result = this.checkForUpdates(params, state, req, res);
jsonMap.putAll(result);
}
// convert to json string
String jsonString = JSONObject.fromObject(jsonMap).toString();
try {
PrintWriter writer = res.getWriter();
writer.print(jsonString);
writer.flush();
} catch (IOException e) {
logger.warn("IOException in doGetJsonResponse() " + e);
}
}
protected Map<String, Object> checkForUpdates(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> result = new HashMap<String, Object>();
boolean changed = false;
long lastcheckLong = 0L;
String lastcheck = params.getString("lastcheck");
if(lastcheck == null || lastcheck.trim().equals("")) {
// do nothing
} else {
try {
lastcheckLong = Long.parseLong(lastcheck);
} catch(Exception e) {
logger.warn("Error parsing long from string: " + lastcheck, e);
}
}
if(lastcheckLong > 0L) {
String citationCollectionId = params.getString("citationCollectionId");
if(citationCollectionId != null && !citationCollectionId.trim().equals("")) {
try {
CitationCollection citationCollection = this.citationService.getCollection(citationCollectionId);
if(citationCollection.getLastModifiedDate().getTime() > lastcheckLong) {
changed = true;
result.put("html", "<div>something goes here</div>");
}
} catch (IdUnusedException e) {
logger.warn("IdUnusedException in checkForUpdates() " + e);
}
}
}
result.put("changed", Boolean.toString(changed));
return result;
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException {
logger.info("doPost()");
// Enumeration<String> names = req.getHeaderNames();
// while(names.hasMoreElements()) {
// String name = names.nextElement();
// String value = req.getHeader(name);
// logger.info("doPost() header " + name + " == " + value);
// }
//
// Cookie[] cookies = req.getCookies();
// for(Cookie cookie : cookies) {
// logger.info("doPost() ==cookie== " + cookie.getName() + " == " + cookie.getValue());
// }
// handle AJAX requests here and send other requests on to the VPPA dispatcher
String isAjaxRequest = req.getParameter("ajaxRequest");
if(isAjaxRequest != null && isAjaxRequest.trim().equalsIgnoreCase(Boolean.toString(true))) {
ParameterParser params = (ParameterParser) req.getAttribute(ATTR_PARAMS);
if(params == null) {
params = new ParameterParser(req);
}
SessionState state = getState(req);
// Check whether this is an AJAX request expecting a JSON response and if it is
// dispatch the request to the buildJsonResponse() method, avoiding VPPA's
// html rendering. Other options might be HTML-fragment, XML, etc.
//String requestedMimetype = (String) toolSession.getAttribute(REQUESTED_MIMETYPE);
String requestedMimetype = params.getString(REQUESTED_MIMETYPE);
logger.info("doPost() requestedMimetype == " + requestedMimetype);
if(requestedMimetype != null && requestedMimetype.equals(MIMETYPE_JSON)) {
doPostJsonResponse(params, state, req, res);
} else if(requestedMimetype != null && requestedMimetype.equals(MIMETYPE_HTML)) {
doPostHtmlFragmentResponse(params, state, req, res);
}
return;
}
super.doPost(req, res);
}
protected void doPostHtmlFragmentResponse(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> result = this.ensureCitationListExists(params, state, req, res);
res.setCharacterEncoding(CHARSET_UTF8);
res.setContentType(MIMETYPE_HTML);
String sakai_csrf_token = params.getString("sakai_csrf_token");
if(sakai_csrf_token != null && ! sakai_csrf_token.trim().equals("")) {
setVmReference("sakai_csrf_token", sakai_csrf_token, req);
}
for(Map.Entry<String,Object> entry : result.entrySet()) {
setVmReference(entry.getKey(), entry.getValue(), req);
}
}
protected void doPostJsonResponse(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
res.setCharacterEncoding(CHARSET_UTF8);
res.setContentType(MIMETYPE_JSON);
Map<String,Object> jsonMap = new HashMap<String,Object>();
String sakai_csrf_token = params.getString("sakai_csrf_token");
if(sakai_csrf_token != null && ! sakai_csrf_token.trim().equals("")) {
jsonMap.put("sakai_csrf_token", sakai_csrf_token);
}
jsonMap.put("timestamp", Long.toString(System.currentTimeMillis()));
String citation_action = params.getString("citation_action");
if(citation_action != null && citation_action.trim().equals(UPDATE_RESOURCE)) {
Map<String,Object> result = this.updateCitationList(params, state, req, res);
jsonMap.putAll(result);
} else if(citation_action != null && citation_action.trim().equals(UPDATE_SAVED_SORT)) {
Map<String,Object> result = this.updateSavedSort(params, state, req, res);
jsonMap.putAll(result);
} else {
Map<String,Object> result = this.createCitationList(params, state, req, res);
jsonMap.putAll(result);
}
// convert to json string
String jsonString = JSONObject.fromObject(jsonMap).toString();
try {
PrintWriter writer = res.getWriter();
writer.print(jsonString);
writer.flush();
} catch (IOException e) {
logger.warn("IOException in doPostJsonResponse() ", e);
// what goes back?
}
}
protected Map<String, Object> updateSavedSort(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> results = new HashMap<String, Object>();
String message = null;
String citationCollectionId = params.getString("citationCollectionId");
String new_sort = params.getString("new_sort");
if(citationCollectionId == null || citationCollectionId.trim().equals("")) {
// need to report error
results.put("message", rb.getString("sort.save.error"));
} else {
if(new_sort == null || new_sort.trim().equals("")) {
new_sort = "default";
}
try {
CitationCollection citationCollection = this.citationService.getCollection(citationCollectionId);
citationCollection.setSort(new_sort, true);
this.citationService.save(citationCollection);
results.put("message", rb.getString("sort.save.success"));
} catch (IdUnusedException e) {
// need to report error
results.put("message", rb.getString("sort.save.error"));
}
}
return results;
}
protected Map<String, Object> createCitationList(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> results = new HashMap<String, Object>();
results.putAll(this.ensureCitationListExists(params, state, req, res));
return results;
}
protected Map<String, Object> updateCitationList(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> results = new HashMap<String, Object>();
String resourceUuid = params.getString("resourceUuid");
String message = null;
if(resourceUuid == null) {
results.putAll(this.ensureCitationListExists(params, state, req, res));
} else {
try {
String resourceId = this.getContentService().resolveUuid(resourceUuid);
ContentResourceEdit edit = getContentService().editResource(resourceId);
this.captureDisplayName(params, state, edit, results);
this.captureDescription(params, state, edit, results);
this.captureAccess(params, state, edit, results);
this.captureAvailability(params, edit, results);
getContentService().commitResource(edit);
message = "Resource updated";
} catch (IdUnusedException e) {
message = e.getMessage();
logger.warn("IdUnusedException in updateCitationList() " + e);
} catch (TypeException e) {
message = e.getMessage();
logger.warn("TypeException in updateCitationList() " + e);
} catch (InUseException e) {
message = e.getMessage();
logger.warn("InUseException in updateCitationList() " + e);
} catch (PermissionException e) {
message = e.getMessage();
logger.warn("PermissionException in updateCitationList() " + e);
} catch (OverQuotaException e) {
message = e.getMessage();
logger.warn("OverQuotaException in updateCitationList() " + e);
} catch (ServerOverloadException e) {
message = e.getMessage();
logger.warn("ServerOverloadException in updateCitationList() " + e);
} catch (VirusFoundException e) {
message = e.getMessage();
logger.warn("VirusFoundException in updateCitationList() " + e);
}
if(message != null && ! message.trim().equals("")) {
results.put("message", message);
}
}
return results;
}
/**
* Check whether we are editing an existing resource or working on a new citation list.
* If it exists, we'll update any attributes that have changed. If it's new, we will
* create it and return the resourceUuid, along with other attributes, in a map.
* @param params
* @param state
* @param req
* @param res
* @return
*/
protected Map<String,Object> ensureCitationListExists(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> results = new HashMap<String,Object>();
String message = null;
String displayName = params.getString("displayName");
if(displayName == null) {
// error ??
}
CitationCollection cCollection = this.getCitationCollection(state, true);
if(cCollection == null) {
// error
} else {
String citationCollectionId = cCollection.getId();
String collectionId = params.getString("collectionId");
if(collectionId == null || collectionId.trim().equals("")) {
ToolSession toolSession = getSessionManager().getCurrentToolSession();
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
collectionId = pipe.getContentEntity().getId();
}
ContentResource resource = null;
String resourceUuid = params.getString("resourceUuid");
String resourceId = null;
if(resourceUuid == null || resourceUuid.trim().equals("")) {
// create resource
if(collectionId == null) {
// error?
message = rb.getString("resource.null_collectionId.error");
} else {
int priority = 0;
// create resource
try {
ContentResourceEdit edit = getContentService().addResource(collectionId, displayName, null, ContentHostingService.MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);
edit.setResourceType(CitationService.CITATION_LIST_ID);
byte[] bytes = citationCollectionId.getBytes();
edit.setContent(bytes );
captureDescription(params, state, edit, results);
captureAccess(params, state, edit, results);
captureAvailability(params, edit, results);
ResourceProperties properties = edit.getPropertiesEdit();
properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, displayName);
properties.addProperty(ContentHostingService.PROP_ALTERNATE_REFERENCE, CitationService.REFERENCE_ROOT);
properties.addProperty(ResourceProperties.PROP_CONTENT_TYPE, ResourceType.MIME_TYPE_HTML);
getContentService().commitResource(edit, priority);
resourceId = edit.getId();
message = rb.getFormattedMessage("resource.new.success", new String[]{ displayName });
} catch (IdUniquenessException e) {
message = e.getMessage();
logger.warn("IdUniquenessException in ensureCitationListExists() " + e);
} catch (IdLengthException e) {
message = e.getMessage();
logger.warn("IdLengthException in ensureCitationListExists() " + e);
} catch (IdInvalidException e) {
message = e.getMessage();
logger.warn("IdInvalidException in ensureCitationListExists() " + e);
} catch (OverQuotaException e) {
message = e.getMessage();
logger.warn("OverQuotaException in ensureCitationListExists() " + e);
} catch (ServerOverloadException e) {
message = e.getMessage();
logger.warn("ServerOverloadException in ensureCitationListExists() " + e);
} catch (PermissionException e) {
message = e.getMessage();
logger.warn("PermissionException in ensureCitationListExists() " + e);
} catch (IdUnusedException e) {
message = e.getMessage();
logger.warn("IdUnusedException in ensureCitationListExists() " + e);
}
}
} else {
// get resource
resourceId = this.getContentService().resolveUuid(resourceUuid);
if(citationCollectionId == null) {
try {
resource = this.contentService.getResource(resourceId);
citationCollectionId = new String(resource.getContent());
} catch (IdUnusedException e) {
message = e.getMessage();
logger.warn("IdUnusedException in getting resource in ensureCitationListExists() " + e);
} catch (TypeException e) {
message = e.getMessage();
logger.warn("TypeException in getting resource in ensureCitationListExists() " + e);
} catch (PermissionException e) {
message = e.getMessage();
logger.warn("PermissionException in getting resource in ensureCitationListExists() " + e);
} catch (ServerOverloadException e) {
message = e.getMessage();
logger.warn("ServerOverloadException in getting citationCollectionId in ensureCitationListExists() " + e);
}
}
// possibly revise displayName, other properties
// commit changes
// report success/failure
}
results.put("citationCollectionId", citationCollectionId);
//results.put("resourceId", resourceId);
resourceUuid = this.getContentService().getUuid(resourceId);
logger.info("ensureCitationListExists() created new resource with resourceUuid == " + resourceUuid + " and resourceId == " + resourceId);
results.put("resourceUuid", resourceUuid );
String clientId = params.getString("saveciteClientId");
if(clientId != null && ! clientId.trim().equals("")) {
Locale locale = rb.getLocale();
List<Map<String,String>> saveciteClients = getConfigurationService().getSaveciteClientsForLocale(locale);
if(saveciteClients != null) {
for(Map<String,String> client : saveciteClients) {
if(client != null && client.get("id") != null && client.get("id").equalsIgnoreCase(clientId)) {
String saveciteUrl = getSearchManager().getSaveciteUrl(resourceUuid,clientId);
try {
saveciteUrl = java.net.URLEncoder.encode(saveciteUrl,"UTF-8");
} catch (UnsupportedEncodingException e) {
logger.warn("Error encoding savecite URL",e);
}
// ${client.searchurl_base}?linkurl_base=${client.saveciteUrl}#if(${client.linkurl_id})&linkurl_id=${client.linkurl_id}
StringBuilder buf = new StringBuilder();
buf.append(client.get("searchurl_base"));
buf.append("?linkurl_base=");
buf.append(saveciteUrl);
if(client.get("linkurl_id") != null && ! client.get("linkurl_id").trim().equals("")) {
buf.append("&linkurl_id=");
buf.append(client.get("linkurl_id"));
}
buf.append('&');
results.put("saveciteUrl", buf.toString());
break;
}
}
}
}
results.put("collectionId", collectionId);
}
results.put("message", message);
return results;
}
private void captureDescription(ParameterParser params, SessionState state,
ContentResourceEdit edit, Map<String, Object> results) {
String description = params.get("description");
String oldDescription = edit.getProperties().getProperty(ResourceProperties.PROP_DESCRIPTION);
if(description == null || description.trim().equals("")) {
if(oldDescription != null) {
edit.getPropertiesEdit().removeProperty(ResourceProperties.PROP_DESCRIPTION);
results.put("description", "");
}
} else {
if(oldDescription == null || ! oldDescription.equals(description)) {
edit.getPropertiesEdit().removeProperty(ResourceProperties.PROP_DESCRIPTION);
edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DESCRIPTION, description);
results.put("description", description);
}
}
}
protected void captureDisplayName(ParameterParser params, SessionState state,
ContentResourceEdit edit, Map<String, Object> results) {
String displayName = params.getString("displayName");
if(displayName == null || displayName.trim().equals("")) {
throw new RuntimeException("invalid name for resource: " + displayName);
}
String oldDisplayName = edit.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
if(oldDisplayName == null || ! oldDisplayName.equals(displayName)) {
ResourcePropertiesEdit props = edit.getPropertiesEdit();
props.removeProperty(ResourceProperties.PROP_DISPLAY_NAME);
props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, displayName);
results.put("displayName", displayName);
}
}
/**
* @param params
* @param edit
* @param results TODO
*/
protected void captureAvailability(ParameterParser params,
ContentResourceEdit edit, Map<String, Object> results) {
boolean hidden = params.getBoolean("hidden");
boolean useReleaseDate = params.getBoolean("use_start_date");
DateFormat df = DateFormat.getDateTimeInstance();
Time releaseDate = null;
if(useReleaseDate) {
String releaseDateStr = params.getString(PROP_RELEASE_DATE);
if(releaseDateStr != null) {
try {
releaseDate = TimeService.newTime(df.parse(releaseDateStr).getTime());
} catch (ParseException e) {
logger.warn("ParseException in captureAvailability() " + e);
}
}
}
Time retractDate = null;
boolean useRetractDate = params.getBoolean("use_end_date");
if(useRetractDate) {
String retractDateStr = params.getString(PROP_RETRACT_DATE);
if(retractDateStr != null) {
try {
retractDate = TimeService.newTime(df.parse(retractDateStr).getTime());
} catch (ParseException e) {
logger.warn("ParseException in captureAvailability() " + e);
}
}
}
boolean oldHidden = edit.isHidden();
Time oldReleaseDate = edit.getReleaseDate();
Time oldRetractDate = edit.getRetractDate();
boolean changesFound = false;
if(oldHidden != hidden) {
results.put(PROP_IS_HIDDEN, Boolean.toString(hidden));
changesFound = true;
}
if(oldReleaseDate == null && releaseDate == null) {
// no change here
} else if((oldReleaseDate == null) || ! oldReleaseDate.equals(releaseDate)) {
if(releaseDate == null) {
results.put(PROP_RELEASE_DATE_STR, df.format(new Date()));
} else {
results.put(PROP_RELEASE_DATE_STR, df.format(new Date(releaseDate.getTime())));
}
results.put(PROP_RELEASE_DATE, releaseDate);
results.put(PROP_USE_RELEASE_DATE, useReleaseDate);
changesFound = true;
}
if(oldRetractDate == null && retractDate == null) {
// no change here
} else if (oldRetractDate == null || ! oldRetractDate.equals(retractDate)) {
if(retractDate == null) {
results.put(PROP_RETRACT_DATE_STR, df.format(new Date(System.currentTimeMillis() + ONE_WEEK)));
} else {
results.put(PROP_RETRACT_DATE_STR, df.format(new Date(retractDate.getTime() )));
}
results.put(PROP_RETRACT_DATE, retractDate);
changesFound = true;
}
if(changesFound) {
edit.setAvailability(hidden, releaseDate, retractDate);
}
}
protected void captureAccess(ParameterParser params, SessionState state,
ContentResourceEdit edit, Map<String, Object> results) {
Map<String,Object> entityProperties = (Map<String, Object>) state.getAttribute(STATE_RESOURCE_ENTITY_PROPERTIES);
boolean changesFound = false;
String access_mode = params.getString("access_mode");
if(access_mode == null) {
access_mode = AccessMode.INHERITED.toString();
}
String oldAccessMode = entityProperties.get(PROP_ACCESS_MODE).toString();
if(oldAccessMode == null) {
oldAccessMode = AccessMode.INHERITED.toString();
}
if(! access_mode.equals(oldAccessMode)) {
results.put(PROP_ACCESS_MODE, AccessMode.fromString(access_mode));
changesFound = true;
}
if(AccessMode.GROUPED.toString().equals(access_mode)) {
// we inherit more than one group and must check whether group access changes at this item
String[] access_groups = params.getStrings("access_groups");
SortedSet<String> new_groups = new TreeSet<String>();
if(access_groups != null) {
new_groups.addAll(Arrays.asList(access_groups));
}
List<Map<String,String>> possibleGroups = (List<Map<String, String>>) entityProperties.get(PROP_POSSIBLE_GROUPS);
if(possibleGroups == null) {
possibleGroups = new ArrayList<Map<String,String>>();
}
Map<String, String> possibleGroupMap = mapGroupRefs(possibleGroups);
SortedSet<String> new_group_refs = convertToRefs(new_groups, possibleGroupMap );
boolean groups_are_inherited = (new_groups.size() == possibleGroupMap.size()) && possibleGroupMap.keySet().containsAll(new_groups);
try {
if(groups_are_inherited) {
edit.clearGroupAccess();
edit.setGroupAccess(new_group_refs);
} else {
edit.setGroupAccess(new_group_refs);
}
edit.clearPublicAccess();
} catch (InconsistentException e) {
logger.warn("InconsistentException in captureAccess() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException in captureAccess() " + e);
}
} else if("public".equals(access_mode)) {
Boolean isPubviewInherited = (Boolean) entityProperties.get(PROP_IS_PUBVIEW_INHERITED);
if(isPubviewInherited == null || ! isPubviewInherited) {
try {
edit.setPublicAccess();
} catch (InconsistentException e) {
logger.warn("InconsistentException in captureAccess() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException in captureAccess() " + e);
}
}
} else if(AccessMode.INHERITED.toString().equals(access_mode)) {
try {
if(edit.getAccess() == AccessMode.GROUPED) {
edit.clearGroupAccess();
}
edit.clearPublicAccess();
} catch (InconsistentException e) {
logger.warn("InconsistentException in captureAccess() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException in captureAccess() " + e);
}
}
// isPubview
results.put(PROP_IS_PUBVIEW, getContentService().isPubView(edit.getId()));
// isPubviewInherited
results.put(PROP_IS_PUBVIEW_INHERITED, new Boolean(getContentService().isInheritingPubView(edit.getId())));
// isPubviewPossible
Boolean preventPublicDisplay = (Boolean) state.getAttribute("resources.request.prevent_public_display");
if(preventPublicDisplay == null) {
preventPublicDisplay = Boolean.FALSE;
}
results.put(PROP_IS_PUBVIEW_POSSIBLE, new Boolean(! preventPublicDisplay.booleanValue()));
// accessMode
results.put(PROP_ACCESS_MODE, edit.getAccess());
// isGroupInherited
results.put(PROP_IS_GROUP_INHERITED, AccessMode.GROUPED == edit.getInheritedAccess());
// possibleGroups
Collection<Group> inheritedGroupObjs = edit.getInheritedGroupObjects();
Map<String,Map<String,String>> groups = new HashMap<String,Map<String,String>>();
if(inheritedGroupObjs != null) {
for(Group group : inheritedGroupObjs) {
Map<String, String> grp = new HashMap<String, String>();
grp.put("groupId", group.getId());
grp.put("title", group.getTitle());
grp.put("description", group.getDescription());
grp.put("entityRef", group.getReference());
groups.put(grp.get("groupId"), grp);
}
}
results.put(PROP_POSSIBLE_GROUPS, groups);
// isGroupPossible
results.put(PROP_IS_GROUP_POSSIBLE, new Boolean(groups != null && groups.size() > 0));
// isSingleGroupInherited
results.put(PROP_IS_SINGLE_GROUP_INHERITED, new Boolean(groups != null && groups.size() == 1));
// isSiteOnly = ! isPubviewPossible && ! isGroupPossible
results.put(PROP_IS_SITE_ONLY, new Boolean(preventPublicDisplay.booleanValue() && (groups == null || groups.size() < 1)));
// isUserSite
SiteService siteService = (SiteService) ComponentManager.get(SiteService.class);
Reference ref = getEntityManager().newReference(edit.getReference());
results.put(PROP_IS_USER_SITE, siteService.isUserSite(ref.getContext()));
}
private Map<String, String> mapGroupRefs(
List<Map<String, String>> possibleGroups) {
Map<String, String> groupRefMap = new HashMap<String, String>();
for(Map<String, String> groupInfo : possibleGroups) {
if(groupInfo.get("groupId") != null && groupInfo.get("entityRef") != null) {
groupRefMap.put(groupInfo.get("groupId"), groupInfo.get("entityRef"));
}
}
return groupRefMap ;
}
public SortedSet<String> convertToRefs(Collection<String> groupIds, Map<String, String> possibleGroupMap)
{
SortedSet<String> groupRefs = new TreeSet<String>();
for(String groupId : groupIds)
{
String groupRef = possibleGroupMap.get(groupId);
if(groupRef != null)
{
groupRefs.add(groupRef);
}
}
return groupRefs;
}
protected void preserveEntityIds(ParameterParser params, SessionState state) {
String resourceId = params.getString("resourceId");
String resourceUuid = params.getString("resourceUuid");
String citationCollectionId = params.getString("citationCollectionId");
if(resourceId == null || resourceId.trim().equals("")) {
// do nothing
} else {
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
}
if(resourceUuid == null || resourceUuid.trim().equals("")) {
// do nothing
} else {
state.setAttribute(CitationHelper.RESOURCE_UUID, resourceUuid);
}
if(citationCollectionId == null || citationCollectionId.trim().equals("")) {
// do nothing
} else {
state.setAttribute(CitationHelper.CITATION_COLLECTION_ID, citationCollectionId);
}
}
protected void putCitationCollectionDetails( Context context, SessionState state )
{
// get the citation list title
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
String refStr = getContentService().getReference(resourceId);
Reference ref = getEntityManager().newReference(refStr);
String collectionTitle = null;
if( ref != null )
{
collectionTitle = ref.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
if(collectionTitle == null) {
collectionTitle = (String)state.getAttribute( STATE_COLLECTION_TITLE );
}
if( collectionTitle != null && !collectionTitle.trim().equals("") )
{
context.put( "collectionTitle", getFormattedText().escapeHtml(collectionTitle));
}
// get the collection we're now working on
String collectionId = (String)state.getAttribute(STATE_CITATION_COLLECTION_ID);
context.put( "collectionId", collectionId );
CitationCollection collection = getCitationCollection(state, false);
int collectionSize = 0;
if (collection == null)
{
logger.warn( "buildAddCitationsPanelContext unable to access citationCollection " + collectionId );
return;
}
else
{
// get the size of the list
collectionSize = collection.size();
}
context.put( "collectionSize", new Integer( collectionSize ) );
}
public String buildImportCitationsPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
context.put("state", state);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
context.put("FORM_NAME", "importForm");
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_IMPORT_CITATIONS;
} // buildImportPanelContext
/**
*
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildAddCitationsPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
context.put("state", state);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// body onload handler
context.put("sakai_onload", "setMainFrameHeight( window.name )");
// get the citation list title
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
String refStr = getContentService().getReference(resourceId);
Reference ref = getEntityManager().newReference(refStr);
String collectionTitle = null;
if( ref != null )
{
collectionTitle = ref.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
if(collectionTitle == null) {
collectionTitle = (String)state.getAttribute( STATE_COLLECTION_TITLE );
}
if( collectionTitle != null && !collectionTitle.trim().equals("") )
{
context.put( "collectionTitle", getFormattedText().escapeHtml(collectionTitle));
}
// get the collection we're now working on
String collectionId = (String)state.getAttribute(STATE_CITATION_COLLECTION_ID);
context.put( "collectionId", collectionId );
CitationCollection citationCollection = getCitationCollection(state, false);
int collectionSize = 0;
if(citationCollection == null)
{
logger.warn( "buildAddCitationsPanelContext unable to access citationCollection " + collectionId );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_ERROR;
}
else
{
// get the size of the list
collectionSize = citationCollection.size();
}
context.put( "collectionSize", new Integer( collectionSize ) );
Locale locale = rb.getLocale();
List<Map<String,String>> saveciteClients = getConfigurationService().getSaveciteClientsForLocale(locale);
if(saveciteClients != null) {
for(Map<String,String> client : saveciteClients) {
String saveciteUrl = getSearchManager().getSaveciteUrl(getContentService().getUuid(resourceId),client.get("id"));
try {
client.put("saveciteUrl", java.net.URLEncoder.encode(saveciteUrl,"UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.warn("Error encoding savecite URL",e);
}
}
context.put("saveciteClients",saveciteClients);
}
// determine which features to display
if( getConfigurationService().isGoogleScholarEnabled() )
{
String googleUrl = getSearchManager().getGoogleScholarUrl(getContentService().getUuid(resourceId));
context.put( "googleUrl", googleUrl );
// object array for formatted messages
Object[] googleArgs = { rb.getString( "linkLabel.google" ) };
context.put( "googleArgs", googleArgs );
}
if( getConfigurationService().librarySearchEnabled() )
{
context.put( "searchLibrary", Boolean.TRUE );
}
// form name
context.put(PARAM_FORM_NAME, ELEMENT_ID_CREATE_FORM);
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_ADD_CITATIONS;
} // buildAddCitationsPanelContext
/**
* build the context.
*
* @return The name of the template to use.
*/
public String buildCreatePanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
context.put("state", state);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
//context.put("sakai_onload", "setPopupHeight('create');checkinWithOpener('create');");
//context.put("sakai_onunload", "window.opener.parent.popups['create']=null;");
//context.put("mainFrameId", CitationHelper.CITATION_FRAME_ID);
//context.put("citationToolId", CitationHelper.CITATION_ID);
//context.put("specialHelperFlag", CitationHelper.SPECIAL_HELPER_ID);
context.put(PARAM_FORM_NAME, ELEMENT_ID_CREATE_FORM);
List schemas = getCitationService().getSchemas();
context.put("TEMPLATES", schemas);
Schema defaultSchema = getCitationService().getDefaultSchema();
context.put("DEFAULT_TEMPLATE", defaultSchema);
// Object array for instruction message
Object[] instrArgs = { rb.getString( "submit.create" ) };
context.put( "instrArgs", instrArgs );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_CREATE;
} // buildCreatePanelContext
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildDatabasePanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// get hierarchy
SearchDatabaseHierarchy hierarchy = ( SearchDatabaseHierarchy )
state.getAttribute(STATE_SEARCH_HIERARCHY);
// get selected category
SearchCategory category = ( SearchCategory ) state.getAttribute(
STATE_SELECTED_CATEGORY );
if( category == null )
{
// bad...
logger.warn( "buildDatabasePanelContext getting null selected " +
"category from state." );
}
// put selected category into context
context.put( "category", category );
// maxDbNum
Integer maxDbNum = new Integer(hierarchy.getNumMaxSearchableDb());
context.put( "maxDbNum", maxDbNum );
// object array for formatted messages
Object[] maxDbArgs = { maxDbNum };
context.put( "maxDbArgs", maxDbArgs );
// validator
context.put("xilator", new Validator());
// change mode back to SEARCH (DATABASE not needed anymore)
setMode( state, Mode.SEARCH );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_DATABASE;
} // buildDatabasePanelContext
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildEditPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
context.put("sakai_onload", "setMainFrameHeight( window.name ); heavyResize();");
//context.put("sakai_onunload", "window.opener.parent.popups['edit']=null;");
//context.put("mainFrameId", CitationHelper.CITATION_FRAME_ID);
//context.put("citationToolId", CitationHelper.CITATION_ID);
//context.put("specialHelperFlag", CitationHelper.SPECIAL_HELPER_ID);
context.put(PARAM_FORM_NAME, ELEMENT_ID_CREATE_FORM);
Citation citation = (Citation) state.getAttribute(CitationHelper.CITATION_EDIT_ITEM);
if(citation == null)
{
doEdit(rundata);
citation = (Citation) state.getAttribute(CitationHelper.CITATION_EDIT_ITEM);
}
context.put("citation", citation);
String citationId = (String) state.getAttribute(CitationHelper.CITATION_EDIT_ID);
String collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
context.put("citationId", citationId);
context.put("collectionId", collectionId);
List schemas = getCitationService().getSchemas();
context.put("TEMPLATES", schemas);
context.put("DEFAULT_TEMPLATE", citation.getSchema());
// Object array for formatted instruction
Object[] instrArgs = { rb.getString( "submit.edit" ) };
context.put( "instrArgs", instrArgs );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_EDIT;
}
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
private String buildErrorPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
//context.put("sakai_onload", "setPopupHeight('error');");
//context.put("sakai_onunload", "window.opener.parent.popups['error']=null;");
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_ERROR;
}
private String buildErrorFatalPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
//context.put("sakai_onload", "setPopupHeight('error');");
//context.put("sakai_onunload", "window.opener.parent.popups['error']=null;");
return TEMPLATE_ERROR_FATAL;
}
/**
* build the context.
*
* @return The name of the template to use.
*/
public String buildListPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
// state.setAttribute("fromListPage", true);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
if( state.removeAttribute( STATE_LIST_NO_SCROLL ) == null )
{
context.put("sakai_onload", "setMainFrameHeight( window.name )");
}
else
{
context.put("sakai_onload", "resizeFrame()");
}
//context.put("mainFrameId", CitationHelper.CITATION_FRAME_ID);
//context.put("citationToolId", CitationHelper.CITATION_ID);
//context.put("specialHelperFlag", CitationHelper.SPECIAL_HELPER_ID);
// get the citation list title
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
try {
ContentResource resource = this.getContentService().getResource(resourceId);
String description = resource.getProperties().getProperty(ResourceProperties.PROP_DESCRIPTION);
context.put("description", description);
} catch (Exception e) {
// TODO: Fix this. What exception is this dealing with?
logger.warn(e.getMessage(), e);
}
String refStr = getContentService().getReference(resourceId);
Reference ref = getEntityManager().newReference(refStr);
String collectionTitle = null;
if( ref != null )
{
collectionTitle = ref.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
if(collectionTitle == null) {
collectionTitle = (String)state.getAttribute( STATE_COLLECTION_TITLE );
}
if( collectionTitle != null && !collectionTitle.trim().equals("") )
{
context.put( "collectionTitle", getFormattedText().escapeHtml(collectionTitle));
}
context.put("openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel());
context.put(PARAM_FORM_NAME, ELEMENT_ID_LIST_FORM);
CitationCollection collection = getCitationCollection(state, true);
// collection size
context.put( "collectionSize", new Integer( collection.size() ) );
// export URLs
String exportUrlSel = collection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_SEL);
String exportUrlAll = collection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_ALL);
context.put("exportUrlSel", exportUrlSel);
context.put("exportUrlAll", exportUrlAll);
Integer listPageSize = (Integer) state.getAttribute(STATE_LIST_PAGE_SIZE);
if(listPageSize == null)
{
listPageSize = defaultListPageSize;
state.setAttribute(STATE_LIST_PAGE_SIZE, listPageSize);
}
context.put("listPageSize", listPageSize);
CitationIterator newIterator = collection.iterator();
CitationIterator oldIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(oldIterator != null)
{
newIterator.setPageSize(listPageSize.intValue());
newIterator.setStart(oldIterator.getStart());
// newIterator.setPage(oldIterator.getPage());
}
context.put("citations", newIterator);
context.put("collectionId", collection.getId());
if(! collection.isEmpty())
{
context.put("show_citations", Boolean.TRUE);
// int page = newIterator.getPage();
// int pageSize = newIterator.getPageSize();
int totalSize = collection.size();
int start = newIterator.getStart();
int end = newIterator.getEnd();
// int start = page * pageSize + 1;
// int end = Math.min((page + 1) * pageSize, totalSize);
Integer[] position = { new Integer(start+1) , new Integer(end), new Integer(totalSize)};
String showing = (String) rb.getFormattedMessage("showing.results", position);
context.put("showing", showing);
}
state.setAttribute(STATE_LIST_ITERATOR, newIterator);
// back to search results button control
context.put("searchResults", state.getAttribute(STATE_SEARCH_RESULTS) );
// constant schema identifier
context.put( "titleProperty", Schema.TITLE );
/*
* Object arrays for formatted messages
*/
Object[] instrMainArgs = { getConfigurationService().getSiteConfigOpenUrlLabel() };
context.put( "instrMainArgs", instrMainArgs );
Object[] instrSubArgs = { rb.getString( "label.finish" ) };
context.put( "instrSubArgs", instrSubArgs );
Object[] emptyListArgs = { rb.getString( "label.menu" ) };
context.put( "emptyListArgs", emptyListArgs );
String sort = (String) state.getAttribute(STATE_SORT);
if (sort == null || sort.trim().length() == 0)
sort = collection.getSort();
context.put("sort", sort);
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_LIST;
} // buildListPanelContext
public String buildReorderPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state) {
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
if( state.removeAttribute( STATE_LIST_NO_SCROLL ) == null ) {
context.put("sakai_onload", "setMainFrameHeight( window.name )");
}
else {
context.put("sakai_onload", "resizeFrame()");
}
// get the citation list title
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
String refStr = getContentService().getReference(resourceId);
Reference ref = getEntityManager().newReference(refStr);
String collectionTitle = null;
if( ref != null ) {
collectionTitle = ref.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
if(collectionTitle == null) {
collectionTitle = (String)state.getAttribute( STATE_COLLECTION_TITLE );
}
else if( !collectionTitle.trim().equals("") ) {
context.put( "collectionTitle", Validator.escapeHtml(collectionTitle));
}
CitationCollection collection = getCitationCollection(state, true);
collection.setSort(CitationCollection.SORT_BY_POSITION,true);
CitationIterator newIterator = collection.iterator();
newIterator.setPageSize(collection.size());
context.put("citations", newIterator);
context.put("collectionId", collection.getId());
state.setAttribute(STATE_LIST_ITERATOR, newIterator);
return TEMPLATE_REORDER;
}
/**
* This method retrieves the CitationCollection for the current session.
* If the CitationCollection is already in session-state and has not been
* updated in the persistent storage since it was last accessed, the copy
* in session-state will be returned. If it has been updated in storage,
* the copy in session-state will be updated and returned. If the
* CitationCollection has not yet been created in storage and the second
* parameter is true, this method will create the collection and return it.
* In that case, values will be added to session-state for attributes named
* STATE_COLLECTION_ID and STATE_COLLECTION. If the CitationCollection has
* not yet been created in storage and the second parameter is false, the
* method will return null.
* @param state The SessionState object for the current session.
* @param create A flag indicating whether the collection should be created
* if it does not already exist.
* @return The CitationCollection for the current session, or null.
*/
protected CitationCollection getCitationCollection(SessionState state, boolean create)
{
CitationCollection citationCollection = (CitationCollection) state.getAttribute(STATE_CITATION_COLLECTION);
if(citationCollection == null)
{
String citationCollectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
if(citationCollectionId == null && create)
{
citationCollection = getCitationService().addCollection();
getCitationService().save(citationCollection);
}
else
{
try
{
citationCollection = getCitationService().getCollection(citationCollectionId);
}
catch (IdUnusedException e)
{
logger.warn("IdUnusedException: CitationHelperAction.getCitationCollection() unable to access citationCollection " + citationCollectionId);
}
if(citationCollection == null && create)
{
citationCollection = getCitationService().addCollection();
getCitationService().save(citationCollection);
}
}
if(citationCollection != null) {
state.setAttribute(STATE_CITATION_COLLECTION, citationCollection);
state.setAttribute(STATE_CITATION_COLLECTION_ID, citationCollection.getId());
}
}
return citationCollection;
}
/**
* build the context.
*
* @return The name of the template to use.
*/
public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
logger.debug("buildMainPanelContext()");
// always put appropriate bundle in velocity context
context.put("tlang", rb);
//context.put("mainFrameId", CitationHelper.CITATION_FRAME_ID);
//context.put("citationToolId", CitationHelper.CITATION_ID);
//context.put("specialHelperFlag", CitationHelper.SPECIAL_HELPER_ID);
// always put whether this is a Resources Add or Revise operation
if( state.getAttribute( STATE_RESOURCES_ADD ) != null )
{
context.put( "resourcesAddAction", Boolean.TRUE );
}
// make sure observers are disabled
VelocityPortletPaneledAction.disableObservers(state);
String template = "";
Mode mode = (Mode) state.getAttribute(CitationHelper.STATE_HELPER_MODE);
if(mode == null)
{
// mode really shouldn't be null here
logger.warn( "buildMainPanelContext() getting null Mode from state" );
mode = Mode.NEW_RESOURCE;
//mode = Mode.ADD_CITATIONS;
setMode(state, mode);
}
// add mode to the template
context.put( "citationsHelperMode", mode );
switch(mode)
{
case NEW_RESOURCE:
template = buildNewResourcePanelContext(portlet, context, rundata, state);
break;
case IMPORT_CITATIONS:
template = buildImportCitationsPanelContext(portlet, context, rundata, state);
break;
case ADD_CITATIONS:
template = buildAddCitationsPanelContext(portlet, context, rundata, state);
break;
case CREATE:
template = buildCreatePanelContext(portlet, context, rundata, state);
break;
case DATABASE:
template = buildDatabasePanelContext(portlet, context, rundata, state);
break;
case EDIT:
template = buildEditPanelContext(portlet, context, rundata, state);
break;
case ERROR:
template = buildErrorPanelContext(portlet, context, rundata, state);
break;
case ERROR_FATAL:
template = buildErrorFatalPanelContext(portlet, context, rundata, state);
break;
case LIST:
template = buildListPanelContext(portlet, context, rundata, state);
break;
case REORDER:
template = buildReorderPanelContext(portlet, context, rundata, state);
break;
case MESSAGE:
template = buildMessagePanelContext(portlet, context, rundata, state);
break;
case SEARCH:
template = buildSearchPanelContext(portlet, context, rundata, state);
break;
case RESULTS:
template = buildResultsPanelContext(portlet, context, rundata, state);
break;
case VIEW:
template = buildViewPanelContext(portlet, context, rundata, state);
break;
}
return template;
} // buildMainPanelContext
public String buildNewResourcePanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state) {
logger.debug("buildNewResourcePanelContext()");
context.put("MIMETYPE_JSON", MIMETYPE_JSON);
context.put("REQUESTED_MIMETYPE", REQUESTED_MIMETYPE);
context.put("xilator", new Validator());
context.put("availability_is_enabled", Boolean.TRUE);
context.put("GROUP_ACCESS", AccessMode.GROUPED);
context.put("INHERITED_ACCESS", AccessMode.INHERITED);
Boolean resourceAdd = (Boolean) state.getAttribute(STATE_RESOURCES_ADD);
if(resourceAdd != null && resourceAdd.equals(true)) {
context.put("resourceAdd", Boolean.TRUE);
context.put(CITATION_ACTION, CREATE_RESOURCE);
} else {
context.put(CITATION_ACTION, UPDATE_RESOURCE);
}
// resource-related
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
String resourceUuid = (String) state.getAttribute(CitationHelper.RESOURCE_UUID);
if(resourceId == null || resourceId.trim().equals("")) {
if(resourceUuid == null || resourceUuid.trim().equals("")) {
// Will be dealt with later by creating new resource when needed
} else if(resourceUuid.startsWith("/")) {
// UUID and ID may be switched
resourceId = resourceUuid;
resourceUuid = this.getContentService().getUuid(resourceId);
if(resourceUuid != null) {
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
state.setAttribute(CitationHelper.RESOURCE_UUID, resourceUuid);
}
} else {
// see if we can get the resourceId from the UUID
resourceId = this.getContentService().resolveUuid(resourceUuid);
if(resourceId != null) {
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
}
}
} else if(resourceUuid == null || resourceUuid.trim().equals("")) {
resourceUuid = this.getContentService().getUuid(resourceId);
if(resourceUuid != null) {
state.setAttribute(CitationHelper.RESOURCE_UUID, resourceUuid);
}
}
if(logger.isInfoEnabled()) {
logger.info("buildNewResourcePanelContext() resourceUuid == " + resourceUuid + " resourceId == " + resourceId);
}
String citationCollectionId = null;
ContentResource resource = null;
Map<String,Object> contentProperties = null;
if(resourceId == null) {
} else {
try {
resource = getContentService().getResource(resourceId);
} catch (IdUnusedException e) {
logger.warn("IdUnusedException geting resource in buildNewResourcePanelContext() " + e);
} catch (TypeException e) {
logger.warn("TypeException geting resource in buildNewResourcePanelContext() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException geting resource in buildNewResourcePanelContext() " + e);
}
// String guid = getContentService().getUuid(resourceId);
// context.put("RESOURCE_ID", guid);
}
if(resource == null) {
context.put(CITATION_ACTION, CREATE_RESOURCE);
ToolSession toolSession = getSessionManager().getCurrentToolSession();
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
String collectionId = pipe.getContentEntity().getId();
context.put("collectionId", collectionId);
ContentCollection collection;
try {
collection = getContentService().getCollection(collectionId);
contentProperties = this.getProperties(collection, state);
} catch (IdUnusedException e) {
logger.warn("IdUnusedException geting collection in buildNewResourcePanelContext() " + e);
} catch (TypeException e) {
logger.warn("TypeException geting collection in buildNewResourcePanelContext() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException geting collection in buildNewResourcePanelContext() " + e);
}
} else {
ResourceProperties props = resource.getProperties();
contentProperties = this.getProperties(resource, state);
context.put("resourceTitle", props.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
context.put("resourceDescription", props.getProperty(ResourceProperties.PROP_DESCRIPTION));
//resourceUuid = this.getContentService().getUuid(resourceId);
context.put("resourceUuid", resourceUuid );
context.put("collectionId", resource.getContainingCollection().getId());
try {
citationCollectionId = new String(resource.getContent());
} catch (ServerOverloadException e) {
logger.warn("ServerOverloadException geting props in buildNewResourcePanelContext() " + e);
}
context.put(CITATION_ACTION, UPDATE_RESOURCE);
}
if(contentProperties == null) {
contentProperties = new HashMap<String,Object>();
}
context.put("contentProperties", contentProperties);
int collectionSize = 0;
CitationCollection citationCollection = null;
if(citationCollectionId == null) {
citationCollectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
//String citationCollectionId = (String) state.getAttribute(CitationHelper.CITATION_COLLECTION_ID);
}
if(citationCollectionId == null) {
} else {
citationCollection = getCitationCollection(state, true);
if(citationCollection == null) {
logger.warn( "buildAddCitationsPanelContext unable to access citationCollection " + citationCollectionId );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_ERROR;
} else {
// get the size of the list
collectionSize = citationCollection.size();
}
context.put("collectionId", citationCollectionId);
}
context.put( "collectionSize", new Integer( collectionSize ) );
Locale locale = rb.getLocale();
List<Map<String,String>> saveciteClients = getConfigurationService().getSaveciteClientsForLocale(locale);
if(saveciteClients != null) {
if(resource != null && resourceId != null) {
for(Map<String,String> client : saveciteClients) {
String saveciteUrl = getSearchManager().getSaveciteUrl(resourceUuid,client.get("id"));
try {
client.put("saveciteUrl", java.net.URLEncoder.encode(saveciteUrl,"UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.warn("Error encoding savecite URL",e);
}
}
}
context.put("saveciteClients",saveciteClients);
}
// determine which features to display
if( getConfigurationService().isGoogleScholarEnabled() ) {
String googleUrl = getSearchManager().getGoogleScholarUrl(getContentService().getUuid(resourceId));
context.put( "googleUrl", googleUrl );
// object array for formatted messages
Object[] googleArgs = { rb.getString( "linkLabel.google" ) };
context.put( "googleArgs", googleArgs );
}
if( getConfigurationService().librarySearchEnabled() ) {
context.put( "searchLibrary", Boolean.TRUE );
}
if(citationCollection == null || citationCollection.size() <= 0) {
} else {
context.put("openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel());
String currentSort = (String) state.getAttribute(STATE_SORT);
if (currentSort == null || currentSort.trim().length() == 0)
currentSort = citationCollection.getSort();
if(currentSort == null || currentSort.trim().length() == 0) {
currentSort = CitationCollection.SORT_BY_TITLE;
}
context.put("currentSort", currentSort);
String savedSort = citationCollection.getSort();
if(savedSort == null || savedSort.trim().equals("")) {
savedSort = CitationCollection.SORT_BY_TITLE;
}
if(savedSort != currentSort) {
citationCollection.setSort(currentSort, true);
}
//context.put(PARAM_FORM_NAME, ELEMENT_ID_LIST_FORM);
// collection size
context.put( "collectionSize", new Integer( citationCollection.size() ) );
// export URLs
String exportUrlSel = citationCollection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_SEL);
String exportUrlAll = citationCollection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_ALL);
context.put("exportUrlSel", exportUrlSel);
context.put("exportUrlAll", exportUrlAll);
Integer listPageSize = (Integer) state.getAttribute(STATE_LIST_PAGE_SIZE);
if(listPageSize == null)
{
listPageSize = defaultListPageSize;
state.setAttribute(STATE_LIST_PAGE_SIZE, listPageSize);
}
context.put("listPageSize", listPageSize);
CitationIterator newIterator = citationCollection.iterator();
CitationIterator oldIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(oldIterator == null) {
newIterator.setPageSize(listPageSize.intValue());
newIterator.setStart(0);
} else {
newIterator.setPageSize(listPageSize.intValue());
newIterator.setStart(oldIterator.getStart());
// newIterator.setPage(oldIterator.getPage());
}
context.put("citations", newIterator);
context.put("citationCollectionId", citationCollection.getId());
if(! citationCollection.isEmpty())
{
context.put("show_citations", Boolean.TRUE);
// int page = newIterator.getPage();
// int pageSize = newIterator.getPageSize();
int totalSize = citationCollection.size();
int start = newIterator.getStart();
int end = newIterator.getEnd();
// int start = page * pageSize + 1;
// int end = Math.min((page + 1) * pageSize, totalSize);
Integer[] position = { new Integer(start+1) , new Integer(end), new Integer(totalSize)};
String showing = (String) rb.getFormattedMessage("showing.results", position);
context.put("showing", showing);
}
state.setAttribute(STATE_LIST_ITERATOR, newIterator);
// constant schema identifier
context.put( "titleProperty", Schema.TITLE );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
}
return TEMPLATE_NEW_RESOURCE;
}
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildMessagePanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
context.put("sakai_onload", "");
//context.put("FORM_NAME", "messageForm");
context.put( "citationId", state.getAttribute( STATE_CITATION_ID ) );
// get the collection we're now working on
String collectionId = (String)state.getAttribute(STATE_CITATION_COLLECTION_ID);
context.put( "collectionId", collectionId );
int size = 0;
CitationCollection collection = getCitationCollection(state, false);
if(collection == null)
{
logger.warn( "buildMessagePanelContext unable to access citationCollection " + collectionId );
}
else
{
size = collection.size();
}
// get the size of the list
context.put( "citationCount", new Integer( size ) );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_MESSAGE;
}
/**
*
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildResultsPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
Caller caller = getCaller(state);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validators
context.put("TextValidator", new QuotedTextValidator());
context.put("xilator", new Validator());
// Set:
// * the javascript to run on page load
// * the page execution context (resources tool or editor integration)
switch (caller)
{
case EDITOR_INTEGRATION:
context.put("sakai_onload", "SRC_initializePageInfo('"
+ ELEMENT_ID_RESULTS_FORM
+ "','"
+ rb.getString("add.results")
+ "'); SRC_verifyWindowOpener();");
context.put("editorIntegration", Boolean.TRUE);
context.put("resourcesTool", Boolean.FALSE);
break;
case RESOURCE_TOOL:
default:
context.put("sakai_onload", "setMainFrameHeight( window.name ); highlightButtonSelections( '" + rb.getString("remove.results") + "' )");
context.put("editorIntegration", Boolean.FALSE);
context.put("resourcesTool", Boolean.TRUE);
// put the citation list title and size
putCitationCollectionDetails(context, state);
break;
}
// signal basic/advanced search
Object basicSearch = state.getAttribute( STATE_BASIC_SEARCH );
context.put( "basicSearch", basicSearch );
if( basicSearch != null )
{
context.put( "searchType", ActiveSearch.BASIC_SEARCH_TYPE );
}
else
{
context.put( "searchType", ActiveSearch.ADVANCED_SEARCH_TYPE );
}
/*
* SEARCH RESULTS
*/
ActiveSearch searchResults = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
if(searchResults != null)
{
context.put("searchResults", searchResults);
List currentResults = (List) state.getAttribute(STATE_CURRENT_RESULTS);
context.put("currentResults", currentResults);
Integer[] position = { new Integer(searchResults.getFirstRecordIndex() + 1) , new Integer(searchResults.getLastRecordIndex()), searchResults.getNumRecordsFound()};
String showing = (String) rb.getFormattedMessage("showing.results", position);
context.put("showing", showing);
}
// selected databases
String[] databaseIds = (String[])state.getAttribute( STATE_CURRENT_DATABASES );
context.put( "selectedDatabases", databaseIds );
// load basic/advanced search form state
loadSearchFormState( context, state );
/*
* OTHER CONTEXT PARAMS
*/
// searchInfo
ActiveSearch searchInfo = (ActiveSearch) state.getAttribute(STATE_SEARCH_INFO);
context.put("searchInfo", searchInfo);
// form name
context.put(PARAM_FORM_NAME, ELEMENT_ID_RESULTS_FORM);
// OpenURL Label
context.put( "openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel() );
// object arrays for formatted messages
Object[] instrMainArgs = { rb.getString( "add.results" ) };
context.put( "instrMainArgs", instrMainArgs );
Object[] instrSubArgs = { rb.getString( "label.new.search" ) };
context.put( "instrSubArgs", instrSubArgs );
/*
* ERROR CHECKING
*/
String alertMessages = (String) state.removeAttribute(STATE_MESSAGE);
if(alertMessages != null)
{
context.put("alertMessages", alertMessages);
}
Object noResults = state.removeAttribute( STATE_NO_RESULTS );
if( noResults != null )
{
context.put( "noResults", noResults );
}
Object noSearch = state.removeAttribute(STATE_NO_KEYWORDS);
if(noSearch != null)
{
context.put("noSearch", noSearch);
}
Object noDatabases = state.removeAttribute( STATE_NO_DATABASES );
if( noDatabases != null )
{
context.put( "noDatabases", noDatabases );
}
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_RESULTS;
} // buildResultsPanelContext
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildSearchPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
Caller caller = getCaller(state);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validators
context.put("TextValidator", new QuotedTextValidator());
context.put("xilator", new Validator());
// Set:
// * the javascript to run on page load
// * the page execution context (resources tool or editor integration)
switch (caller)
{
case EDITOR_INTEGRATION:
context.put("sakai_onload", "SRC_verifyWindowOpener(); showTopCategory();");
context.put("editorIntegration", Boolean.TRUE);
context.put("resourcesTool", Boolean.FALSE);
break;
case RESOURCE_TOOL:
default:
context.put("sakai_onload", "setMainFrameHeight( window.name ); showTopCategory();");
context.put("editorIntegration", Boolean.FALSE);
context.put("resourcesTool", Boolean.TRUE);
// put citation list title/size
putCitationCollectionDetails(context, state);
break;
}
// resource-related
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
String guid = getContentService().getUuid(resourceId);
context.put("RESOURCE_ID", guid);
// category information from hierarchy
SearchDatabaseHierarchy hierarchy = (SearchDatabaseHierarchy) state.getAttribute(STATE_SEARCH_HIERARCHY);
context.put( "defaultCategory", hierarchy.getDefaultCategory() );
context.put( "categoryListing", hierarchy.getCategoryListing() );
// load basic/advanced search form state
loadSearchFormState( context, state );
/*
* MISCELLANEOUS CONTEXT PARAMS
*/
// default to basicSearch
context.put( "basicSearch", state.getAttribute( STATE_BASIC_SEARCH ) );
// searchInfo
ActiveSearch searchInfo = (ActiveSearch) state.getAttribute(STATE_SEARCH_INFO);
context.put("searchInfo", searchInfo);
// max number of searchable databases
Integer maxDbNum = new Integer(hierarchy.getNumMaxSearchableDb());
context.put( "maxDbNum", maxDbNum );
// form name
context.put(PARAM_FORM_NAME, ELEMENT_ID_SEARCH_FORM);
// OpenURL Label
context.put( "openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel() );
// object arrays for formatted messages
Object[] instrArgs = { rb.getString( "submit.search" ) };
context.put( "instrArgs", instrArgs );
String searchType = null;
if (searchInfo != null)
{
searchType = searchInfo.getSearchType();
}
if (searchType == null)
searchType = ActiveSearch.BASIC_SEARCH_TYPE;
context.put("searchType", searchType);
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_SEARCH;
} // buildSearchPanelContext
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildViewPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
//context.put("sakai_onload", "setMainFrameHeight('" + CitationHelper.CITATION_FRAME_ID + "');");
//context.put("mainFrameId", CitationHelper.CITATION_FRAME_ID);
//context.put("citationToolId", CitationHelper.CITATION_ID);
//context.put("specialHelperFlag", CitationHelper.SPECIAL_HELPER_ID);
context.put(PARAM_FORM_NAME, ELEMENT_ID_VIEW_FORM);
Citation citation = (Citation) state.getAttribute(CitationHelper.CITATION_VIEW_ITEM);
if(citation == null)
{
doEdit(rundata);
citation = (Citation) state.getAttribute(CitationHelper.CITATION_VIEW_ITEM);
}
context.put("citation", citation);
String citationId = (String) state.getAttribute(CitationHelper.CITATION_VIEW_ID);
String collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
context.put("citationId", citationId);
context.put("collectionId", collectionId);
List schemas = getCitationService().getSchemas();
context.put("TEMPLATES", schemas);
context.put("DEFAULT_TEMPLATE", citation.getSchema());
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_VIEW;
} // buildViewPanelContext
/**
*
* @param context
* @param state
*/
protected void loadSearchFormState( Context context, SessionState state )
{
// remember data previously entered
if( state.getAttribute( STATE_BASIC_SEARCH ) != null )
{
/* basic search */
context.put( "keywords", ( String )state.getAttribute( STATE_KEYWORDS ) );
// default advanced search selections
context.put( "advField1", AdvancedSearchHelper.KEYWORD_ID );
context.put( "advField2", AdvancedSearchHelper.AUTHOR_ID );
context.put( "advField3", AdvancedSearchHelper.TITLE_ID );
context.put( "advField4", AdvancedSearchHelper.SUBJECT_ID );
context.put( "advField5", AdvancedSearchHelper.YEAR_ID );
}
else
{
/* advanced search */
// field selections
AdvancedSearchHelper.putFieldSelections( context, state );
// field criteria
AdvancedSearchHelper.putFieldCriteria( context, state );
}
// basic/advanced search types
context.put( "basicSearchType", ActiveSearch.BASIC_SEARCH_TYPE );
context.put( "advancedSearchType", ActiveSearch.ADVANCED_SEARCH_TYPE );
}
/**
*
*/
public void doFinish ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ToolSession toolSession = getSessionManager().getCurrentToolSession();
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
if (pipe == null)
{
logger.warn( "doFinish() pipe = null");
setMode(state, Mode.ERROR_FATAL);
return;
}
int citationCount = 0;
// if(pipe.getAction().getActionType() == ResourceToolAction.ActionType.CREATE_BY_HELPER)
// {
// /* PIPE remove */
//// SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//
// SecurityService securityService = (SecurityService) ComponentManager.get(SecurityService.class);
// // delete the temporary resource
// String temporaryResourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
// ContentResource tempResource = null;
// try
// {
// // get the temp resource
// tempResource = getContentService().getResource(temporaryResourceId);
//
// // use the temp resource to 'create' the real resource
// pipe.setRevisedContent(tempResource.getContent());
//
// // remove the temp resource
// if( getCitationService().allowRemoveCitationList( temporaryResourceId ) )
// {
// // setup a SecurityAdvisor
// CitationListSecurityAdviser advisor = new CitationListSecurityAdviser(
// getSessionManager().getCurrentSessionUserId(),
// ContentHostingService.AUTH_RESOURCE_REMOVE_ANY,
// tempResource.getReference() );
//
// try {
// securityService.pushAdvisor(advisor);
//
// // remove temp resource
// getContentService().removeResource(temporaryResourceId);
// } catch(Exception e) {
// logger.warn("Exception removing temporary resource for a citation list: " + temporaryResourceId + " --> " + e);
// } finally {
// // pop advisor
// securityService.popAdvisor(advisor);
// }
//
// tempResource = null;
// }
// }
// catch (PermissionException e)
// {
//
// logger.warn("PermissionException ", e);
// }
// catch (IdUnusedException e)
// {
//
// logger.warn("IdUnusedException ", e);
// }
// catch (TypeException e)
// {
//
// logger.warn("TypeException ", e);
// }
//// catch (InUseException e)
//// {
////
//// logger.warn("InUseException ", e);
//// }
// catch (ServerOverloadException e)
// {
//
// logger.warn("ServerOverloadException ", e);
// }
// catch (Exception e)
// {
//
// logger.warn("Exception ", e);
// }
// }
// // set content (mime) type
// pipe.setRevisedMimeType(ResourceType.MIME_TYPE_HTML);
// pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_TYPE, ResourceType.MIME_TYPE_HTML);
//
// // set the alternative_reference to point to reference_root for CitationService
// pipe.setRevisedResourceProperty(ContentHostingService.PROP_ALTERNATE_REFERENCE, CitationService.REFERENCE_ROOT);
/* PIPE remove */
// SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// get the collection we're now working on
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
String collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
String[] args = new String[]{ Integer.toString(collection.size()) };
String size_str = rb.getFormattedMessage("citation.count", args);
pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_LENGTH, size_str);
// leave helper mode
pipe.setActionCanceled(false);
pipe.setErrorEncountered(false);
pipe.setActionCompleted(true);
toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE);
toolSession.removeAttribute(CitationHelper.CITATION_HELPER_INITIALIZED);
cleanup(toolSession, CitationHelper.CITATION_PREFIX, state);
// Remove session sort
state.removeAttribute(STATE_SORT);
// Remove session collection
state.removeAttribute(STATE_CITATION_COLLECTION_ID);
state.removeAttribute(STATE_CITATION_COLLECTION);
state.removeAttribute("fromListPage");
}
} // doFinish
/**
* Cancel the action for which the helper was launched.
*/
public void doCancel(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ToolSession toolSession = getSessionManager().getCurrentToolSession();
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
if (pipe == null)
{
logger.warn( "doCancel() pipe = null");
setMode(state, Mode.ERROR_FATAL);
return;
}
if(pipe.getAction().getActionType() == ResourceToolAction.ActionType.CREATE_BY_HELPER)
{
// TODO: delete the citation collection and all citations
// TODO: delete the temporary resource
// String temporaryResourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
// ContentResourceEdit edit = null;
// try
// {
// edit = getContentService().editResource(temporaryResourceId);
// getContentService().removeResource(edit);
// edit = null;
// }
// catch (PermissionException e)
// {
//
// logger.warn("PermissionException ", e);
// }
// catch (IdUnusedException e)
// {
//
// logger.warn("IdUnusedException ", e);
// }
// catch (TypeException e)
// {
//
// logger.warn("TypeException ", e);
// }
// catch (InUseException e)
// {
//
// logger.warn("InUseException ", e);
// }
//
// if(edit != null)
// {
// getContentService().cancelResource(edit);
// }
}
// leave helper mode
pipe.setActionCanceled(true);
pipe.setErrorEncountered(false);
pipe.setActionCompleted(true);
toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE);
toolSession.removeAttribute(CitationHelper.CITATION_HELPER_INITIALIZED);
state.removeAttribute("fromListPage");
cleanup(toolSession, CitationHelper.CITATION_PREFIX, state);
}
/**
* Adds a citation to the current citation collection. Called from the search-results popup.
*/
public void doAddCitation ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// get the citation from search results, add it to the citation collection, and rebuild the context
String[] citationIds = params.getStrings("citationId");
String collectionId = params.getString("collectionId");
Integer page = (Integer) state.getAttribute(STATE_LIST_PAGE);
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
CitationCollection tempCollection = search.getSearchResults();
Map index = search.getIndex();
if(index == null)
{
index = new Hashtable();
search.setIndex(index);
}
CitationCollection permCollection = getCitationCollection(state, true);
if(permCollection == null) {
// error
} else {
for(int i = 0; i < citationIds.length; i++)
{
try
{
Citation citation = tempCollection.getCitation(citationIds[i]);
citation.setAdded(true);
permCollection.add(citation);
}
catch(IdUnusedException ex)
{
logger.info("doAdd: unable to add citation " + citationIds[i] + " to collection " + collectionId);
}
}
getCitationService().save(permCollection);
}
// setMode(state, Mode.LIST);
}
/**
* Removes a citation from the current citation collection. Called from the search-results popup.
*/
public void doRemove ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// get the citation number from search results, remove it from the citation collection, and rebuild the context
// get the citation from search results, add it to the citation collection, and rebuild the context
String[] citationIds = params.getStrings("citationId");
String collectionId = params.getString("collectionId");
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
CitationCollection tempCollection = search.getSearchResults();
Map index = search.getIndex();
if(index == null)
{
index = new Hashtable();
search.setIndex(index);
}
CitationCollection permCollection = getCitationCollection(state, true);
if(permCollection == null) {
// error
} else {
for(int i = 0; i < citationIds.length; i++)
{
try
{
Citation citation = tempCollection.getCitation(citationIds[i]);
citation.setAdded(false);
permCollection.remove(citation);
}
catch(IdUnusedException ex)
{
logger.info("doAdd: unable to add citation " + citationIds[i] + " to collection " + collectionId);
}
}
getCitationService().save(permCollection);
}
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
}
public void doDatabasePopulate( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// get category id
String categoryId = params.get( "categoryId" );
logger.debug( "doDatabasePopulate() categoryId from URL: " + categoryId );
if( categoryId == null )
{
// should not be null
setMode( state, Mode.ERROR );
return;
}
else
{
/* TODO can probably do this in build-method (don't need category in state)*/
// get selected category, put it in state
SearchDatabaseHierarchy hierarchy = ( SearchDatabaseHierarchy )
state.getAttribute( STATE_SEARCH_HIERARCHY );
SearchCategory category = hierarchy.getCategory( categoryId );
state.setAttribute( STATE_SELECTED_CATEGORY, category );
setMode(state, Mode.DATABASE);
}
}
/**
*
* @param data
*/
public void doImportPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
this.preserveEntityIds(params, state);
setMode(state, Mode.IMPORT_CITATIONS);
} // doImportPage
/**
*
* @param data
*/
public void doImport ( RunData data)
{
logger.debug( "doImport called.");
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
Iterator iter = params.getNames();
String param = null;
while (iter.hasNext())
{
param = (String) iter.next();
logger.debug( "param = " + param);
logger.debug( param + " value = " + params.get(param));
}
String collectionId = params.getString("collectionId");
if(collectionId == null)
{
collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
}
CitationCollection collection = null;
collection = getCitationCollection(state, false);
String ristext = params.get("ristext");
// We're going to read the RIS file from the submitted form's textarea first. If that's
// empty we'll read it from the uploaded file. We'll crate a BufferedReader in either
// circumstance so that the parsing code need not know where the ris text came from.
java.io.BufferedReader bread = null;
if (ristext.trim().length() > 0) // form has text in the risimport textarea
{
java.io.StringReader risStringReader = new java.io.StringReader(ristext);
bread = new java.io.BufferedReader(risStringReader);
logger.debug( "String buffered reader ready");
} // end RIS text is in the textarea
else // textarea empty, set the read of the import from the file
{
String upload = params.get("risupload");
logger.debug( "Upload String = " + upload);
FileItem risImport = params.getFileItem("risupload");
if (risImport == null)
{
logger.debug( "risImport is null.");
return;
}
logger.debug("Filename = " + risImport.getFileName());
InputStream risImportStream = risImport.getInputStream();
// Attempt to detect the encoding of the file.
BOMInputStream irs = new BOMInputStream(risImportStream);
// below is needed if UTF-8 above is commented out
Reader isr = null;
String bomCharsetName = null;
try
{
bomCharsetName = irs.getBOMCharsetName();
if (bomCharsetName != null)
{
isr = new InputStreamReader(risImportStream, bomCharsetName);
}
} catch (UnsupportedEncodingException uee)
{
// Something strange as the JRE should support all the formats.
logger.info("Problem using character set when importing RIS: "+ bomCharsetName);
}
catch (IOException ioe)
{
// Probably won't get any further, but may as well try.
logger.debug("Problem reading the character set from RIS import: "+ ioe.getMessage());
}
// Fallback to platform default
if (isr == null) {
isr = new InputStreamReader(irs);
}
bread = new java.io.BufferedReader(isr);
} // end set the read of the import from the uploaded file.
// The below code is a major work in progress.
// This code is for demonstration purposes only. No gambling or production use!
StringBuilder fileString = new StringBuilder();
String importLine = null;
java.util.List importList = new java.util.ArrayList();
// Read the BufferedReader and populate the importList. Each entry in the list
// is a line in the RIS import "file".
try
{
while ((importLine = bread.readLine()) != null)
{
importLine = importLine.trim();
if (importLine != null && importLine.length() > 2)
{
importList.add(importLine);
if(logger.isDebugEnabled()) {
fileString.append("\n");
fileString.append(importLine);
}
}
} // end while
} // end try
catch(Exception e)
{
logger.debug("ISR error = " + e);
} // end catch
finally {
if (bread != null) {
try {
bread.close();
} catch (IOException e) {
// tried
}
}
}
if(logger.isDebugEnabled()) {
logger.debug("fileString = \n" + fileString.toString());
}
// tempList holds the entries read in to make a citation up to and
// including the ER entry from importList
List tempList = new java.util.ArrayList();
Citation importCitation = getCitationService().getTemporaryCitation();
CitationCollection importCollection = getCitationService().getTemporaryCollection();
int sucessfullyReadCitations = 0;
int totalNumberCitations = 0;
// Read each entry in the RIS List and build a citation
for(int i=0; i< importList.size(); i++)
{
String importEntryString = (String) importList.get(i);
// logger.debug("Import line (#1) = " + importEntryString);
// logger.debug("Substring is = " + importEntryString.substring(0, 2));
tempList.add(importEntryString);
// make sure importEntryString can be tested for "ER" existence. It could
// be a dinky invalid line less than 2 characters.
if (importEntryString != null && importEntryString.length() > 1 &&
importEntryString.substring(0, 2).equalsIgnoreCase("ER"))
{
// end of citation (signaled by ER).
totalNumberCitations++;
logger.debug("------> Trying to add citation " + totalNumberCitations);
if (importCitation.importFromRisList(tempList)) // import went well
{
importCollection.add(importCitation);
sucessfullyReadCitations++;
}
tempList.clear();
importCitation = getCitationService().getTemporaryCitation();
}
} // end for
logger.debug("Done reading in " + sucessfullyReadCitations + " / " + totalNumberCitations + " citations.");
collection.addAll(importCollection);
getCitationService().save(collection);
// remove collection from state
state.removeAttribute(STATE_CITATION_COLLECTION);
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // end doImport()
public void doCreateResource(RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
setMode(state, Mode.NEW_RESOURCE);
//state.setAttribute(CitationHelper.SPECIAL_HELPER_ID, CitationHelper.CITATION_ID);
}
/**
*
*/
public void doCreate ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
setMode(state, Mode.CREATE);
//state.setAttribute(CitationHelper.SPECIAL_HELPER_ID, CitationHelper.CITATION_ID);
} // doCreate
/**
* Fetch the calling application
* @param state The session state
* @return The calling application (default to Resources if nothing is set)
*/
protected Caller getCaller(SessionState state)
{
Caller caller = (Caller) state.getAttribute(CITATIONS_HELPER_CALLER);
return (caller == null) ? Caller.RESOURCE_TOOL : Caller.EDITOR_INTEGRATION;
}
/**
* Set the calling applcation
* @param state The session state
* @param caller The calling application
*/
protected void setCaller(SessionState state, Caller caller)
{
state.setAttribute(CITATIONS_HELPER_CALLER, caller);
}
/**
* @param state
* @param new_mode
*/
protected void setMode(SessionState state, Mode new_mode)
{
// set state attributes
state.setAttribute( CitationHelper.STATE_HELPER_MODE, new_mode );
}
/**
*
*/
public void doCreateCitation ( RunData data)
{
// get the state object and the parameter parser
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
Set validPropertyNames = getCitationService().getValidPropertyNames();
String mediatype = params.getString("type");
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
// create a citation
Citation citation = getCitationService().addCitation(mediatype);
updateCitationFromParams(citation, params);
// add citation to current collection
collection.add(citation);
getCitationService().save(collection);
}
// call buildListPanelContext to show updated list
//state.setAttribute(CitationHelper.SPECIAL_HELPER_ID, CitationHelper.CITATION_ID);
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doCreateCitation
/**
* @param citation
* @param params
*/
protected void updateCitationFromParams(Citation citation, ParameterParser params)
{
Schema schema = citation.getSchema();
List fields = schema.getFields();
Iterator fieldIt = fields.iterator();
while(fieldIt.hasNext())
{
Field field = (Field) fieldIt.next();
String name = field.getIdentifier();
if(field.isMultivalued())
{
List values = new Vector();
String count = params.getString(name + "_count");
int num = 10;
try
{
num = Integer.parseInt(count);
for(int i = 0; i < num; i++)
{
String value = params.getString(name + i);
if(value != null && !values.contains(value))
{
values.add(value);
}
}
citation.updateCitationProperty(name, values);
}
catch(NumberFormatException e)
{
}
}
else
{
String value = params.getString(name);
citation.setCitationProperty(name, value);
if(name.equals(Schema.TITLE))
{
citation.setDisplayName(value);
}
}
}
int urlCount = 0;
try
{
urlCount = params.getInt("url_count");
}
catch(Exception e)
{
logger.debug("doCreateCitation: unable to parse int for urlCount");
}
// clear preferredUrl - if there is one, we will find it after looping
// through all customUrls below
citation.setPreferredUrl( null );
String id = null;
for(int i = 0; i < urlCount; i++)
{
String label = params.getString("label_" + i);
String url = params.getString("url_" + i);
String urlid = params.getString("urlid_" + i);
String preferred = params.getString( "pref_" + i );
String addPrefix = params.getString( "addprefix_" + i );
if(url == null)
{
logger.debug("doCreateCitation: url null? " + url);
}
else
{
try
{
url = validateURL(url);
}
catch (MalformedURLException e)
{
logger.debug("doCreateCitation: unable to validate URL: " + url);
continue;
}
}
if(label == null || url == null)
{
logger.debug("doCreateCitation: label null? " + label + " url null? " + url);
continue;
}
else if(urlid == null || urlid.trim().equals(""))
{
id = citation.addCustomUrl(label, url, addPrefix);
if( preferred != null && !preferred.trim().equals( "" ) )
{
// this customUrl is the new preferredUrl
citation.setPreferredUrl( id );
}
}
else
{
// update an existing customUrl
citation.updateCustomUrl(urlid, label, url, addPrefix);
if( preferred != null && !preferred.trim().equals( "" ) )
{
// this customUrl is the new preferredUrl
citation.setPreferredUrl( urlid );
}
}
}
}
/**
*
*/
public void doEdit ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String citationId = params.getString("citationId");
String collectionId = params.getString("collectionId");
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
Citation citation = null;
try
{
citation = collection.getCitation(citationId);
}
catch (IdUnusedException e)
{
// add an alert (below)
}
if(citation == null)
{
addAlert(state, rb.getString("alert.access"));
}
else
{
state.setAttribute(CitationHelper.CITATION_EDIT_ID, citationId);
state.setAttribute(CitationHelper.CITATION_EDIT_ITEM, citation);
setMode(state, Mode.EDIT);
}
}
} // doEdit
/**
*
*/
public void doList ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doList
public void doResults( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
setMode(state, Mode.RESULTS);
}
/**
*
*/
public void doAddCitations ( RunData data)
{
logger.debug("doAddCitations()");
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
preserveEntityIds(params, state);
//setMode(state, Mode.ADD_CITATIONS);
setMode(state, Mode.NEW_RESOURCE);
logger.debug("doAddCitations()");
} // doAddCitations
public void doMessageFrame(RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// get params
String citationId = params.getString("citationId");
String collectionId = params.getString("collectionId");
String operation = params.getString("operation");
// check params
if( operation == null )
{
logger.warn( "doMessageFrame() 'operation' null argument" );
setMode(state, Mode.ERROR);
return;
}
if( operation.trim().equalsIgnoreCase( "refreshCount" ) )
{
// do not need to do anything, let buildMessagePanelContext update
// count for citations
setMode( state, Mode.MESSAGE );
return;
}
if( operation == null || citationId == null || collectionId == null )
{
logger.warn( "doMessageFrame() null argument - operation: " +
operation + ", citationId: " + citationId + ", " +
"collectionId: " + collectionId );
setMode(state, Mode.ERROR);
return;
}
// get Citation using citationId
List<Citation> currentResults = (List<Citation>) state.getAttribute(STATE_CURRENT_RESULTS);
Citation citation = null;
for( Citation c : currentResults )
{
if( c.getId().equals( citationId ) )
{
citation = c;
break;
}
}
if( citation == null ) {
logger.warn( "doMessageFrame() bad citationId: " + citationId );
setMode(state, Mode.ERROR);
return;
}
// get CitationCollection using collectionId
CitationCollection collection = getCitationCollection(state, false);
if(collection == null) {
logger.warn( "doMessageFrame() unable to access citationCollection " + collectionId );
} else {
// do operation
if(operation.equalsIgnoreCase("add"))
{
logger.debug("adding citation " + citationId + " to " + collectionId);
citation.setAdded( true );
collection.add( citation );
getCitationService().save(collection);
}
else if(operation.equalsIgnoreCase("remove"))
{
logger.debug("removing citation " + citationId + " from " + collectionId);
collection.remove( citation );
citation.setAdded( false );
getCitationService().save(collection);
}
else
{
// do nothing
logger.debug("null operation: " + operation);
}
// store the citation's new id to send back to UI
state.setAttribute( STATE_CITATION_ID, citation.getId() );
}
setMode(state, Mode.MESSAGE);
}
public void doRemoveAllCitations( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String collectionId = params.getString("collectionId");
CitationCollection collection = getCitationCollection(state, false);
if(collection == null)
{
// TODO add alert and log error
logger.warn("CitationHelperAction.doRemoveCitation collection null: " + collectionId);
}
else
{
// remove all citations
List<Citation> citations = collection.getCitations();
if( citations != null && citations.size() > 0 )
{
for( Citation citation : citations )
{
collection.remove( citation );
}
getCitationService().save(collection);
}
}
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doRemoveAllCitations
public void doShowReorderCitations( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
setMode(state, Mode.REORDER);
} // doShowReorderCitations
public void doReorderCitations( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
String orderedCitationIds = params.getString("orderedCitationIds");
CitationCollection collection = getCitationCollection(state, false);
String[] splitIds = orderedCitationIds.split(",");
try
{
for(int i = 1;i <= splitIds.length;i++)
{
collection.getCitation(splitIds[i - 1]).setPosition(i);
}
getCitationService().save(collection);
}
catch(IdUnusedException iue)
{
logger.error("One of the supplied citation ids was invalid. The new order was not saved.");
}
// Had to do this to force a reload from storage in buildListPanelContext
state.removeAttribute(STATE_CITATION_COLLECTION);
state.setAttribute(STATE_SORT, CitationCollection.SORT_BY_POSITION);
setMode(state, Mode.NEW_RESOURCE);
} // doReorderCitations
public void doRemoveSelectedCitations( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String collectionId = params.getString("collectionId");
CitationCollection collection = getCitationCollection(state, false);
if(collection == null)
{
// TODO add alert and log error
logger.warn("doRemoveSelectedCitation() collection null: " + collectionId);
}
else
{
// remove selected citations
String[] paramCitationIds = params.getStrings("citationId");
if( paramCitationIds != null && paramCitationIds.length > 0 )
{
List<String> citationIds = new java.util.ArrayList<String>();
citationIds.addAll(Arrays.asList(paramCitationIds));
try
{
for( String citationId : citationIds )
{
Citation citation = collection.getCitation(citationId);
collection.remove(citation);
}
getCitationService().save(collection);
}
catch( IdUnusedException e )
{
logger.warn("doRemoveSelectedCitation() unable to get and remove citation", e );
}
}
}
state.setAttribute( STATE_LIST_NO_SCROLL, Boolean.TRUE );
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doRemoveSelectedCitations
/**
*
*/
public void doReviseCitation (RunData data)
{
// get the state object and the parameter parser
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// Set validPropertyNames = getCitationService().getValidPropertyNames();
// String mediatype = params.getString("type");
CitationCollection collection = getCitationCollection(state, false);
if(collection == null)
{
// TODO add alert and log error
}
else
{
String citationId = (String) state.getAttribute(CitationHelper.CITATION_EDIT_ID);
if(citationId != null)
{
try
{
Citation citation = collection.getCitation(citationId);
String schemaId = params.getString("type");
Schema schema = getCitationService().getSchema(schemaId);
citation.setSchema(schema);
updateCitationFromParams(citation, params);
// add citation to current collection
collection.saveCitation(citation);
}
catch (IdUnusedException e)
{
// TODO add alert and log error
}
getCitationService().save(collection);
}
}
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doReviseCitation
/**
*
* @param data
*/
public void doCancelSearch( RunData data )
{
// get state and params
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// cancel the running search
ActiveSearch search = ( ActiveSearch )state.getAttribute( STATE_SEARCH_INFO );
if( search != null )
{
Thread searchThread = search.getSearchThread();
if( searchThread != null )
{
try
{
searchThread.interrupt();
}
catch( SecurityException se )
{
// not able to interrupt search
logger.warn( "doSearch() [in ThreadGroup "
+ Thread.currentThread().getThreadGroup().getName()
+ "] unable to interrupt search Thread [name="
+ searchThread.getName()
+ ", id=" + searchThread.getId()
+ ", group=" + searchThread.getThreadGroup().getName()
+ "]");
}
}
}
} // doCancelSearch
/**
* Resources Tool/Citation Helper search
* @param data Runtime data
*/
public void doSearch ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
logger.debug("doSearch()");
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
//doSearchCommon(state, Mode.ADD_CITATIONS);
doSearchCommon(state, Mode.NEW_RESOURCE);
}
/**
* Common "doSearch()" support
* @param state Session state
* @param errorMode Next mode to set if we have database hierarchy problems
*/
protected void doSearchCommon(SessionState state, Mode errorMode)
{
// remove attributes from an old search session, if any
state.removeAttribute( STATE_SEARCH_RESULTS );
state.removeAttribute( STATE_CURRENT_RESULTS );
state.removeAttribute( STATE_KEYWORDS );
// indicate a basic search
state.setAttribute( STATE_BASIC_SEARCH, new Object() );
try
{
SearchDatabaseHierarchy hierarchy = getSearchManager().getSearchHierarchy();
if (hierarchy == null)
{
addAlert(state, rb.getString("search.problem"));
setMode(state, errorMode);
return;
}
state.setAttribute(STATE_SEARCH_HIERARCHY, hierarchy);
setMode(state, Mode.SEARCH);
}
catch (SearchException exception)
{
String error = exception.getMessage();
if ((error == null) || (error.length() == 0))
{
error = rb.getString("search.problem");
}
addAlert(state, error);
setMode(state, Mode.ERROR);
}
}
/**
*
*/
public void doBeginSearch ( RunData data)
{
// get state and params
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// get search object from state
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_INFO);
if(search == null)
{
logger.debug( "doBeginSearch() got null ActiveSearch from state." );
search = getSearchManager().newSearch();
}
// get databases selected
String[] databaseIds = params.getStrings( "databasesSelected" );
// check the databases to make sure they are indeed searchable by this user
if( databaseIds != null )
{
if(logger.isDebugEnabled())
{
logger.debug( "Databases selected:" );
for( String databaseId : databaseIds )
{
logger.debug( " " + databaseId );
}
}
SearchDatabaseHierarchy hierarchy =
(SearchDatabaseHierarchy)state.getAttribute(STATE_SEARCH_HIERARCHY);
for( int i = 0; i < databaseIds.length; i++ )
{
if( !hierarchy.isSearchableDatabase( databaseIds[ i ] ) )
{
// TODO collect a list of the databases which are
// not searchable and pass them to the UI
// do not search if databases selected
// are not searchable by this user
state.setAttribute( STATE_UNAUTHORIZED_DB, Boolean.TRUE );
logger.warn( "doBeginSearch() unauthorized database: " + databaseIds[i] );
setMode(state, Mode.RESULTS);
return;
}
}
/*
* Specify which databases should be searched
*/
search.setDatabaseIds(databaseIds);
state.setAttribute( STATE_CURRENT_DATABASES, databaseIds );
}
else
{
// no databases selected, cannot continue
state.setAttribute( STATE_NO_DATABASES, Boolean.TRUE );
setMode(state, Mode.RESULTS);
return;
}
/*
* do basic/advanced search-specific processing
*/
// determine which type of search has been issued
String searchType = params.getString( "searchType" );
if( searchType != null && searchType.equalsIgnoreCase( ActiveSearch.ADVANCED_SEARCH_TYPE ) )
{
doAdvancedSearch( params, state, search );
}
else
{
doBasicSearch( params, state, search );
}
// check for a cancel
String cancel = params.getString( "cancelOp" );
if( cancel != null && !cancel.trim().equals("") )
{
if( cancel.equalsIgnoreCase( ELEMENT_ID_RESULTS_FORM ) )
{
state.setAttribute( STATE_CANCEL_PAGE, Mode.RESULTS );
}
else
{
state.setAttribute( STATE_CANCEL_PAGE, Mode.SEARCH );
}
}
/*
* BEGIN SEARCH
*/
try
{
// set search thread to the current thread
search.setSearchThread( Thread.currentThread() );
state.setAttribute( STATE_SEARCH_INFO, search );
// initiate the search
List latestResults = search.viewPage();
String msg = search.getStatusMessage();
if(msg != null)
{
addAlert(state, msg);
search.setStatusMessage();
}
if( latestResults != null )
{
state.setAttribute(STATE_SEARCH_RESULTS, search);
state.setAttribute(STATE_CURRENT_RESULTS, latestResults);
setMode(state, Mode.RESULTS);
}
}
catch(SearchException se)
{
// either page indices are off or there has been a metasearch error
// do some logging & find the proper alert message
StringBuilder alertMsg = new StringBuilder( se.getMessage() );
logger.warn("doBeginSearch() SearchException: " + alertMsg );
if( search.getStatusMessage() != null && !search.getStatusMessage().trim().equals("") )
{
logger.warn( " |-- nested metasearch error: " + search.getStatusMessage() );
alertMsg.append( " (" + search.getStatusMessage() + ")" );
}
// add an alert and set the next mode
addAlert( state, alertMsg.toString() );
state.setAttribute( STATE_NO_RESULTS, Boolean.TRUE );
setMode(state, Mode.RESULTS);
return;
}
catch( SearchCancelException sce )
{
logger.debug( "doBeginSearch() SearchCancelException: user cancelled search" );
setMode( state, (Mode)state.getAttribute(STATE_CANCEL_PAGE) );
}
ActiveSearch newSearch = getSearchManager().newSearch();
state.setAttribute( STATE_SEARCH_INFO, newSearch );
} // doBeginSearch
/**
* Sets up a basic search.
*
* @param params request parameters from doBeginSearch
* @param state session state
* @param search current search
*/
protected void doBasicSearch( ParameterParser params, SessionState state, ActiveSearch search )
{
// signal a basic search
state.setAttribute( STATE_BASIC_SEARCH, new Object() );
search.setSearchType( ActiveSearch.BASIC_SEARCH_TYPE );
// get keywords
String keywords = params.getString("keywords");
if(keywords == null || keywords.trim().equals(""))
{
logger.warn( "doBasicSearch() getting null/empty keywords" );
}
// set up search query
SearchQuery basicQuery = new org.sakaiproject.citation.util.impl.SearchQuery();
basicQuery.addKeywords( keywords );
// set query for this search
search.setBasicQuery( basicQuery );
// save state
state.setAttribute( STATE_KEYWORDS, keywords );
} // doBasicSearch
/**
* Sets up an advanced search.
*
* @param params request parameters from doBeginSearch
* @param state session state
* @param search current search
*/
protected void doAdvancedSearch( ParameterParser params, SessionState state, ActiveSearch search )
{
// signal an advanced search
state.removeAttribute( STATE_BASIC_SEARCH );
search.setSearchType( ActiveSearch.ADVANCED_SEARCH_TYPE );
// clear old state
AdvancedSearchHelper.clearAdvancedFormState( state );
// set selected fields
AdvancedSearchHelper.setFieldSelections( params, state );
// set entered criteria
AdvancedSearchHelper.setFieldCriteria( params, state );
// get a Map of advancedCritera for the search
search.setAdvancedQuery( AdvancedSearchHelper.getAdvancedCriteria( state ) );
}
/**
*
*/
public void doNextListPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
CitationIterator listIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(listIterator == null)
{
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
listIterator = collection.iterator();
state.setAttribute(STATE_LIST_ITERATOR, listIterator);
}
}
if(listIterator != null && listIterator.hasNextPage())
{
listIterator.nextPage();
}
} // doNextListPage
/**
*
*/
public void doPrevListPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
CitationIterator listIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(listIterator == null)
{
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
listIterator = collection.iterator();
state.setAttribute(STATE_LIST_ITERATOR, listIterator);
}
}
if(listIterator != null && listIterator.hasPreviousPage())
{
listIterator.previousPage();
}
} // doSearch
/**
*
*/
public void doLastListPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
CitationIterator listIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(listIterator == null)
{
listIterator = collection.iterator();
state.setAttribute(STATE_LIST_ITERATOR, listIterator);
} else {
int pageSize = listIterator.getPageSize();
int totalSize = collection.size();
int lastPage = 0;
listIterator.setStart(totalSize - pageSize);
}
}
} // doSearch
/**
*
*/
public void doFirstListPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
if(state.getAttribute(CitationHelper.RESOURCE_ID) == null) {
String resourceId = params.get("resourceId");
if(resourceId == null || resourceId.trim().equals("")) {
String resourceUuid = (String) state.getAttribute(CitationHelper.RESOURCE_UUID);
if(resourceUuid == null || resourceUuid.trim().equals("")) {
resourceUuid = params.get("resourceUuid");
}
if(resourceUuid == null || resourceUuid.trim().equals("")) {
// Error? We can't identify resource
} else {
resourceId = this.getContentService().resolveUuid(resourceUuid);
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
state.setAttribute(CitationHelper.RESOURCE_UUID, resourceUuid);
}
} else {
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
}
}
CitationIterator listIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(listIterator == null)
{
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
listIterator = collection.iterator();
state.setAttribute(STATE_LIST_ITERATOR, listIterator);
}
}
if(listIterator != null) {
listIterator.setStart(0);
}
} // doSearch
/**
*
*/
public void doNextSearchPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
if(search == null)
{
search = getSearchManager().newSearch();
}
// search.prepareForNextPage();
try
{
List latestResults = search.viewPage(search.getViewPageNumber() + 1);
String msg = search.getStatusMessage();
if(msg != null)
{
addAlert(state, msg);
search.setStatusMessage();
}
state.setAttribute(STATE_CURRENT_RESULTS, latestResults);
setMode(state, Mode.RESULTS);
}
catch (SearchException e)
{
logger.warn("doNextSearchPage: " + e.getMessage());
addAlert(state, rb.getString( "error.search" ) );
setMode(state, Mode.RESULTS);
}
catch(Exception e)
{
logger.warn("doNextSearchPage: " + e.getMessage());
}
} // doSearch
/**
*
*/
public void doPrevSearchPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
if(search == null)
{
search = getSearchManager().newSearch();
}
// search.prepareForNextPage();
try
{
List latestResults = search.viewPage(search.getViewPageNumber() - 1);
String msg = search.getStatusMessage();
if(msg != null)
{
addAlert(state, msg);
search.setStatusMessage();
}
state.setAttribute(STATE_CURRENT_RESULTS, latestResults);
setMode(state, Mode.RESULTS);
}
catch (SearchException e)
{
logger.warn("doPrevSearchPage: " + e.getMessage());
addAlert(state, rb.getString( "error.search" ) );
setMode(state, Mode.RESULTS);
}
catch(Exception e)
{
logger.warn("doPrevSearchPage: " + e.getMessage());
}
} // doSearch
/**
*
*/
public void doFirstSearchPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
if(search == null)
{
search = getSearchManager().newSearch();
}
// search.prepareForNextPage();
try
{
List latestResults = search.viewPage(0);
String msg = search.getStatusMessage();
if(msg != null)
{
addAlert(state, msg);
search.setStatusMessage();
}
state.setAttribute(STATE_CURRENT_RESULTS, latestResults);
setMode(state, Mode.RESULTS);
}
catch (SearchException e)
{
logger.warn("doFirstSearchPage: " + e.getMessage());
addAlert(state, rb.getString( "error.search" ) );
setMode(state, Mode.RESULTS);
}
catch(Exception e)
{
logger.warn("doFirstSearchPage: " + e.getMessage());
}
} // doSearch
/**
*
*/
public void doChangeSearchPageSize ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
if(search == null)
{
search = getSearchManager().newSearch();
state.setAttribute(STATE_SEARCH_RESULTS, search);
}
// search.prepareForNextPage();
// check for top or bottom page selector
String pageSelector = params.get( "pageSelector" );
int pageSize;
if( pageSelector.equals( "top" ) )
{
pageSize = params.getInt( "pageSizeTop" );
}
else
{
pageSize = params.getInt("pageSizeBottom");
}
if(pageSize > 0)
{
// use the new value
}
else
{
// use the old value
pageSize = search.getViewPageSize();
}
state.setAttribute(STATE_RESULTS_PAGE_SIZE, new Integer(pageSize));
try
{
int last = search.getLastRecordIndex();
int page = (last - 1)/pageSize;
search.setViewPageSize(pageSize);
List latestResults = search.viewPage(page);
String msg = search.getStatusMessage();
if(msg != null)
{
addAlert(state, msg);
search.setStatusMessage();
}
state.setAttribute(STATE_CURRENT_RESULTS, latestResults);
setMode(state, Mode.RESULTS);
}
catch (SearchException e)
{
logger.warn("doChangeSearchPageSize: " + e.getMessage());
addAlert(state, rb.getString( "error.search" ) );
setMode(state, Mode.RESULTS);
}
catch(Exception e)
{
logger.warn("doChangeSearchPageSize: " + e.getMessage());
}
} // doChangeSearchPageSize
/**
*
*/
public void doChangeListPageSize ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
int pageSize = params.getInt( "newPageSize" );
if(pageSize < 1) {
// check for top or bottom page selector
String pageSelector = params.get( "pageSelector" );
if( pageSelector.equals( "top" ) )
{
pageSize = params.getInt( "pageSizeTop" );
}
else
{
pageSize = params.getInt("pageSizeBottom");
}
}
if(pageSize > 0)
{
state.setAttribute(STATE_LIST_PAGE_SIZE, new Integer(pageSize));
CitationIterator tempIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
tempIterator.setPageSize(pageSize);
state.removeAttribute(STATE_LIST_ITERATOR);
state.setAttribute(STATE_LIST_ITERATOR, tempIterator);
}
} // doSearch
/**
*
*/
public void doView ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String citationId = params.getString("citationId");
String collectionId = params.getString("collectionId");
CitationCollection collection = getCitationCollection(state, false);
if(collection == null)
{
addAlert(state, rb.getString("alert.access"));
}
else
{
Citation citation = null;
try
{
citation = collection.getCitation(citationId);
}
catch (IdUnusedException e)
{
// add an alert (below)
}
if(citation == null)
{
addAlert(state, rb.getString("alert.access"));
}
else
{
state.setAttribute(CitationHelper.CITATION_VIEW_ID, citationId);
state.setAttribute(CitationHelper.CITATION_VIEW_ITEM, citation);
setMode(state, Mode.VIEW);
}
}
} // doView
/**
* This method is used to ensure the Citations Helper is not invoked by
* the Resources tool in a state other than ADD_CITATIONS or LIST. It uses
* a simple state machine to accomplish this
*
* @return the Mode that the Citations Helper should be in
*/
protected Mode validateState()
{
return null;
}
/**
* This method is called upon each Citations Helper request to properly
* initialize the Citations Helper in case of a null Mode. Returns true if
* succeeded, false otherwise
*
* @param state
*/
protected boolean initHelper(SessionState state)
{
logger.info("initHelper()");
Mode mode;
/*
* Editor Integration support
*/
if (getCaller(state) == Caller.EDITOR_INTEGRATION)
{
mode = (Mode) state.getAttribute(CitationHelper.STATE_HELPER_MODE);
if (mode == null)
{
logger.debug("initHelper(): mode is undefined, using " + Mode.NEW_RESOURCE);
setMode(state, Mode.NEW_RESOURCE);
}
if (state.getAttribute(STATE_RESULTS_PAGE_SIZE) == null)
{
logger.debug("initHelper(): result page size is undefined, using "
+ DEFAULT_RESULTS_PAGE_SIZE);
state.setAttribute(STATE_RESULTS_PAGE_SIZE, DEFAULT_RESULTS_PAGE_SIZE);
}
return true;
}
/*
* Resources Tool support
*/
ToolSession toolSession = getSessionManager().getCurrentToolSession();
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
// TODO: if not entering as a helper, will we need to create pipe???
if (pipe == null)
{
logger.warn( "initHelper() pipe = null");
setMode(state, Mode.ERROR_FATAL);
return true;
}
if(pipe.isActionCompleted())
{
return true;
}
/*
* Resources Tool/Citation Helper support
*/
if( toolSession.getAttribute(CitationHelper.CITATION_HELPER_INITIALIZED) == null )
{
// we're starting afresh: an action has been clicked in Resources
// set the Mode according to our action
switch(pipe.getAction().getActionType())
{
//case CREATE:
case CREATE_BY_HELPER:
// ContentResource tempResource = createTemporaryResource(pipe);
//
// // tempResource could be null if exception encountered
// if( tempResource == null )
// {
// // leave helper
// pipe.setActionCompleted( true );
// toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE);
// toolSession.removeAttribute(CitationHelper.CITATION_HELPER_INITIALIZED);
// cleanup( toolSession, CitationHelper.CITATION_PREFIX, state);
//
// return false;
// }
// state.setAttribute(CitationHelper.RESOURCE_ID, tempResource.getId());
//
// String displayName = tempResource.getProperties().getProperty( org.sakaiproject.entity.api.ResourceProperties.PROP_DISPLAY_NAME );
// state.setAttribute( STATE_COLLECTION_TITLE , displayName );
//
// try
// {
// state.setAttribute(STATE_COLLECTION_ID, new String(tempResource.getContent()));
// }
// catch (ServerOverloadException e)
// {
// logger.warn("ServerOverloadException ", e);
// }
state.setAttribute( STATE_RESOURCES_ADD, Boolean.TRUE );
//setMode(state, Mode.ADD_CITATIONS);
setMode(state, Mode.NEW_RESOURCE);
break;
case REVISE_CONTENT:
state.setAttribute(CitationHelper.RESOURCE_ID, pipe.getContentEntity().getId());
try
{
state.setAttribute(STATE_CITATION_COLLECTION_ID, new String(((ContentResource) pipe.getContentEntity()).getContent()));
}
catch (ServerOverloadException e)
{
logger.warn("ServerOverloadException ", e);
}
state.removeAttribute( STATE_RESOURCES_ADD );
setMode(state, Mode.NEW_RESOURCE);
break;
default:
break;
}
// set Citations Helper to "initialized"
//pipe.setInitializationId( "initialized" );
toolSession.setAttribute(CitationHelper.CITATION_HELPER_INITIALIZED, Boolean.toString(true));
}
else
{
// we're in the middle of a Citations Helper workflow:
// Citations Helper has been "initialized"
// (pipe.initializationId != null)
// make sure we have a Mode to display
mode = (Mode) state.getAttribute(CitationHelper.STATE_HELPER_MODE);
if( mode == null )
{
// default to ADD_CITATIONS
//setMode( state, Mode.ADD_CITATIONS );
setMode( state, Mode.NEW_RESOURCE );
}
}
if(state.getAttribute(STATE_RESULTS_PAGE_SIZE) == null)
{
state.setAttribute(STATE_RESULTS_PAGE_SIZE, DEFAULT_RESULTS_PAGE_SIZE);
}
if(state.getAttribute(STATE_LIST_PAGE_SIZE) == null)
{
state.setAttribute(STATE_LIST_PAGE_SIZE, defaultListPageSize);
}
return true;
} // initHelper
/**
*
* @param pipe
* @return
*/
protected ContentResource createTemporaryResource(ResourceToolActionPipe pipe)
{
try
{
ContentResourceEdit newItem = getContentService().addResource(pipe.getContentEntity().getId(), rb.getString("new.citations.list"), null, ContentHostingService.MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);
newItem.setResourceType(getCitationService().CITATION_LIST_ID);
newItem.setContentType( ResourceType.MIME_TYPE_HTML );
//newItem.setHidden();
ResourcePropertiesEdit props = newItem.getPropertiesEdit();
// set the alternative_reference to point to reference_root for CitationService
props.addProperty(getContentService().PROP_ALTERNATE_REFERENCE, CitationService.REFERENCE_ROOT);
props.addProperty(ResourceProperties.PROP_CONTENT_TYPE, ResourceType.MIME_TYPE_HTML);
props.addProperty(getCitationService().PROP_TEMPORARY_CITATION_LIST, Boolean.TRUE.toString());
CitationCollection collection = getCitationService().addCollection();
newItem.setContent(collection.getId().getBytes());
newItem.setContentType(ResourceType.MIME_TYPE_HTML);
getContentService().commitResource(newItem, NotificationService.NOTI_NONE);
return newItem;
}
catch (PermissionException e)
{
logger.warn("PermissionException ", e);
}
catch (IdUniquenessException e)
{
logger.warn("IdUniquenessException ", e);
}
catch (IdLengthException e)
{
logger.warn("IdLengthException ", e);
}
catch (IdInvalidException e)
{
logger.warn("IdInvalidException ", e);
}
catch (IdUnusedException e)
{
logger.warn("IdUnusedException ", e);
}
catch (OverQuotaException e)
{
logger.warn( e.getMessage() );
// send an error back to Resources
pipe.setErrorEncountered( true );
pipe.setErrorMessage( rb.getString( "action.create.quota" ) );
}
catch (ServerOverloadException e)
{
logger.warn("ServerOverloadException ", e);
}
return null;
}
protected String validateURL(String url) throws MalformedURLException
{
if (url == null || url.trim().equals (""))
{
throw new MalformedURLException();
}
url = url.trim();
// does this URL start with a transport?
if (url.indexOf ("://") == -1)
{
// if it's missing the transport, add http://
url = "http://" + url;
}
// valid protocol?
try
{
// test to see if the input validates as a URL.
// Checks string for format only.
URL u = new URL(url);
}
catch (MalformedURLException e1)
{
try
{
Pattern pattern = Pattern.compile("\\s*([a-zA-Z0-9]+)://([^\\n]+)");
Matcher matcher = pattern.matcher(url);
if(matcher.matches())
{
// if URL has "unknown" protocol, check remaider with
// "http" protocol and accept input it that validates.
URL test = new URL("http://" + matcher.group(2));
}
else
{
throw e1;
}
}
catch (MalformedURLException e2)
{
throw e1;
}
}
return url;
}
public static class QuotedTextValidator
{
/**
* Return a string for insertion in a quote in an HTML tag (as the value of an element's attribute.
*
* @param string
* The string to escape.
* @return the escaped string.
*/
public static String escapeQuotedString(String string)
{
if (string == null) return "";
string = string.trim();
try
{
// convert the string to bytes in UTF-8
byte[] bytes = string.getBytes("UTF-8");
StringBuilder buf = new StringBuilder();
for (int i = 0; i < bytes.length; i++)
{
byte b = bytes[i];
if (b == '"')
{
buf.append("\\\"");
}
else if(b == '\\')
{
buf.append("\\\\");
}
else
{
buf.append((char) b);
}
}
String rv = buf.toString();
return rv;
}
catch (Exception e)
{
return string;
}
} // escapeQuotedString
/**
* Return a string that is safe to place into a JavaScript value wrapped
* in single quotes. In addition, all double quotes (") are replaced by
* the entity <i>"</i>.
*
* @param string The original string
* @return The [possibly] escaped string
*/
public static String escapeHtmlAndJsQuoted(String string)
{
String escapedText = getFormattedText().escapeJsQuoted(string);
return escapedText.replaceAll("\"", """);
}
}
/**
* Cleans up tool state used internally. Useful before leaving helper mode.
*
* @param toolSession
* @param prefix
*/
protected void cleanup(ToolSession toolSession, String prefix,
SessionState sessionState )
{
// cleanup everything dealing with citations
Enumeration attributeNames = toolSession.getAttributeNames();
while(attributeNames.hasMoreElements())
{
String aName = (String) attributeNames.nextElement();
if(aName.startsWith(prefix))
{
toolSession.removeAttribute(aName);
}
}
// re-enable observers
VelocityPortletPaneledAction.enableObservers(sessionState);
}
public void doSortCollection( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String collectionId = params.getString("collectionId");
String sort = params.getString("currentSort");
if(sort == null || sort.trim().equals("")) {
sort = CitationCollection.SORT_BY_TITLE;
}
CitationCollection collection = null;
if(collectionId == null)
{
collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
}
logger.debug("doSortCollection sort type = " + sort);
collection = getCitationCollection(state, false);
if(collection == null)
{
// TODO add alert and log error
logger.warn("doSortCollection() collection null: " + collectionId);
}
else
{
// sort the citation list
logger.debug("doSortCollection() ready to sort");
if (sort.equalsIgnoreCase(CitationCollection.SORT_BY_TITLE))
collection.setSort(CitationCollection.SORT_BY_TITLE, true);
else if (sort.equalsIgnoreCase(CitationCollection.SORT_BY_AUTHOR))
collection.setSort(CitationCollection.SORT_BY_AUTHOR, true);
else if (sort.equalsIgnoreCase(CitationCollection.SORT_BY_YEAR))
collection.setSort(CitationCollection.SORT_BY_YEAR , true);
else if (sort.equalsIgnoreCase(CitationCollection.SORT_BY_POSITION))
collection.setSort(CitationCollection.SORT_BY_POSITION , true);
state.setAttribute(STATE_SORT, sort);
Iterator iter = collection.iterator();
while (iter.hasNext())
{
Citation tempCit = (Citation) iter.next();
logger.debug("doSortCollection() tempcit 1 -------------");
logger.debug("doSortCollection() tempcit 1 (author) = " + tempCit.getFirstAuthor());
logger.debug("doSortCollection() tempcit 1 (year) = " + tempCit.getYear());
logger.debug("doSortCollection() tempcit 1 = " + tempCit.getDisplayName());
} // end while
// set the list iterator to the start of the list after a change in sort
CitationIterator listIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(listIterator != null)
{
listIterator.setStart(0);
}
} // end else
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doSortCollection
public void doSaveCollection(RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String collectionId = params.getString("collectionId");
CitationCollection collection = null;
if(collectionId == null)
{
collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
}
collection = getCitationCollection(state, false);
if(collection == null)
{
// TODO add alert and log error
logger.warn("doSaveCollection() collection null: " + collectionId);
return;
}
else
{
// save the collection (this will persist the sort order to the db)
getCitationService().save(collection);
String sort = collection.getSort();
if (sort != null)
state.setAttribute(STATE_SORT, sort);
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
}
} // end doSaveCollection
public class CitationListSecurityAdviser implements SecurityAdvisor
{
String userId;
String function;
String reference;
public CitationListSecurityAdviser(String userId, String function, String reference)
{
super();
this.userId = userId;
this.function = function;
this.reference = reference;
}
public SecurityAdvice isAllowed(String userId, String function, String reference)
{
SecurityAdvice advice = SecurityAdvice.PASS;
if((this.userId == null || this.userId.equals(userId)) && (this.function == null || this.function.equals(function)) || (this.reference == null || this.reference.equals(reference)))
{
advice = SecurityAdvice.ALLOWED;
}
return advice;
}
}
// temporary -- replace with a method in content-util
public static int preserveRequestState(SessionState state, String[] prefixes)
{
Map requestState = new HashMap();
int requestStateId = 0;
while(requestStateId == 0)
{
requestStateId = (int) (Math.random() * Integer.MAX_VALUE);
}
List<String> attrNames = state.getAttributeNames();
for(String attrName : attrNames)
{
for(String prefix : prefixes)
{
if(attrName.startsWith(prefix))
{
requestState.put(attrName,state.getAttribute(attrName));
break;
}
}
}
Object pipe = state.getAttribute(ResourceToolAction.ACTION_PIPE);
if(pipe != null)
{
requestState.put(ResourceToolAction.ACTION_PIPE, pipe);
}
Tool tool = getToolManager().getCurrentTool();
Object url = state.getAttribute(tool.getId() + Tool.HELPER_DONE_URL);
if( url != null)
{
requestState.put(tool.getId() + Tool.HELPER_DONE_URL, url);
}
state.setAttribute(CitationHelper.RESOURCES_SYS_PREFIX + requestStateId, requestState);
logger.debug("preserveRequestState() requestStateId == " + requestStateId + "\n" + requestState);
return requestStateId;
}
// temporary -- replace with a value in content-util or content-api
public static void restoreRequestState(SessionState state, String[] prefixes, int requestStateId)
{
Map<String, String> requestState = (Map<String, String>) state.removeAttribute(CitationHelper.RESOURCES_SYS_PREFIX + requestStateId);
logger.debug("restoreRequestState() requestStateId == " + requestStateId + "\n" + requestState);
if(requestState != null)
{
List<String> attrNames = state.getAttributeNames();
for(String attrName : attrNames)
{
for(String prefix : prefixes)
{
if(attrName.startsWith(prefix))
{
state.removeAttribute(attrName);
break;
}
}
}
for(Map.Entry<String, String> entry : requestState.entrySet())
{
state.setAttribute(entry.getKey(), entry.getValue());
}
}
}
protected Map<String,Object> getProperties(ContentEntity entity, SessionState state) {
Map<String,Object> props = new HashMap<String,Object>();
ResourceProperties properties = entity.getProperties();
Reference ref = getEntityManager().newReference(entity.getReference());
DateFormat df = DateFormat.getDateTimeInstance();
// isHidden
props.put(PROP_IS_HIDDEN, new Boolean(entity.isHidden()));
// releaseDate, useReleaseDate
Date releaseDate = null;
if(entity.getReleaseDate() == null) {
releaseDate = new Date(System.currentTimeMillis());
props.put(PROP_USE_RELEASE_DATE, Boolean.FALSE);
} else {
releaseDate = new Date(entity.getReleaseDate().getTime());
props.put(PROP_USE_RELEASE_DATE, Boolean.TRUE);
}
props.put(PROP_RELEASE_DATE_STR, df.format(releaseDate));
props.put(PROP_RELEASE_DATE, releaseDate);
// retractDate, useRetractDate
Date retractDate = null;
if(entity.getRetractDate() == null) {
retractDate = new Date(System.currentTimeMillis() + ONE_WEEK);
props.put(PROP_USE_RETRACT_DATE, Boolean.FALSE);
} else {
retractDate = new Date(entity.getRetractDate().getTime());
props.put(PROP_USE_RETRACT_DATE, Boolean.TRUE);
}
props.put(PROP_RETRACT_DATE_STR, df.format(retractDate));
props.put(PROP_RETRACT_DATE, retractDate);
// isCollection
props.put(PROP_IS_COLLECTION, entity.isCollection());
// isDropbox
props.put(PROP_IS_DROPBOX, new Boolean(getContentService().isInDropbox(entity.getId())));
// isSiteCollection
props.put(PROP_IS_SITE_COLLECTION, new Boolean(ref.getContext() != null && ref.getContext().equals(entity.getId())));
// isPubview
props.put(PROP_IS_PUBVIEW, getContentService().isPubView(entity.getId()));
// isPubviewInherited
props.put(PROP_IS_PUBVIEW_INHERITED, new Boolean(getContentService().isInheritingPubView(entity.getId())));
// isPubviewPossible
Boolean preventPublicDisplay = (Boolean) state.getAttribute("resources.request.prevent_public_display");
if(preventPublicDisplay == null) {
preventPublicDisplay = Boolean.FALSE;
}
props.put(PROP_IS_PUBVIEW_POSSIBLE, new Boolean(! preventPublicDisplay.booleanValue()));
// accessMode
AccessMode accessMode = entity.getAccess();
props.put(PROP_ACCESS_MODE, accessMode);
// isGroupInherited
props.put(PROP_IS_GROUP_INHERITED, AccessMode.GROUPED == entity.getInheritedAccess());
SiteService siteService = (SiteService) ComponentManager.get(SiteService.class);
Set<String> currentGroups = new TreeSet<String>();
if(AccessMode.GROUPED == accessMode) {
for(Group gr : (Collection<Group>) entity.getGroupObjects()) {
currentGroups.add(gr.getId());
}
}
// possibleGroups
Collection<Group> inheritedGroupObjs = null;
if(entity.getInheritedAccess() == AccessMode.GROUPED) {
inheritedGroupObjs = entity.getInheritedGroupObjects();
} else {
try {
Site site = siteService.getSite(ref.getContext());
inheritedGroupObjs = site.getGroups();
} catch (IdUnusedException e) {
logger.warn("IdUnusedException in getProperties() " + e);
}
}
List<Map<String,String>> groups = new ArrayList<Map<String,String>>();
if(inheritedGroupObjs != null) {
Collection<Group> groupsWithRemovePermission = null;
if(AccessMode.GROUPED == accessMode)
{
groupsWithRemovePermission = contentService.getGroupsWithRemovePermission(entity.getId());
String container = ref.getContainer();
if(container != null)
{
Collection<Group> more = contentService.getGroupsWithRemovePermission(container);
if(more != null && ! more.isEmpty())
{
groupsWithRemovePermission.addAll(more);
}
}
} else if(AccessMode.GROUPED == entity.getInheritedAccess()) {
groupsWithRemovePermission = contentService.getGroupsWithRemovePermission(ref.getContainer());
}
else if(ref.getContext() != null && contentService.getSiteCollection(ref.getContext()) != null)
{
groupsWithRemovePermission = contentService.getGroupsWithRemovePermission(contentService.getSiteCollection(ref.getContext()));
}
Set<String> idsOfGroupsWithRemovePermission = new TreeSet<String>();
if(groupsWithRemovePermission != null) {
for(Group gr : groupsWithRemovePermission) {
idsOfGroupsWithRemovePermission.add(gr.getId());
}
}
for(Group group : inheritedGroupObjs) {
Map<String, String> grp = new HashMap<String, String>();
grp.put("groupId", group.getId());
grp.put("title", group.getTitle());
grp.put("description", group.getDescription());
grp.put("entityRef", group.getReference());
if(currentGroups.contains(group.getId())) {
grp.put("isLocal", Boolean.toString(true));
}
if(idsOfGroupsWithRemovePermission.contains(group.getId())) {
grp.put("allowedRemove", Boolean.toString(true));
}
groups.add(grp);
}
}
props.put(PROP_POSSIBLE_GROUPS, groups);
// isGroupPossible
props.put(PROP_IS_GROUP_POSSIBLE, new Boolean(groups != null && groups.size() > 0));
// isSingleGroupInherited
props.put(PROP_IS_SINGLE_GROUP_INHERITED, new Boolean(groups != null && groups.size() == 1));
// isSiteOnly = ! isPubviewPossible && ! isGroupPossible
props.put(PROP_IS_SITE_ONLY, new Boolean(preventPublicDisplay.booleanValue() && (groups == null || groups.size() < 1)));
// isUserSite
props.put(PROP_IS_USER_SITE, siteService.isUserSite(ref.getContext()));
// getSelectedConditionKey
// getSubmittedResourceFilter
// isUseConditionalRelease
state.setAttribute(STATE_RESOURCE_ENTITY_PROPERTIES, props);
return props;
}
protected CitationService getCitationService() {
if(this.citationService == null) {
this.citationService = (CitationService) ComponentManager.get(CitationService.class);
}
return this.citationService;
}
protected ConfigurationService getConfigurationService() {
if(this.configurationService == null) {
this.configurationService = (ConfigurationService) ComponentManager.get(ConfigurationService.class);
}
return this.configurationService;
}
protected SearchManager getSearchManager() {
if(this.searchManager == null) {
this.searchManager = (SearchManager) ComponentManager.get(SearchManager.class);
}
return this.searchManager;
}
protected ContentHostingService getContentService() {
if(this.contentService == null) {
this.contentService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService");
}
return this.contentService;
}
protected EntityManager getEntityManager() {
if(this.entityManager == null) {
this.entityManager = (EntityManager) ComponentManager.get(EntityManager.class);
}
return this.entityManager;
}
protected SessionManager getSessionManager() {
if(this.sessionManager == null) {
this.sessionManager = (SessionManager) ComponentManager.get(SessionManager.class);
}
return this.sessionManager;
}
protected static ToolManager getToolManager() {
if(toolManager == null) {
toolManager = (ToolManager) ComponentManager.get(ToolManager.class);
}
return toolManager;
}
protected static FormattedText getFormattedText() {
if(formattedText == null) {
formattedText = (FormattedText) ComponentManager.get(FormattedText.class);
}
return formattedText;
}
} // class CitationHelperAction
| citations/citations-tool/tool/src/java/org/sakaiproject/citation/tool/CitationHelperAction.java | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2006, 2007, 2008, 2009 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.citation.tool;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.io.input.BOMInputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.antivirus.api.VirusFoundException;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.VelocityPortletPaneledAction;
import org.sakaiproject.citation.api.ActiveSearch;
import org.sakaiproject.citation.api.Citation;
import org.sakaiproject.citation.api.CitationCollection;
import org.sakaiproject.citation.api.CitationHelper;
import org.sakaiproject.citation.api.CitationIterator;
import org.sakaiproject.citation.api.CitationService;
import org.sakaiproject.citation.api.ConfigurationService;
import org.sakaiproject.citation.api.Schema;
import org.sakaiproject.citation.api.Schema.Field;
import org.sakaiproject.citation.api.SearchCategory;
import org.sakaiproject.citation.api.SearchDatabaseHierarchy;
import org.sakaiproject.citation.api.SearchManager;
import org.sakaiproject.citation.util.api.SearchCancelException;
import org.sakaiproject.citation.util.api.SearchException;
import org.sakaiproject.citation.util.api.SearchQuery;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.content.api.ContentCollection;
import org.sakaiproject.content.api.ContentEntity;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.content.api.GroupAwareEntity.AccessMode;
import org.sakaiproject.content.api.ResourceToolAction;
import org.sakaiproject.content.api.ResourceToolActionPipe;
import org.sakaiproject.content.api.ResourceType;
import org.sakaiproject.entity.api.EntityManager;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdLengthException;
import org.sakaiproject.exception.IdUniquenessException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.InconsistentException;
import org.sakaiproject.exception.OverQuotaException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.ServerOverloadException;
import org.sakaiproject.exception.TypeException;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.api.ToolException;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.util.FileItem;
import org.sakaiproject.util.ParameterParser;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.Validator;
import org.sakaiproject.util.api.FormattedText;
/**
*
*/
public class CitationHelperAction extends VelocityPortletPaneledAction
{
/**
* This class contains constants and utility methods to maintain state of
* the advanced search form UI and process submitted data
*
* @author gbhatnag
*/
protected static class AdvancedSearchHelper
{
/* ids for fields */
public static final String KEYWORD_ID = "keyword";
public static final String AUTHOR_ID = "author";
public static final String TITLE_ID = "title";
public static final String SUBJECT_ID = "subject";
public static final String YEAR_ID = "year";
/* keys to hold state information */
public static final String STATE_FIELD1 = CitationHelper.CITATION_PREFIX + "advField1";
public static final String STATE_FIELD2 = CitationHelper.CITATION_PREFIX + "advField2";
public static final String STATE_FIELD3 = CitationHelper.CITATION_PREFIX + "advField3";
public static final String STATE_FIELD4 = CitationHelper.CITATION_PREFIX + "advField4";
public static final String STATE_FIELD5 = CitationHelper.CITATION_PREFIX + "advField5";
public static final String STATE_CRITERIA1 = CitationHelper.CITATION_PREFIX + "advCriteria1";
public static final String STATE_CRITERIA2 = CitationHelper.CITATION_PREFIX + "advCriteria2";
public static final String STATE_CRITERIA3 = CitationHelper.CITATION_PREFIX + "advCriteria3";
public static final String STATE_CRITERIA4 = CitationHelper.CITATION_PREFIX + "advCriteria4";
public static final String STATE_CRITERIA5 = CitationHelper.CITATION_PREFIX + "advCriteria5";
/**
* Puts field selections stored in session state (using setFieldSelections())
* into the given context
*
* @param context context to put field selections into
* @param state SessionState to pull field selections from
*/
public static void putFieldSelections( Context context, SessionState state )
{
/*
context.put( "advField1", ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD1 ) );
context.put( "advField2", ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD2 ) );
context.put( "advField3", ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD3 ) );
context.put( "advField4", ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD4 ) );
context.put( "advField5", ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD5 ) );
*/
String advField1 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD1 );
String advField2 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD2 );
String advField3 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD3 );
String advField4 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD4 );
String advField5 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD5 );
if( advField1 != null && !advField1.trim().equals("") )
{
context.put( "advField1", advField1 );
}
else
{
context.put( "advField1", KEYWORD_ID );
}
if( advField2 != null && !advField2.trim().equals("") )
{
context.put( "advField2", advField2 );
}
else
{
context.put( "advField2", AUTHOR_ID );
}
if( advField3 != null && !advField3.trim().equals("") )
{
context.put( "advField3", advField3 );
}
else
{
context.put( "advField3", TITLE_ID );
}
if( advField4 != null && !advField4.trim().equals("") )
{
context.put( "advField4", advField4 );
}
else
{
context.put( "advField4", SUBJECT_ID );
}
if( advField5 != null && !advField5.trim().equals("") )
{
context.put( "advField5", advField5 );
}
else
{
context.put( "advField5", YEAR_ID );
}
}
/**
* Puts field criteria stored in session state (using setFieldCriteria())
* into the given context
*
* @param context context to put field criteria into
* @param state SessionState to pull field criteria from
*/
public static void putFieldCriteria( Context context, SessionState state )
{
context.put( "advCriteria1", ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA1 ) );
context.put( "advCriteria2", ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA2 ) );
context.put( "advCriteria3", ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA3 ) );
context.put( "advCriteria4", ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA4 ) );
context.put( "advCriteria5", ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA5 ) );
}
/**
* Sets user-selected fields in session state from request parameters
*
* @param params request parameters from doBeginSearch
* @param state SessionState to store field selections
*/
public static void setFieldSelections( ParameterParser params, SessionState state )
{
String advField1 = params.getString( "advField1" );
if( advField1 != null && !advField1.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_FIELD1, advField1 );
}
String advField2 = params.getString( "advField2" );
if( advField2 != null && !advField2.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_FIELD2, advField2 );
}
String advField3 = params.getString( "advField3" );
if( advField3 != null && !advField3.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_FIELD3, advField3 );
}
String advField4 = params.getString( "advField4" );
if( advField4 != null && !advField4.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_FIELD4, advField4 );
}
String advField5 = params.getString( "advField5" );
if( advField5 != null && !advField5.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_FIELD5, advField5 );
}
}
/**
* Sets user-entered search field criteria in session state
* from request parameters
*
* @param params request parameters from doBeginSearch
* @param state SessionState to store field criteria
*/
public static void setFieldCriteria( ParameterParser params, SessionState state )
{
String advCriteria1 = params.getString( "advCriteria1" );
if( advCriteria1 != null && !advCriteria1.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_CRITERIA1, advCriteria1 );
}
String advCriteria2 = params.getString( "advCriteria2" );
if( advCriteria2 != null && !advCriteria2.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_CRITERIA2, advCriteria2 );
}
String advCriteria3 = params.getString( "advCriteria3" );
if( advCriteria3 != null && !advCriteria3.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_CRITERIA3, advCriteria3 );
}
String advCriteria4 = params.getString( "advCriteria4" );
if( advCriteria4 != null && !advCriteria4.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_CRITERIA4, advCriteria4 );
}
String advCriteria5 = params.getString( "advCriteria5" );
if( advCriteria5 != null && !advCriteria5.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_CRITERIA5, advCriteria5 );
}
}
public static SearchQuery getAdvancedCriteria( SessionState state )
{
String advField1 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD1 );
String advField2 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD2 );
String advField3 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD3 );
String advField4 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD4 );
String advField5 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD5 );
String advCriteria1 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA1 );
String advCriteria2 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA2 );
String advCriteria3 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA3 );
String advCriteria4 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA4 );
String advCriteria5 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA5 );
SearchQuery searchQuery = new org.sakaiproject.citation.util.impl.SearchQuery();
/*
* put fielded, non-null criteria into the searchQuery
*/
if( advField1 != null && advCriteria1 != null )
{
if( advField1.equalsIgnoreCase( KEYWORD_ID ) )
{
searchQuery.addKeywords( advCriteria1 );
}
else if( advField1.equalsIgnoreCase( AUTHOR_ID ) )
{
searchQuery.addAuthor( advCriteria1 );
}
else if( advField1.equalsIgnoreCase( TITLE_ID ) )
{
searchQuery.addTitle( advCriteria1 );
}
else if( advField1.equalsIgnoreCase( SUBJECT_ID ) )
{
searchQuery.addSubject( advCriteria1 );
}
else if( advField1.equalsIgnoreCase( YEAR_ID ) )
{
searchQuery.addYear( advCriteria1 );
}
}
if( advField2 != null && advCriteria2 != null )
{
if( advField2.equalsIgnoreCase( KEYWORD_ID ) )
{
searchQuery.addKeywords( advCriteria2 );
}
else if( advField2.equalsIgnoreCase( AUTHOR_ID ) )
{
searchQuery.addAuthor( advCriteria2 );
}
else if( advField2.equalsIgnoreCase( TITLE_ID ) )
{
searchQuery.addTitle( advCriteria2 );
}
else if( advField2.equalsIgnoreCase( SUBJECT_ID ) )
{
searchQuery.addSubject( advCriteria2 );
}
else if( advField2.equalsIgnoreCase( YEAR_ID ) )
{
searchQuery.addYear( advCriteria2 );
}
}
if( advField3 != null && advCriteria3 != null )
{
if( advField3.equalsIgnoreCase( KEYWORD_ID ) )
{
searchQuery.addKeywords( advCriteria3 );
}
else if( advField3.equalsIgnoreCase( AUTHOR_ID ) )
{
searchQuery.addAuthor( advCriteria3 );
}
else if( advField3.equalsIgnoreCase( TITLE_ID ) )
{
searchQuery.addTitle( advCriteria3 );
}
else if( advField3.equalsIgnoreCase( SUBJECT_ID ) )
{
searchQuery.addSubject( advCriteria3 );
}
else if( advField3.equalsIgnoreCase( YEAR_ID ) )
{
searchQuery.addYear( advCriteria3 );
}
}
if( advField4 != null && advCriteria4 != null )
{
if( advField4.equalsIgnoreCase( KEYWORD_ID ) )
{
searchQuery.addKeywords( advCriteria4 );
}
else if( advField4.equalsIgnoreCase( AUTHOR_ID ) )
{
searchQuery.addAuthor( advCriteria4 );
}
else if( advField4.equalsIgnoreCase( TITLE_ID ) )
{
searchQuery.addTitle( advCriteria4 );
}
else if( advField4.equalsIgnoreCase( SUBJECT_ID ) )
{
searchQuery.addSubject( advCriteria4 );
}
else if( advField4.equalsIgnoreCase( YEAR_ID ) )
{
searchQuery.addYear( advCriteria4 );
}
}
if( advField5 != null && advCriteria5 != null )
{
if( advField5.equalsIgnoreCase( KEYWORD_ID ) )
{
searchQuery.addKeywords( advCriteria5 );
}
else if( advField5.equalsIgnoreCase( AUTHOR_ID ) )
{
searchQuery.addAuthor( advCriteria5 );
}
else if( advField5.equalsIgnoreCase( TITLE_ID ) )
{
searchQuery.addTitle( advCriteria5 );
}
else if( advField5.equalsIgnoreCase( SUBJECT_ID ) )
{
searchQuery.addSubject( advCriteria5 );
}
else if( advField5.equalsIgnoreCase( YEAR_ID ) )
{
searchQuery.addYear( advCriteria5 );
}
}
return searchQuery;
}
public static void clearAdvancedFormState( SessionState state )
{
state.removeAttribute( AdvancedSearchHelper.STATE_FIELD1 );
state.removeAttribute( AdvancedSearchHelper.STATE_FIELD2 );
state.removeAttribute( AdvancedSearchHelper.STATE_FIELD3 );
state.removeAttribute( AdvancedSearchHelper.STATE_FIELD4 );
state.removeAttribute( AdvancedSearchHelper.STATE_FIELD5 );
state.removeAttribute( AdvancedSearchHelper.STATE_CRITERIA1 );
state.removeAttribute( AdvancedSearchHelper.STATE_CRITERIA2 );
state.removeAttribute( AdvancedSearchHelper.STATE_CRITERIA3 );
state.removeAttribute( AdvancedSearchHelper.STATE_CRITERIA4 );
state.removeAttribute( AdvancedSearchHelper.STATE_CRITERIA5 );
}
}
protected final static Log logger = LogFactory.getLog(CitationHelperAction.class);
public static ResourceLoader rb = new ResourceLoader("citations");
protected CitationService citationService;
protected ConfigurationService configurationService;
protected SearchManager searchManager;
protected ContentHostingService contentService;
protected EntityManager entityManager;
protected SessionManager sessionManager;
protected static FormattedText formattedText;
protected static ToolManager toolManager;
public static final Integer DEFAULT_RESULTS_PAGE_SIZE = new Integer(10);
public static final Integer DEFAULT_LIST_PAGE_SIZE = new Integer(50);
public static Integer defaultListPageSize = DEFAULT_LIST_PAGE_SIZE;
protected static final String ELEMENT_ID_CREATE_FORM = "createForm";
protected static final String ELEMENT_ID_EDIT_FORM = "editForm";
protected static final String ELEMENT_ID_LIST_FORM = "listForm";
protected static final String ELEMENT_ID_SEARCH_FORM = "searchForm";
protected static final String ELEMENT_ID_RESULTS_FORM = "resultsForm";
protected static final String ELEMENT_ID_VIEW_FORM = "viewForm";
/**
* The calling application reflects the nature of our caller
*/
public final static String CITATIONS_HELPER_CALLER = "citations_helper_caller";
public enum Caller
{
RESOURCE_TOOL,
EDITOR_INTEGRATION;
}
/**
* Mode defines a complete set of values describing the user's navigation intentions
*/
public enum Mode
{
NEW_RESOURCE,
DATABASE,
CREATE,
EDIT,
ERROR,
ERROR_FATAL,
LIST,
REORDER,
ADD_CITATIONS,
IMPORT_CITATIONS,
MESSAGE,
SEARCH,
RESULTS,
VIEW;
}
/*
* define a set of "fake" Modes (asynchronous calls) to maintain proper
* back-button stack state
*/
protected static Set<Mode> ignoreModes = new java.util.HashSet<Mode>();
static {
ignoreModes.add( Mode.DATABASE );
ignoreModes.add( Mode.MESSAGE );
}
protected static final String PARAM_FORM_NAME = "FORM_NAME";
protected static final String STATE_RESOURCES_ADD = CitationHelper.CITATION_PREFIX + "resources_add";
protected static final String STATE_CURRENT_DATABASES = CitationHelper.CITATION_PREFIX + "current_databases";
protected static final String STATE_CANCEL_PAGE = CitationHelper.CITATION_PREFIX + "cancel_page";
protected static final String STATE_CITATION_COLLECTION_ID = CitationHelper.CITATION_PREFIX + "citation_collection_id";
protected static final String STATE_CITATION_COLLECTION = CitationHelper.CITATION_PREFIX + "citation_collection";
protected static final String STATE_CITATION_ID = CitationHelper.CITATION_PREFIX + "citation_id";
protected static final String STATE_COLLECTION_TITLE = CitationHelper.CITATION_PREFIX + "collection_name";
protected static final String STATE_CURRENT_REPOSITORY = CitationHelper.CITATION_PREFIX + "current_repository";
protected static final String STATE_CURRENT_RESULTS = CitationHelper.CITATION_PREFIX + "current_results";
protected static final String STATE_LIST_ITERATOR = CitationHelper.CITATION_PREFIX + "list_iterator";
protected static final String STATE_LIST_PAGE = CitationHelper.CITATION_PREFIX + "list_page";
protected static final String STATE_LIST_PAGE_SIZE = CitationHelper.CITATION_PREFIX + "list_page_size";
protected static final String STATE_LIST_NO_SCROLL = CitationHelper.CITATION_PREFIX + "list_no_scroll";
protected static final String STATE_NO_KEYWORDS = CitationHelper.CITATION_PREFIX + "no_search_criteria";
protected static final String STATE_NO_DATABASES = CitationHelper.CITATION_PREFIX + "no_databases";
protected static final String STATE_NO_RESULTS = CitationHelper.CITATION_PREFIX + "no_results";
protected static final String STATE_SEARCH_HIERARCHY = CitationHelper.CITATION_PREFIX + "search_hierarchy";
protected static final String STATE_SELECTED_CATEGORY = CitationHelper.CITATION_PREFIX + "selected_category";
protected static final String STATE_DEFAULT_CATEGORY = CitationHelper.CITATION_PREFIX + "default_category";
protected static final String STATE_UNAUTHORIZED_DB = CitationHelper.CITATION_PREFIX + "unauthorized_database";
protected static final String STATE_REPOSITORY_MAP = CitationHelper.CITATION_PREFIX + "repository_map";
protected static final String STATE_RESULTS_PAGE_SIZE = CitationHelper.CITATION_PREFIX + "results_page_size";
protected static final String STATE_KEYWORDS = CitationHelper.CITATION_PREFIX + "search_criteria";
protected static final String STATE_SEARCH_INFO = CitationHelper.CITATION_PREFIX + "search_info";
protected static final String STATE_BASIC_SEARCH = CitationHelper.CITATION_PREFIX + "basic_search";
protected static final String STATE_SEARCH_RESULTS = CitationHelper.CITATION_PREFIX + "search_results";
protected static final String STATE_RESOURCE_ENTITY_PROPERTIES = CitationHelper.CITATION_PREFIX + "citationList_properties";
protected static final String STATE_SORT = CitationHelper.CITATION_PREFIX + "sort";
protected static final String TEMPLATE_NEW_RESOURCE = "citation/new_resource";
protected static final String TEMPLATE_CREATE = "citation/create";
protected static final String TEMPLATE_EDIT = "citation/edit";
protected static final String TEMPLATE_ERROR = "citation/error";
protected static final String TEMPLATE_ERROR_FATAL = "citation/error_fatal";
protected static final String TEMPLATE_LIST = "citation/list";
protected static final String TEMPLATE_REORDER = "citation/reorder";
protected static final String TEMPLATE_ADD_CITATIONS = "citation/add_citations";
protected static final String TEMPLATE_IMPORT_CITATIONS = "citation/import_citations";
protected static final String TEMPLATE_MESSAGE = "citation/_message";
protected static final String TEMPLATE_SEARCH = "citation/search";
protected static final String TEMPLATE_RESULTS = "citation/results";
protected static final String TEMPLATE_VIEW = "citation/view";
protected static final String TEMPLATE_DATABASE = "citation/_databases";
protected static final String PROP_ACCESS_MODE = "accessMode";
protected static final String PROP_IS_COLLECTION = "isCollection";
protected static final String PROP_IS_DROPBOX = "isDropbox";
protected static final String PROP_IS_GROUP_INHERITED = "isGroupInherited";
protected static final String PROP_IS_GROUP_POSSIBLE = "isGroupPossible";
protected static final String PROP_IS_HIDDEN = "isHidden";
protected static final String PROP_IS_PUBVIEW = "isPubview";
protected static final String PROP_IS_PUBVIEW_INHERITED = "isPubviewInherited";
protected static final String PROP_IS_PUBVIEW_POSSIBLE = "isPubviewPossible";
protected static final String PROP_IS_SINGLE_GROUP_INHERITED = "isSingleGroupInherited";
protected static final String PROP_IS_SITE_COLLECTION = "isSiteCollection";
protected static final String PROP_IS_SITE_ONLY = "isSiteOnly";
protected static final String PROP_IS_USER_SITE = "isUserSite";
protected static final String PROP_POSSIBLE_GROUPS = "possibleGroups";
protected static final String PROP_RELEASE_DATE = "releaseDate";
protected static final String PROP_RELEASE_DATE_STR = "releaseDateStr";
protected static final String PROP_RETRACT_DATE = "retractDate";
protected static final String PROP_RETRACT_DATE_STR = "retractDateStr";
protected static final String PROP_USE_RELEASE_DATE = "useReleaseDate";
protected static final String PROP_USE_RETRACT_DATE = "useRetractDate";
public static final String CITATION_ACTION = "citation_action";
public static final String UPDATE_RESOURCE = "update_resource";
public static final String CREATE_RESOURCE = "create_resource";
public static final String IMPORT_CITATIONS = "import_citations";
public static final String UPDATE_SAVED_SORT = "update_saved_sort";
public static final String CHECK_FOR_UPDATES = "check_for_updates";
public static final String MIMETYPE_JSON = "application/json";
public static final String MIMETYPE_HTML = "text/html";
public static final String REQUESTED_MIMETYPE = "requested_mimetype";
public static final String CHARSET_UTF8 = "UTF-8";
/** A long representing the number of milliseconds in one week. Used for date calculations */
public static final long ONE_DAY = 24L * 60L * 60L * 1000L;
/** A long representing the number of milliseconds in one week. Used for date calculations */
public static final long ONE_WEEK = 7L * ONE_DAY;
public void init() throws ServletException {
ServerConfigurationService scs
= (ServerConfigurationService) ComponentManager.get(ServerConfigurationService.class);
if(scs != null) {
defaultListPageSize = scs.getInt("citations.default.list.page.size", DEFAULT_LIST_PAGE_SIZE);
} else {
logger.warn("Failed to get default list page size as ServerConfigurationService is null. Defaulting to " + DEFAULT_LIST_PAGE_SIZE);
defaultListPageSize = DEFAULT_LIST_PAGE_SIZE;
}
}
/**
* Check for the helper-done case locally and handle it before letting the VPPA.toolModeDispatch() handle the actual dispatch.
* @see org.sakaiproject.cheftool.VelocityPortletPaneledAction#toolModeDispatch(java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void toolModeDispatch(String methodBase, String methodExt, HttpServletRequest req, HttpServletResponse res)
throws ToolException
{
logger.debug("toolModeDispatch()");
//SessionState sstate = getState(req);
ToolSession toolSession = getSessionManager().getCurrentToolSession();
//String mode = (String) sstate.getAttribute(ResourceToolAction.STATE_MODE);
//Object started = toolSession.getAttribute(ResourceToolAction.STARTED);
Object done = toolSession.getAttribute(ResourceToolAction.DONE);
// if we're done or not properly initialized, redirect to Resources
if ( done != null || !initHelper( getState(req) ) )
{
toolSession.removeAttribute(ResourceToolAction.STARTED);
Tool tool = getToolManager().getCurrentTool();
String url = (String) toolSession.getAttribute(tool.getId() + Tool.HELPER_DONE_URL);
toolSession.removeAttribute(tool.getId() + Tool.HELPER_DONE_URL);
try
{
res.sendRedirect(url); // TODO
}
catch (IOException e)
{
logger.warn("IOException", e);
// Log.warn("chef", this + " : ", e);
}
return;
}
super.toolModeDispatch(methodBase, methodExt, req, res);
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException {
logger.info("doGet()");
String isAjaxRequest = req.getParameter("ajaxRequest");
if(isAjaxRequest != null && isAjaxRequest.trim().equalsIgnoreCase(Boolean.toString(true))) {
ParameterParser params = (ParameterParser) req.getAttribute(ATTR_PARAMS);
if(params == null) {
params = new ParameterParser(req);
}
SessionState state = getState(req);
// Check whether this is an AJAX request expecting a JSON response and if it is
// dispatch the request to the buildJsonResponse() method, avoiding VPPA's
// html rendering. Other options might be HTML-fragment, XML, etc.
//String requestedMimetype = (String) toolSession.getAttribute(REQUESTED_MIMETYPE);
String requestedMimetype = params.getString(REQUESTED_MIMETYPE);
logger.info("doGet() requestedMimetype == " + requestedMimetype);
if(requestedMimetype != null && requestedMimetype.equals(MIMETYPE_JSON)) {
doGetJsonResponse(params, state, req, res);
} else if(requestedMimetype != null && requestedMimetype.equals(MIMETYPE_HTML)) {
doGetHtmlFragmentResponse(params, state, req, res);
} else {
// throw something
}
return;
}
super.doGet(req, res);
}
protected void doGetHtmlFragmentResponse(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
}
protected void doGetJsonResponse(ParameterParser params, SessionState state,
HttpServletRequest req, HttpServletResponse res) {
res.setCharacterEncoding(CHARSET_UTF8);
res.setContentType(MIMETYPE_JSON);
Map<String,Object> jsonMap = new HashMap<String,Object>();
String sakai_csrf_token = params.getString("sakai_csrf_token");
if(sakai_csrf_token != null && ! sakai_csrf_token.trim().equals("")) {
jsonMap.put("sakai_csrf_token", sakai_csrf_token);
}
jsonMap.put("timestamp", Long.toString(System.currentTimeMillis()));
String citation_action = params.getString("citation_action");
if(citation_action != null && citation_action.trim().equals(CHECK_FOR_UPDATES)) {
Map<String,Object> result = this.checkForUpdates(params, state, req, res);
jsonMap.putAll(result);
}
// convert to json string
String jsonString = JSONObject.fromObject(jsonMap).toString();
try {
PrintWriter writer = res.getWriter();
writer.print(jsonString);
writer.flush();
} catch (IOException e) {
logger.warn("IOException in doGetJsonResponse() " + e);
}
}
protected Map<String, Object> checkForUpdates(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> result = new HashMap<String, Object>();
boolean changed = false;
long lastcheckLong = 0L;
String lastcheck = params.getString("lastcheck");
if(lastcheck == null || lastcheck.trim().equals("")) {
// do nothing
} else {
try {
lastcheckLong = Long.parseLong(lastcheck);
} catch(Exception e) {
logger.warn("Error parsing long from string: " + lastcheck, e);
}
}
if(lastcheckLong > 0L) {
String citationCollectionId = params.getString("citationCollectionId");
if(citationCollectionId != null && !citationCollectionId.trim().equals("")) {
try {
CitationCollection citationCollection = this.citationService.getCollection(citationCollectionId);
if(citationCollection.getLastModifiedDate().getTime() > lastcheckLong) {
changed = true;
result.put("html", "<div>something goes here</div>");
}
} catch (IdUnusedException e) {
logger.warn("IdUnusedException in checkForUpdates() " + e);
}
}
}
result.put("changed", Boolean.toString(changed));
return result;
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException {
logger.info("doPost()");
// Enumeration<String> names = req.getHeaderNames();
// while(names.hasMoreElements()) {
// String name = names.nextElement();
// String value = req.getHeader(name);
// logger.info("doPost() header " + name + " == " + value);
// }
//
// Cookie[] cookies = req.getCookies();
// for(Cookie cookie : cookies) {
// logger.info("doPost() ==cookie== " + cookie.getName() + " == " + cookie.getValue());
// }
// handle AJAX requests here and send other requests on to the VPPA dispatcher
String isAjaxRequest = req.getParameter("ajaxRequest");
if(isAjaxRequest != null && isAjaxRequest.trim().equalsIgnoreCase(Boolean.toString(true))) {
ParameterParser params = (ParameterParser) req.getAttribute(ATTR_PARAMS);
if(params == null) {
params = new ParameterParser(req);
}
SessionState state = getState(req);
// Check whether this is an AJAX request expecting a JSON response and if it is
// dispatch the request to the buildJsonResponse() method, avoiding VPPA's
// html rendering. Other options might be HTML-fragment, XML, etc.
//String requestedMimetype = (String) toolSession.getAttribute(REQUESTED_MIMETYPE);
String requestedMimetype = params.getString(REQUESTED_MIMETYPE);
logger.info("doPost() requestedMimetype == " + requestedMimetype);
if(requestedMimetype != null && requestedMimetype.equals(MIMETYPE_JSON)) {
doPostJsonResponse(params, state, req, res);
} else if(requestedMimetype != null && requestedMimetype.equals(MIMETYPE_HTML)) {
doPostHtmlFragmentResponse(params, state, req, res);
}
return;
}
super.doPost(req, res);
}
protected void doPostHtmlFragmentResponse(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> result = this.ensureCitationListExists(params, state, req, res);
res.setCharacterEncoding(CHARSET_UTF8);
res.setContentType(MIMETYPE_HTML);
String sakai_csrf_token = params.getString("sakai_csrf_token");
if(sakai_csrf_token != null && ! sakai_csrf_token.trim().equals("")) {
setVmReference("sakai_csrf_token", sakai_csrf_token, req);
}
for(Map.Entry<String,Object> entry : result.entrySet()) {
setVmReference(entry.getKey(), entry.getValue(), req);
}
}
protected void doPostJsonResponse(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
res.setCharacterEncoding(CHARSET_UTF8);
res.setContentType(MIMETYPE_JSON);
Map<String,Object> jsonMap = new HashMap<String,Object>();
String sakai_csrf_token = params.getString("sakai_csrf_token");
if(sakai_csrf_token != null && ! sakai_csrf_token.trim().equals("")) {
jsonMap.put("sakai_csrf_token", sakai_csrf_token);
}
jsonMap.put("timestamp", Long.toString(System.currentTimeMillis()));
String citation_action = params.getString("citation_action");
if(citation_action != null && citation_action.trim().equals(UPDATE_RESOURCE)) {
Map<String,Object> result = this.updateCitationList(params, state, req, res);
jsonMap.putAll(result);
} else if(citation_action != null && citation_action.trim().equals(UPDATE_SAVED_SORT)) {
Map<String,Object> result = this.updateSavedSort(params, state, req, res);
jsonMap.putAll(result);
} else {
Map<String,Object> result = this.createCitationList(params, state, req, res);
jsonMap.putAll(result);
}
// convert to json string
String jsonString = JSONObject.fromObject(jsonMap).toString();
try {
PrintWriter writer = res.getWriter();
writer.print(jsonString);
writer.flush();
} catch (IOException e) {
logger.warn("IOException in doPostJsonResponse() ", e);
// what goes back?
}
}
protected Map<String, Object> updateSavedSort(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> results = new HashMap<String, Object>();
String message = null;
String citationCollectionId = params.getString("citationCollectionId");
String new_sort = params.getString("new_sort");
if(citationCollectionId == null || citationCollectionId.trim().equals("")) {
// need to report error
results.put("message", rb.getString("sort.save.error"));
} else {
if(new_sort == null || new_sort.trim().equals("")) {
new_sort = "default";
}
try {
CitationCollection citationCollection = this.citationService.getCollection(citationCollectionId);
citationCollection.setSort(new_sort, true);
this.citationService.save(citationCollection);
results.put("message", rb.getString("sort.save.success"));
} catch (IdUnusedException e) {
// need to report error
results.put("message", rb.getString("sort.save.error"));
}
}
return results;
}
protected Map<String, Object> createCitationList(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> results = new HashMap<String, Object>();
results.putAll(this.ensureCitationListExists(params, state, req, res));
return results;
}
protected Map<String, Object> updateCitationList(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> results = new HashMap<String, Object>();
String resourceUuid = params.getString("resourceUuid");
String message = null;
if(resourceUuid == null) {
results.putAll(this.ensureCitationListExists(params, state, req, res));
} else {
try {
String resourceId = this.getContentService().resolveUuid(resourceUuid);
ContentResourceEdit edit = getContentService().editResource(resourceId);
this.captureDisplayName(params, state, edit, results);
this.captureDescription(params, state, edit, results);
this.captureAccess(params, state, edit, results);
this.captureAvailability(params, edit, results);
getContentService().commitResource(edit);
message = "Resource updated";
} catch (IdUnusedException e) {
message = e.getMessage();
logger.warn("IdUnusedException in updateCitationList() " + e);
} catch (TypeException e) {
message = e.getMessage();
logger.warn("TypeException in updateCitationList() " + e);
} catch (InUseException e) {
message = e.getMessage();
logger.warn("InUseException in updateCitationList() " + e);
} catch (PermissionException e) {
message = e.getMessage();
logger.warn("PermissionException in updateCitationList() " + e);
} catch (OverQuotaException e) {
message = e.getMessage();
logger.warn("OverQuotaException in updateCitationList() " + e);
} catch (ServerOverloadException e) {
message = e.getMessage();
logger.warn("ServerOverloadException in updateCitationList() " + e);
} catch (VirusFoundException e) {
message = e.getMessage();
logger.warn("VirusFoundException in updateCitationList() " + e);
}
if(message != null && ! message.trim().equals("")) {
results.put("message", message);
}
}
return results;
}
/**
* Check whether we are editing an existing resource or working on a new citation list.
* If it exists, we'll update any attributes that have changed. If it's new, we will
* create it and return the resourceUuid, along with other attributes, in a map.
* @param params
* @param state
* @param req
* @param res
* @return
*/
protected Map<String,Object> ensureCitationListExists(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> results = new HashMap<String,Object>();
String message = null;
String displayName = params.getString("displayName");
if(displayName == null) {
// error ??
}
CitationCollection cCollection = this.getCitationCollection(state, true);
if(cCollection == null) {
// error
} else {
String citationCollectionId = cCollection.getId();
String collectionId = params.getString("collectionId");
if(collectionId == null || collectionId.trim().equals("")) {
ToolSession toolSession = getSessionManager().getCurrentToolSession();
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
collectionId = pipe.getContentEntity().getId();
}
ContentResource resource = null;
String resourceUuid = params.getString("resourceUuid");
String resourceId = null;
if(resourceUuid == null || resourceUuid.trim().equals("")) {
// create resource
if(collectionId == null) {
// error?
message = rb.getString("resource.null_collectionId.error");
} else {
int priority = 0;
// create resource
try {
ContentResourceEdit edit = getContentService().addResource(collectionId, displayName, null, ContentHostingService.MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);
edit.setResourceType(CitationService.CITATION_LIST_ID);
byte[] bytes = citationCollectionId.getBytes();
edit.setContent(bytes );
captureDescription(params, state, edit, results);
captureAccess(params, state, edit, results);
captureAvailability(params, edit, results);
ResourceProperties properties = edit.getPropertiesEdit();
properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, displayName);
properties.addProperty(ContentHostingService.PROP_ALTERNATE_REFERENCE, CitationService.REFERENCE_ROOT);
properties.addProperty(ResourceProperties.PROP_CONTENT_TYPE, ResourceType.MIME_TYPE_HTML);
getContentService().commitResource(edit, priority);
resourceId = edit.getId();
message = rb.getFormattedMessage("resource.new.success", new String[]{ displayName });
} catch (IdUniquenessException e) {
message = e.getMessage();
logger.warn("IdUniquenessException in ensureCitationListExists() " + e);
} catch (IdLengthException e) {
message = e.getMessage();
logger.warn("IdLengthException in ensureCitationListExists() " + e);
} catch (IdInvalidException e) {
message = e.getMessage();
logger.warn("IdInvalidException in ensureCitationListExists() " + e);
} catch (OverQuotaException e) {
message = e.getMessage();
logger.warn("OverQuotaException in ensureCitationListExists() " + e);
} catch (ServerOverloadException e) {
message = e.getMessage();
logger.warn("ServerOverloadException in ensureCitationListExists() " + e);
} catch (PermissionException e) {
message = e.getMessage();
logger.warn("PermissionException in ensureCitationListExists() " + e);
} catch (IdUnusedException e) {
message = e.getMessage();
logger.warn("IdUnusedException in ensureCitationListExists() " + e);
}
}
} else {
// get resource
resourceId = this.getContentService().resolveUuid(resourceUuid);
if(citationCollectionId == null) {
try {
resource = this.contentService.getResource(resourceId);
citationCollectionId = new String(resource.getContent());
} catch (IdUnusedException e) {
message = e.getMessage();
logger.warn("IdUnusedException in getting resource in ensureCitationListExists() " + e);
} catch (TypeException e) {
message = e.getMessage();
logger.warn("TypeException in getting resource in ensureCitationListExists() " + e);
} catch (PermissionException e) {
message = e.getMessage();
logger.warn("PermissionException in getting resource in ensureCitationListExists() " + e);
} catch (ServerOverloadException e) {
message = e.getMessage();
logger.warn("ServerOverloadException in getting citationCollectionId in ensureCitationListExists() " + e);
}
}
// possibly revise displayName, other properties
// commit changes
// report success/failure
}
results.put("citationCollectionId", citationCollectionId);
//results.put("resourceId", resourceId);
resourceUuid = this.getContentService().getUuid(resourceId);
logger.info("ensureCitationListExists() created new resource with resourceUuid == " + resourceUuid + " and resourceId == " + resourceId);
results.put("resourceUuid", resourceUuid );
String clientId = params.getString("saveciteClientId");
if(clientId != null && ! clientId.trim().equals("")) {
Locale locale = rb.getLocale();
List<Map<String,String>> saveciteClients = getConfigurationService().getSaveciteClientsForLocale(locale);
if(saveciteClients != null) {
for(Map<String,String> client : saveciteClients) {
if(client != null && client.get("id") != null && client.get("id").equalsIgnoreCase(clientId)) {
String saveciteUrl = getSearchManager().getSaveciteUrl(resourceUuid,clientId);
try {
saveciteUrl = java.net.URLEncoder.encode(saveciteUrl,"UTF-8");
} catch (UnsupportedEncodingException e) {
logger.warn("Error encoding savecite URL",e);
}
// ${client.searchurl_base}?linkurl_base=${client.saveciteUrl}#if(${client.linkurl_id})&linkurl_id=${client.linkurl_id}
StringBuilder buf = new StringBuilder();
buf.append(client.get("searchurl_base"));
buf.append("?linkurl_base=");
buf.append(saveciteUrl);
if(client.get("linkurl_id") != null && ! client.get("linkurl_id").trim().equals("")) {
buf.append("&linkurl_id=");
buf.append(client.get("linkurl_id"));
}
buf.append('&');
results.put("saveciteUrl", buf.toString());
break;
}
}
}
}
results.put("collectionId", collectionId);
}
results.put("message", message);
return results;
}
private void captureDescription(ParameterParser params, SessionState state,
ContentResourceEdit edit, Map<String, Object> results) {
String description = params.get("description");
String oldDescription = edit.getProperties().getProperty(ResourceProperties.PROP_DESCRIPTION);
if(description == null || description.trim().equals("")) {
if(oldDescription != null) {
edit.getPropertiesEdit().removeProperty(ResourceProperties.PROP_DESCRIPTION);
results.put("description", "");
}
} else {
if(oldDescription == null || ! oldDescription.equals(description)) {
edit.getPropertiesEdit().removeProperty(ResourceProperties.PROP_DESCRIPTION);
edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DESCRIPTION, description);
results.put("description", description);
}
}
}
protected void captureDisplayName(ParameterParser params, SessionState state,
ContentResourceEdit edit, Map<String, Object> results) {
String displayName = params.getString("displayName");
if(displayName == null || displayName.trim().equals("")) {
throw new RuntimeException("invalid name for resource: " + displayName);
}
String oldDisplayName = edit.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
if(oldDisplayName == null || ! oldDisplayName.equals(displayName)) {
ResourcePropertiesEdit props = edit.getPropertiesEdit();
props.removeProperty(ResourceProperties.PROP_DISPLAY_NAME);
props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, displayName);
results.put("displayName", displayName);
}
}
/**
* @param params
* @param edit
* @param results TODO
*/
protected void captureAvailability(ParameterParser params,
ContentResourceEdit edit, Map<String, Object> results) {
boolean hidden = params.getBoolean("hidden");
boolean useReleaseDate = params.getBoolean("use_start_date");
DateFormat df = DateFormat.getDateTimeInstance();
Time releaseDate = null;
if(useReleaseDate) {
String releaseDateStr = params.getString(PROP_RELEASE_DATE);
if(releaseDateStr != null) {
try {
releaseDate = TimeService.newTime(df.parse(releaseDateStr).getTime());
} catch (ParseException e) {
logger.warn("ParseException in captureAvailability() " + e);
}
}
}
Time retractDate = null;
boolean useRetractDate = params.getBoolean("use_end_date");
if(useRetractDate) {
String retractDateStr = params.getString(PROP_RETRACT_DATE);
if(retractDateStr != null) {
try {
retractDate = TimeService.newTime(df.parse(retractDateStr).getTime());
} catch (ParseException e) {
logger.warn("ParseException in captureAvailability() " + e);
}
}
}
boolean oldHidden = edit.isHidden();
Time oldReleaseDate = edit.getReleaseDate();
Time oldRetractDate = edit.getRetractDate();
boolean changesFound = false;
if(oldHidden != hidden) {
results.put(PROP_IS_HIDDEN, Boolean.toString(hidden));
changesFound = true;
}
if(oldReleaseDate == null && releaseDate == null) {
// no change here
} else if((oldReleaseDate == null) || ! oldReleaseDate.equals(releaseDate)) {
if(releaseDate == null) {
results.put(PROP_RELEASE_DATE_STR, df.format(new Date()));
} else {
results.put(PROP_RELEASE_DATE_STR, df.format(new Date(releaseDate.getTime())));
}
results.put(PROP_RELEASE_DATE, releaseDate);
results.put(PROP_USE_RELEASE_DATE, useReleaseDate);
changesFound = true;
}
if(oldRetractDate == null && retractDate == null) {
// no change here
} else if (oldRetractDate == null || ! oldRetractDate.equals(retractDate)) {
if(retractDate == null) {
results.put(PROP_RETRACT_DATE_STR, df.format(new Date(System.currentTimeMillis() + ONE_WEEK)));
} else {
results.put(PROP_RETRACT_DATE_STR, df.format(new Date(retractDate.getTime() )));
}
results.put(PROP_RETRACT_DATE, retractDate);
changesFound = true;
}
if(changesFound) {
edit.setAvailability(hidden, releaseDate, retractDate);
}
}
protected void captureAccess(ParameterParser params, SessionState state,
ContentResourceEdit edit, Map<String, Object> results) {
Map<String,Object> entityProperties = (Map<String, Object>) state.getAttribute(STATE_RESOURCE_ENTITY_PROPERTIES);
boolean changesFound = false;
String access_mode = params.getString("access_mode");
if(access_mode == null) {
access_mode = AccessMode.INHERITED.toString();
}
String oldAccessMode = entityProperties.get(PROP_ACCESS_MODE).toString();
if(oldAccessMode == null) {
oldAccessMode = AccessMode.INHERITED.toString();
}
if(! access_mode.equals(oldAccessMode)) {
results.put(PROP_ACCESS_MODE, AccessMode.fromString(access_mode));
changesFound = true;
}
if(AccessMode.GROUPED.toString().equals(access_mode)) {
// we inherit more than one group and must check whether group access changes at this item
String[] access_groups = params.getStrings("access_groups");
SortedSet<String> new_groups = new TreeSet<String>();
if(access_groups != null) {
new_groups.addAll(Arrays.asList(access_groups));
}
List<Map<String,String>> possibleGroups = (List<Map<String, String>>) entityProperties.get(PROP_POSSIBLE_GROUPS);
if(possibleGroups == null) {
possibleGroups = new ArrayList<Map<String,String>>();
}
Map<String, String> possibleGroupMap = mapGroupRefs(possibleGroups);
SortedSet<String> new_group_refs = convertToRefs(new_groups, possibleGroupMap );
boolean groups_are_inherited = (new_groups.size() == possibleGroupMap.size()) && possibleGroupMap.keySet().containsAll(new_groups);
try {
if(groups_are_inherited) {
edit.clearGroupAccess();
edit.setGroupAccess(new_group_refs);
} else {
edit.setGroupAccess(new_group_refs);
}
edit.clearPublicAccess();
} catch (InconsistentException e) {
logger.warn("InconsistentException in captureAccess() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException in captureAccess() " + e);
}
} else if("public".equals(access_mode)) {
Boolean isPubviewInherited = (Boolean) entityProperties.get(PROP_IS_PUBVIEW_INHERITED);
if(isPubviewInherited == null || ! isPubviewInherited) {
try {
edit.setPublicAccess();
} catch (InconsistentException e) {
logger.warn("InconsistentException in captureAccess() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException in captureAccess() " + e);
}
}
} else if(AccessMode.INHERITED.toString().equals(access_mode)) {
try {
if(edit.getAccess() == AccessMode.GROUPED) {
edit.clearGroupAccess();
}
edit.clearPublicAccess();
} catch (InconsistentException e) {
logger.warn("InconsistentException in captureAccess() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException in captureAccess() " + e);
}
}
// isPubview
results.put(PROP_IS_PUBVIEW, getContentService().isPubView(edit.getId()));
// isPubviewInherited
results.put(PROP_IS_PUBVIEW_INHERITED, new Boolean(getContentService().isInheritingPubView(edit.getId())));
// isPubviewPossible
Boolean preventPublicDisplay = (Boolean) state.getAttribute("resources.request.prevent_public_display");
if(preventPublicDisplay == null) {
preventPublicDisplay = Boolean.FALSE;
}
results.put(PROP_IS_PUBVIEW_POSSIBLE, new Boolean(! preventPublicDisplay.booleanValue()));
// accessMode
results.put(PROP_ACCESS_MODE, edit.getAccess());
// isGroupInherited
results.put(PROP_IS_GROUP_INHERITED, AccessMode.GROUPED == edit.getInheritedAccess());
// possibleGroups
Collection<Group> inheritedGroupObjs = edit.getInheritedGroupObjects();
Map<String,Map<String,String>> groups = new HashMap<String,Map<String,String>>();
if(inheritedGroupObjs != null) {
for(Group group : inheritedGroupObjs) {
Map<String, String> grp = new HashMap<String, String>();
grp.put("groupId", group.getId());
grp.put("title", group.getTitle());
grp.put("description", group.getDescription());
grp.put("entityRef", group.getReference());
groups.put(grp.get("groupId"), grp);
}
}
results.put(PROP_POSSIBLE_GROUPS, groups);
// isGroupPossible
results.put(PROP_IS_GROUP_POSSIBLE, new Boolean(groups != null && groups.size() > 0));
// isSingleGroupInherited
results.put(PROP_IS_SINGLE_GROUP_INHERITED, new Boolean(groups != null && groups.size() == 1));
// isSiteOnly = ! isPubviewPossible && ! isGroupPossible
results.put(PROP_IS_SITE_ONLY, new Boolean(preventPublicDisplay.booleanValue() && (groups == null || groups.size() < 1)));
// isUserSite
SiteService siteService = (SiteService) ComponentManager.get(SiteService.class);
Reference ref = getEntityManager().newReference(edit.getReference());
results.put(PROP_IS_USER_SITE, siteService.isUserSite(ref.getContext()));
}
private Map<String, String> mapGroupRefs(
List<Map<String, String>> possibleGroups) {
Map<String, String> groupRefMap = new HashMap<String, String>();
for(Map<String, String> groupInfo : possibleGroups) {
if(groupInfo.get("groupId") != null && groupInfo.get("entityRef") != null) {
groupRefMap.put(groupInfo.get("groupId"), groupInfo.get("entityRef"));
}
}
return groupRefMap ;
}
public SortedSet<String> convertToRefs(Collection<String> groupIds, Map<String, String> possibleGroupMap)
{
SortedSet<String> groupRefs = new TreeSet<String>();
for(String groupId : groupIds)
{
String groupRef = possibleGroupMap.get(groupId);
if(groupRef != null)
{
groupRefs.add(groupRef);
}
}
return groupRefs;
}
protected void preserveEntityIds(ParameterParser params, SessionState state) {
String resourceId = params.getString("resourceId");
String resourceUuid = params.getString("resourceUuid");
String citationCollectionId = params.getString("citationCollectionId");
if(resourceId == null || resourceId.trim().equals("")) {
// do nothing
} else {
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
}
if(resourceUuid == null || resourceUuid.trim().equals("")) {
// do nothing
} else {
state.setAttribute(CitationHelper.RESOURCE_UUID, resourceUuid);
}
if(citationCollectionId == null || citationCollectionId.trim().equals("")) {
// do nothing
} else {
state.setAttribute(CitationHelper.CITATION_COLLECTION_ID, citationCollectionId);
}
}
protected void putCitationCollectionDetails( Context context, SessionState state )
{
// get the citation list title
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
String refStr = getContentService().getReference(resourceId);
Reference ref = getEntityManager().newReference(refStr);
String collectionTitle = null;
if( ref != null )
{
collectionTitle = ref.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
if(collectionTitle == null) {
collectionTitle = (String)state.getAttribute( STATE_COLLECTION_TITLE );
}
if( collectionTitle != null && !collectionTitle.trim().equals("") )
{
context.put( "collectionTitle", getFormattedText().escapeHtml(collectionTitle));
}
// get the collection we're now working on
String collectionId = (String)state.getAttribute(STATE_CITATION_COLLECTION_ID);
context.put( "collectionId", collectionId );
CitationCollection collection = getCitationCollection(state, false);
int collectionSize = 0;
if (collection == null)
{
logger.warn( "buildAddCitationsPanelContext unable to access citationCollection " + collectionId );
return;
}
else
{
// get the size of the list
collectionSize = collection.size();
}
context.put( "collectionSize", new Integer( collectionSize ) );
}
public String buildImportCitationsPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
context.put("state", state);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
context.put("FORM_NAME", "importForm");
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_IMPORT_CITATIONS;
} // buildImportPanelContext
/**
*
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildAddCitationsPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
context.put("state", state);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// body onload handler
context.put("sakai_onload", "setMainFrameHeight( window.name )");
// get the citation list title
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
String refStr = getContentService().getReference(resourceId);
Reference ref = getEntityManager().newReference(refStr);
String collectionTitle = null;
if( ref != null )
{
collectionTitle = ref.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
if(collectionTitle == null) {
collectionTitle = (String)state.getAttribute( STATE_COLLECTION_TITLE );
}
if( collectionTitle != null && !collectionTitle.trim().equals("") )
{
context.put( "collectionTitle", getFormattedText().escapeHtml(collectionTitle));
}
// get the collection we're now working on
String collectionId = (String)state.getAttribute(STATE_CITATION_COLLECTION_ID);
context.put( "collectionId", collectionId );
CitationCollection citationCollection = getCitationCollection(state, false);
int collectionSize = 0;
if(citationCollection == null)
{
logger.warn( "buildAddCitationsPanelContext unable to access citationCollection " + collectionId );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_ERROR;
}
else
{
// get the size of the list
collectionSize = citationCollection.size();
}
context.put( "collectionSize", new Integer( collectionSize ) );
Locale locale = rb.getLocale();
List<Map<String,String>> saveciteClients = getConfigurationService().getSaveciteClientsForLocale(locale);
if(saveciteClients != null) {
for(Map<String,String> client : saveciteClients) {
String saveciteUrl = getSearchManager().getSaveciteUrl(getContentService().getUuid(resourceId),client.get("id"));
try {
client.put("saveciteUrl", java.net.URLEncoder.encode(saveciteUrl,"UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.warn("Error encoding savecite URL",e);
}
}
context.put("saveciteClients",saveciteClients);
}
// determine which features to display
if( getConfigurationService().isGoogleScholarEnabled() )
{
String googleUrl = getSearchManager().getGoogleScholarUrl(getContentService().getUuid(resourceId));
context.put( "googleUrl", googleUrl );
// object array for formatted messages
Object[] googleArgs = { rb.getString( "linkLabel.google" ) };
context.put( "googleArgs", googleArgs );
}
if( getConfigurationService().librarySearchEnabled() )
{
context.put( "searchLibrary", Boolean.TRUE );
}
// form name
context.put(PARAM_FORM_NAME, ELEMENT_ID_CREATE_FORM);
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_ADD_CITATIONS;
} // buildAddCitationsPanelContext
/**
* build the context.
*
* @return The name of the template to use.
*/
public String buildCreatePanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
context.put("state", state);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
//context.put("sakai_onload", "setPopupHeight('create');checkinWithOpener('create');");
//context.put("sakai_onunload", "window.opener.parent.popups['create']=null;");
//context.put("mainFrameId", CitationHelper.CITATION_FRAME_ID);
//context.put("citationToolId", CitationHelper.CITATION_ID);
//context.put("specialHelperFlag", CitationHelper.SPECIAL_HELPER_ID);
context.put(PARAM_FORM_NAME, ELEMENT_ID_CREATE_FORM);
List schemas = getCitationService().getSchemas();
context.put("TEMPLATES", schemas);
Schema defaultSchema = getCitationService().getDefaultSchema();
context.put("DEFAULT_TEMPLATE", defaultSchema);
// Object array for instruction message
Object[] instrArgs = { rb.getString( "submit.create" ) };
context.put( "instrArgs", instrArgs );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_CREATE;
} // buildCreatePanelContext
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildDatabasePanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// get hierarchy
SearchDatabaseHierarchy hierarchy = ( SearchDatabaseHierarchy )
state.getAttribute(STATE_SEARCH_HIERARCHY);
// get selected category
SearchCategory category = ( SearchCategory ) state.getAttribute(
STATE_SELECTED_CATEGORY );
if( category == null )
{
// bad...
logger.warn( "buildDatabasePanelContext getting null selected " +
"category from state." );
}
// put selected category into context
context.put( "category", category );
// maxDbNum
Integer maxDbNum = new Integer(hierarchy.getNumMaxSearchableDb());
context.put( "maxDbNum", maxDbNum );
// object array for formatted messages
Object[] maxDbArgs = { maxDbNum };
context.put( "maxDbArgs", maxDbArgs );
// validator
context.put("xilator", new Validator());
// change mode back to SEARCH (DATABASE not needed anymore)
setMode( state, Mode.SEARCH );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_DATABASE;
} // buildDatabasePanelContext
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildEditPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
context.put("sakai_onload", "setMainFrameHeight( window.name ); heavyResize();");
//context.put("sakai_onunload", "window.opener.parent.popups['edit']=null;");
//context.put("mainFrameId", CitationHelper.CITATION_FRAME_ID);
//context.put("citationToolId", CitationHelper.CITATION_ID);
//context.put("specialHelperFlag", CitationHelper.SPECIAL_HELPER_ID);
context.put(PARAM_FORM_NAME, ELEMENT_ID_CREATE_FORM);
Citation citation = (Citation) state.getAttribute(CitationHelper.CITATION_EDIT_ITEM);
if(citation == null)
{
doEdit(rundata);
citation = (Citation) state.getAttribute(CitationHelper.CITATION_EDIT_ITEM);
}
context.put("citation", citation);
String citationId = (String) state.getAttribute(CitationHelper.CITATION_EDIT_ID);
String collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
context.put("citationId", citationId);
context.put("collectionId", collectionId);
List schemas = getCitationService().getSchemas();
context.put("TEMPLATES", schemas);
context.put("DEFAULT_TEMPLATE", citation.getSchema());
// Object array for formatted instruction
Object[] instrArgs = { rb.getString( "submit.edit" ) };
context.put( "instrArgs", instrArgs );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_EDIT;
}
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
private String buildErrorPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
//context.put("sakai_onload", "setPopupHeight('error');");
//context.put("sakai_onunload", "window.opener.parent.popups['error']=null;");
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_ERROR;
}
private String buildErrorFatalPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
//context.put("sakai_onload", "setPopupHeight('error');");
//context.put("sakai_onunload", "window.opener.parent.popups['error']=null;");
return TEMPLATE_ERROR_FATAL;
}
/**
* build the context.
*
* @return The name of the template to use.
*/
public String buildListPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
// state.setAttribute("fromListPage", true);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
if( state.removeAttribute( STATE_LIST_NO_SCROLL ) == null )
{
context.put("sakai_onload", "setMainFrameHeight( window.name )");
}
else
{
context.put("sakai_onload", "resizeFrame()");
}
//context.put("mainFrameId", CitationHelper.CITATION_FRAME_ID);
//context.put("citationToolId", CitationHelper.CITATION_ID);
//context.put("specialHelperFlag", CitationHelper.SPECIAL_HELPER_ID);
// get the citation list title
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
try {
ContentResource resource = this.getContentService().getResource(resourceId);
String description = resource.getProperties().getProperty(ResourceProperties.PROP_DESCRIPTION);
context.put("description", description);
} catch (Exception e) {
// TODO: Fix this. What exception is this dealing with?
logger.warn(e.getMessage(), e);
}
String refStr = getContentService().getReference(resourceId);
Reference ref = getEntityManager().newReference(refStr);
String collectionTitle = null;
if( ref != null )
{
collectionTitle = ref.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
if(collectionTitle == null) {
collectionTitle = (String)state.getAttribute( STATE_COLLECTION_TITLE );
}
if( collectionTitle != null && !collectionTitle.trim().equals("") )
{
context.put( "collectionTitle", getFormattedText().escapeHtml(collectionTitle));
}
context.put("openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel());
context.put(PARAM_FORM_NAME, ELEMENT_ID_LIST_FORM);
CitationCollection collection = getCitationCollection(state, true);
// collection size
context.put( "collectionSize", new Integer( collection.size() ) );
// export URLs
String exportUrlSel = collection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_SEL);
String exportUrlAll = collection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_ALL);
context.put("exportUrlSel", exportUrlSel);
context.put("exportUrlAll", exportUrlAll);
Integer listPageSize = (Integer) state.getAttribute(STATE_LIST_PAGE_SIZE);
if(listPageSize == null)
{
listPageSize = defaultListPageSize;
state.setAttribute(STATE_LIST_PAGE_SIZE, listPageSize);
}
context.put("listPageSize", listPageSize);
CitationIterator newIterator = collection.iterator();
CitationIterator oldIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(oldIterator != null)
{
newIterator.setPageSize(listPageSize.intValue());
newIterator.setStart(oldIterator.getStart());
// newIterator.setPage(oldIterator.getPage());
}
context.put("citations", newIterator);
context.put("collectionId", collection.getId());
if(! collection.isEmpty())
{
context.put("show_citations", Boolean.TRUE);
// int page = newIterator.getPage();
// int pageSize = newIterator.getPageSize();
int totalSize = collection.size();
int start = newIterator.getStart();
int end = newIterator.getEnd();
// int start = page * pageSize + 1;
// int end = Math.min((page + 1) * pageSize, totalSize);
Integer[] position = { new Integer(start+1) , new Integer(end), new Integer(totalSize)};
String showing = (String) rb.getFormattedMessage("showing.results", position);
context.put("showing", showing);
}
state.setAttribute(STATE_LIST_ITERATOR, newIterator);
// back to search results button control
context.put("searchResults", state.getAttribute(STATE_SEARCH_RESULTS) );
// constant schema identifier
context.put( "titleProperty", Schema.TITLE );
/*
* Object arrays for formatted messages
*/
Object[] instrMainArgs = { getConfigurationService().getSiteConfigOpenUrlLabel() };
context.put( "instrMainArgs", instrMainArgs );
Object[] instrSubArgs = { rb.getString( "label.finish" ) };
context.put( "instrSubArgs", instrSubArgs );
Object[] emptyListArgs = { rb.getString( "label.menu" ) };
context.put( "emptyListArgs", emptyListArgs );
String sort = (String) state.getAttribute(STATE_SORT);
if (sort == null || sort.trim().length() == 0)
sort = collection.getSort();
context.put("sort", sort);
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_LIST;
} // buildListPanelContext
public String buildReorderPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state) {
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
if( state.removeAttribute( STATE_LIST_NO_SCROLL ) == null ) {
context.put("sakai_onload", "setMainFrameHeight( window.name )");
}
else {
context.put("sakai_onload", "resizeFrame()");
}
// get the citation list title
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
String refStr = getContentService().getReference(resourceId);
Reference ref = getEntityManager().newReference(refStr);
String collectionTitle = null;
if( ref != null ) {
collectionTitle = ref.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
if(collectionTitle == null) {
collectionTitle = (String)state.getAttribute( STATE_COLLECTION_TITLE );
}
else if( !collectionTitle.trim().equals("") ) {
context.put( "collectionTitle", Validator.escapeHtml(collectionTitle));
}
CitationCollection collection = getCitationCollection(state, true);
collection.setSort(CitationCollection.SORT_BY_POSITION,true);
CitationIterator newIterator = collection.iterator();
context.put("citations", newIterator);
context.put("collectionId", collection.getId());
state.setAttribute(STATE_LIST_ITERATOR, newIterator);
return TEMPLATE_REORDER;
}
/**
* This method retrieves the CitationCollection for the current session.
* If the CitationCollection is already in session-state and has not been
* updated in the persistent storage since it was last accessed, the copy
* in session-state will be returned. If it has been updated in storage,
* the copy in session-state will be updated and returned. If the
* CitationCollection has not yet been created in storage and the second
* parameter is true, this method will create the collection and return it.
* In that case, values will be added to session-state for attributes named
* STATE_COLLECTION_ID and STATE_COLLECTION. If the CitationCollection has
* not yet been created in storage and the second parameter is false, the
* method will return null.
* @param state The SessionState object for the current session.
* @param create A flag indicating whether the collection should be created
* if it does not already exist.
* @return The CitationCollection for the current session, or null.
*/
protected CitationCollection getCitationCollection(SessionState state, boolean create)
{
CitationCollection citationCollection = (CitationCollection) state.getAttribute(STATE_CITATION_COLLECTION);
if(citationCollection == null)
{
String citationCollectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
if(citationCollectionId == null && create)
{
citationCollection = getCitationService().addCollection();
getCitationService().save(citationCollection);
}
else
{
try
{
citationCollection = getCitationService().getCollection(citationCollectionId);
}
catch (IdUnusedException e)
{
logger.warn("IdUnusedException: CitationHelperAction.getCitationCollection() unable to access citationCollection " + citationCollectionId);
}
if(citationCollection == null && create)
{
citationCollection = getCitationService().addCollection();
getCitationService().save(citationCollection);
}
}
if(citationCollection != null) {
state.setAttribute(STATE_CITATION_COLLECTION, citationCollection);
state.setAttribute(STATE_CITATION_COLLECTION_ID, citationCollection.getId());
}
}
return citationCollection;
}
/**
* build the context.
*
* @return The name of the template to use.
*/
public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
logger.debug("buildMainPanelContext()");
// always put appropriate bundle in velocity context
context.put("tlang", rb);
//context.put("mainFrameId", CitationHelper.CITATION_FRAME_ID);
//context.put("citationToolId", CitationHelper.CITATION_ID);
//context.put("specialHelperFlag", CitationHelper.SPECIAL_HELPER_ID);
// always put whether this is a Resources Add or Revise operation
if( state.getAttribute( STATE_RESOURCES_ADD ) != null )
{
context.put( "resourcesAddAction", Boolean.TRUE );
}
// make sure observers are disabled
VelocityPortletPaneledAction.disableObservers(state);
String template = "";
Mode mode = (Mode) state.getAttribute(CitationHelper.STATE_HELPER_MODE);
if(mode == null)
{
// mode really shouldn't be null here
logger.warn( "buildMainPanelContext() getting null Mode from state" );
mode = Mode.NEW_RESOURCE;
//mode = Mode.ADD_CITATIONS;
setMode(state, mode);
}
// add mode to the template
context.put( "citationsHelperMode", mode );
switch(mode)
{
case NEW_RESOURCE:
template = buildNewResourcePanelContext(portlet, context, rundata, state);
break;
case IMPORT_CITATIONS:
template = buildImportCitationsPanelContext(portlet, context, rundata, state);
break;
case ADD_CITATIONS:
template = buildAddCitationsPanelContext(portlet, context, rundata, state);
break;
case CREATE:
template = buildCreatePanelContext(portlet, context, rundata, state);
break;
case DATABASE:
template = buildDatabasePanelContext(portlet, context, rundata, state);
break;
case EDIT:
template = buildEditPanelContext(portlet, context, rundata, state);
break;
case ERROR:
template = buildErrorPanelContext(portlet, context, rundata, state);
break;
case ERROR_FATAL:
template = buildErrorFatalPanelContext(portlet, context, rundata, state);
break;
case LIST:
template = buildListPanelContext(portlet, context, rundata, state);
break;
case REORDER:
template = buildReorderPanelContext(portlet, context, rundata, state);
break;
case MESSAGE:
template = buildMessagePanelContext(portlet, context, rundata, state);
break;
case SEARCH:
template = buildSearchPanelContext(portlet, context, rundata, state);
break;
case RESULTS:
template = buildResultsPanelContext(portlet, context, rundata, state);
break;
case VIEW:
template = buildViewPanelContext(portlet, context, rundata, state);
break;
}
return template;
} // buildMainPanelContext
public String buildNewResourcePanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state) {
logger.debug("buildNewResourcePanelContext()");
context.put("MIMETYPE_JSON", MIMETYPE_JSON);
context.put("REQUESTED_MIMETYPE", REQUESTED_MIMETYPE);
context.put("xilator", new Validator());
context.put("availability_is_enabled", Boolean.TRUE);
context.put("GROUP_ACCESS", AccessMode.GROUPED);
context.put("INHERITED_ACCESS", AccessMode.INHERITED);
Boolean resourceAdd = (Boolean) state.getAttribute(STATE_RESOURCES_ADD);
if(resourceAdd != null && resourceAdd.equals(true)) {
context.put("resourceAdd", Boolean.TRUE);
context.put(CITATION_ACTION, CREATE_RESOURCE);
} else {
context.put(CITATION_ACTION, UPDATE_RESOURCE);
}
// resource-related
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
String resourceUuid = (String) state.getAttribute(CitationHelper.RESOURCE_UUID);
if(resourceId == null || resourceId.trim().equals("")) {
if(resourceUuid == null || resourceUuid.trim().equals("")) {
// Will be dealt with later by creating new resource when needed
} else if(resourceUuid.startsWith("/")) {
// UUID and ID may be switched
resourceId = resourceUuid;
resourceUuid = this.getContentService().getUuid(resourceId);
if(resourceUuid != null) {
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
state.setAttribute(CitationHelper.RESOURCE_UUID, resourceUuid);
}
} else {
// see if we can get the resourceId from the UUID
resourceId = this.getContentService().resolveUuid(resourceUuid);
if(resourceId != null) {
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
}
}
} else if(resourceUuid == null || resourceUuid.trim().equals("")) {
resourceUuid = this.getContentService().getUuid(resourceId);
if(resourceUuid != null) {
state.setAttribute(CitationHelper.RESOURCE_UUID, resourceUuid);
}
}
if(logger.isInfoEnabled()) {
logger.info("buildNewResourcePanelContext() resourceUuid == " + resourceUuid + " resourceId == " + resourceId);
}
String citationCollectionId = null;
ContentResource resource = null;
Map<String,Object> contentProperties = null;
if(resourceId == null) {
} else {
try {
resource = getContentService().getResource(resourceId);
} catch (IdUnusedException e) {
logger.warn("IdUnusedException geting resource in buildNewResourcePanelContext() " + e);
} catch (TypeException e) {
logger.warn("TypeException geting resource in buildNewResourcePanelContext() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException geting resource in buildNewResourcePanelContext() " + e);
}
// String guid = getContentService().getUuid(resourceId);
// context.put("RESOURCE_ID", guid);
}
if(resource == null) {
context.put(CITATION_ACTION, CREATE_RESOURCE);
ToolSession toolSession = getSessionManager().getCurrentToolSession();
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
String collectionId = pipe.getContentEntity().getId();
context.put("collectionId", collectionId);
ContentCollection collection;
try {
collection = getContentService().getCollection(collectionId);
contentProperties = this.getProperties(collection, state);
} catch (IdUnusedException e) {
logger.warn("IdUnusedException geting collection in buildNewResourcePanelContext() " + e);
} catch (TypeException e) {
logger.warn("TypeException geting collection in buildNewResourcePanelContext() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException geting collection in buildNewResourcePanelContext() " + e);
}
} else {
ResourceProperties props = resource.getProperties();
contentProperties = this.getProperties(resource, state);
context.put("resourceTitle", props.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
context.put("resourceDescription", props.getProperty(ResourceProperties.PROP_DESCRIPTION));
//resourceUuid = this.getContentService().getUuid(resourceId);
context.put("resourceUuid", resourceUuid );
context.put("collectionId", resource.getContainingCollection().getId());
try {
citationCollectionId = new String(resource.getContent());
} catch (ServerOverloadException e) {
logger.warn("ServerOverloadException geting props in buildNewResourcePanelContext() " + e);
}
context.put(CITATION_ACTION, UPDATE_RESOURCE);
}
if(contentProperties == null) {
contentProperties = new HashMap<String,Object>();
}
context.put("contentProperties", contentProperties);
int collectionSize = 0;
CitationCollection citationCollection = null;
if(citationCollectionId == null) {
citationCollectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
//String citationCollectionId = (String) state.getAttribute(CitationHelper.CITATION_COLLECTION_ID);
}
if(citationCollectionId == null) {
} else {
citationCollection = getCitationCollection(state, true);
if(citationCollection == null) {
logger.warn( "buildAddCitationsPanelContext unable to access citationCollection " + citationCollectionId );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_ERROR;
} else {
// get the size of the list
collectionSize = citationCollection.size();
}
context.put("collectionId", citationCollectionId);
}
context.put( "collectionSize", new Integer( collectionSize ) );
Locale locale = rb.getLocale();
List<Map<String,String>> saveciteClients = getConfigurationService().getSaveciteClientsForLocale(locale);
if(saveciteClients != null) {
if(resource != null && resourceId != null) {
for(Map<String,String> client : saveciteClients) {
String saveciteUrl = getSearchManager().getSaveciteUrl(resourceUuid,client.get("id"));
try {
client.put("saveciteUrl", java.net.URLEncoder.encode(saveciteUrl,"UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.warn("Error encoding savecite URL",e);
}
}
}
context.put("saveciteClients",saveciteClients);
}
// determine which features to display
if( getConfigurationService().isGoogleScholarEnabled() ) {
String googleUrl = getSearchManager().getGoogleScholarUrl(getContentService().getUuid(resourceId));
context.put( "googleUrl", googleUrl );
// object array for formatted messages
Object[] googleArgs = { rb.getString( "linkLabel.google" ) };
context.put( "googleArgs", googleArgs );
}
if( getConfigurationService().librarySearchEnabled() ) {
context.put( "searchLibrary", Boolean.TRUE );
}
if(citationCollection == null || citationCollection.size() <= 0) {
} else {
context.put("openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel());
String currentSort = (String) state.getAttribute(STATE_SORT);
if (currentSort == null || currentSort.trim().length() == 0)
currentSort = citationCollection.getSort();
if(currentSort == null || currentSort.trim().length() == 0) {
currentSort = CitationCollection.SORT_BY_TITLE;
}
context.put("currentSort", currentSort);
String savedSort = citationCollection.getSort();
if(savedSort == null || savedSort.trim().equals("")) {
savedSort = CitationCollection.SORT_BY_TITLE;
}
if(savedSort != currentSort) {
citationCollection.setSort(currentSort, true);
}
//context.put(PARAM_FORM_NAME, ELEMENT_ID_LIST_FORM);
// collection size
context.put( "collectionSize", new Integer( citationCollection.size() ) );
// export URLs
String exportUrlSel = citationCollection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_SEL);
String exportUrlAll = citationCollection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_ALL);
context.put("exportUrlSel", exportUrlSel);
context.put("exportUrlAll", exportUrlAll);
Integer listPageSize = (Integer) state.getAttribute(STATE_LIST_PAGE_SIZE);
if(listPageSize == null)
{
listPageSize = defaultListPageSize;
state.setAttribute(STATE_LIST_PAGE_SIZE, listPageSize);
}
context.put("listPageSize", listPageSize);
CitationIterator newIterator = citationCollection.iterator();
CitationIterator oldIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(oldIterator == null) {
newIterator.setPageSize(listPageSize.intValue());
newIterator.setStart(0);
} else {
newIterator.setPageSize(listPageSize.intValue());
newIterator.setStart(oldIterator.getStart());
// newIterator.setPage(oldIterator.getPage());
}
context.put("citations", newIterator);
context.put("citationCollectionId", citationCollection.getId());
if(! citationCollection.isEmpty())
{
context.put("show_citations", Boolean.TRUE);
// int page = newIterator.getPage();
// int pageSize = newIterator.getPageSize();
int totalSize = citationCollection.size();
int start = newIterator.getStart();
int end = newIterator.getEnd();
// int start = page * pageSize + 1;
// int end = Math.min((page + 1) * pageSize, totalSize);
Integer[] position = { new Integer(start+1) , new Integer(end), new Integer(totalSize)};
String showing = (String) rb.getFormattedMessage("showing.results", position);
context.put("showing", showing);
}
state.setAttribute(STATE_LIST_ITERATOR, newIterator);
// constant schema identifier
context.put( "titleProperty", Schema.TITLE );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
}
return TEMPLATE_NEW_RESOURCE;
}
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildMessagePanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
context.put("sakai_onload", "");
//context.put("FORM_NAME", "messageForm");
context.put( "citationId", state.getAttribute( STATE_CITATION_ID ) );
// get the collection we're now working on
String collectionId = (String)state.getAttribute(STATE_CITATION_COLLECTION_ID);
context.put( "collectionId", collectionId );
int size = 0;
CitationCollection collection = getCitationCollection(state, false);
if(collection == null)
{
logger.warn( "buildMessagePanelContext unable to access citationCollection " + collectionId );
}
else
{
size = collection.size();
}
// get the size of the list
context.put( "citationCount", new Integer( size ) );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_MESSAGE;
}
/**
*
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildResultsPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
Caller caller = getCaller(state);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validators
context.put("TextValidator", new QuotedTextValidator());
context.put("xilator", new Validator());
// Set:
// * the javascript to run on page load
// * the page execution context (resources tool or editor integration)
switch (caller)
{
case EDITOR_INTEGRATION:
context.put("sakai_onload", "SRC_initializePageInfo('"
+ ELEMENT_ID_RESULTS_FORM
+ "','"
+ rb.getString("add.results")
+ "'); SRC_verifyWindowOpener();");
context.put("editorIntegration", Boolean.TRUE);
context.put("resourcesTool", Boolean.FALSE);
break;
case RESOURCE_TOOL:
default:
context.put("sakai_onload", "setMainFrameHeight( window.name ); highlightButtonSelections( '" + rb.getString("remove.results") + "' )");
context.put("editorIntegration", Boolean.FALSE);
context.put("resourcesTool", Boolean.TRUE);
// put the citation list title and size
putCitationCollectionDetails(context, state);
break;
}
// signal basic/advanced search
Object basicSearch = state.getAttribute( STATE_BASIC_SEARCH );
context.put( "basicSearch", basicSearch );
if( basicSearch != null )
{
context.put( "searchType", ActiveSearch.BASIC_SEARCH_TYPE );
}
else
{
context.put( "searchType", ActiveSearch.ADVANCED_SEARCH_TYPE );
}
/*
* SEARCH RESULTS
*/
ActiveSearch searchResults = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
if(searchResults != null)
{
context.put("searchResults", searchResults);
List currentResults = (List) state.getAttribute(STATE_CURRENT_RESULTS);
context.put("currentResults", currentResults);
Integer[] position = { new Integer(searchResults.getFirstRecordIndex() + 1) , new Integer(searchResults.getLastRecordIndex()), searchResults.getNumRecordsFound()};
String showing = (String) rb.getFormattedMessage("showing.results", position);
context.put("showing", showing);
}
// selected databases
String[] databaseIds = (String[])state.getAttribute( STATE_CURRENT_DATABASES );
context.put( "selectedDatabases", databaseIds );
// load basic/advanced search form state
loadSearchFormState( context, state );
/*
* OTHER CONTEXT PARAMS
*/
// searchInfo
ActiveSearch searchInfo = (ActiveSearch) state.getAttribute(STATE_SEARCH_INFO);
context.put("searchInfo", searchInfo);
// form name
context.put(PARAM_FORM_NAME, ELEMENT_ID_RESULTS_FORM);
// OpenURL Label
context.put( "openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel() );
// object arrays for formatted messages
Object[] instrMainArgs = { rb.getString( "add.results" ) };
context.put( "instrMainArgs", instrMainArgs );
Object[] instrSubArgs = { rb.getString( "label.new.search" ) };
context.put( "instrSubArgs", instrSubArgs );
/*
* ERROR CHECKING
*/
String alertMessages = (String) state.removeAttribute(STATE_MESSAGE);
if(alertMessages != null)
{
context.put("alertMessages", alertMessages);
}
Object noResults = state.removeAttribute( STATE_NO_RESULTS );
if( noResults != null )
{
context.put( "noResults", noResults );
}
Object noSearch = state.removeAttribute(STATE_NO_KEYWORDS);
if(noSearch != null)
{
context.put("noSearch", noSearch);
}
Object noDatabases = state.removeAttribute( STATE_NO_DATABASES );
if( noDatabases != null )
{
context.put( "noDatabases", noDatabases );
}
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_RESULTS;
} // buildResultsPanelContext
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildSearchPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
Caller caller = getCaller(state);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validators
context.put("TextValidator", new QuotedTextValidator());
context.put("xilator", new Validator());
// Set:
// * the javascript to run on page load
// * the page execution context (resources tool or editor integration)
switch (caller)
{
case EDITOR_INTEGRATION:
context.put("sakai_onload", "SRC_verifyWindowOpener(); showTopCategory();");
context.put("editorIntegration", Boolean.TRUE);
context.put("resourcesTool", Boolean.FALSE);
break;
case RESOURCE_TOOL:
default:
context.put("sakai_onload", "setMainFrameHeight( window.name ); showTopCategory();");
context.put("editorIntegration", Boolean.FALSE);
context.put("resourcesTool", Boolean.TRUE);
// put citation list title/size
putCitationCollectionDetails(context, state);
break;
}
// resource-related
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
String guid = getContentService().getUuid(resourceId);
context.put("RESOURCE_ID", guid);
// category information from hierarchy
SearchDatabaseHierarchy hierarchy = (SearchDatabaseHierarchy) state.getAttribute(STATE_SEARCH_HIERARCHY);
context.put( "defaultCategory", hierarchy.getDefaultCategory() );
context.put( "categoryListing", hierarchy.getCategoryListing() );
// load basic/advanced search form state
loadSearchFormState( context, state );
/*
* MISCELLANEOUS CONTEXT PARAMS
*/
// default to basicSearch
context.put( "basicSearch", state.getAttribute( STATE_BASIC_SEARCH ) );
// searchInfo
ActiveSearch searchInfo = (ActiveSearch) state.getAttribute(STATE_SEARCH_INFO);
context.put("searchInfo", searchInfo);
// max number of searchable databases
Integer maxDbNum = new Integer(hierarchy.getNumMaxSearchableDb());
context.put( "maxDbNum", maxDbNum );
// form name
context.put(PARAM_FORM_NAME, ELEMENT_ID_SEARCH_FORM);
// OpenURL Label
context.put( "openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel() );
// object arrays for formatted messages
Object[] instrArgs = { rb.getString( "submit.search" ) };
context.put( "instrArgs", instrArgs );
String searchType = null;
if (searchInfo != null)
{
searchType = searchInfo.getSearchType();
}
if (searchType == null)
searchType = ActiveSearch.BASIC_SEARCH_TYPE;
context.put("searchType", searchType);
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_SEARCH;
} // buildSearchPanelContext
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildViewPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
//context.put("sakai_onload", "setMainFrameHeight('" + CitationHelper.CITATION_FRAME_ID + "');");
//context.put("mainFrameId", CitationHelper.CITATION_FRAME_ID);
//context.put("citationToolId", CitationHelper.CITATION_ID);
//context.put("specialHelperFlag", CitationHelper.SPECIAL_HELPER_ID);
context.put(PARAM_FORM_NAME, ELEMENT_ID_VIEW_FORM);
Citation citation = (Citation) state.getAttribute(CitationHelper.CITATION_VIEW_ITEM);
if(citation == null)
{
doEdit(rundata);
citation = (Citation) state.getAttribute(CitationHelper.CITATION_VIEW_ITEM);
}
context.put("citation", citation);
String citationId = (String) state.getAttribute(CitationHelper.CITATION_VIEW_ID);
String collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
context.put("citationId", citationId);
context.put("collectionId", collectionId);
List schemas = getCitationService().getSchemas();
context.put("TEMPLATES", schemas);
context.put("DEFAULT_TEMPLATE", citation.getSchema());
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_VIEW;
} // buildViewPanelContext
/**
*
* @param context
* @param state
*/
protected void loadSearchFormState( Context context, SessionState state )
{
// remember data previously entered
if( state.getAttribute( STATE_BASIC_SEARCH ) != null )
{
/* basic search */
context.put( "keywords", ( String )state.getAttribute( STATE_KEYWORDS ) );
// default advanced search selections
context.put( "advField1", AdvancedSearchHelper.KEYWORD_ID );
context.put( "advField2", AdvancedSearchHelper.AUTHOR_ID );
context.put( "advField3", AdvancedSearchHelper.TITLE_ID );
context.put( "advField4", AdvancedSearchHelper.SUBJECT_ID );
context.put( "advField5", AdvancedSearchHelper.YEAR_ID );
}
else
{
/* advanced search */
// field selections
AdvancedSearchHelper.putFieldSelections( context, state );
// field criteria
AdvancedSearchHelper.putFieldCriteria( context, state );
}
// basic/advanced search types
context.put( "basicSearchType", ActiveSearch.BASIC_SEARCH_TYPE );
context.put( "advancedSearchType", ActiveSearch.ADVANCED_SEARCH_TYPE );
}
/**
*
*/
public void doFinish ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ToolSession toolSession = getSessionManager().getCurrentToolSession();
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
if (pipe == null)
{
logger.warn( "doFinish() pipe = null");
setMode(state, Mode.ERROR_FATAL);
return;
}
int citationCount = 0;
// if(pipe.getAction().getActionType() == ResourceToolAction.ActionType.CREATE_BY_HELPER)
// {
// /* PIPE remove */
//// SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//
// SecurityService securityService = (SecurityService) ComponentManager.get(SecurityService.class);
// // delete the temporary resource
// String temporaryResourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
// ContentResource tempResource = null;
// try
// {
// // get the temp resource
// tempResource = getContentService().getResource(temporaryResourceId);
//
// // use the temp resource to 'create' the real resource
// pipe.setRevisedContent(tempResource.getContent());
//
// // remove the temp resource
// if( getCitationService().allowRemoveCitationList( temporaryResourceId ) )
// {
// // setup a SecurityAdvisor
// CitationListSecurityAdviser advisor = new CitationListSecurityAdviser(
// getSessionManager().getCurrentSessionUserId(),
// ContentHostingService.AUTH_RESOURCE_REMOVE_ANY,
// tempResource.getReference() );
//
// try {
// securityService.pushAdvisor(advisor);
//
// // remove temp resource
// getContentService().removeResource(temporaryResourceId);
// } catch(Exception e) {
// logger.warn("Exception removing temporary resource for a citation list: " + temporaryResourceId + " --> " + e);
// } finally {
// // pop advisor
// securityService.popAdvisor(advisor);
// }
//
// tempResource = null;
// }
// }
// catch (PermissionException e)
// {
//
// logger.warn("PermissionException ", e);
// }
// catch (IdUnusedException e)
// {
//
// logger.warn("IdUnusedException ", e);
// }
// catch (TypeException e)
// {
//
// logger.warn("TypeException ", e);
// }
//// catch (InUseException e)
//// {
////
//// logger.warn("InUseException ", e);
//// }
// catch (ServerOverloadException e)
// {
//
// logger.warn("ServerOverloadException ", e);
// }
// catch (Exception e)
// {
//
// logger.warn("Exception ", e);
// }
// }
// // set content (mime) type
// pipe.setRevisedMimeType(ResourceType.MIME_TYPE_HTML);
// pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_TYPE, ResourceType.MIME_TYPE_HTML);
//
// // set the alternative_reference to point to reference_root for CitationService
// pipe.setRevisedResourceProperty(ContentHostingService.PROP_ALTERNATE_REFERENCE, CitationService.REFERENCE_ROOT);
/* PIPE remove */
// SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// get the collection we're now working on
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
String collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
String[] args = new String[]{ Integer.toString(collection.size()) };
String size_str = rb.getFormattedMessage("citation.count", args);
pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_LENGTH, size_str);
// leave helper mode
pipe.setActionCanceled(false);
pipe.setErrorEncountered(false);
pipe.setActionCompleted(true);
toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE);
toolSession.removeAttribute(CitationHelper.CITATION_HELPER_INITIALIZED);
cleanup(toolSession, CitationHelper.CITATION_PREFIX, state);
// Remove session sort
state.removeAttribute(STATE_SORT);
// Remove session collection
state.removeAttribute(STATE_CITATION_COLLECTION_ID);
state.removeAttribute(STATE_CITATION_COLLECTION);
state.removeAttribute("fromListPage");
}
} // doFinish
/**
* Cancel the action for which the helper was launched.
*/
public void doCancel(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ToolSession toolSession = getSessionManager().getCurrentToolSession();
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
if (pipe == null)
{
logger.warn( "doCancel() pipe = null");
setMode(state, Mode.ERROR_FATAL);
return;
}
if(pipe.getAction().getActionType() == ResourceToolAction.ActionType.CREATE_BY_HELPER)
{
// TODO: delete the citation collection and all citations
// TODO: delete the temporary resource
// String temporaryResourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
// ContentResourceEdit edit = null;
// try
// {
// edit = getContentService().editResource(temporaryResourceId);
// getContentService().removeResource(edit);
// edit = null;
// }
// catch (PermissionException e)
// {
//
// logger.warn("PermissionException ", e);
// }
// catch (IdUnusedException e)
// {
//
// logger.warn("IdUnusedException ", e);
// }
// catch (TypeException e)
// {
//
// logger.warn("TypeException ", e);
// }
// catch (InUseException e)
// {
//
// logger.warn("InUseException ", e);
// }
//
// if(edit != null)
// {
// getContentService().cancelResource(edit);
// }
}
// leave helper mode
pipe.setActionCanceled(true);
pipe.setErrorEncountered(false);
pipe.setActionCompleted(true);
toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE);
toolSession.removeAttribute(CitationHelper.CITATION_HELPER_INITIALIZED);
state.removeAttribute("fromListPage");
cleanup(toolSession, CitationHelper.CITATION_PREFIX, state);
}
/**
* Adds a citation to the current citation collection. Called from the search-results popup.
*/
public void doAddCitation ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// get the citation from search results, add it to the citation collection, and rebuild the context
String[] citationIds = params.getStrings("citationId");
String collectionId = params.getString("collectionId");
Integer page = (Integer) state.getAttribute(STATE_LIST_PAGE);
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
CitationCollection tempCollection = search.getSearchResults();
Map index = search.getIndex();
if(index == null)
{
index = new Hashtable();
search.setIndex(index);
}
CitationCollection permCollection = getCitationCollection(state, true);
if(permCollection == null) {
// error
} else {
for(int i = 0; i < citationIds.length; i++)
{
try
{
Citation citation = tempCollection.getCitation(citationIds[i]);
citation.setAdded(true);
permCollection.add(citation);
}
catch(IdUnusedException ex)
{
logger.info("doAdd: unable to add citation " + citationIds[i] + " to collection " + collectionId);
}
}
getCitationService().save(permCollection);
}
// setMode(state, Mode.LIST);
}
/**
* Removes a citation from the current citation collection. Called from the search-results popup.
*/
public void doRemove ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// get the citation number from search results, remove it from the citation collection, and rebuild the context
// get the citation from search results, add it to the citation collection, and rebuild the context
String[] citationIds = params.getStrings("citationId");
String collectionId = params.getString("collectionId");
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
CitationCollection tempCollection = search.getSearchResults();
Map index = search.getIndex();
if(index == null)
{
index = new Hashtable();
search.setIndex(index);
}
CitationCollection permCollection = getCitationCollection(state, true);
if(permCollection == null) {
// error
} else {
for(int i = 0; i < citationIds.length; i++)
{
try
{
Citation citation = tempCollection.getCitation(citationIds[i]);
citation.setAdded(false);
permCollection.remove(citation);
}
catch(IdUnusedException ex)
{
logger.info("doAdd: unable to add citation " + citationIds[i] + " to collection " + collectionId);
}
}
getCitationService().save(permCollection);
}
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
}
public void doDatabasePopulate( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// get category id
String categoryId = params.get( "categoryId" );
logger.debug( "doDatabasePopulate() categoryId from URL: " + categoryId );
if( categoryId == null )
{
// should not be null
setMode( state, Mode.ERROR );
return;
}
else
{
/* TODO can probably do this in build-method (don't need category in state)*/
// get selected category, put it in state
SearchDatabaseHierarchy hierarchy = ( SearchDatabaseHierarchy )
state.getAttribute( STATE_SEARCH_HIERARCHY );
SearchCategory category = hierarchy.getCategory( categoryId );
state.setAttribute( STATE_SELECTED_CATEGORY, category );
setMode(state, Mode.DATABASE);
}
}
/**
*
* @param data
*/
public void doImportPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
this.preserveEntityIds(params, state);
setMode(state, Mode.IMPORT_CITATIONS);
} // doImportPage
/**
*
* @param data
*/
public void doImport ( RunData data)
{
logger.debug( "doImport called.");
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
Iterator iter = params.getNames();
String param = null;
while (iter.hasNext())
{
param = (String) iter.next();
logger.debug( "param = " + param);
logger.debug( param + " value = " + params.get(param));
}
String collectionId = params.getString("collectionId");
if(collectionId == null)
{
collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
}
CitationCollection collection = null;
collection = getCitationCollection(state, false);
String ristext = params.get("ristext");
// We're going to read the RIS file from the submitted form's textarea first. If that's
// empty we'll read it from the uploaded file. We'll crate a BufferedReader in either
// circumstance so that the parsing code need not know where the ris text came from.
java.io.BufferedReader bread = null;
if (ristext.trim().length() > 0) // form has text in the risimport textarea
{
java.io.StringReader risStringReader = new java.io.StringReader(ristext);
bread = new java.io.BufferedReader(risStringReader);
logger.debug( "String buffered reader ready");
} // end RIS text is in the textarea
else // textarea empty, set the read of the import from the file
{
String upload = params.get("risupload");
logger.debug( "Upload String = " + upload);
FileItem risImport = params.getFileItem("risupload");
if (risImport == null)
{
logger.debug( "risImport is null.");
return;
}
logger.debug("Filename = " + risImport.getFileName());
InputStream risImportStream = risImport.getInputStream();
// Attempt to detect the encoding of the file.
BOMInputStream irs = new BOMInputStream(risImportStream);
// below is needed if UTF-8 above is commented out
Reader isr = null;
String bomCharsetName = null;
try
{
bomCharsetName = irs.getBOMCharsetName();
if (bomCharsetName != null)
{
isr = new InputStreamReader(risImportStream, bomCharsetName);
}
} catch (UnsupportedEncodingException uee)
{
// Something strange as the JRE should support all the formats.
logger.info("Problem using character set when importing RIS: "+ bomCharsetName);
}
catch (IOException ioe)
{
// Probably won't get any further, but may as well try.
logger.debug("Problem reading the character set from RIS import: "+ ioe.getMessage());
}
// Fallback to platform default
if (isr == null) {
isr = new InputStreamReader(irs);
}
bread = new java.io.BufferedReader(isr);
} // end set the read of the import from the uploaded file.
// The below code is a major work in progress.
// This code is for demonstration purposes only. No gambling or production use!
StringBuilder fileString = new StringBuilder();
String importLine = null;
java.util.List importList = new java.util.ArrayList();
// Read the BufferedReader and populate the importList. Each entry in the list
// is a line in the RIS import "file".
try
{
while ((importLine = bread.readLine()) != null)
{
importLine = importLine.trim();
if (importLine != null && importLine.length() > 2)
{
importList.add(importLine);
if(logger.isDebugEnabled()) {
fileString.append("\n");
fileString.append(importLine);
}
}
} // end while
} // end try
catch(Exception e)
{
logger.debug("ISR error = " + e);
} // end catch
finally {
if (bread != null) {
try {
bread.close();
} catch (IOException e) {
// tried
}
}
}
if(logger.isDebugEnabled()) {
logger.debug("fileString = \n" + fileString.toString());
}
// tempList holds the entries read in to make a citation up to and
// including the ER entry from importList
List tempList = new java.util.ArrayList();
Citation importCitation = getCitationService().getTemporaryCitation();
CitationCollection importCollection = getCitationService().getTemporaryCollection();
int sucessfullyReadCitations = 0;
int totalNumberCitations = 0;
// Read each entry in the RIS List and build a citation
for(int i=0; i< importList.size(); i++)
{
String importEntryString = (String) importList.get(i);
// logger.debug("Import line (#1) = " + importEntryString);
// logger.debug("Substring is = " + importEntryString.substring(0, 2));
tempList.add(importEntryString);
// make sure importEntryString can be tested for "ER" existence. It could
// be a dinky invalid line less than 2 characters.
if (importEntryString != null && importEntryString.length() > 1 &&
importEntryString.substring(0, 2).equalsIgnoreCase("ER"))
{
// end of citation (signaled by ER).
totalNumberCitations++;
logger.debug("------> Trying to add citation " + totalNumberCitations);
if (importCitation.importFromRisList(tempList)) // import went well
{
importCollection.add(importCitation);
sucessfullyReadCitations++;
}
tempList.clear();
importCitation = getCitationService().getTemporaryCitation();
}
} // end for
logger.debug("Done reading in " + sucessfullyReadCitations + " / " + totalNumberCitations + " citations.");
collection.addAll(importCollection);
getCitationService().save(collection);
// remove collection from state
state.removeAttribute(STATE_CITATION_COLLECTION);
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // end doImport()
public void doCreateResource(RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
setMode(state, Mode.NEW_RESOURCE);
//state.setAttribute(CitationHelper.SPECIAL_HELPER_ID, CitationHelper.CITATION_ID);
}
/**
*
*/
public void doCreate ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
setMode(state, Mode.CREATE);
//state.setAttribute(CitationHelper.SPECIAL_HELPER_ID, CitationHelper.CITATION_ID);
} // doCreate
/**
* Fetch the calling application
* @param state The session state
* @return The calling application (default to Resources if nothing is set)
*/
protected Caller getCaller(SessionState state)
{
Caller caller = (Caller) state.getAttribute(CITATIONS_HELPER_CALLER);
return (caller == null) ? Caller.RESOURCE_TOOL : Caller.EDITOR_INTEGRATION;
}
/**
* Set the calling applcation
* @param state The session state
* @param caller The calling application
*/
protected void setCaller(SessionState state, Caller caller)
{
state.setAttribute(CITATIONS_HELPER_CALLER, caller);
}
/**
* @param state
* @param new_mode
*/
protected void setMode(SessionState state, Mode new_mode)
{
// set state attributes
state.setAttribute( CitationHelper.STATE_HELPER_MODE, new_mode );
}
/**
*
*/
public void doCreateCitation ( RunData data)
{
// get the state object and the parameter parser
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
Set validPropertyNames = getCitationService().getValidPropertyNames();
String mediatype = params.getString("type");
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
// create a citation
Citation citation = getCitationService().addCitation(mediatype);
updateCitationFromParams(citation, params);
// add citation to current collection
collection.add(citation);
getCitationService().save(collection);
}
// call buildListPanelContext to show updated list
//state.setAttribute(CitationHelper.SPECIAL_HELPER_ID, CitationHelper.CITATION_ID);
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doCreateCitation
/**
* @param citation
* @param params
*/
protected void updateCitationFromParams(Citation citation, ParameterParser params)
{
Schema schema = citation.getSchema();
List fields = schema.getFields();
Iterator fieldIt = fields.iterator();
while(fieldIt.hasNext())
{
Field field = (Field) fieldIt.next();
String name = field.getIdentifier();
if(field.isMultivalued())
{
List values = new Vector();
String count = params.getString(name + "_count");
int num = 10;
try
{
num = Integer.parseInt(count);
for(int i = 0; i < num; i++)
{
String value = params.getString(name + i);
if(value != null && !values.contains(value))
{
values.add(value);
}
}
citation.updateCitationProperty(name, values);
}
catch(NumberFormatException e)
{
}
}
else
{
String value = params.getString(name);
citation.setCitationProperty(name, value);
if(name.equals(Schema.TITLE))
{
citation.setDisplayName(value);
}
}
}
int urlCount = 0;
try
{
urlCount = params.getInt("url_count");
}
catch(Exception e)
{
logger.debug("doCreateCitation: unable to parse int for urlCount");
}
// clear preferredUrl - if there is one, we will find it after looping
// through all customUrls below
citation.setPreferredUrl( null );
String id = null;
for(int i = 0; i < urlCount; i++)
{
String label = params.getString("label_" + i);
String url = params.getString("url_" + i);
String urlid = params.getString("urlid_" + i);
String preferred = params.getString( "pref_" + i );
String addPrefix = params.getString( "addprefix_" + i );
if(url == null)
{
logger.debug("doCreateCitation: url null? " + url);
}
else
{
try
{
url = validateURL(url);
}
catch (MalformedURLException e)
{
logger.debug("doCreateCitation: unable to validate URL: " + url);
continue;
}
}
if(label == null || url == null)
{
logger.debug("doCreateCitation: label null? " + label + " url null? " + url);
continue;
}
else if(urlid == null || urlid.trim().equals(""))
{
id = citation.addCustomUrl(label, url, addPrefix);
if( preferred != null && !preferred.trim().equals( "" ) )
{
// this customUrl is the new preferredUrl
citation.setPreferredUrl( id );
}
}
else
{
// update an existing customUrl
citation.updateCustomUrl(urlid, label, url, addPrefix);
if( preferred != null && !preferred.trim().equals( "" ) )
{
// this customUrl is the new preferredUrl
citation.setPreferredUrl( urlid );
}
}
}
}
/**
*
*/
public void doEdit ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String citationId = params.getString("citationId");
String collectionId = params.getString("collectionId");
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
Citation citation = null;
try
{
citation = collection.getCitation(citationId);
}
catch (IdUnusedException e)
{
// add an alert (below)
}
if(citation == null)
{
addAlert(state, rb.getString("alert.access"));
}
else
{
state.setAttribute(CitationHelper.CITATION_EDIT_ID, citationId);
state.setAttribute(CitationHelper.CITATION_EDIT_ITEM, citation);
setMode(state, Mode.EDIT);
}
}
} // doEdit
/**
*
*/
public void doList ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doList
public void doResults( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
setMode(state, Mode.RESULTS);
}
/**
*
*/
public void doAddCitations ( RunData data)
{
logger.debug("doAddCitations()");
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
preserveEntityIds(params, state);
//setMode(state, Mode.ADD_CITATIONS);
setMode(state, Mode.NEW_RESOURCE);
logger.debug("doAddCitations()");
} // doAddCitations
public void doMessageFrame(RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// get params
String citationId = params.getString("citationId");
String collectionId = params.getString("collectionId");
String operation = params.getString("operation");
// check params
if( operation == null )
{
logger.warn( "doMessageFrame() 'operation' null argument" );
setMode(state, Mode.ERROR);
return;
}
if( operation.trim().equalsIgnoreCase( "refreshCount" ) )
{
// do not need to do anything, let buildMessagePanelContext update
// count for citations
setMode( state, Mode.MESSAGE );
return;
}
if( operation == null || citationId == null || collectionId == null )
{
logger.warn( "doMessageFrame() null argument - operation: " +
operation + ", citationId: " + citationId + ", " +
"collectionId: " + collectionId );
setMode(state, Mode.ERROR);
return;
}
// get Citation using citationId
List<Citation> currentResults = (List<Citation>) state.getAttribute(STATE_CURRENT_RESULTS);
Citation citation = null;
for( Citation c : currentResults )
{
if( c.getId().equals( citationId ) )
{
citation = c;
break;
}
}
if( citation == null ) {
logger.warn( "doMessageFrame() bad citationId: " + citationId );
setMode(state, Mode.ERROR);
return;
}
// get CitationCollection using collectionId
CitationCollection collection = getCitationCollection(state, false);
if(collection == null) {
logger.warn( "doMessageFrame() unable to access citationCollection " + collectionId );
} else {
// do operation
if(operation.equalsIgnoreCase("add"))
{
logger.debug("adding citation " + citationId + " to " + collectionId);
citation.setAdded( true );
collection.add( citation );
getCitationService().save(collection);
}
else if(operation.equalsIgnoreCase("remove"))
{
logger.debug("removing citation " + citationId + " from " + collectionId);
collection.remove( citation );
citation.setAdded( false );
getCitationService().save(collection);
}
else
{
// do nothing
logger.debug("null operation: " + operation);
}
// store the citation's new id to send back to UI
state.setAttribute( STATE_CITATION_ID, citation.getId() );
}
setMode(state, Mode.MESSAGE);
}
public void doRemoveAllCitations( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String collectionId = params.getString("collectionId");
CitationCollection collection = getCitationCollection(state, false);
if(collection == null)
{
// TODO add alert and log error
logger.warn("CitationHelperAction.doRemoveCitation collection null: " + collectionId);
}
else
{
// remove all citations
List<Citation> citations = collection.getCitations();
if( citations != null && citations.size() > 0 )
{
for( Citation citation : citations )
{
collection.remove( citation );
}
getCitationService().save(collection);
}
}
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doRemoveAllCitations
public void doShowReorderCitations( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
setMode(state, Mode.REORDER);
} // doShowReorderCitations
public void doReorderCitations( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
String orderedCitationIds = params.getString("orderedCitationIds");
CitationCollection collection = getCitationCollection(state, false);
String[] splitIds = orderedCitationIds.split(",");
try
{
for(int i = 1;i <= splitIds.length;i++)
{
collection.getCitation(splitIds[i - 1]).setPosition(i);
}
getCitationService().save(collection);
}
catch(IdUnusedException iue)
{
logger.error("One of the supplied citation ids was invalid. The new order was not saved.");
}
// Had to do this to force a reload from storage in buildListPanelContext
state.removeAttribute(STATE_CITATION_COLLECTION);
state.setAttribute(STATE_SORT, CitationCollection.SORT_BY_POSITION);
setMode(state, Mode.NEW_RESOURCE);
} // doReorderCitations
public void doRemoveSelectedCitations( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String collectionId = params.getString("collectionId");
CitationCollection collection = getCitationCollection(state, false);
if(collection == null)
{
// TODO add alert and log error
logger.warn("doRemoveSelectedCitation() collection null: " + collectionId);
}
else
{
// remove selected citations
String[] paramCitationIds = params.getStrings("citationId");
if( paramCitationIds != null && paramCitationIds.length > 0 )
{
List<String> citationIds = new java.util.ArrayList<String>();
citationIds.addAll(Arrays.asList(paramCitationIds));
try
{
for( String citationId : citationIds )
{
Citation citation = collection.getCitation(citationId);
collection.remove(citation);
}
getCitationService().save(collection);
}
catch( IdUnusedException e )
{
logger.warn("doRemoveSelectedCitation() unable to get and remove citation", e );
}
}
}
state.setAttribute( STATE_LIST_NO_SCROLL, Boolean.TRUE );
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doRemoveSelectedCitations
/**
*
*/
public void doReviseCitation (RunData data)
{
// get the state object and the parameter parser
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// Set validPropertyNames = getCitationService().getValidPropertyNames();
// String mediatype = params.getString("type");
CitationCollection collection = getCitationCollection(state, false);
if(collection == null)
{
// TODO add alert and log error
}
else
{
String citationId = (String) state.getAttribute(CitationHelper.CITATION_EDIT_ID);
if(citationId != null)
{
try
{
Citation citation = collection.getCitation(citationId);
String schemaId = params.getString("type");
Schema schema = getCitationService().getSchema(schemaId);
citation.setSchema(schema);
updateCitationFromParams(citation, params);
// add citation to current collection
collection.saveCitation(citation);
}
catch (IdUnusedException e)
{
// TODO add alert and log error
}
getCitationService().save(collection);
}
}
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doReviseCitation
/**
*
* @param data
*/
public void doCancelSearch( RunData data )
{
// get state and params
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// cancel the running search
ActiveSearch search = ( ActiveSearch )state.getAttribute( STATE_SEARCH_INFO );
if( search != null )
{
Thread searchThread = search.getSearchThread();
if( searchThread != null )
{
try
{
searchThread.interrupt();
}
catch( SecurityException se )
{
// not able to interrupt search
logger.warn( "doSearch() [in ThreadGroup "
+ Thread.currentThread().getThreadGroup().getName()
+ "] unable to interrupt search Thread [name="
+ searchThread.getName()
+ ", id=" + searchThread.getId()
+ ", group=" + searchThread.getThreadGroup().getName()
+ "]");
}
}
}
} // doCancelSearch
/**
* Resources Tool/Citation Helper search
* @param data Runtime data
*/
public void doSearch ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
logger.debug("doSearch()");
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
//doSearchCommon(state, Mode.ADD_CITATIONS);
doSearchCommon(state, Mode.NEW_RESOURCE);
}
/**
* Common "doSearch()" support
* @param state Session state
* @param errorMode Next mode to set if we have database hierarchy problems
*/
protected void doSearchCommon(SessionState state, Mode errorMode)
{
// remove attributes from an old search session, if any
state.removeAttribute( STATE_SEARCH_RESULTS );
state.removeAttribute( STATE_CURRENT_RESULTS );
state.removeAttribute( STATE_KEYWORDS );
// indicate a basic search
state.setAttribute( STATE_BASIC_SEARCH, new Object() );
try
{
SearchDatabaseHierarchy hierarchy = getSearchManager().getSearchHierarchy();
if (hierarchy == null)
{
addAlert(state, rb.getString("search.problem"));
setMode(state, errorMode);
return;
}
state.setAttribute(STATE_SEARCH_HIERARCHY, hierarchy);
setMode(state, Mode.SEARCH);
}
catch (SearchException exception)
{
String error = exception.getMessage();
if ((error == null) || (error.length() == 0))
{
error = rb.getString("search.problem");
}
addAlert(state, error);
setMode(state, Mode.ERROR);
}
}
/**
*
*/
public void doBeginSearch ( RunData data)
{
// get state and params
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// get search object from state
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_INFO);
if(search == null)
{
logger.debug( "doBeginSearch() got null ActiveSearch from state." );
search = getSearchManager().newSearch();
}
// get databases selected
String[] databaseIds = params.getStrings( "databasesSelected" );
// check the databases to make sure they are indeed searchable by this user
if( databaseIds != null )
{
if(logger.isDebugEnabled())
{
logger.debug( "Databases selected:" );
for( String databaseId : databaseIds )
{
logger.debug( " " + databaseId );
}
}
SearchDatabaseHierarchy hierarchy =
(SearchDatabaseHierarchy)state.getAttribute(STATE_SEARCH_HIERARCHY);
for( int i = 0; i < databaseIds.length; i++ )
{
if( !hierarchy.isSearchableDatabase( databaseIds[ i ] ) )
{
// TODO collect a list of the databases which are
// not searchable and pass them to the UI
// do not search if databases selected
// are not searchable by this user
state.setAttribute( STATE_UNAUTHORIZED_DB, Boolean.TRUE );
logger.warn( "doBeginSearch() unauthorized database: " + databaseIds[i] );
setMode(state, Mode.RESULTS);
return;
}
}
/*
* Specify which databases should be searched
*/
search.setDatabaseIds(databaseIds);
state.setAttribute( STATE_CURRENT_DATABASES, databaseIds );
}
else
{
// no databases selected, cannot continue
state.setAttribute( STATE_NO_DATABASES, Boolean.TRUE );
setMode(state, Mode.RESULTS);
return;
}
/*
* do basic/advanced search-specific processing
*/
// determine which type of search has been issued
String searchType = params.getString( "searchType" );
if( searchType != null && searchType.equalsIgnoreCase( ActiveSearch.ADVANCED_SEARCH_TYPE ) )
{
doAdvancedSearch( params, state, search );
}
else
{
doBasicSearch( params, state, search );
}
// check for a cancel
String cancel = params.getString( "cancelOp" );
if( cancel != null && !cancel.trim().equals("") )
{
if( cancel.equalsIgnoreCase( ELEMENT_ID_RESULTS_FORM ) )
{
state.setAttribute( STATE_CANCEL_PAGE, Mode.RESULTS );
}
else
{
state.setAttribute( STATE_CANCEL_PAGE, Mode.SEARCH );
}
}
/*
* BEGIN SEARCH
*/
try
{
// set search thread to the current thread
search.setSearchThread( Thread.currentThread() );
state.setAttribute( STATE_SEARCH_INFO, search );
// initiate the search
List latestResults = search.viewPage();
String msg = search.getStatusMessage();
if(msg != null)
{
addAlert(state, msg);
search.setStatusMessage();
}
if( latestResults != null )
{
state.setAttribute(STATE_SEARCH_RESULTS, search);
state.setAttribute(STATE_CURRENT_RESULTS, latestResults);
setMode(state, Mode.RESULTS);
}
}
catch(SearchException se)
{
// either page indices are off or there has been a metasearch error
// do some logging & find the proper alert message
StringBuilder alertMsg = new StringBuilder( se.getMessage() );
logger.warn("doBeginSearch() SearchException: " + alertMsg );
if( search.getStatusMessage() != null && !search.getStatusMessage().trim().equals("") )
{
logger.warn( " |-- nested metasearch error: " + search.getStatusMessage() );
alertMsg.append( " (" + search.getStatusMessage() + ")" );
}
// add an alert and set the next mode
addAlert( state, alertMsg.toString() );
state.setAttribute( STATE_NO_RESULTS, Boolean.TRUE );
setMode(state, Mode.RESULTS);
return;
}
catch( SearchCancelException sce )
{
logger.debug( "doBeginSearch() SearchCancelException: user cancelled search" );
setMode( state, (Mode)state.getAttribute(STATE_CANCEL_PAGE) );
}
ActiveSearch newSearch = getSearchManager().newSearch();
state.setAttribute( STATE_SEARCH_INFO, newSearch );
} // doBeginSearch
/**
* Sets up a basic search.
*
* @param params request parameters from doBeginSearch
* @param state session state
* @param search current search
*/
protected void doBasicSearch( ParameterParser params, SessionState state, ActiveSearch search )
{
// signal a basic search
state.setAttribute( STATE_BASIC_SEARCH, new Object() );
search.setSearchType( ActiveSearch.BASIC_SEARCH_TYPE );
// get keywords
String keywords = params.getString("keywords");
if(keywords == null || keywords.trim().equals(""))
{
logger.warn( "doBasicSearch() getting null/empty keywords" );
}
// set up search query
SearchQuery basicQuery = new org.sakaiproject.citation.util.impl.SearchQuery();
basicQuery.addKeywords( keywords );
// set query for this search
search.setBasicQuery( basicQuery );
// save state
state.setAttribute( STATE_KEYWORDS, keywords );
} // doBasicSearch
/**
* Sets up an advanced search.
*
* @param params request parameters from doBeginSearch
* @param state session state
* @param search current search
*/
protected void doAdvancedSearch( ParameterParser params, SessionState state, ActiveSearch search )
{
// signal an advanced search
state.removeAttribute( STATE_BASIC_SEARCH );
search.setSearchType( ActiveSearch.ADVANCED_SEARCH_TYPE );
// clear old state
AdvancedSearchHelper.clearAdvancedFormState( state );
// set selected fields
AdvancedSearchHelper.setFieldSelections( params, state );
// set entered criteria
AdvancedSearchHelper.setFieldCriteria( params, state );
// get a Map of advancedCritera for the search
search.setAdvancedQuery( AdvancedSearchHelper.getAdvancedCriteria( state ) );
}
/**
*
*/
public void doNextListPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
CitationIterator listIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(listIterator == null)
{
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
listIterator = collection.iterator();
state.setAttribute(STATE_LIST_ITERATOR, listIterator);
}
}
if(listIterator != null && listIterator.hasNextPage())
{
listIterator.nextPage();
}
} // doNextListPage
/**
*
*/
public void doPrevListPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
CitationIterator listIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(listIterator == null)
{
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
listIterator = collection.iterator();
state.setAttribute(STATE_LIST_ITERATOR, listIterator);
}
}
if(listIterator != null && listIterator.hasPreviousPage())
{
listIterator.previousPage();
}
} // doSearch
/**
*
*/
public void doLastListPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
CitationIterator listIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(listIterator == null)
{
listIterator = collection.iterator();
state.setAttribute(STATE_LIST_ITERATOR, listIterator);
} else {
int pageSize = listIterator.getPageSize();
int totalSize = collection.size();
int lastPage = 0;
listIterator.setStart(totalSize - pageSize);
}
}
} // doSearch
/**
*
*/
public void doFirstListPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
if(state.getAttribute(CitationHelper.RESOURCE_ID) == null) {
String resourceId = params.get("resourceId");
if(resourceId == null || resourceId.trim().equals("")) {
String resourceUuid = (String) state.getAttribute(CitationHelper.RESOURCE_UUID);
if(resourceUuid == null || resourceUuid.trim().equals("")) {
resourceUuid = params.get("resourceUuid");
}
if(resourceUuid == null || resourceUuid.trim().equals("")) {
// Error? We can't identify resource
} else {
resourceId = this.getContentService().resolveUuid(resourceUuid);
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
state.setAttribute(CitationHelper.RESOURCE_UUID, resourceUuid);
}
} else {
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
}
}
CitationIterator listIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(listIterator == null)
{
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
listIterator = collection.iterator();
state.setAttribute(STATE_LIST_ITERATOR, listIterator);
}
}
if(listIterator != null) {
listIterator.setStart(0);
}
} // doSearch
/**
*
*/
public void doNextSearchPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
if(search == null)
{
search = getSearchManager().newSearch();
}
// search.prepareForNextPage();
try
{
List latestResults = search.viewPage(search.getViewPageNumber() + 1);
String msg = search.getStatusMessage();
if(msg != null)
{
addAlert(state, msg);
search.setStatusMessage();
}
state.setAttribute(STATE_CURRENT_RESULTS, latestResults);
setMode(state, Mode.RESULTS);
}
catch (SearchException e)
{
logger.warn("doNextSearchPage: " + e.getMessage());
addAlert(state, rb.getString( "error.search" ) );
setMode(state, Mode.RESULTS);
}
catch(Exception e)
{
logger.warn("doNextSearchPage: " + e.getMessage());
}
} // doSearch
/**
*
*/
public void doPrevSearchPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
if(search == null)
{
search = getSearchManager().newSearch();
}
// search.prepareForNextPage();
try
{
List latestResults = search.viewPage(search.getViewPageNumber() - 1);
String msg = search.getStatusMessage();
if(msg != null)
{
addAlert(state, msg);
search.setStatusMessage();
}
state.setAttribute(STATE_CURRENT_RESULTS, latestResults);
setMode(state, Mode.RESULTS);
}
catch (SearchException e)
{
logger.warn("doPrevSearchPage: " + e.getMessage());
addAlert(state, rb.getString( "error.search" ) );
setMode(state, Mode.RESULTS);
}
catch(Exception e)
{
logger.warn("doPrevSearchPage: " + e.getMessage());
}
} // doSearch
/**
*
*/
public void doFirstSearchPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
if(search == null)
{
search = getSearchManager().newSearch();
}
// search.prepareForNextPage();
try
{
List latestResults = search.viewPage(0);
String msg = search.getStatusMessage();
if(msg != null)
{
addAlert(state, msg);
search.setStatusMessage();
}
state.setAttribute(STATE_CURRENT_RESULTS, latestResults);
setMode(state, Mode.RESULTS);
}
catch (SearchException e)
{
logger.warn("doFirstSearchPage: " + e.getMessage());
addAlert(state, rb.getString( "error.search" ) );
setMode(state, Mode.RESULTS);
}
catch(Exception e)
{
logger.warn("doFirstSearchPage: " + e.getMessage());
}
} // doSearch
/**
*
*/
public void doChangeSearchPageSize ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
if(search == null)
{
search = getSearchManager().newSearch();
state.setAttribute(STATE_SEARCH_RESULTS, search);
}
// search.prepareForNextPage();
// check for top or bottom page selector
String pageSelector = params.get( "pageSelector" );
int pageSize;
if( pageSelector.equals( "top" ) )
{
pageSize = params.getInt( "pageSizeTop" );
}
else
{
pageSize = params.getInt("pageSizeBottom");
}
if(pageSize > 0)
{
// use the new value
}
else
{
// use the old value
pageSize = search.getViewPageSize();
}
state.setAttribute(STATE_RESULTS_PAGE_SIZE, new Integer(pageSize));
try
{
int last = search.getLastRecordIndex();
int page = (last - 1)/pageSize;
search.setViewPageSize(pageSize);
List latestResults = search.viewPage(page);
String msg = search.getStatusMessage();
if(msg != null)
{
addAlert(state, msg);
search.setStatusMessage();
}
state.setAttribute(STATE_CURRENT_RESULTS, latestResults);
setMode(state, Mode.RESULTS);
}
catch (SearchException e)
{
logger.warn("doChangeSearchPageSize: " + e.getMessage());
addAlert(state, rb.getString( "error.search" ) );
setMode(state, Mode.RESULTS);
}
catch(Exception e)
{
logger.warn("doChangeSearchPageSize: " + e.getMessage());
}
} // doChangeSearchPageSize
/**
*
*/
public void doChangeListPageSize ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
int pageSize = params.getInt( "newPageSize" );
if(pageSize < 1) {
// check for top or bottom page selector
String pageSelector = params.get( "pageSelector" );
if( pageSelector.equals( "top" ) )
{
pageSize = params.getInt( "pageSizeTop" );
}
else
{
pageSize = params.getInt("pageSizeBottom");
}
}
if(pageSize > 0)
{
state.setAttribute(STATE_LIST_PAGE_SIZE, new Integer(pageSize));
CitationIterator tempIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
tempIterator.setPageSize(pageSize);
state.removeAttribute(STATE_LIST_ITERATOR);
state.setAttribute(STATE_LIST_ITERATOR, tempIterator);
}
} // doSearch
/**
*
*/
public void doView ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String citationId = params.getString("citationId");
String collectionId = params.getString("collectionId");
CitationCollection collection = getCitationCollection(state, false);
if(collection == null)
{
addAlert(state, rb.getString("alert.access"));
}
else
{
Citation citation = null;
try
{
citation = collection.getCitation(citationId);
}
catch (IdUnusedException e)
{
// add an alert (below)
}
if(citation == null)
{
addAlert(state, rb.getString("alert.access"));
}
else
{
state.setAttribute(CitationHelper.CITATION_VIEW_ID, citationId);
state.setAttribute(CitationHelper.CITATION_VIEW_ITEM, citation);
setMode(state, Mode.VIEW);
}
}
} // doView
/**
* This method is used to ensure the Citations Helper is not invoked by
* the Resources tool in a state other than ADD_CITATIONS or LIST. It uses
* a simple state machine to accomplish this
*
* @return the Mode that the Citations Helper should be in
*/
protected Mode validateState()
{
return null;
}
/**
* This method is called upon each Citations Helper request to properly
* initialize the Citations Helper in case of a null Mode. Returns true if
* succeeded, false otherwise
*
* @param state
*/
protected boolean initHelper(SessionState state)
{
logger.info("initHelper()");
Mode mode;
/*
* Editor Integration support
*/
if (getCaller(state) == Caller.EDITOR_INTEGRATION)
{
mode = (Mode) state.getAttribute(CitationHelper.STATE_HELPER_MODE);
if (mode == null)
{
logger.debug("initHelper(): mode is undefined, using " + Mode.NEW_RESOURCE);
setMode(state, Mode.NEW_RESOURCE);
}
if (state.getAttribute(STATE_RESULTS_PAGE_SIZE) == null)
{
logger.debug("initHelper(): result page size is undefined, using "
+ DEFAULT_RESULTS_PAGE_SIZE);
state.setAttribute(STATE_RESULTS_PAGE_SIZE, DEFAULT_RESULTS_PAGE_SIZE);
}
return true;
}
/*
* Resources Tool support
*/
ToolSession toolSession = getSessionManager().getCurrentToolSession();
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
// TODO: if not entering as a helper, will we need to create pipe???
if (pipe == null)
{
logger.warn( "initHelper() pipe = null");
setMode(state, Mode.ERROR_FATAL);
return true;
}
if(pipe.isActionCompleted())
{
return true;
}
/*
* Resources Tool/Citation Helper support
*/
if( toolSession.getAttribute(CitationHelper.CITATION_HELPER_INITIALIZED) == null )
{
// we're starting afresh: an action has been clicked in Resources
// set the Mode according to our action
switch(pipe.getAction().getActionType())
{
//case CREATE:
case CREATE_BY_HELPER:
// ContentResource tempResource = createTemporaryResource(pipe);
//
// // tempResource could be null if exception encountered
// if( tempResource == null )
// {
// // leave helper
// pipe.setActionCompleted( true );
// toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE);
// toolSession.removeAttribute(CitationHelper.CITATION_HELPER_INITIALIZED);
// cleanup( toolSession, CitationHelper.CITATION_PREFIX, state);
//
// return false;
// }
// state.setAttribute(CitationHelper.RESOURCE_ID, tempResource.getId());
//
// String displayName = tempResource.getProperties().getProperty( org.sakaiproject.entity.api.ResourceProperties.PROP_DISPLAY_NAME );
// state.setAttribute( STATE_COLLECTION_TITLE , displayName );
//
// try
// {
// state.setAttribute(STATE_COLLECTION_ID, new String(tempResource.getContent()));
// }
// catch (ServerOverloadException e)
// {
// logger.warn("ServerOverloadException ", e);
// }
state.setAttribute( STATE_RESOURCES_ADD, Boolean.TRUE );
//setMode(state, Mode.ADD_CITATIONS);
setMode(state, Mode.NEW_RESOURCE);
break;
case REVISE_CONTENT:
state.setAttribute(CitationHelper.RESOURCE_ID, pipe.getContentEntity().getId());
try
{
state.setAttribute(STATE_CITATION_COLLECTION_ID, new String(((ContentResource) pipe.getContentEntity()).getContent()));
}
catch (ServerOverloadException e)
{
logger.warn("ServerOverloadException ", e);
}
state.removeAttribute( STATE_RESOURCES_ADD );
setMode(state, Mode.NEW_RESOURCE);
break;
default:
break;
}
// set Citations Helper to "initialized"
//pipe.setInitializationId( "initialized" );
toolSession.setAttribute(CitationHelper.CITATION_HELPER_INITIALIZED, Boolean.toString(true));
}
else
{
// we're in the middle of a Citations Helper workflow:
// Citations Helper has been "initialized"
// (pipe.initializationId != null)
// make sure we have a Mode to display
mode = (Mode) state.getAttribute(CitationHelper.STATE_HELPER_MODE);
if( mode == null )
{
// default to ADD_CITATIONS
//setMode( state, Mode.ADD_CITATIONS );
setMode( state, Mode.NEW_RESOURCE );
}
}
if(state.getAttribute(STATE_RESULTS_PAGE_SIZE) == null)
{
state.setAttribute(STATE_RESULTS_PAGE_SIZE, DEFAULT_RESULTS_PAGE_SIZE);
}
if(state.getAttribute(STATE_LIST_PAGE_SIZE) == null)
{
state.setAttribute(STATE_LIST_PAGE_SIZE, defaultListPageSize);
}
return true;
} // initHelper
/**
*
* @param pipe
* @return
*/
protected ContentResource createTemporaryResource(ResourceToolActionPipe pipe)
{
try
{
ContentResourceEdit newItem = getContentService().addResource(pipe.getContentEntity().getId(), rb.getString("new.citations.list"), null, ContentHostingService.MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);
newItem.setResourceType(getCitationService().CITATION_LIST_ID);
newItem.setContentType( ResourceType.MIME_TYPE_HTML );
//newItem.setHidden();
ResourcePropertiesEdit props = newItem.getPropertiesEdit();
// set the alternative_reference to point to reference_root for CitationService
props.addProperty(getContentService().PROP_ALTERNATE_REFERENCE, CitationService.REFERENCE_ROOT);
props.addProperty(ResourceProperties.PROP_CONTENT_TYPE, ResourceType.MIME_TYPE_HTML);
props.addProperty(getCitationService().PROP_TEMPORARY_CITATION_LIST, Boolean.TRUE.toString());
CitationCollection collection = getCitationService().addCollection();
newItem.setContent(collection.getId().getBytes());
newItem.setContentType(ResourceType.MIME_TYPE_HTML);
getContentService().commitResource(newItem, NotificationService.NOTI_NONE);
return newItem;
}
catch (PermissionException e)
{
logger.warn("PermissionException ", e);
}
catch (IdUniquenessException e)
{
logger.warn("IdUniquenessException ", e);
}
catch (IdLengthException e)
{
logger.warn("IdLengthException ", e);
}
catch (IdInvalidException e)
{
logger.warn("IdInvalidException ", e);
}
catch (IdUnusedException e)
{
logger.warn("IdUnusedException ", e);
}
catch (OverQuotaException e)
{
logger.warn( e.getMessage() );
// send an error back to Resources
pipe.setErrorEncountered( true );
pipe.setErrorMessage( rb.getString( "action.create.quota" ) );
}
catch (ServerOverloadException e)
{
logger.warn("ServerOverloadException ", e);
}
return null;
}
protected String validateURL(String url) throws MalformedURLException
{
if (url == null || url.trim().equals (""))
{
throw new MalformedURLException();
}
url = url.trim();
// does this URL start with a transport?
if (url.indexOf ("://") == -1)
{
// if it's missing the transport, add http://
url = "http://" + url;
}
// valid protocol?
try
{
// test to see if the input validates as a URL.
// Checks string for format only.
URL u = new URL(url);
}
catch (MalformedURLException e1)
{
try
{
Pattern pattern = Pattern.compile("\\s*([a-zA-Z0-9]+)://([^\\n]+)");
Matcher matcher = pattern.matcher(url);
if(matcher.matches())
{
// if URL has "unknown" protocol, check remaider with
// "http" protocol and accept input it that validates.
URL test = new URL("http://" + matcher.group(2));
}
else
{
throw e1;
}
}
catch (MalformedURLException e2)
{
throw e1;
}
}
return url;
}
public static class QuotedTextValidator
{
/**
* Return a string for insertion in a quote in an HTML tag (as the value of an element's attribute.
*
* @param string
* The string to escape.
* @return the escaped string.
*/
public static String escapeQuotedString(String string)
{
if (string == null) return "";
string = string.trim();
try
{
// convert the string to bytes in UTF-8
byte[] bytes = string.getBytes("UTF-8");
StringBuilder buf = new StringBuilder();
for (int i = 0; i < bytes.length; i++)
{
byte b = bytes[i];
if (b == '"')
{
buf.append("\\\"");
}
else if(b == '\\')
{
buf.append("\\\\");
}
else
{
buf.append((char) b);
}
}
String rv = buf.toString();
return rv;
}
catch (Exception e)
{
return string;
}
} // escapeQuotedString
/**
* Return a string that is safe to place into a JavaScript value wrapped
* in single quotes. In addition, all double quotes (") are replaced by
* the entity <i>"</i>.
*
* @param string The original string
* @return The [possibly] escaped string
*/
public static String escapeHtmlAndJsQuoted(String string)
{
String escapedText = getFormattedText().escapeJsQuoted(string);
return escapedText.replaceAll("\"", """);
}
}
/**
* Cleans up tool state used internally. Useful before leaving helper mode.
*
* @param toolSession
* @param prefix
*/
protected void cleanup(ToolSession toolSession, String prefix,
SessionState sessionState )
{
// cleanup everything dealing with citations
Enumeration attributeNames = toolSession.getAttributeNames();
while(attributeNames.hasMoreElements())
{
String aName = (String) attributeNames.nextElement();
if(aName.startsWith(prefix))
{
toolSession.removeAttribute(aName);
}
}
// re-enable observers
VelocityPortletPaneledAction.enableObservers(sessionState);
}
public void doSortCollection( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String collectionId = params.getString("collectionId");
String sort = params.getString("currentSort");
if(sort == null || sort.trim().equals("")) {
sort = CitationCollection.SORT_BY_TITLE;
}
CitationCollection collection = null;
if(collectionId == null)
{
collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
}
logger.debug("doSortCollection sort type = " + sort);
collection = getCitationCollection(state, false);
if(collection == null)
{
// TODO add alert and log error
logger.warn("doSortCollection() collection null: " + collectionId);
}
else
{
// sort the citation list
logger.debug("doSortCollection() ready to sort");
if (sort.equalsIgnoreCase(CitationCollection.SORT_BY_TITLE))
collection.setSort(CitationCollection.SORT_BY_TITLE, true);
else if (sort.equalsIgnoreCase(CitationCollection.SORT_BY_AUTHOR))
collection.setSort(CitationCollection.SORT_BY_AUTHOR, true);
else if (sort.equalsIgnoreCase(CitationCollection.SORT_BY_YEAR))
collection.setSort(CitationCollection.SORT_BY_YEAR , true);
else if (sort.equalsIgnoreCase(CitationCollection.SORT_BY_POSITION))
collection.setSort(CitationCollection.SORT_BY_POSITION , true);
state.setAttribute(STATE_SORT, sort);
Iterator iter = collection.iterator();
while (iter.hasNext())
{
Citation tempCit = (Citation) iter.next();
logger.debug("doSortCollection() tempcit 1 -------------");
logger.debug("doSortCollection() tempcit 1 (author) = " + tempCit.getFirstAuthor());
logger.debug("doSortCollection() tempcit 1 (year) = " + tempCit.getYear());
logger.debug("doSortCollection() tempcit 1 = " + tempCit.getDisplayName());
} // end while
// set the list iterator to the start of the list after a change in sort
CitationIterator listIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(listIterator != null)
{
listIterator.setStart(0);
}
} // end else
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doSortCollection
public void doSaveCollection(RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String collectionId = params.getString("collectionId");
CitationCollection collection = null;
if(collectionId == null)
{
collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
}
collection = getCitationCollection(state, false);
if(collection == null)
{
// TODO add alert and log error
logger.warn("doSaveCollection() collection null: " + collectionId);
return;
}
else
{
// save the collection (this will persist the sort order to the db)
getCitationService().save(collection);
String sort = collection.getSort();
if (sort != null)
state.setAttribute(STATE_SORT, sort);
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
}
} // end doSaveCollection
public class CitationListSecurityAdviser implements SecurityAdvisor
{
String userId;
String function;
String reference;
public CitationListSecurityAdviser(String userId, String function, String reference)
{
super();
this.userId = userId;
this.function = function;
this.reference = reference;
}
public SecurityAdvice isAllowed(String userId, String function, String reference)
{
SecurityAdvice advice = SecurityAdvice.PASS;
if((this.userId == null || this.userId.equals(userId)) && (this.function == null || this.function.equals(function)) || (this.reference == null || this.reference.equals(reference)))
{
advice = SecurityAdvice.ALLOWED;
}
return advice;
}
}
// temporary -- replace with a method in content-util
public static int preserveRequestState(SessionState state, String[] prefixes)
{
Map requestState = new HashMap();
int requestStateId = 0;
while(requestStateId == 0)
{
requestStateId = (int) (Math.random() * Integer.MAX_VALUE);
}
List<String> attrNames = state.getAttributeNames();
for(String attrName : attrNames)
{
for(String prefix : prefixes)
{
if(attrName.startsWith(prefix))
{
requestState.put(attrName,state.getAttribute(attrName));
break;
}
}
}
Object pipe = state.getAttribute(ResourceToolAction.ACTION_PIPE);
if(pipe != null)
{
requestState.put(ResourceToolAction.ACTION_PIPE, pipe);
}
Tool tool = getToolManager().getCurrentTool();
Object url = state.getAttribute(tool.getId() + Tool.HELPER_DONE_URL);
if( url != null)
{
requestState.put(tool.getId() + Tool.HELPER_DONE_URL, url);
}
state.setAttribute(CitationHelper.RESOURCES_SYS_PREFIX + requestStateId, requestState);
logger.debug("preserveRequestState() requestStateId == " + requestStateId + "\n" + requestState);
return requestStateId;
}
// temporary -- replace with a value in content-util or content-api
public static void restoreRequestState(SessionState state, String[] prefixes, int requestStateId)
{
Map<String, String> requestState = (Map<String, String>) state.removeAttribute(CitationHelper.RESOURCES_SYS_PREFIX + requestStateId);
logger.debug("restoreRequestState() requestStateId == " + requestStateId + "\n" + requestState);
if(requestState != null)
{
List<String> attrNames = state.getAttributeNames();
for(String attrName : attrNames)
{
for(String prefix : prefixes)
{
if(attrName.startsWith(prefix))
{
state.removeAttribute(attrName);
break;
}
}
}
for(Map.Entry<String, String> entry : requestState.entrySet())
{
state.setAttribute(entry.getKey(), entry.getValue());
}
}
}
protected Map<String,Object> getProperties(ContentEntity entity, SessionState state) {
Map<String,Object> props = new HashMap<String,Object>();
ResourceProperties properties = entity.getProperties();
Reference ref = getEntityManager().newReference(entity.getReference());
DateFormat df = DateFormat.getDateTimeInstance();
// isHidden
props.put(PROP_IS_HIDDEN, new Boolean(entity.isHidden()));
// releaseDate, useReleaseDate
Date releaseDate = null;
if(entity.getReleaseDate() == null) {
releaseDate = new Date(System.currentTimeMillis());
props.put(PROP_USE_RELEASE_DATE, Boolean.FALSE);
} else {
releaseDate = new Date(entity.getReleaseDate().getTime());
props.put(PROP_USE_RELEASE_DATE, Boolean.TRUE);
}
props.put(PROP_RELEASE_DATE_STR, df.format(releaseDate));
props.put(PROP_RELEASE_DATE, releaseDate);
// retractDate, useRetractDate
Date retractDate = null;
if(entity.getRetractDate() == null) {
retractDate = new Date(System.currentTimeMillis() + ONE_WEEK);
props.put(PROP_USE_RETRACT_DATE, Boolean.FALSE);
} else {
retractDate = new Date(entity.getRetractDate().getTime());
props.put(PROP_USE_RETRACT_DATE, Boolean.TRUE);
}
props.put(PROP_RETRACT_DATE_STR, df.format(retractDate));
props.put(PROP_RETRACT_DATE, retractDate);
// isCollection
props.put(PROP_IS_COLLECTION, entity.isCollection());
// isDropbox
props.put(PROP_IS_DROPBOX, new Boolean(getContentService().isInDropbox(entity.getId())));
// isSiteCollection
props.put(PROP_IS_SITE_COLLECTION, new Boolean(ref.getContext() != null && ref.getContext().equals(entity.getId())));
// isPubview
props.put(PROP_IS_PUBVIEW, getContentService().isPubView(entity.getId()));
// isPubviewInherited
props.put(PROP_IS_PUBVIEW_INHERITED, new Boolean(getContentService().isInheritingPubView(entity.getId())));
// isPubviewPossible
Boolean preventPublicDisplay = (Boolean) state.getAttribute("resources.request.prevent_public_display");
if(preventPublicDisplay == null) {
preventPublicDisplay = Boolean.FALSE;
}
props.put(PROP_IS_PUBVIEW_POSSIBLE, new Boolean(! preventPublicDisplay.booleanValue()));
// accessMode
AccessMode accessMode = entity.getAccess();
props.put(PROP_ACCESS_MODE, accessMode);
// isGroupInherited
props.put(PROP_IS_GROUP_INHERITED, AccessMode.GROUPED == entity.getInheritedAccess());
SiteService siteService = (SiteService) ComponentManager.get(SiteService.class);
Set<String> currentGroups = new TreeSet<String>();
if(AccessMode.GROUPED == accessMode) {
for(Group gr : (Collection<Group>) entity.getGroupObjects()) {
currentGroups.add(gr.getId());
}
}
// possibleGroups
Collection<Group> inheritedGroupObjs = null;
if(entity.getInheritedAccess() == AccessMode.GROUPED) {
inheritedGroupObjs = entity.getInheritedGroupObjects();
} else {
try {
Site site = siteService.getSite(ref.getContext());
inheritedGroupObjs = site.getGroups();
} catch (IdUnusedException e) {
logger.warn("IdUnusedException in getProperties() " + e);
}
}
List<Map<String,String>> groups = new ArrayList<Map<String,String>>();
if(inheritedGroupObjs != null) {
Collection<Group> groupsWithRemovePermission = null;
if(AccessMode.GROUPED == accessMode)
{
groupsWithRemovePermission = contentService.getGroupsWithRemovePermission(entity.getId());
String container = ref.getContainer();
if(container != null)
{
Collection<Group> more = contentService.getGroupsWithRemovePermission(container);
if(more != null && ! more.isEmpty())
{
groupsWithRemovePermission.addAll(more);
}
}
} else if(AccessMode.GROUPED == entity.getInheritedAccess()) {
groupsWithRemovePermission = contentService.getGroupsWithRemovePermission(ref.getContainer());
}
else if(ref.getContext() != null && contentService.getSiteCollection(ref.getContext()) != null)
{
groupsWithRemovePermission = contentService.getGroupsWithRemovePermission(contentService.getSiteCollection(ref.getContext()));
}
Set<String> idsOfGroupsWithRemovePermission = new TreeSet<String>();
if(groupsWithRemovePermission != null) {
for(Group gr : groupsWithRemovePermission) {
idsOfGroupsWithRemovePermission.add(gr.getId());
}
}
for(Group group : inheritedGroupObjs) {
Map<String, String> grp = new HashMap<String, String>();
grp.put("groupId", group.getId());
grp.put("title", group.getTitle());
grp.put("description", group.getDescription());
grp.put("entityRef", group.getReference());
if(currentGroups.contains(group.getId())) {
grp.put("isLocal", Boolean.toString(true));
}
if(idsOfGroupsWithRemovePermission.contains(group.getId())) {
grp.put("allowedRemove", Boolean.toString(true));
}
groups.add(grp);
}
}
props.put(PROP_POSSIBLE_GROUPS, groups);
// isGroupPossible
props.put(PROP_IS_GROUP_POSSIBLE, new Boolean(groups != null && groups.size() > 0));
// isSingleGroupInherited
props.put(PROP_IS_SINGLE_GROUP_INHERITED, new Boolean(groups != null && groups.size() == 1));
// isSiteOnly = ! isPubviewPossible && ! isGroupPossible
props.put(PROP_IS_SITE_ONLY, new Boolean(preventPublicDisplay.booleanValue() && (groups == null || groups.size() < 1)));
// isUserSite
props.put(PROP_IS_USER_SITE, siteService.isUserSite(ref.getContext()));
// getSelectedConditionKey
// getSubmittedResourceFilter
// isUseConditionalRelease
state.setAttribute(STATE_RESOURCE_ENTITY_PROPERTIES, props);
return props;
}
protected CitationService getCitationService() {
if(this.citationService == null) {
this.citationService = (CitationService) ComponentManager.get(CitationService.class);
}
return this.citationService;
}
protected ConfigurationService getConfigurationService() {
if(this.configurationService == null) {
this.configurationService = (ConfigurationService) ComponentManager.get(ConfigurationService.class);
}
return this.configurationService;
}
protected SearchManager getSearchManager() {
if(this.searchManager == null) {
this.searchManager = (SearchManager) ComponentManager.get(SearchManager.class);
}
return this.searchManager;
}
protected ContentHostingService getContentService() {
if(this.contentService == null) {
this.contentService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService");
}
return this.contentService;
}
protected EntityManager getEntityManager() {
if(this.entityManager == null) {
this.entityManager = (EntityManager) ComponentManager.get(EntityManager.class);
}
return this.entityManager;
}
protected SessionManager getSessionManager() {
if(this.sessionManager == null) {
this.sessionManager = (SessionManager) ComponentManager.get(SessionManager.class);
}
return this.sessionManager;
}
protected static ToolManager getToolManager() {
if(toolManager == null) {
toolManager = (ToolManager) ComponentManager.get(ToolManager.class);
}
return toolManager;
}
protected static FormattedText getFormattedText() {
if(formattedText == null) {
formattedText = (FormattedText) ComponentManager.get(FormattedText.class);
}
return formattedText;
}
} // class CitationHelperAction
| SAK-22296
Set the iterator's page size to the full size of the collection. It was set to the current page size before which made it a bit useless.
git-svn-id: dce76f8a399c671fe9c0e23b6e81ff8638f82523@111666 66ffb92e-73f9-0310-93c1-f5514f145a0a
| citations/citations-tool/tool/src/java/org/sakaiproject/citation/tool/CitationHelperAction.java | SAK-22296 |
|
Java | apache-2.0 | 2949acb1ba047950464f2008d2bea67eacb9bc23 | 0 | lukecwik/incubator-beam,rangadi/beam,apache/beam,tgroh/beam,charlesccychen/beam,robertwb/incubator-beam,charlesccychen/incubator-beam,markflyhigh/incubator-beam,tgroh/beam,lukecwik/incubator-beam,charlesccychen/incubator-beam,robertwb/incubator-beam,charlesccychen/beam,robertwb/incubator-beam,RyanSkraba/beam,rangadi/incubator-beam,apache/beam,rangadi/beam,apache/beam,chamikaramj/beam,robertwb/incubator-beam,charlesccychen/beam,charlesccychen/beam,apache/beam,robertwb/incubator-beam,lukecwik/incubator-beam,iemejia/incubator-beam,RyanSkraba/beam,lukecwik/incubator-beam,chamikaramj/beam,chamikaramj/beam,chamikaramj/beam,tgroh/incubator-beam,charlesccychen/incubator-beam,RyanSkraba/beam,markflyhigh/incubator-beam,rangadi/beam,chamikaramj/beam,rangadi/beam,lukecwik/incubator-beam,tgroh/beam,apache/beam,apache/beam,chamikaramj/beam,tgroh/beam,rangadi/beam,apache/beam,robertwb/incubator-beam,RyanSkraba/beam,lukecwik/incubator-beam,apache/beam,chamikaramj/beam,tgroh/incubator-beam,markflyhigh/incubator-beam,RyanSkraba/beam,mxm/incubator-beam,charlesccychen/beam,lukecwik/incubator-beam,chamikaramj/beam,robertwb/incubator-beam,apache/beam,markflyhigh/incubator-beam,chamikaramj/beam,RyanSkraba/beam,rangadi/incubator-beam,markflyhigh/incubator-beam,robertwb/incubator-beam,apache/beam,robertwb/incubator-beam,mxm/incubator-beam,lukecwik/incubator-beam,chamikaramj/beam,lukecwik/incubator-beam,apache/beam,rangadi/beam,markflyhigh/incubator-beam,rangadi/beam,lukecwik/incubator-beam,iemejia/incubator-beam,rangadi/incubator-beam,robertwb/incubator-beam,markflyhigh/incubator-beam,RyanSkraba/beam,charlesccychen/beam,charlesccychen/beam | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.runners.core.construction.graph;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Iterables;
import com.google.common.graph.MutableNetwork;
import com.google.common.graph.Network;
import com.google.common.graph.NetworkBuilder;
import com.google.protobuf.InvalidProtocolBufferException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.beam.model.pipeline.v1.RunnerApi;
import org.apache.beam.model.pipeline.v1.RunnerApi.Components;
import org.apache.beam.model.pipeline.v1.RunnerApi.Environment;
import org.apache.beam.model.pipeline.v1.RunnerApi.PCollection;
import org.apache.beam.model.pipeline.v1.RunnerApi.PTransform;
import org.apache.beam.model.pipeline.v1.RunnerApi.ParDoPayload;
import org.apache.beam.model.pipeline.v1.RunnerApi.Pipeline;
import org.apache.beam.runners.core.construction.Environments;
import org.apache.beam.runners.core.construction.PTransformTranslation;
import org.apache.beam.runners.core.construction.RehydratedComponents;
import org.apache.beam.runners.core.construction.graph.PipelineNode.PCollectionNode;
import org.apache.beam.runners.core.construction.graph.PipelineNode.PTransformNode;
/**
* A {@link Pipeline} which has additional methods to relate nodes in the graph relative to each
* other.
*/
public class QueryablePipeline {
// TODO: Is it better to have the signatures here require nodes in almost all contexts, or should
// they all take strings? Nodes gives some degree of type signalling that names might not, but
// it's more painful to construct the node. However, right now the traversal is done starting
// at the roots and using nodes everywhere based on what any query has returned.
/**
* Create a new {@link QueryablePipeline} based on the provided components.
*
* <p>The returned {@link QueryablePipeline} will contain only the primitive transforms present
* within the provided components.
*/
public static QueryablePipeline fromComponents(Components components) {
return new QueryablePipeline(components);
}
private final Components components;
private final RehydratedComponents rehydratedComponents;
/**
* The {@link Pipeline} represented by a {@link Network}.
*
* <p>This is a directed bipartite graph consisting of {@link PTransformNode PTransformNodes} and
* {@link PCollectionNode PCollectionNodes}. Each {@link PCollectionNode} has exactly one in edge,
* and an arbitrary number of out edges. Each {@link PTransformNode} has an arbitrary number of in
* and out edges.
*
* <p>Parallel edges are permitted, as a {@link PCollectionNode} can be consumed by a single
* {@link PTransformNode} any number of times with different local names.
*/
private final Network<PipelineNode, PipelineEdge> pipelineNetwork;
private QueryablePipeline(Components allComponents) {
this.components = retainOnlyPrimitives(allComponents);
this.rehydratedComponents = RehydratedComponents.forComponents(this.components);
this.pipelineNetwork = buildNetwork(this.components);
}
/** Produces a {@link RunnerApi.Components} which contains only primitive transforms. */
@VisibleForTesting
static RunnerApi.Components retainOnlyPrimitives(RunnerApi.Components components) {
RunnerApi.Components.Builder flattenedBuilder = components.toBuilder();
flattenedBuilder.clearTransforms();
for (Map.Entry<String, PTransform> transformEntry : components.getTransformsMap().entrySet()) {
PTransform transform = transformEntry.getValue();
boolean isPrimitive = isPrimitiveTransform(transform);
if (isPrimitive) {
flattenedBuilder.putTransforms(transformEntry.getKey(), transform);
}
}
return flattenedBuilder.build();
}
/**
* Returns true if the provided transform is a primitive. A primitive has no subtransforms and
* produces a new {@link PCollection}.
*
* <p>Note that this precludes primitive transforms which only consume input and produce no
* PCollections as output.
*/
private static boolean isPrimitiveTransform(PTransform transform) {
return transform.getSubtransformsCount() == 0
&& !transform.getInputsMap().values().containsAll(transform.getOutputsMap().values());
}
private MutableNetwork<PipelineNode, PipelineEdge> buildNetwork(Components components) {
MutableNetwork<PipelineNode, PipelineEdge> network =
NetworkBuilder.directed()
.allowsParallelEdges(true)
.allowsSelfLoops(false)
.build();
Set<PCollectionNode> unproducedCollections = new HashSet<>();
for (Map.Entry<String, PTransform> transformEntry : components.getTransformsMap().entrySet()) {
String transformId = transformEntry.getKey();
PTransform transform = transformEntry.getValue();
PTransformNode transformNode =
PipelineNode.pTransform(transformId, this.components.getTransformsOrThrow(transformId));
network.addNode(transformNode);
for (String produced : transform.getOutputsMap().values()) {
PCollectionNode producedNode =
PipelineNode.pCollection(produced, components.getPcollectionsOrThrow(produced));
network.addNode(producedNode);
network.addEdge(transformNode, producedNode, new PerElementEdge());
checkState(
network.inDegree(producedNode) == 1,
"A %s should have exactly one producing %s, %s has %s",
PCollectionNode.class.getSimpleName(),
PTransformNode.class.getSimpleName(),
producedNode,
network.successors(producedNode));
unproducedCollections.remove(producedNode);
}
for (Map.Entry<String, String> consumed : transform.getInputsMap().entrySet()) {
// This loop may add an edge between the consumed PCollection and the current PTransform.
// The local name of the transform must be used to determine the type of edge.
String pcollectionId = consumed.getValue();
PCollectionNode consumedNode =
PipelineNode.pCollection(
pcollectionId, this.components.getPcollectionsOrThrow(pcollectionId));
if (network.addNode(consumedNode)) {
// This node has been added to the network for the first time, so it has no producer.
unproducedCollections.add(consumedNode);
}
if (getLocalSideInputNames(transform).contains(consumed.getKey())) {
network.addEdge(consumedNode, transformNode, new SingletonEdge());
} else {
network.addEdge(consumedNode, transformNode, new PerElementEdge());
}
}
}
checkState(
unproducedCollections.isEmpty(),
"%ss %s were consumed but never produced",
PCollectionNode.class.getSimpleName(),
unproducedCollections);
return network;
}
/**
* Return the set of all {@link PCollectionNode PCollection Nodes} which are consumed as side
* inputs.
*/
private Set<PCollectionNode> getConsumedAsSideInputs() {
return pipelineNetwork
.edges()
.stream()
.filter(edge -> !edge.isPerElement())
.map(edge -> (PCollectionNode) pipelineNetwork.incidentNodes(edge).source())
.collect(Collectors.toSet());
}
/**
* Get the transforms that are roots of this {@link QueryablePipeline}. These are all nodes which
* have no input {@link PCollection}.
*/
public Set<PTransformNode> getRootTransforms() {
return pipelineNetwork
.nodes()
.stream()
.filter(pipelineNode -> pipelineNetwork.inEdges(pipelineNode).isEmpty())
.map(pipelineNode -> (PTransformNode) pipelineNode)
.collect(Collectors.toSet());
}
public PTransformNode getProducer(PCollectionNode pcollection) {
return (PTransformNode) Iterables.getOnlyElement(pipelineNetwork.predecessors(pcollection));
}
/**
* Get all of the {@link PTransformNode PTransforms} which consume the provided {@link
* PCollectionNode} on a per-element basis.
*
* <p>If a {@link PTransformNode} consumes a {@link PCollectionNode} on a per-element basis one or
* more times, it will appear a single time in the result.
*
* <p>In theory, a transform may consume a single {@link PCollectionNode} in both a per-element
* and singleton manner. If this is the case, the transform node is included in the result, as it
* does consume the {@link PCollectionNode} on a per-element basis.
*/
public Set<PTransformNode> getPerElementConsumers(PCollectionNode pCollection) {
return pipelineNetwork
.successors(pCollection)
.stream()
.filter(
consumer ->
pipelineNetwork
.edgesConnecting(pCollection, consumer)
.stream()
.anyMatch(PipelineEdge::isPerElement))
.map(pipelineNode -> (PTransformNode) pipelineNode)
.collect(Collectors.toSet());
}
public Set<PCollectionNode> getOutputPCollections(PTransformNode ptransform) {
return pipelineNetwork
.successors(ptransform)
.stream()
.map(pipelineNode -> (PCollectionNode) pipelineNode)
.collect(Collectors.toSet());
}
public Components getComponents() {
return components;
}
/**
* Returns the {@link PCollectionNode PCollectionNodes} that the provided transform consumes as
* side inputs.
*/
public Collection<PCollectionNode> getSideInputs(PTransformNode transform) {
return getLocalSideInputNames(transform.getTransform())
.stream()
.map(localName -> {
String pcollectionId = transform.getTransform().getInputsOrThrow(localName);
return PipelineNode.pCollection(
pcollectionId, components.getPcollectionsOrThrow(pcollectionId));
})
.collect(Collectors.toSet());
}
private Set<String> getLocalSideInputNames(PTransform transform) {
if (PTransformTranslation.PAR_DO_TRANSFORM_URN.equals(transform.getSpec().getUrn())) {
try {
return ParDoPayload.parseFrom(transform.getSpec().getPayload()).getSideInputsMap().keySet();
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException(e);
}
} else {
return Collections.emptySet();
}
}
public Optional<Environment> getEnvironment(PTransformNode parDo) {
return Environments.getEnvironment(parDo.getTransform(), rehydratedComponents);
}
private interface PipelineEdge {
boolean isPerElement();
}
private static class PerElementEdge implements PipelineEdge {
@Override
public boolean isPerElement() {
return true;
}
}
private static class SingletonEdge implements PipelineEdge {
@Override
public boolean isPerElement() {
return false;
}
}
}
| runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/graph/QueryablePipeline.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.runners.core.construction.graph;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Iterables;
import com.google.common.graph.MutableNetwork;
import com.google.common.graph.Network;
import com.google.common.graph.NetworkBuilder;
import com.google.protobuf.InvalidProtocolBufferException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.beam.model.pipeline.v1.RunnerApi;
import org.apache.beam.model.pipeline.v1.RunnerApi.Components;
import org.apache.beam.model.pipeline.v1.RunnerApi.Environment;
import org.apache.beam.model.pipeline.v1.RunnerApi.PCollection;
import org.apache.beam.model.pipeline.v1.RunnerApi.PTransform;
import org.apache.beam.model.pipeline.v1.RunnerApi.ParDoPayload;
import org.apache.beam.model.pipeline.v1.RunnerApi.Pipeline;
import org.apache.beam.runners.core.construction.Environments;
import org.apache.beam.runners.core.construction.PTransformTranslation;
import org.apache.beam.runners.core.construction.RehydratedComponents;
import org.apache.beam.runners.core.construction.graph.PipelineNode.PCollectionNode;
import org.apache.beam.runners.core.construction.graph.PipelineNode.PTransformNode;
/**
* A {@link Pipeline} which has additional methods to relate nodes in the graph relative to each
* other.
*/
public class QueryablePipeline {
// TODO: Is it better to have the signatures here require nodes in almost all contexts, or should
// they all take strings? Nodes gives some degree of type signalling that names might not, but
// it's more painful to construct the node. However, right now the traversal is done starting
// at the roots and using nodes everywhere based on what any query has returned.
/**
* Create a new {@link QueryablePipeline} based on the provided components.
*
* <p>The returned {@link QueryablePipeline} will contain only the primitive transforms present
* within the provided components.
*/
public static QueryablePipeline fromComponents(Components components) {
return new QueryablePipeline(components);
}
private final Components components;
private final RehydratedComponents rehydratedComponents;
/**
* The {@link Pipeline} represented by a {@link Network}.
*
* <p>This is a directed bipartite graph consisting of {@link PTransformNode PTransformNodes} and
* {@link PCollectionNode PCollectionNodes}. Each {@link PCollectionNode} has exactly one in edge,
* and an arbitrary number of out edges. Each {@link PTransformNode} has an arbitrary number of in
* and out edges.
*
* <p>Parallel edges are permitted, as a {@link PCollectionNode} can be consumed by a single
* {@link PTransformNode} any number of times with different local names.
*/
private final Network<PipelineNode, PipelineEdge> pipelineNetwork;
private final LoadingCache<PipelineNode, Long> nodeWeights =
CacheBuilder.newBuilder()
.build(
new CacheLoader<PipelineNode, Long>() {
@Override
public Long load(PipelineNode node) throws Exception {
// root nodes have weight 1;
long weight = 1;
for (PipelineNode pred : pipelineNetwork.predecessors(node)) {
weight += nodeWeights.get(pred);
}
return weight;
}
});
private QueryablePipeline(Components allComponents) {
this.components = retainOnlyPrimitives(allComponents);
this.rehydratedComponents = RehydratedComponents.forComponents(this.components);
this.pipelineNetwork = buildNetwork(this.components);
}
/** Produces a {@link RunnerApi.Components} which contains only primitive transforms. */
@VisibleForTesting
static RunnerApi.Components retainOnlyPrimitives(RunnerApi.Components components) {
RunnerApi.Components.Builder flattenedBuilder = components.toBuilder();
flattenedBuilder.clearTransforms();
for (Map.Entry<String, PTransform> transformEntry : components.getTransformsMap().entrySet()) {
PTransform transform = transformEntry.getValue();
boolean isPrimitive = isPrimitiveTransform(transform);
if (isPrimitive) {
flattenedBuilder.putTransforms(transformEntry.getKey(), transform);
}
}
return flattenedBuilder.build();
}
/**
* Returns true if the provided transform is a primitive. A primitive has no subtransforms and
* produces a new {@link PCollection}.
*
* <p>Note that this precludes primitive transforms which only consume input and produce no
* PCollections as output.
*/
private static boolean isPrimitiveTransform(PTransform transform) {
return transform.getSubtransformsCount() == 0
&& !transform.getInputsMap().values().containsAll(transform.getOutputsMap().values());
}
private MutableNetwork<PipelineNode, PipelineEdge> buildNetwork(Components components) {
MutableNetwork<PipelineNode, PipelineEdge> network =
NetworkBuilder.directed()
.allowsParallelEdges(true)
.allowsSelfLoops(false)
.build();
Set<PCollectionNode> unproducedCollections = new HashSet<>();
for (Map.Entry<String, PTransform> transformEntry : components.getTransformsMap().entrySet()) {
String transformId = transformEntry.getKey();
PTransform transform = transformEntry.getValue();
PTransformNode transformNode =
PipelineNode.pTransform(transformId, this.components.getTransformsOrThrow(transformId));
network.addNode(transformNode);
for (String produced : transform.getOutputsMap().values()) {
PCollectionNode producedNode =
PipelineNode.pCollection(produced, components.getPcollectionsOrThrow(produced));
network.addNode(producedNode);
network.addEdge(transformNode, producedNode, new PerElementEdge());
checkState(
network.inDegree(producedNode) == 1,
"A %s should have exactly one producing %s, %s has %s",
PCollectionNode.class.getSimpleName(),
PTransformNode.class.getSimpleName(),
producedNode,
network.successors(producedNode));
unproducedCollections.remove(producedNode);
}
for (Map.Entry<String, String> consumed : transform.getInputsMap().entrySet()) {
// This loop may add an edge between the consumed PCollection and the current PTransform.
// The local name of the transform must be used to determine the type of edge.
String pcollectionId = consumed.getValue();
PCollectionNode consumedNode =
PipelineNode.pCollection(
pcollectionId, this.components.getPcollectionsOrThrow(pcollectionId));
if (network.addNode(consumedNode)) {
// This node has been added to the network for the first time, so it has no producer.
unproducedCollections.add(consumedNode);
}
if (getLocalSideInputNames(transform).contains(consumed.getKey())) {
network.addEdge(consumedNode, transformNode, new SingletonEdge());
} else {
network.addEdge(consumedNode, transformNode, new PerElementEdge());
}
}
}
checkState(
unproducedCollections.isEmpty(),
"%ss %s were consumed but never produced",
PCollectionNode.class.getSimpleName(),
unproducedCollections);
return network;
}
/**
* Return the set of all {@link PCollectionNode PCollection Nodes} which are consumed as side
* inputs.
*/
private Set<PCollectionNode> getConsumedAsSideInputs() {
return pipelineNetwork
.edges()
.stream()
.filter(edge -> !edge.isPerElement())
.map(edge -> (PCollectionNode) pipelineNetwork.incidentNodes(edge).source())
.collect(Collectors.toSet());
}
/**
* Get the transforms that are roots of this {@link QueryablePipeline}. These are all nodes which
* have no input {@link PCollection}.
*/
public Set<PTransformNode> getRootTransforms() {
return pipelineNetwork
.nodes()
.stream()
.filter(pipelineNode -> pipelineNetwork.inEdges(pipelineNode).isEmpty())
.map(pipelineNode -> (PTransformNode) pipelineNode)
.collect(Collectors.toSet());
}
public PTransformNode getProducer(PCollectionNode pcollection) {
return (PTransformNode) Iterables.getOnlyElement(pipelineNetwork.predecessors(pcollection));
}
/**
* Get all of the {@link PTransformNode PTransforms} which consume the provided {@link
* PCollectionNode} on a per-element basis.
*
* <p>If a {@link PTransformNode} consumes a {@link PCollectionNode} on a per-element basis one or
* more times, it will appear a single time in the result.
*
* <p>In theory, a transform may consume a single {@link PCollectionNode} in both a per-element
* and singleton manner. If this is the case, the transform node is included in the result, as it
* does consume the {@link PCollectionNode} on a per-element basis.
*/
public Set<PTransformNode> getPerElementConsumers(PCollectionNode pCollection) {
return pipelineNetwork
.successors(pCollection)
.stream()
.filter(
consumer ->
pipelineNetwork
.edgesConnecting(pCollection, consumer)
.stream()
.anyMatch(PipelineEdge::isPerElement))
.map(pipelineNode -> (PTransformNode) pipelineNode)
.collect(Collectors.toSet());
}
public Set<PCollectionNode> getOutputPCollections(PTransformNode ptransform) {
return pipelineNetwork
.successors(ptransform)
.stream()
.map(pipelineNode -> (PCollectionNode) pipelineNode)
.collect(Collectors.toSet());
}
public Components getComponents() {
return components;
}
/**
* Returns the {@link PCollectionNode PCollectionNodes} that the provided transform consumes as
* side inputs.
*/
public Collection<PCollectionNode> getSideInputs(PTransformNode transform) {
return getLocalSideInputNames(transform.getTransform())
.stream()
.map(localName -> {
String pcollectionId = transform.getTransform().getInputsOrThrow(localName);
return PipelineNode.pCollection(
pcollectionId, components.getPcollectionsOrThrow(pcollectionId));
})
.collect(Collectors.toSet());
}
private Set<String> getLocalSideInputNames(PTransform transform) {
if (PTransformTranslation.PAR_DO_TRANSFORM_URN.equals(transform.getSpec().getUrn())) {
try {
return ParDoPayload.parseFrom(transform.getSpec().getPayload()).getSideInputsMap().keySet();
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException(e);
}
} else {
return Collections.emptySet();
}
}
public Optional<Environment> getEnvironment(PTransformNode parDo) {
return Environments.getEnvironment(parDo.getTransform(), rehydratedComponents);
}
private interface PipelineEdge {
boolean isPerElement();
}
private static class PerElementEdge implements PipelineEdge {
@Override
public boolean isPerElement() {
return true;
}
}
private static class SingletonEdge implements PipelineEdge {
@Override
public boolean isPerElement() {
return false;
}
}
}
| fixup! Add a multi-stage fuser
| runners/core-construction-java/src/main/java/org/apache/beam/runners/core/construction/graph/QueryablePipeline.java | fixup! Add a multi-stage fuser |
|
Java | apache-2.0 | b4c2a4cd90fe2457694de722a38deb83a32c256c | 0 | Governance/rtgov-ui,Governance/rtgov-ui | /*
* Copyright 2013 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.monitoring.ui.server.services.impl;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.overlord.monitoring.ui.client.shared.beans.SituationsFilterBean;
import org.overlord.monitoring.ui.server.i18n.Messages;
import org.overlord.rtgov.activity.model.Context;
import org.overlord.rtgov.analytics.situation.Situation;
import org.overlord.rtgov.analytics.situation.Situation.Severity;
/**
* This class provides access to the situations db.
*
*/
public class SituationRepository {
private static final String OVERLORD_RTGOV_SITUATIONS = "overlord-rtgov-situations"; //$NON-NLS-1$
private static volatile Messages i18n = new Messages();
private EntityManagerFactory _entityManagerFactory=null;
private static final Logger LOG=Logger.getLogger(SituationRepository.class.getName());
/**
* The situation repository constructor.
*/
public SituationRepository() {
init();
}
/**
* Initialize the situation repository.
*/
protected void init() {
_entityManagerFactory = Persistence.createEntityManagerFactory(OVERLORD_RTGOV_SITUATIONS);
}
/**
* This method returns an entity manager.
*
* @return The entity manager
*/
protected EntityManager getEntityManager() {
return (_entityManagerFactory.createEntityManager());
}
/**
* This method closes the supplied entity manager.
*
* @param em The entity manager
*/
protected void closeEntityManager(EntityManager em) {
if (em != null) {
em.close();
}
}
/**
* This method returns the situation associated with the supplied id.
*
* @param id The id
* @return The situation, or null if not found
* @throws Exception Failed to get situation
*/
public Situation getSituation(String id) throws Exception {
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest(i18n.format("SituationsRepository.GetSit", id)); //$NON-NLS-1$
}
EntityManager em=getEntityManager();
Situation ret=null;
try {
ret=(Situation)em.createQuery("SELECT sit FROM Situation sit " //$NON-NLS-1$
+"WHERE sit.id = '"+id+"'") //$NON-NLS-1$ //$NON-NLS-2$
.getSingleResult();
// TODO: Temporary workaround until Situation model changed to use eager fetch
if (ret != null) {
loadSituation(ret);
}
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest(i18n.format("SituationsRepository.Result", ret)); //$NON-NLS-1$
}
} finally {
closeEntityManager(em);
}
return (ret);
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public java.util.List<Situation> getSituations(SituationsFilterBean filter) throws Exception {
java.util.List<Situation> ret=null;
EntityManager em=getEntityManager();
try {
// Build the query string
StringBuffer queryString=new StringBuffer();
if (filter.getSeverity() != null && filter.getSeverity().trim().length() > 0) {
queryString.append("sit.severity = :severity "); //$NON-NLS-1$
}
if (filter.getType() != null && filter.getType().trim().length() > 0) {
if (queryString.length() > 0) {
queryString.append("AND "); //$NON-NLS-1$
}
queryString.append("sit.type = '"+filter.getType()+"' "); //$NON-NLS-1$//$NON-NLS-2$
}
if (filter.getTimestampFrom() != null) {
if (queryString.length() > 0) {
queryString.append("AND "); //$NON-NLS-1$
}
queryString.append("sit.timestamp >= "+filter.getTimestampFrom().getTime()+" "); //$NON-NLS-1$//$NON-NLS-2$
}
if (filter.getTimestampTo() != null) {
if (queryString.length() > 0) {
queryString.append("AND "); //$NON-NLS-1$
}
queryString.append("sit.timestamp <= "+filter.getTimestampTo().getTime()+" "); //$NON-NLS-1$//$NON-NLS-2$
}
if (queryString.length() > 0) {
queryString.insert(0, "WHERE "); //$NON-NLS-1$
}
queryString.insert(0, "SELECT sit from Situation sit "); //$NON-NLS-1$
Query query=em.createQuery(queryString.toString());
if (filter.getSeverity() != null && filter.getSeverity().trim().length() > 0) {
String severityName=Character.toUpperCase(filter.getSeverity().charAt(0))
+filter.getSeverity().substring(1);
Severity severity=Severity.valueOf(severityName);
query.setParameter("severity", severity); //$NON-NLS-1$
}
ret = query.getResultList();
// TODO: Temporary workaround until Situation model changed to use eager fetch
for (Situation sit : ret) {
loadSituation(sit);
}
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest(i18n.format("SituationsRepository.SitResult", ret)); //$NON-NLS-1$
}
} finally {
closeEntityManager(em);
}
return (ret);
}
private void loadSituation(final Situation sit) {
try {
for (@SuppressWarnings("unused") Context c : sit.getContext()) {
}
for (@SuppressWarnings("unused") Object val : sit.getProperties().values()) {
}
} catch (Throwable t) {
// Ignore - may be due to change in API post ER4
}
}
}
| overlord-monitoring-war-eap61/src/main/java/org/overlord/monitoring/ui/server/services/impl/SituationRepository.java | /*
* Copyright 2013 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.monitoring.ui.server.services.impl;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.overlord.monitoring.ui.client.shared.beans.SituationsFilterBean;
import org.overlord.monitoring.ui.server.i18n.Messages;
import org.overlord.rtgov.activity.model.Context;
import org.overlord.rtgov.analytics.situation.Situation;
import org.overlord.rtgov.analytics.situation.Situation.Severity;
/**
* This class provides access to the situations db.
*
*/
public class SituationRepository {
private static final String OVERLORD_RTGOV_SITUATIONS = "overlord-rtgov-situations"; //$NON-NLS-1$
private static volatile Messages i18n = new Messages();
private EntityManagerFactory _entityManagerFactory=null;
private static final Logger LOG=Logger.getLogger(SituationRepository.class.getName());
/**
* The situation repository constructor.
*/
public SituationRepository() {
init();
}
/**
* Initialize the situation repository.
*/
protected void init() {
_entityManagerFactory = Persistence.createEntityManagerFactory(OVERLORD_RTGOV_SITUATIONS);
}
/**
* This method returns an entity manager.
*
* @return The entity manager
*/
protected EntityManager getEntityManager() {
return (_entityManagerFactory.createEntityManager());
}
/**
* This method closes the supplied entity manager.
*
* @param em The entity manager
*/
protected void closeEntityManager(EntityManager em) {
if (em != null) {
em.close();
}
}
/**
* This method returns the situation associated with the supplied id.
*
* @param id The id
* @return The situation, or null if not found
* @throws Exception Failed to get situation
*/
public Situation getSituation(String id) throws Exception {
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest(i18n.format("SituationsRepository.GetSit", id)); //$NON-NLS-1$
}
EntityManager em=getEntityManager();
Situation ret=null;
try {
ret=(Situation)em.createQuery("SELECT sit FROM Situation sit " //$NON-NLS-1$
+"WHERE sit.id = '"+id+"'") //$NON-NLS-1$ //$NON-NLS-2$
.getSingleResult();
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest(i18n.format("SituationsRepository.Result", ret)); //$NON-NLS-1$
}
} finally {
closeEntityManager(em);
}
return (ret);
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public java.util.List<Situation> getSituations(SituationsFilterBean filter) throws Exception {
java.util.List<Situation> ret=null;
EntityManager em=getEntityManager();
try {
// Build the query string
StringBuffer queryString=new StringBuffer();
if (filter.getSeverity() != null && filter.getSeverity().trim().length() > 0) {
queryString.append("sit.severity = :severity "); //$NON-NLS-1$
}
if (filter.getType() != null && filter.getType().trim().length() > 0) {
if (queryString.length() > 0) {
queryString.append("AND "); //$NON-NLS-1$
}
queryString.append("sit.type = '"+filter.getType()+"' "); //$NON-NLS-1$//$NON-NLS-2$
}
if (filter.getTimestampFrom() != null) {
if (queryString.length() > 0) {
queryString.append("AND "); //$NON-NLS-1$
}
queryString.append("sit.timestamp >= "+filter.getTimestampFrom().getTime()+" "); //$NON-NLS-1$//$NON-NLS-2$
}
if (filter.getTimestampTo() != null) {
if (queryString.length() > 0) {
queryString.append("AND "); //$NON-NLS-1$
}
queryString.append("sit.timestamp <= "+filter.getTimestampTo().getTime()+" "); //$NON-NLS-1$//$NON-NLS-2$
}
if (queryString.length() > 0) {
queryString.insert(0, "WHERE "); //$NON-NLS-1$
}
queryString.insert(0, "SELECT sit from Situation sit "); //$NON-NLS-1$
Query query=em.createQuery(queryString.toString());
if (filter.getSeverity() != null && filter.getSeverity().trim().length() > 0) {
String severityName=Character.toUpperCase(filter.getSeverity().charAt(0))
+filter.getSeverity().substring(1);
Severity severity=Severity.valueOf(severityName);
query.setParameter("severity", severity); //$NON-NLS-1$
}
ret = query.getResultList();
// TODO: Temporary workaround until Situation model changed to use eager fetch
try {
for (Situation sit : ret) {
for (@SuppressWarnings("unused") Context c : sit.getContext()) {
}
for (@SuppressWarnings("unused") Object val : sit.getProperties().values()) {
}
}
} catch (Throwable t) {
// Ignore - may be due to change in API post ER4
}
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest(i18n.format("SituationsRepository.SitResult", ret)); //$NON-NLS-1$
}
} finally {
closeEntityManager(em);
}
return (ret);
}
}
| Force loading of situations for both calls
| overlord-monitoring-war-eap61/src/main/java/org/overlord/monitoring/ui/server/services/impl/SituationRepository.java | Force loading of situations for both calls |
|
Java | apache-2.0 | 95b266f1c5fed337b054686c4ccd3d2d9e31f78d | 0 | database-rider/database-rider,database-rider/database-rider,database-rider/database-rider,database-rider/database-rider | /*
*
* The DbUnit Database Testing Framework
* Copyright (C)2002-2008, DbUnit.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package com.github.database.rider.core.dataset.builder;
import com.github.database.rider.core.configuration.DBUnitConfig;
import org.dbunit.dataset.*;
import org.dbunit.dataset.stream.BufferedConsumer;
import org.dbunit.dataset.stream.IDataSetConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import static com.github.database.rider.core.dataset.builder.BuilderUtil.convertCase;
public class DataSetBuilder {
private CachedDataSet dataSet = new CachedDataSet();
private IDataSetConsumer consumer = new BufferedConsumer(dataSet);
private final Map<String, TableMetaDataBuilder> tableNameToMetaData = new HashMap<>();
private final Logger LOGGER = LoggerFactory.getLogger(getClass().getName());
private final DBUnitConfig config;
private TableBuilder tableBuilder;
private final Map<String, Object> defaultValues = new HashMap<>();
private String currentTableName;
private final Map<String, Map<String, Object>> tableDefaultValues = new HashMap<>();
public DataSetBuilder() {
try {
consumer.startDataSet();
config = DBUnitConfig.fromGlobalConfig();
} catch (DataSetException e) {
LOGGER.error("Could not create DataSetBuilder.", e);
throw new RuntimeException("Could not create DataSetBuilder.", e);
}
}
/**
* Starts creating a dataset for the given table, ex:
* <pre>
* {@code
* builder.table("user")
* .row()
* .column("id", 1)
* .column("name", "@dbunit")
* }
* @param tableName
*/
public TableBuilder table(String tableName) {
tableBuilder = new TableBuilder(this, tableName);
return tableBuilder;
}
/**
* Creates a dbunit dataset for current builder
*/
public IDataSet build() {
try {
if (tableBuilder != null && !tableBuilder.getCurrentRowBuilder().isAdded() && tableBuilder.getCurrentRowBuilder().hasColumns()) {
add(tableBuilder.getCurrentRowBuilder());
tableBuilder.getCurrentRowBuilder().setAdded(true);
}
endTableIfNecessary();
consumer.endDataSet();
return dataSet;
} catch (DataSetException e) {
LOGGER.error("Could not create dataset.", e);
throw new RuntimeException("Could not create DataSet.", e);
}
}
/**
* Adds a previously created dataset to current builder
* @param iDataSet dbunit dataset
*/
public DataSetBuilder addDataSet(final IDataSet iDataSet) {
try {
IDataSet[] dataSets = {build(), iDataSet};
CompositeDataSet composite = new CompositeDataSet(dataSets);
this.dataSet = new CachedDataSet(composite);
consumer = new BufferedConsumer(this.dataSet);
return this;
} catch (DataSetException e) {
LOGGER.error("Could not add dataset.", e);
throw new RuntimeException("Could not add dataset.", e);
}
}
/**
* Add a previously created row to current dataset, ex:
* <pre>
* {@code
* RowBuilder user1Row = new DataSetBuilder().table("USER")
* .row()
* .column("id", "1")
* .column("name", "user1");
* RowBuilder user2Row = new DataSetBuilder().table("USER")
* .row()
* .column("id", "2")
* .column("name", "user2");
*
* IDataSet iDataSet = builder.add(user1Row).add(user2Row)
* }
* </pre>
*/
public DataSetBuilder add(BasicRowBuilder row) {
try {
fillUndefinedColumns(row);
ITableMetaData metaData = updateTableMetaData(row);
Object[] values = extractValues(row, metaData);
notifyConsumer(values);
return this;
} catch (DataSetException e) {
LOGGER.error("Could not add dataset row.", e);
throw new RuntimeException("Could not add dataset row.", e);
}
}
/**
* Adds a default value for the given column for all tables
* The default value will be used only if the column was not specified
*
* @param columnName
* @param value
*/
public DataSetBuilder defaultValue(String columnName, Object value) {
defaultValues.put(convertCase(columnName, config), value);
return this;
}
private Object[] extractValues(BasicRowBuilder row, ITableMetaData metaData) throws DataSetException {
return row.values(metaData.getColumns());
}
private void notifyConsumer(Object[] values) throws DataSetException {
consumer.row(values);
}
private ITableMetaData updateTableMetaData(BasicRowBuilder row) throws DataSetException {
TableMetaDataBuilder builder = metaDataBuilderFor(row.getTableName());
int previousNumberOfColumns = builder.numberOfColumns();
ITableMetaData metaData = builder.with(row.toMetaData()).build();
int newNumberOfColumns = metaData.getColumns().length;
boolean addedNewColumn = newNumberOfColumns > previousNumberOfColumns;
handleTable(metaData, addedNewColumn);
return metaData;
}
private void handleTable(ITableMetaData metaData, boolean addedNewColumn) throws DataSetException {
if (isNewTable(metaData.getTableName())) {
endTableIfNecessary();
startTable(metaData);
} else if (addedNewColumn) {
startTable(metaData);
}
}
private void startTable(ITableMetaData metaData) throws DataSetException {
currentTableName = metaData.getTableName();
consumer.startTable(metaData);
}
private void endTable() throws DataSetException {
consumer.endTable();
currentTableName = null;
}
private void endTableIfNecessary() throws DataSetException {
if (hasCurrentTable()) {
endTable();
}
}
private boolean hasCurrentTable() {
return currentTableName != null;
}
private boolean isNewTable(String tableName) {
return currentTableName == null || !convertCase(currentTableName, config).equals(convertCase(tableName, config));
}
private TableMetaDataBuilder metaDataBuilderFor(String tableName) {
String key = convertCase(tableName, config);
if (containsKey(key)) {
return tableNameToMetaData.get(key);
}
TableMetaDataBuilder builder = createNewTableMetaDataBuilder(tableName);
tableNameToMetaData.put(key, builder);
return builder;
}
protected TableMetaDataBuilder createNewTableMetaDataBuilder(String tableName) {
return new TableMetaDataBuilder(tableName);
}
private boolean containsKey(String key) {
return tableNameToMetaData.containsKey(key);
}
protected void fillUndefinedColumns(BasicRowBuilder row) {
if(!defaultValues.isEmpty()) {
for (String column : defaultValues.keySet()) {
if (!row.getColumnsValues().containsKey(column)) {
row.getColumnsValues().put(column, defaultValues.get(column));
}
}
}
if(hasDefaulValuesForTable(row.getTableName())) {
for (Map.Entry<String, Object> column : getDefaultValuesForTable(row.getTableName()).entrySet()) {
if (!row.getColumnsValues().containsKey(column.getKey())) {
row.getColumnsValues().put(column.getKey(), column.getValue());
}
}
}
}
protected boolean hasDefaulValuesForTable(String tableName) {
String key = tableName.toLowerCase();
return tableDefaultValues.containsKey(key);
}
protected Map<String, Object> getDefaultValuesForTable(String tableName) {
String key = tableName.toLowerCase();
if(!hasDefaulValuesForTable(key)) {
return new HashMap<>();
}
return tableDefaultValues.get(key);
}
protected void addTableDefaultValue(String tableName, String columnName, Object value) {
String key = tableName.toLowerCase();
if(!hasDefaulValuesForTable(key)) {
tableDefaultValues.put(key, new HashMap<String, Object>());
}
tableDefaultValues.get(key).put(convertCase(columnName, config), value);
}
}
| rider-core/src/main/java/com/github/database/rider/core/dataset/builder/DataSetBuilder.java | /*
*
* The DbUnit Database Testing Framework
* Copyright (C)2002-2008, DbUnit.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package com.github.database.rider.core.dataset.builder;
import com.github.database.rider.core.configuration.DBUnitConfig;
import org.dbunit.dataset.*;
import org.dbunit.dataset.stream.BufferedConsumer;
import org.dbunit.dataset.stream.IDataSetConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import static com.github.database.rider.core.dataset.builder.BuilderUtil.convertCase;
public class DataSetBuilder {
private CachedDataSet dataSet = new CachedDataSet();
private IDataSetConsumer consumer = new BufferedConsumer(dataSet);
private final Map<String, TableMetaDataBuilder> tableNameToMetaData = new HashMap<>();
private final Logger LOGGER = LoggerFactory.getLogger(getClass().getName());
private final DBUnitConfig config;
private TableBuilder tableBuilder;
private final Map<String, Object> defaultValues = new HashMap<>();
private String currentTableName;
private final Map<String, Map<String, Object>> tableDefaultValues = new HashMap<>();
public DataSetBuilder() {
try {
consumer.startDataSet();
config = DBUnitConfig.fromGlobalConfig();
} catch (DataSetException e) {
LOGGER.error("Could not create DataSetBuilder.", e);
throw new RuntimeException("Could not create DataSetBuilder.", e);
}
}
/**
* Starts creating a dataset for the given table, ex:
* <pre>
* {@code
* builder.table("user")
* .row()
* .column("id", 1)
* .column("name", "@dbunit")
* }
* @param tableName
*/
public TableBuilder table(String tableName) {
tableBuilder = new TableBuilder(this, tableName);
return tableBuilder;
}
/**
* Creates a dbunit dataset for current builder
*/
public IDataSet build() {
try {
if (tableBuilder != null && !tableBuilder.getCurrentRowBuilder().isAdded()) {
add(tableBuilder.getCurrentRowBuilder());
tableBuilder.getCurrentRowBuilder().setAdded(true);
}
endTableIfNecessary();
consumer.endDataSet();
return dataSet;
} catch (DataSetException e) {
LOGGER.error("Could not create dataset.", e);
throw new RuntimeException("Could not create DataSet.", e);
}
}
/**
* Adds a previously created dataset to current builder
* @param iDataSet dbunit dataset
*/
public DataSetBuilder addDataSet(final IDataSet iDataSet) {
try {
IDataSet[] dataSets = {build(), iDataSet};
CompositeDataSet composite = new CompositeDataSet(dataSets);
this.dataSet = new CachedDataSet(composite);
consumer = new BufferedConsumer(this.dataSet);
return this;
} catch (DataSetException e) {
LOGGER.error("Could not add dataset.", e);
throw new RuntimeException("Could not add dataset.", e);
}
}
/**
* Add a previously created row to current dataset, ex:
* <pre>
* {@code
* RowBuilder user1Row = new DataSetBuilder().table("USER")
* .row()
* .column("id", "1")
* .column("name", "user1");
* RowBuilder user2Row = new DataSetBuilder().table("USER")
* .row()
* .column("id", "2")
* .column("name", "user2");
*
* IDataSet iDataSet = builder.add(user1Row).add(user2Row)
* }
* </pre>
*/
public DataSetBuilder add(BasicRowBuilder row) {
try {
fillUndefinedColumns(row);
ITableMetaData metaData = updateTableMetaData(row);
Object[] values = extractValues(row, metaData);
notifyConsumer(values);
return this;
} catch (DataSetException e) {
LOGGER.error("Could not add dataset row.", e);
throw new RuntimeException("Could not add dataset row.", e);
}
}
/**
* Adds a default value for the given column for all tables
* The default value will be used only if the column was not specified
*
* @param columnName
* @param value
*/
public DataSetBuilder defaultValue(String columnName, Object value) {
defaultValues.put(convertCase(columnName, config), value);
return this;
}
private Object[] extractValues(BasicRowBuilder row, ITableMetaData metaData) throws DataSetException {
return row.values(metaData.getColumns());
}
private void notifyConsumer(Object[] values) throws DataSetException {
consumer.row(values);
}
private ITableMetaData updateTableMetaData(BasicRowBuilder row) throws DataSetException {
TableMetaDataBuilder builder = metaDataBuilderFor(row.getTableName());
int previousNumberOfColumns = builder.numberOfColumns();
ITableMetaData metaData = builder.with(row.toMetaData()).build();
int newNumberOfColumns = metaData.getColumns().length;
boolean addedNewColumn = newNumberOfColumns > previousNumberOfColumns;
handleTable(metaData, addedNewColumn);
return metaData;
}
private void handleTable(ITableMetaData metaData, boolean addedNewColumn) throws DataSetException {
if (isNewTable(metaData.getTableName())) {
endTableIfNecessary();
startTable(metaData);
} else if (addedNewColumn) {
startTable(metaData);
}
}
private void startTable(ITableMetaData metaData) throws DataSetException {
currentTableName = metaData.getTableName();
consumer.startTable(metaData);
}
private void endTable() throws DataSetException {
consumer.endTable();
currentTableName = null;
}
private void endTableIfNecessary() throws DataSetException {
if (hasCurrentTable()) {
endTable();
}
}
private boolean hasCurrentTable() {
return currentTableName != null;
}
private boolean isNewTable(String tableName) {
return currentTableName == null || !convertCase(currentTableName, config).equals(convertCase(tableName, config));
}
private TableMetaDataBuilder metaDataBuilderFor(String tableName) {
String key = convertCase(tableName, config);
if (containsKey(key)) {
return tableNameToMetaData.get(key);
}
TableMetaDataBuilder builder = createNewTableMetaDataBuilder(tableName);
tableNameToMetaData.put(key, builder);
return builder;
}
protected TableMetaDataBuilder createNewTableMetaDataBuilder(String tableName) {
return new TableMetaDataBuilder(tableName);
}
private boolean containsKey(String key) {
return tableNameToMetaData.containsKey(key);
}
protected void fillUndefinedColumns(BasicRowBuilder row) {
if(!defaultValues.isEmpty()) {
for (String column : defaultValues.keySet()) {
if (!row.getColumnsValues().containsKey(column)) {
row.getColumnsValues().put(column, defaultValues.get(column));
}
}
}
if(hasDefaulValuesForTable(row.getTableName())) {
for (Map.Entry<String, Object> column : getDefaultValuesForTable(row.getTableName()).entrySet()) {
if (!row.getColumnsValues().containsKey(column.getKey())) {
row.getColumnsValues().put(column.getKey(), column.getValue());
}
}
}
}
protected boolean hasDefaulValuesForTable(String tableName) {
String key = tableName.toLowerCase();
return tableDefaultValues.containsKey(key);
}
protected Map<String, Object> getDefaultValuesForTable(String tableName) {
String key = tableName.toLowerCase();
if(!hasDefaulValuesForTable(key)) {
return new HashMap<>();
}
return tableDefaultValues.get(key);
}
protected void addTableDefaultValue(String tableName, String columnName, Object value) {
String key = tableName.toLowerCase();
if(!hasDefaulValuesForTable(key)) {
tableDefaultValues.put(key, new HashMap<String, Object>());
}
tableDefaultValues.get(key).put(convertCase(columnName, config), value);
}
}
| refs #129
| rider-core/src/main/java/com/github/database/rider/core/dataset/builder/DataSetBuilder.java | refs #129 |
|
Java | apache-2.0 | 86cd2d6eabef2bdb15193b28fe51ee6c20e470ae | 0 | e-biz/gatling-liferay,e-biz/gatling-liferay,e-biz/gatling-liferay,e-biz/gatling-liferay | package com.excilys.liferay.gatling;
import com.excilys.liferay.gatling.model.Request;
import com.excilys.liferay.gatling.model.Scenario;
import com.excilys.liferay.gatling.model.Simulation;
import com.excilys.liferay.gatling.mustache.ScriptGeneratorGatling;
import com.excilys.liferay.gatling.service.RequestLocalServiceUtil;
import com.excilys.liferay.gatling.service.ScenarioLocalServiceUtil;
import com.excilys.liferay.gatling.service.SimulationLocalServiceUtil;
import com.excilys.liferay.gatling.util.DisplayLayout;
import com.excilys.liferay.gatling.util.DisplayLayoutUtil;
import com.excilys.liferay.gatling.util.GatlingUtil;
import com.excilys.liferay.gatling.util.IdDisplayLayout;
import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.HttpHeaders;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.Group;
import com.liferay.portal.model.Layout;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.service.LayoutLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.util.bridges.mvc.MVCPortlet;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;
import javax.portlet.ReadOnlyException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.ValidatorException;
/**
* Portlet implementation class GatlingPortlet.
*/
public class GatlingPortlet extends MVCPortlet {
/**
* attribute mustacheFoctory.
*/
private MustacheFactory mf = new DefaultMustacheFactory();
/**
* logging.
*/
private static final Log LOG = LogFactoryUtil.getLog(GatlingPortlet.class);
/**
* pages of portlet.
*/
protected String jspListSimulation, jspEditSimulation, jspEditScenario, jspFormFirstScenario, jspHelp;
/**
* get all name page and create the role 'gatling' on init portlet.
* @throws PortletException
*/
@Override
public void init() throws PortletException {
jspListSimulation = getInitParameter("list-simulation-jsp");
jspEditSimulation = getInitParameter("edit-simulation-jsp");
jspEditScenario = getInitParameter("edit-scenario-jsp");
jspFormFirstScenario = getInitParameter("form-first-scenario-jsp");
jspHelp = getInitParameter("help-jsp");
super.init();
}
/**
* Adds a new Simulation to the database.
*
* @param request
* @param response
* @throws Exception
*/
public void addSimulation(final ActionRequest request, final ActionResponse response) throws Exception {
Simulation simulation = SimulationLocalServiceUtil.addSimulationFromRequest(request, response);
if (simulation != null) {
int scenarioListSize = ScenarioLocalServiceUtil.countBySimulationId(simulation.getSimulation_id());
response.setRenderParameter("simulationId", Long.toString(simulation.getSimulation_id()));
// If new simulation the redirect to add First scenario page else edit simulation page
LOG.info("Simulation added");
response.setRenderParameter("page", scenarioListSize == 0 ? jspFormFirstScenario : jspEditSimulation);
} else {
LOG.debug("Simulation fails to add");
response.setRenderParameter("page", jspListSimulation);
}
}
/**
* edit simulation method
*
* @param request
* @param response
* @throws Exception
*/
public void editSimulation(ActionRequest request, ActionResponse response) throws Exception {
long simulationId = ParamUtil.getLong(request, "simulationId");
LOG.info("edit Simulation with id : " + simulationId);
Simulation simulation = SimulationLocalServiceUtil.getSimulation(simulationId);
simulation.setName(ParamUtil.getString(request, "simulationName"));
String variable = GatlingUtil.createVariableName("Simulation", ParamUtil.getString(request, "variableSimulationName"));
simulation.setVariableName(variable);
SimulationLocalServiceUtil.updateSimulation(simulation);
response.setRenderParameter("simulationId", Long.toString(simulationId));
response.setRenderParameter("page", jspEditSimulation);
}
/**
* remove simulation method
*
* @param request
* @param response
* @throws Exception
*/
public void removeSimulation(ActionRequest request, ActionResponse response) throws Exception {
long simulationId = ParamUtil.getLong(request, "simulationId");
if (LOG.isDebugEnabled()) {
LOG.debug("remove Simulation with id : " + simulationId);
}
SimulationLocalServiceUtil.removeSimulationCascade(simulationId);
response.setRenderParameter("page", jspListSimulation);
}
/**
* Add a new Scenario to the database.
* @param request
* @param response
* @throws Exception
*/
public void addScenario(final ActionRequest request, final ActionResponse response) throws Exception {
Scenario scenario = ScenarioLocalServiceUtil.addScenarioFromRequest(request, response);
String first = ParamUtil.getString(request, "first");
if (scenario != null) {
// redirect to editScenario
response.setRenderParameter("scenarioId", Long.toString(scenario.getScenario_id()));
response.setRenderParameter("page", jspEditScenario);
} else {
response.setRenderParameter("simulationId", Long.toString(ParamUtil.getLong(request, "simulationId")));
response.setRenderParameter("page", !first.equals("") ? jspFormFirstScenario : jspEditSimulation);
response.setRenderParameter("page", jspEditSimulation);
}
}
/**
* edit scenario.
*
* @param request
* @param response
* @throws SystemException
* @throws PortalException
*/
public void editScenario(final ActionRequest request, final ActionResponse response) throws SystemException, PortalException {
LOG.debug("edit scenario controler");
Scenario scenario = ScenarioLocalServiceUtil.editScenarioFromRequest(request, response);
response.setRenderParameter("page", scenario != null ? jspEditSimulation : jspListSimulation);
if (scenario != null) {
response.setRenderParameter("simulationId", Long.toString(scenario.getSimulation_id()));
}
}
/**
* Remove scenario from database.
* @param request
* @param response
* @throws PortalException
* @throws SystemException
*/
public void removeScenario(final ActionRequest request, final ActionResponse response)
throws PortalException, SystemException {
long scenarioId = ParamUtil.getLong(request, "scenarioId");
long simulationId = ParamUtil.getLong(request, "simulationId");
if (LOG.isDebugEnabled()){
LOG.debug("remove Scenario with id : " + scenarioId);
}
// cascade delete
ScenarioLocalServiceUtil.removeByIdCascade(scenarioId);
response.setRenderParameter("simulationId", Long.toString(simulationId));
response.setRenderParameter("page", jspEditSimulation);
}
/**
* Remove request from database.
* @param request
* @param response
* @throws PortalException
* @throws SystemException
*/
public void removeRequest(final ActionRequest request, final ActionResponse response) throws PortalException, SystemException {
long requestId = Long.parseLong(request.getParameter("requestId"));
RequestLocalServiceUtil.deleteRequest(requestId);
LOG.debug("request deleted succefully ");
}
/**
* get the scenario state, if completed or not yet.
* @param scenario
* @return
*/
private int scenarioState(Scenario scenario) {
try {
int count = RequestLocalServiceUtil.countByScenarioIdAndUsed(scenario.getScenario_id());
if (count != 0 && scenario.getDuration() != 0 && scenario.getUsers_per_seconds() != 0) {
// completed scenario = case if all minimal information are
// completed
return 2;
} else if (count != 0 && (scenario.getDuration() == 0 || scenario.getUsers_per_seconds() == 0)) {
// incomplete scenario = case if one or more information detail of
// scenario are not completed but there is request selected
return 1;
} else if ((count == 0)) {
//case if not request selected to that scenario = empty scenario
return 0;
}
// case if not request selected to that scenario = empty scenario
return 0;
} catch (SystemException e) {
if (LOG.isErrorEnabled()){
LOG.error("enable to determine Scenario state " + e.getMessage());
}
return 0;
}
}
/**
* get the simulation state, if all scenario are completed or not yet.
* @param simulation
* @return
*/
public int simulationState(final Simulation simulation) {
try {
List<Scenario> scenariosList = ScenarioLocalServiceUtil.findBySimulationId(simulation.getSimulation_id());
int checkNumberCompleted = 0;
for (Scenario scenario : scenariosList) {
if (scenarioState(scenario) == 2) {
checkNumberCompleted++;
}
}
if ((checkNumberCompleted == 0) || (scenariosList.size() == 0)) {
//if no one scenario is completed = simulation empty
return 0;
} else if (checkNumberCompleted == scenariosList.size()) {
//if all scenario completed = simulation complited
return 2;
} else {
//other case = simulation incompleted
return 1;
}
} catch (SystemException e) {
if (LOG.isErrorEnabled()) {
LOG.error("enable to determine Simulation state " + e.getMessage());
}
return 0;
}
}
/**
* View method : redirect to requested page and send necessary parameters.
*/
@Override
public void doView(final RenderRequest renderRequest, final RenderResponse renderResponse) throws IOException, PortletException {
/* get the path for next jsp or by default jspListSimulation */
String page = ParamUtil.get(renderRequest, "page", jspListSimulation);
//view.jsp => list of the simulations
if (page.equals(jspListSimulation)) {
LOG.debug("DoView : List Simulation");
List<Simulation> simulationList = new ArrayList<Simulation>();
Map<Simulation, Integer[]> simulationMap = new HashMap<Simulation, Integer[]>();
try {
simulationList = SimulationLocalServiceUtil.getSimulations(0, SimulationLocalServiceUtil.getSimulationsCount());
for (Simulation simulation : simulationList) {
Integer[] simulationInfos = new Integer[2];
List<Scenario> scenarioList = ScenarioLocalServiceUtil.findBySimulationId(simulation.getSimulation_id());
simulationInfos[0] = scenarioList.size();
simulationInfos[1] = simulationState(simulation);
simulationMap.put(simulation, simulationInfos);
}
} catch (SystemException e) {
throw new RuntimeException("error with getSimulation with localServiceUtil " + e.getMessage());
}
String JSListName = GatlingUtil.createJSListOfSimulationName(simulationList);
final PortletPreferences prefs = renderRequest.getPreferences();
String gatlingVersionString;
gatlingVersionString = prefs.getValue("gatlingVersion", null);
renderRequest.setAttribute("gatlingVersion", gatlingVersionString);
renderRequest.setAttribute("listOfSimulationName", JSListName);
renderRequest.setAttribute("listSimulation", simulationList);
renderRequest.setAttribute("MapSimulation", simulationMap);
} else if (page.equals(jspEditSimulation) || page.equals(jspFormFirstScenario)) {
/*
* Edit simulation, get and send scenarios list to jsp page
*/
LOG.debug("DoView : Edit Simulation");
Long id = (Long) ParamUtil.getLong(renderRequest, "simulationId");
if(id==null)
throw new NullPointerException("simulation id is null");
Simulation simulation;
try {
simulation = SimulationLocalServiceUtil.getSimulation(id);
renderRequest.setAttribute("simulation", simulation);
// List of Scenario
List<Scenario> scenarioList = ScenarioLocalServiceUtil.findBySimulationId(simulation.getSimulation_id());
// map <scenario, scenarioInfo>
Map<Scenario, Number[]> scenariosMap = new HashMap<Scenario, Number[]>();
for (Scenario scenario : scenarioList) {
Number[] info = new Number[3];
info[2] = scenarioState(scenario);
info[0] = RequestLocalServiceUtil.countByScenarioIdAndUsed(scenario.getScenario_id());
info[1] = RequestLocalServiceUtil.countByScenarioId(scenario.getScenario_id());
scenariosMap.put(scenario, info);
}
String JSListName = GatlingUtil.createJSListOfScenarioName(scenarioList);
renderRequest.setAttribute("listOfScenarioName", JSListName);
/*
* get list of simulation (for edit name)
*/
List<Simulation> listSimulations = SimulationLocalServiceUtil.getSimulations(0,
SimulationLocalServiceUtil.getSimulationsCount());
String JSListSimName = GatlingUtil.createJSListOfSimulationName(listSimulations);
renderRequest.setAttribute("listOfSimulationName", JSListSimName);
renderRequest.setAttribute("listScenario", scenarioList);
renderRequest.setAttribute("MapScenario", scenariosMap);
} catch (SystemException | PortalException e) {
throw new RuntimeException("error with get scenario list with localServiceUtil " + e.getMessage());
}
// List of Sites
List<Group> listGroups = GatlingUtil.getListOfSites();
renderRequest.setAttribute("listGroup", listGroups);
}else if (page.equals(jspEditScenario)) {
/*
* Edit scenario -> request list send to jsp page
*/
LOG.debug("DoView : Edit Scenario");
if (ParamUtil.getLong(renderRequest, "scenarioId") == 0) {
throw new NullPointerException("scenario id is null");
}
try {
// get scenario
Scenario scenario = ScenarioLocalServiceUtil.getScenario(ParamUtil.getLong(renderRequest, "scenarioId"));
Simulation simulation = SimulationLocalServiceUtil.getSimulation(scenario.getSimulation_id());
//update friendlyUrl of site if changed
String oldFriendlyURL = scenario.getUrl_site();
final ThemeDisplay themeDisplay = (ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
String currentFriendlyURL = GroupLocalServiceUtil.fetchGroup(scenario.getGroup_id()).getIconURL(themeDisplay);
currentFriendlyURL = currentFriendlyURL.split("/")[0]+"//"+currentFriendlyURL.split("/")[2]+"/web"+GroupLocalServiceUtil.fetchGroup(scenario.getGroup_id()).getFriendlyURL();
if (! oldFriendlyURL.equals(currentFriendlyURL)) {
//update site url
scenario.setUrl_site(currentFriendlyURL);
ScenarioLocalServiceUtil.updateScenario(scenario);
}
//get public layout list
long groupId = scenario.getGroup_id();
List<Layout> listPublicLayouts = LayoutLocalServiceUtil.getLayouts(groupId, false, 0);
// and private layouts
List<Layout> listPrivateLayouts = LayoutLocalServiceUtil.getLayouts(groupId, true, 0);
//get site name
String siteName = GroupLocalServiceUtil.getGroup(groupId).getName();
//create DisplayLayoutList with actuel layout(public and private) of the site and old layout added from requests
List<DisplayLayout> displayLayoutList = new ArrayList<DisplayLayout>();
DisplayLayoutUtil.addLayoutToDisplayLayoutList(displayLayoutList, listPublicLayouts);
DisplayLayoutUtil.addLayoutToDisplayLayoutList(displayLayoutList, listPrivateLayouts);
// Get Hierachy (used to add a button if a row is a parent)
Map<IdDisplayLayout, List<IdDisplayLayout>> hierachy = new LinkedHashMap<IdDisplayLayout, List<IdDisplayLayout>>();
DisplayLayoutUtil.mapHierachy(displayLayoutList, hierachy);
//get list of request to add the old page to DisplayLayout
List<Request> listRequests = RequestLocalServiceUtil.findByScenarioId(ParamUtil.get(renderRequest, "scenarioId", 0));
//Merge Layout and Request in DisplayLayout List
displayLayoutList = DisplayLayoutUtil.addRequestToDisplayLayoutList(displayLayoutList, listRequests);
// Get list of used names
List<Scenario> scenariolist = ScenarioLocalServiceUtil.getScenarios(0, ScenarioLocalServiceUtil.getScenariosCount());
String JSListName = GatlingUtil.createJSListOfScenarioName(scenariolist);
//add private and public url of site
String privateURL = scenario.getUrl_site().replace("web", "group");
String publicURL = scenario.getUrl_site();
//add request parameters
renderRequest.setAttribute("simulationName", simulation.getName());
renderRequest.setAttribute("scenario", scenario);
renderRequest.setAttribute("listPages", displayLayoutList);
renderRequest.setAttribute("hierachy", hierachy);
renderRequest.setAttribute("siteName", siteName);
renderRequest.setAttribute("privateURL", privateURL);
renderRequest.setAttribute("publicURL", publicURL);
renderRequest.setAttribute("listOfScenarioName", JSListName);
} catch (SystemException | PortalException e) {
throw new RuntimeException("connot get layout list: " + e.getMessage());
}
}
/* redirect to jsp page */
include(page, renderRequest, renderResponse);
}
/**
*
*/
@Override
public void serveResource(final ResourceRequest request, final ResourceResponse response) {
/*
* Get template from version
*/
int gatlingVersion = ParamUtil.getInteger(request, "gatlingVersion");
//add user preference
final PortletPreferences prefs = request.getPreferences();
try {
prefs.setValue("gatlingVersion", Integer.toString(gatlingVersion));
prefs.store();
} catch (ReadOnlyException | ValidatorException | IOException e) {
throw new RuntimeException("connot add user preferences for gatling version " + e.getMessage());
}
//scripting Gatling
String template;
switch (gatlingVersion) {
case 1:
template = "resources/templateGatling1.5.mustache";
break;
case 2:
template = "resources/templateGatling2.0.mustache";
break;
default:
template = "resources/templateGatling2.0.mustache";
break;
}
/*
* Get simulations ids
*/
long[] simulationsIds = ParamUtil.getLongValues(request, "export");
Simulation simulation;
Date date = new Date();
Mustache mustache = mf.compile(template);
if (simulationsIds.length > 1) {
response.setContentType("application/zip");
response.addProperty("Content-Disposition", "attachment; filename = GatlingSimulations" + date.getTime() + ".zip");
try {
ZipOutputStream zipOutputStream = new ZipOutputStream(response.getPortletOutputStream());
for (long id : simulationsIds) {
if (id > 0) {
simulation = SimulationLocalServiceUtil.getSimulation(id);
zipOutputStream.putNextEntry(new ZipEntry("Simulation" + simulation.getName() + date.getTime() + ".scala"));
mustache.execute(new PrintWriter(zipOutputStream), new ScriptGeneratorGatling(id)).flush();
zipOutputStream.closeEntry();
}
}
zipOutputStream.close();
} catch (Exception e) {
throw new RuntimeException("connot export zip for scenario(s) " + e.getMessage());
}
} else if (simulationsIds.length == 1 && simulationsIds[0] > 0) {
//create and export only one file with scenario script for this simulation id
response.setContentType("application/x-wais-source");
try {
simulation = SimulationLocalServiceUtil.getSimulation(simulationsIds[0]);
response.addProperty("Content-Disposition", "attachment; filename=Simulation" + simulation.getName() + date.getTime() + ".scala");
OutputStream out = response.getPortletOutputStream();
mustache.execute(new PrintWriter(out), new ScriptGeneratorGatling(simulationsIds[0])).flush();
out.close();
} catch (Exception e) {
throw new RuntimeException("connot export script file " + e.getMessage());
}
} else {
//if no one valide simulation id received then error
throw new NullPointerException("nothing to export");
}
response.addProperty(HttpHeaders.CACHE_CONTROL, "max-age=3600, must-revalidate");
}
} | liferay-plugins-sdk-gatling/portlets/gatling-liferay-portlet/docroot/WEB-INF/src/com/excilys/liferay/gatling/GatlingPortlet.java | package com.excilys.liferay.gatling;
import com.excilys.liferay.gatling.model.Request;
import com.excilys.liferay.gatling.model.Scenario;
import com.excilys.liferay.gatling.model.Simulation;
import com.excilys.liferay.gatling.mustache.ScriptGeneratorGatling;
import com.excilys.liferay.gatling.service.RequestLocalServiceUtil;
import com.excilys.liferay.gatling.service.ScenarioLocalServiceUtil;
import com.excilys.liferay.gatling.service.SimulationLocalServiceUtil;
import com.excilys.liferay.gatling.util.DisplayLayout;
import com.excilys.liferay.gatling.util.DisplayLayoutUtil;
import com.excilys.liferay.gatling.util.GatlingUtil;
import com.excilys.liferay.gatling.util.IdDisplayLayout;
import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.HttpHeaders;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.Group;
import com.liferay.portal.model.Layout;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.service.LayoutLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.util.bridges.mvc.MVCPortlet;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;
import javax.portlet.ReadOnlyException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.ValidatorException;
/**
* Portlet implementation class GatlingPortlet.
*/
public class GatlingPortlet extends MVCPortlet {
/**
* attribute mustacheFoctory.
*/
private MustacheFactory mf = new DefaultMustacheFactory();
/**
* logging.
*/
private static final Log LOG = LogFactoryUtil.getLog(GatlingPortlet.class);
/**
* pages of portlet.
*/
protected String jspListSimulation, jspEditSimulation, jspEditScenario, jspFormFirstScenario, jspHelp;
/**
* get all name page and create the role 'gatling' on init portlet.
* @throws PortletException
*/
@Override
public void init() throws PortletException {
jspListSimulation = getInitParameter("list-simulation-jsp");
jspEditSimulation = getInitParameter("edit-simulation-jsp");
jspEditScenario = getInitParameter("edit-scenario-jsp");
jspFormFirstScenario = getInitParameter("form-first-scenario-jsp");
jspHelp = getInitParameter("help-jsp");
super.init();
}
/**
* Adds a new Simulation to the database.
*
* @param request
* @param response
* @throws Exception
*/
public void addSimulation(final ActionRequest request, final ActionResponse response) throws Exception {
Simulation simulation = SimulationLocalServiceUtil.addSimulationFromRequest(request, response);
if (simulation != null) {
int scenarioListSize = ScenarioLocalServiceUtil.countBySimulationId(simulation.getSimulation_id());
response.setRenderParameter("simulationId", Long.toString(simulation.getSimulation_id()));
// If new simulation the redirect to add First scenario page else edit simulation page
LOG.info("Simulation added");
response.setRenderParameter("page", scenarioListSize == 0 ? jspFormFirstScenario : jspEditSimulation);
} else {
LOG.debug("Simulation fails to add");
response.setRenderParameter("page", jspListSimulation);
}
}
/**
* edit simulation method
*
* @param request
* @param response
* @throws Exception
*/
public void editSimulation(ActionRequest request, ActionResponse response) throws Exception {
long simulationId = ParamUtil.getLong(request, "simulationId");
LOG.info("edit Simulation with id : " + simulationId);
Simulation simulation = SimulationLocalServiceUtil.getSimulation(simulationId);
simulation.setName(ParamUtil.getString(request, "simulationName"));
String variable = GatlingUtil.createVariableName("Simulation", ParamUtil.getString(request, "variableSimulationName"));
simulation.setVariableName(variable);
SimulationLocalServiceUtil.updateSimulation(simulation);
response.setRenderParameter("simulationId", Long.toString(simulationId));
response.setRenderParameter("page", jspEditSimulation);
}
/**
* remove simulation method
*
* @param request
* @param response
* @throws Exception
*/
public void removeSimulation(ActionRequest request, ActionResponse response) throws Exception {
long simulationId = ParamUtil.getLong(request, "simulationId");
if (LOG.isDebugEnabled()) {
LOG.debug("remove Simulation with id : " + simulationId);
}
SimulationLocalServiceUtil.removeSimulationCascade(simulationId);
response.setRenderParameter("page", jspListSimulation);
}
/**
* Add a new Scenario to the database.
* @param request
* @param response
* @throws Exception
*/
public void addScenario(final ActionRequest request, final ActionResponse response) throws Exception {
Scenario scenario = ScenarioLocalServiceUtil.addScenarioFromRequest(request, response);
String first = ParamUtil.getString(request, "first");
if (scenario != null) {
// redirect to editScenario
response.setRenderParameter("scenarioId", Long.toString(scenario.getScenario_id()));
response.setRenderParameter("page", jspEditScenario);
} else {
response.setRenderParameter("simulationId", Long.toString(ParamUtil.getLong(request, "simulationId")));
response.setRenderParameter("page", !first.equals("") ? jspFormFirstScenario : jspEditSimulation);
response.setRenderParameter("page", jspEditSimulation);
}
}
/**
* edit scenario.
*
* @param request
* @param response
* @throws SystemException
* @throws PortalException
*/
public void editScenario(final ActionRequest request, final ActionResponse response) throws SystemException, PortalException {
LOG.debug("edit scenario controler");
Scenario scenario = ScenarioLocalServiceUtil.editScenarioFromRequest(request, response);
response.setRenderParameter("page", scenario != null ? jspEditSimulation : jspListSimulation);
if (scenario != null) {
response.setRenderParameter("simulationId", Long.toString(scenario.getSimulation_id()));
}
}
/**
* Remove scenario from database.
* @param request
* @param response
* @throws PortalException
* @throws SystemException
*/
public void removeScenario(final ActionRequest request, final ActionResponse response)
throws PortalException, SystemException {
long scenarioId = ParamUtil.getLong(request, "scenarioId");
long simulationId = ParamUtil.getLong(request, "simulationId");
if (LOG.isDebugEnabled()){
LOG.debug("remove Scenario with id : " + scenarioId);
}
// cascade delete
ScenarioLocalServiceUtil.removeByIdCascade(scenarioId);
response.setRenderParameter("simulationId", Long.toString(simulationId));
response.setRenderParameter("page", jspEditSimulation);
}
/**
* Remove request from database.
* @param request
* @param response
* @throws PortalException
* @throws SystemException
*/
public void removeRequest(final ActionRequest request, final ActionResponse response) throws PortalException, SystemException {
long requestId = Long.parseLong(request.getParameter("requestId"));
RequestLocalServiceUtil.deleteRequest(requestId);
LOG.debug("request deleted succefully ");
}
/**
* get the scenario state, if completed or not yet.
* @param scenario
* @return
*/
private int scenarioState(Scenario scenario) {
try {
int count = RequestLocalServiceUtil.countByScenarioIdAndUsed(scenario.getScenario_id());
if (count != 0 && scenario.getDuration() != 0 && scenario.getUsers_per_seconds() != 0) {
// completed scenario = case if all minimal information are
// completed
return 2;
} else if (count != 0 && (scenario.getDuration() == 0 || scenario.getUsers_per_seconds() == 0)) {
// incomplete scenario = case if one or more information detail of
// scenario are not completed but there is request selected
return 1;
} else if ((count == 0)) {
//case if not request selected to that scenario = empty scenario
return 0;
}
// case if not request selected to that scenario = empty scenario
return 0;
} catch (SystemException e) {
if (LOG.isErrorEnabled()){
LOG.error("enable to determine Scenario state " + e.getMessage());
}
return 0;
}
}
/**
* get the simulation state, if all scenario are completed or not yet.
* @param simulation
* @return
*/
public int simulationState(final Simulation simulation) {
try {
List<Scenario> scenariosList = ScenarioLocalServiceUtil.findBySimulationId(simulation.getSimulation_id());
int checkNumberCompleted = 0;
for (Scenario scenario : scenariosList) {
if (scenarioState(scenario) == 2) {
checkNumberCompleted++;
}
}
if ((checkNumberCompleted == 0) || (scenariosList.size() == 0)) {
//if no one scenario is completed = simulation empty
return 0;
} else if (checkNumberCompleted == scenariosList.size()) {
//if all scenario completed = simulation complited
return 2;
} else {
//other case = simulation incompleted
return 1;
}
} catch (SystemException e) {
if (LOG.isErrorEnabled()) {
LOG.error("enable to determine Simulation state " + e.getMessage());
}
return 0;
}
}
/**
* View method : redirect to requested page and send necessary parameters.
*/
@Override
public void doView(final RenderRequest renderRequest, final RenderResponse renderResponse) throws IOException, PortletException {
/* get the path for next jsp or by default jspListSimulation */
String page = ParamUtil.get(renderRequest, "page", jspListSimulation);
//view.jsp => list of the simulations
if (page.equals(jspListSimulation)) {
LOG.debug("DoView : List Simulation");
List<Simulation> simulationList = new ArrayList<Simulation>();
Map<Simulation, Integer[]> simulationMap = new HashMap<Simulation, Integer[]>();
try {
simulationList = SimulationLocalServiceUtil.getSimulations(0, SimulationLocalServiceUtil.getSimulationsCount());
for (Simulation simulation : simulationList) {
Integer[] simulationInfos = new Integer[2];
List<Scenario> scenarioList = ScenarioLocalServiceUtil.findBySimulationId(simulation.getSimulation_id());
simulationInfos[0] = scenarioList.size();
simulationInfos[1] = simulationState(simulation);
simulationMap.put(simulation, simulationInfos);
}
} catch (SystemException e) {
throw new RuntimeException("error with getSimulation with localServiceUtil " + e.getMessage());
}
String JSListName = GatlingUtil.createJSListOfSimulationName(simulationList);
final PortletPreferences prefs = renderRequest.getPreferences();
String gatlingVersionString;
gatlingVersionString = prefs.getValue("gatlingVersion", null);
renderRequest.setAttribute("gatlingVersion", gatlingVersionString);
renderRequest.setAttribute("listOfSimulationName", JSListName);
renderRequest.setAttribute("listSimulation", simulationList);
renderRequest.setAttribute("MapSimulation", simulationMap);
} else if (page.equals(jspEditSimulation) || page.equals(jspFormFirstScenario)) {
/*
* Edit simulation, get and send scenarios list to jsp page
*/
LOG.debug("DoView : Edit Simulation");
Long id = (Long) ParamUtil.getLong(renderRequest, "simulationId");
if(id==null)
throw new NullPointerException("simulation id is null");
Simulation simulation;
try {
simulation = SimulationLocalServiceUtil.getSimulation(id);
renderRequest.setAttribute("simulation", simulation);
// List of Scenario
List<Scenario> scenarioList = ScenarioLocalServiceUtil.findBySimulationId(simulation.getSimulation_id());
// map <scenario, scenarioInfo>
Map<Scenario, Number[]> scenariosMap = new HashMap<Scenario, Number[]>();
for (Scenario scenario : scenarioList) {
Number[] info = new Number[3];
info[2] = scenarioState(scenario);
info[0] = RequestLocalServiceUtil.countByScenarioIdAndUsed(scenario.getScenario_id());
info[1] = RequestLocalServiceUtil.countByScenarioId(scenario.getScenario_id());
scenariosMap.put(scenario, info);
}
String JSListName = GatlingUtil.createJSListOfScenarioName(scenarioList);
renderRequest.setAttribute("listOfScenarioName", JSListName);
/*
* get list of simulation (for edit name)
*/
List<Simulation> listSimulations = SimulationLocalServiceUtil.getSimulations(0,
SimulationLocalServiceUtil.getSimulationsCount());
String JSListSimName = GatlingUtil.createJSListOfSimulationName(listSimulations);
renderRequest.setAttribute("listOfSimulationName", JSListSimName);
renderRequest.setAttribute("listScenario", scenarioList);
renderRequest.setAttribute("MapScenario", scenariosMap);
} catch (SystemException | PortalException e) {
throw new RuntimeException("error with get scenario list with localServiceUtil " + e.getMessage());
}
// List of Sites
List<Group> listGroups = GatlingUtil.getListOfSites();
renderRequest.setAttribute("listGroup", listGroups);
}else if (page.equals(jspEditScenario)) {
/*
* Edit scenario -> request list send to jsp page
*/
LOG.debug("DoView : Edit Scenario");
if (ParamUtil.getLong(renderRequest, "scenarioId") == 0) {
throw new NullPointerException("scenario id is null");
}
try {
// get scenario
Scenario scenario = ScenarioLocalServiceUtil.getScenario(ParamUtil.getLong(renderRequest, "scenarioId"));
Simulation simulation = SimulationLocalServiceUtil.getSimulation(scenario.getSimulation_id());
//update freindlyUrl of site if changed
String oldFreindlyURL = scenario.getUrl_site();
final ThemeDisplay themeDisplay = (ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
String currentFreindlyURL = GroupLocalServiceUtil.fetchGroup(scenario.getGroup_id()).getIconURL(themeDisplay);
currentFreindlyURL = currentFreindlyURL.split("/")[0]+"//"+currentFreindlyURL.split("/")[2]+"/web"+GroupLocalServiceUtil.fetchGroup(scenario.getGroup_id()).getFriendlyURL();
if (! oldFreindlyURL.equals(currentFreindlyURL)) {
//update site url
scenario.setUrl_site(currentFreindlyURL);
ScenarioLocalServiceUtil.updateScenario(scenario);
}
//get public layout list
long groupId = scenario.getGroup_id();
List<Layout> listPublicLayouts = LayoutLocalServiceUtil.getLayouts(groupId, false, 0);
// and private layouts
List<Layout> listPrivateLayouts = LayoutLocalServiceUtil.getLayouts(groupId, true, 0);
//get site name
String siteName = GroupLocalServiceUtil.getGroup(groupId).getName();
//create DisplayLayoutList with actuel layout(public and private) of the site and old layout added from requests
List<DisplayLayout> displayLayoutList = new ArrayList<DisplayLayout>();
DisplayLayoutUtil.addLayoutToDisplayLayoutList(displayLayoutList, listPublicLayouts);
DisplayLayoutUtil.addLayoutToDisplayLayoutList(displayLayoutList, listPrivateLayouts);
// Get Hierachy (used to add a button if a row is a parent)
Map<IdDisplayLayout, List<IdDisplayLayout>> hierachy = new LinkedHashMap<IdDisplayLayout, List<IdDisplayLayout>>();
DisplayLayoutUtil.mapHierachy(displayLayoutList, hierachy);
//get list of request to add the old page to DisplayLayout
List<Request> listRequests = RequestLocalServiceUtil.findByScenarioId(ParamUtil.get(renderRequest, "scenarioId", 0));
//Merge Layout and Request in DisplayLayout List
displayLayoutList = DisplayLayoutUtil.addRequestToDisplayLayoutList(displayLayoutList, listRequests);
// Get list of used names
List<Scenario> scenariolist = ScenarioLocalServiceUtil.getScenarios(0, ScenarioLocalServiceUtil.getScenariosCount());
String JSListName = GatlingUtil.createJSListOfScenarioName(scenariolist);
//add private and public url of site
String privateURL = scenario.getUrl_site().replace("web", "group");
String publicURL = scenario.getUrl_site();
//add request parameters
renderRequest.setAttribute("simulationName", simulation.getName());
renderRequest.setAttribute("scenario", scenario);
renderRequest.setAttribute("listPages", displayLayoutList);
renderRequest.setAttribute("hierachy", hierachy);
renderRequest.setAttribute("siteName", siteName);
renderRequest.setAttribute("privateURL", privateURL);
renderRequest.setAttribute("publicURL", publicURL);
renderRequest.setAttribute("listOfScenarioName", JSListName);
} catch (SystemException | PortalException e) {
throw new RuntimeException("connot get layout list: " + e.getMessage());
}
}
/* redirect to jsp page */
include(page, renderRequest, renderResponse);
}
/**
*
*/
@Override
public void serveResource(final ResourceRequest request, final ResourceResponse response) {
/*
* Get template from version
*/
int gatlingVersion = ParamUtil.getInteger(request, "gatlingVersion");
//add user preference
final PortletPreferences prefs = request.getPreferences();
try {
prefs.setValue("gatlingVersion", Integer.toString(gatlingVersion));
prefs.store();
} catch (ReadOnlyException | ValidatorException | IOException e) {
throw new RuntimeException("connot add user preferences for gatling version " + e.getMessage());
}
//scripting Gatling
String template;
switch (gatlingVersion) {
case 1:
template = "resources/templateGatling1.5.mustache";
break;
case 2:
template = "resources/templateGatling2.0.mustache";
break;
default:
template = "resources/templateGatling2.0.mustache";
break;
}
/*
* Get simulations ids
*/
long[] simulationsIds = ParamUtil.getLongValues(request, "export");
Simulation simulation;
Date date = new Date();
Mustache mustache = mf.compile(template);
if (simulationsIds.length > 1) {
response.setContentType("application/zip");
response.addProperty("Content-Disposition", "attachment; filename = GatlingSimulations" + date.getTime() + ".zip");
try {
ZipOutputStream zipOutputStream = new ZipOutputStream(response.getPortletOutputStream());
for (long id : simulationsIds) {
if (id > 0) {
simulation = SimulationLocalServiceUtil.getSimulation(id);
zipOutputStream.putNextEntry(new ZipEntry("Simulation" + simulation.getName() + date.getTime() + ".scala"));
mustache.execute(new PrintWriter(zipOutputStream), new ScriptGeneratorGatling(id)).flush();
zipOutputStream.closeEntry();
}
}
zipOutputStream.close();
} catch (Exception e) {
throw new RuntimeException("connot export zip for scenario(s) " + e.getMessage());
}
} else if (simulationsIds.length == 1 && simulationsIds[0] > 0) {
//create and export only one file with scenario script for this simulation id
response.setContentType("application/x-wais-source");
try {
simulation = SimulationLocalServiceUtil.getSimulation(simulationsIds[0]);
response.addProperty("Content-Disposition", "attachment; filename=Simulation" + simulation.getName() + date.getTime() + ".scala");
OutputStream out = response.getPortletOutputStream();
mustache.execute(new PrintWriter(out), new ScriptGeneratorGatling(simulationsIds[0])).flush();
out.close();
} catch (Exception e) {
throw new RuntimeException("connot export script file " + e.getMessage());
}
} else {
//if no one valide simulation id received then error
throw new NullPointerException("nothing to export");
}
response.addProperty(HttpHeaders.CACHE_CONTROL, "max-age=3600, must-revalidate");
}
} | correction freind->friend
| liferay-plugins-sdk-gatling/portlets/gatling-liferay-portlet/docroot/WEB-INF/src/com/excilys/liferay/gatling/GatlingPortlet.java | correction freind->friend |
|
Java | apache-2.0 | e34a9c70f728947dc19e58e57167c30e8c91bb53 | 0 | MalharJenkins/incubator-apex-core,devtagare/incubator-apex-core,apache/incubator-apex-core,mattqzhang/apex-core,tweise/incubator-apex-core,sandeshh/apex-core,apache/incubator-apex-core,PramodSSImmaneni/incubator-apex-core,tushargosavi/apex-core,apache/incubator-apex-core,vrozov/incubator-apex-core,sandeshh/apex-core,mt0803/incubator-apex-core,klynchDS/incubator-apex-core,mattqzhang/apex-core,vrozov/apex-core,brightchen/incubator-apex-core,tushargosavi/incubator-apex-core,MalharJenkins/incubator-apex-core,aniruddhas/incubator-apex-core,simplifi-it/otterx,ishark/incubator-apex-core,sandeshh/apex-core,deepak-narkhede/apex-core,PramodSSImmaneni/apex-core,mt0803/incubator-apex-core,sandeshh/incubator-apex-core,tweise/incubator-apex-core,ishark/incubator-apex-core,devtagare/incubator-apex-core,deepak-narkhede/apex-core,tushargosavi/apex-core,tushargosavi/apex-core,tweise/incubator-apex-core,tushargosavi/incubator-apex-core,PramodSSImmaneni/apex-core,brightchen/apex-core,vrozov/incubator-apex-core,brightchen/incubator-apex-core,tushargosavi/incubator-apex-core,klynchDS/incubator-apex-core,simplifi-it/otterx,andyperlitch/incubator-apex-core,vrozov/incubator-apex-core,vrozov/apex-core,deepak-narkhede/apex-core,chinmaykolhatkar/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,PramodSSImmaneni/incubator-apex-core,mattqzhang/apex-core,tweise/apex-core,simplifi-it/otterx,sandeshh/incubator-apex-core,amberarrow/incubator-apex-core,andyperlitch/incubator-apex-core,brightchen/apex-core,PramodSSImmaneni/incubator-apex-core,aniruddhas/incubator-apex-core,tweise/apex-core,brightchen/apex-core,vrozov/apex-core,tweise/apex-core,amberarrow/incubator-apex-core,PramodSSImmaneni/apex-core,chinmaykolhatkar/incubator-apex-core,devtagare/incubator-apex-core,sandeshh/incubator-apex-core,ishark/incubator-apex-core | /**
* Copyright (c) 2012 Malhar, Inc. All rights reserved.
*/
package com.malhartech.stream;
import com.malhartech.api.Sink;
import com.malhartech.api.StreamCodec;
import com.malhartech.api.StreamCodec.DataStatePair;
import com.malhartech.bufferserver.client.Subscriber;
import com.malhartech.engine.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implement tuple flow from buffer server to the node in a logical stream<p>
* <br>
* Extends SocketInputStream as buffer server and node communicate via a socket<br>
* This buffer server is a read instance of a stream and takes care of connectivity with upstream buffer server<br>
*/
public class BufferServerSubscriber extends Subscriber implements Stream<Object>
{
private final HashMap<String, Sink<Object>> outputs = new HashMap<String, Sink<Object>>();
private long baseSeconds; // needed here
private int lastWindowId = WindowGenerator.MAX_WINDOW_ID;
@SuppressWarnings("VolatileArrayField")
private volatile Sink<Object>[] sinks = NO_SINKS;
private Sink<Object>[] emergencySinks = NO_SINKS;
private Sink<Object>[] normalSinks = NO_SINKS;
private StreamCodec<Object> serde;
DataStatePair dsp = new DataStatePair();
public BufferServerSubscriber(String id)
{
super(id);
}
@Override
public void activate(StreamContext context)
{
logger.debug("registering subscriber: id={} upstreamId={} streamLogicalName={} windowId={} mask={} partitions={} server={}", new Object[] {context.getSinkId(), context.getSourceId(), context.getId(), context.getStartingWindowId(), context.getPartitionMask(), context.getPartitions(), context.getBufferServerAddress()});
baseSeconds = context.getStartingWindowId() & 0xffffffff00000000L;
serde = context.attr(StreamContext.CODEC).get();
activateSinks();
activate(context.getId() + '/' + context.getSinkId(), context.getSourceId(), context.getPartitionMask(), context.getPartitions(), context.getStartingWindowId());
}
@Override
public void onMessage(byte[] buffer, int offset, int size)
{
com.malhartech.bufferserver.packet.Tuple data = com.malhartech.bufferserver.packet.Tuple.getTuple(buffer, offset, size);
Tuple t;
switch (data.getType()) {
case CHECKPOINT:
serde.resetState();
return;
case CODEC_STATE:
dsp.state = data.getData();
return;
case PAYLOAD:
dsp.data = data.getData();
Object o = serde.fromByteArray(dsp);
distribute(o);
return;
case END_WINDOW:
//logger.debug("received {}", data);
t = new EndWindowTuple();
t.setWindowId(baseSeconds | (lastWindowId = data.getWindowId()));
break;
case END_STREAM:
t = new EndStreamTuple();
t.setWindowId(baseSeconds | data.getWindowId());
break;
case RESET_WINDOW:
baseSeconds = (long)data.getBaseSeconds() << 32;
if (lastWindowId < WindowGenerator.MAX_WINDOW_ID) {
return;
}
t = new ResetWindowTuple();
t.setWindowId(baseSeconds | data.getWindowWidth());
break;
case BEGIN_WINDOW:
logger.debug("received {}", data);
t = new Tuple(data.getType());
t.setWindowId(baseSeconds | data.getWindowId());
break;
case NO_MESSAGE:
return;
default:
throw new IllegalArgumentException("Unhandled Message Type " + data.getType());
}
distribute(t);
}
@Override
@SuppressWarnings("unchecked")
public synchronized void setSink(String id, Sink<Object> sink)
{
if (sink == null) {
outputs.remove(id);
if (outputs.isEmpty()) {
sinks = NO_SINKS;
}
}
else {
outputs.put(id, (Sink)sink);
if (sinks != NO_SINKS) {
activateSinks();
}
}
}
@Override
public boolean isMultiSinkCapable()
{
return true;
}
void activateSinks()
{
@SuppressWarnings("unchecked")
Sink<Object>[] newSinks = (Sink<Object>[])Array.newInstance(Sink.class, outputs.size());
int i = 0;
for (final Sink<Object> s: outputs.values()) {
newSinks[i++] = s;
}
sinks = newSinks;
}
@Override
public void process(Object tuple)
{
throw new IllegalAccessError("Attempt to pass payload " + tuple + " to " + this + " from source other than buffer server!");
}
@Override
public void setup(StreamContext context)
{
super.setup(context.getBufferServerAddress(), context.attr(StreamContext.EVENT_LOOP).get());
}
@SuppressWarnings("unchecked")
void distribute(Object o)
{
int i = sinks.length;
try {
while (i-- > 0) {
sinks[i].process(o);
}
}
catch (IllegalStateException ise) {
suspendRead();
if (emergencySinks.length != sinks.length) {
emergencySinks = (Sink<Object>[])Array.newInstance(Sink.class, sinks.length);
}
for (int n = emergencySinks.length; n-- > 0;) {
emergencySinks[n] = new EmergencySink();
if (n <= i) {
emergencySinks[n].process(o);
}
}
normalSinks = sinks;
sinks = emergencySinks;
}
}
@Override
public void endMessage()
{
if (sinks == emergencySinks) {
new Thread("EmergencyThread")
{
final Sink<Object>[] esinks = emergencySinks;
@Override
@SuppressWarnings({"NestedSynchronizedStatement", "UnusedAssignment"})
public void run()
{
synchronized (BufferServerSubscriber.this) {
boolean iterate = false;
do {
try {
for (int n = esinks.length; n-- > 0;) {
@SuppressWarnings("unchecked")
final ArrayList<Object> list = (ArrayList<Object>)esinks[n];
synchronized (list) {
Iterator<Object> iterator = list.iterator();
while (iterator.hasNext()) {
iterate = true;
normalSinks[n].process(iterator.next()); /* this can throw an exception */
iterate = false;
iterator.remove();
}
}
}
}
catch (IllegalStateException ise) {
}
}
while (iterate);
sinks = normalSinks;
}
resumeRead();
}
}.start();
}
}
private class EmergencySink extends ArrayList<Object> implements Sink<Object>
{
private static final long serialVersionUID = 201304031531L;
@Override
public synchronized void process(Object tuple)
{
add(tuple);
}
}
private static final Logger logger = LoggerFactory.getLogger(BufferServerSubscriber.class);
}
| engine/src/main/java/com/malhartech/stream/BufferServerSubscriber.java | /**
* Copyright (c) 2012 Malhar, Inc. All rights reserved.
*/
package com.malhartech.stream;
import com.malhartech.api.Sink;
import com.malhartech.api.StreamCodec;
import com.malhartech.api.StreamCodec.DataStatePair;
import com.malhartech.bufferserver.client.Subscriber;
import com.malhartech.engine.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implement tuple flow from buffer server to the node in a logical stream<p>
* <br>
* Extends SocketInputStream as buffer server and node communicate via a socket<br>
* This buffer server is a read instance of a stream and takes care of connectivity with upstream buffer server<br>
*/
public class BufferServerSubscriber extends Subscriber implements Stream<Object>
{
private final HashMap<String, Sink<Object>> outputs = new HashMap<String, Sink<Object>>();
private long baseSeconds; // needed here
private int lastWindowId = WindowGenerator.MAX_WINDOW_ID;
@SuppressWarnings("VolatileArrayField")
private volatile Sink<Object>[] sinks = NO_SINKS;
private Sink<Object>[] emergencySinks = NO_SINKS;
private Sink<Object>[] normalSinks = NO_SINKS;
private StreamCodec<Object> serde;
DataStatePair dsp = new DataStatePair();
public BufferServerSubscriber(String id)
{
super(id);
}
@Override
public void activate(StreamContext context)
{
logger.debug("registering subscriber: id={} upstreamId={} streamLogicalName={} windowId={} mask={} partitions={} server={}", new Object[] {context.getSinkId(), context.getSourceId(), context.getId(), context.getStartingWindowId(), context.getPartitionMask(), context.getPartitions(), context.getBufferServerAddress()});
baseSeconds = context.getStartingWindowId() & 0xffffffff00000000L;
serde = context.attr(StreamContext.CODEC).get();
activateSinks();
activate(context.getId() + '/' + context.getSinkId(), context.getSourceId(), context.getPartitionMask(), context.getPartitions(), context.getStartingWindowId());
}
@Override
public void onMessage(byte[] buffer, int offset, int size)
{
com.malhartech.bufferserver.packet.Tuple data = com.malhartech.bufferserver.packet.Tuple.getTuple(buffer, offset, size);
Tuple t;
switch (data.getType()) {
case CHECKPOINT:
serde.resetState();
return;
case CODEC_STATE:
dsp.state = data.getData();
return;
case PAYLOAD:
dsp.data = data.getData();
Object o = serde.fromByteArray(dsp);
distribute(o);
return;
case END_WINDOW:
//logger.debug("received {}", data);
t = new EndWindowTuple();
t.setWindowId(baseSeconds | (lastWindowId = data.getWindowId()));
break;
case END_STREAM:
t = new EndStreamTuple();
t.setWindowId(baseSeconds | data.getWindowId());
break;
case RESET_WINDOW:
baseSeconds = (long)data.getBaseSeconds() << 32;
if (lastWindowId < WindowGenerator.MAX_WINDOW_ID) {
return;
}
t = new ResetWindowTuple();
t.setWindowId(baseSeconds | data.getWindowWidth());
break;
case BEGIN_WINDOW:
//logger.debug("received {}", data);
t = new Tuple(data.getType());
t.setWindowId(baseSeconds | data.getWindowId());
break;
case NO_MESSAGE:
return;
default:
throw new IllegalArgumentException("Unhandled Message Type " + data.getType());
}
distribute(t);
}
@Override
@SuppressWarnings("unchecked")
public synchronized void setSink(String id, Sink<Object> sink)
{
if (sink == null) {
outputs.remove(id);
if (outputs.isEmpty()) {
sinks = NO_SINKS;
}
}
else {
outputs.put(id, (Sink)sink);
if (sinks != NO_SINKS) {
activateSinks();
}
}
}
@Override
public boolean isMultiSinkCapable()
{
return true;
}
void activateSinks()
{
logger.debug("activating sinks = {} on {}", outputs);
@SuppressWarnings("unchecked")
Sink<Object>[] newSinks = (Sink<Object>[])Array.newInstance(Sink.class, outputs.size());
int i = 0;
for (final Sink<Object> s: outputs.values()) {
newSinks[i++] = s;
}
sinks = newSinks;
}
@Override
public void process(Object tuple)
{
throw new IllegalAccessError("Attempt to pass payload " + tuple + " to " + this + " from source other than buffer server!");
}
@Override
public void setup(StreamContext context)
{
super.setup(context.getBufferServerAddress(), context.attr(StreamContext.EVENT_LOOP).get());
}
@SuppressWarnings("unchecked")
void distribute(Object o)
{
int i = sinks.length;
try {
while (i-- > 0) {
sinks[i].process(o);
}
}
catch (IllegalStateException ise) {
suspendRead();
if (emergencySinks.length != sinks.length) {
emergencySinks = (Sink<Object>[])Array.newInstance(Sink.class, sinks.length);
}
for (int n = emergencySinks.length; n-- > 0;) {
emergencySinks[n] = new EmergencySink();
if (n <= i) {
emergencySinks[n].process(o);
}
}
normalSinks = sinks;
sinks = emergencySinks;
}
}
@Override
public void endMessage()
{
if (sinks == emergencySinks) {
new Thread("EmergencyThread")
{
final Sink<Object>[] esinks = emergencySinks;
@Override
@SuppressWarnings({"NestedSynchronizedStatement", "UnusedAssignment"})
public void run()
{
synchronized (BufferServerSubscriber.this) {
boolean iterate = false;
do {
try {
for (int n = esinks.length; n-- > 0;) {
@SuppressWarnings("unchecked")
final ArrayList<Object> list = (ArrayList<Object>)esinks[n];
synchronized (list) {
Iterator<Object> iterator = list.iterator();
while (iterator.hasNext()) {
iterate = true;
normalSinks[n].process(iterator.next()); /* this can throw an exception */
iterate = false;
iterator.remove();
}
}
}
}
catch (IllegalStateException ise) {
}
}
while (iterate);
sinks = normalSinks;
}
resumeRead();
}
}.start();
}
}
private class EmergencySink extends ArrayList<Object> implements Sink<Object>
{
private static final long serialVersionUID = 201304031531L;
@Override
public synchronized void process(Object tuple)
{
add(tuple);
}
}
private static final Logger logger = LoggerFactory.getLogger(BufferServerSubscriber.class);
}
| added debugging. | engine/src/main/java/com/malhartech/stream/BufferServerSubscriber.java | added debugging. |
|
Java | apache-2.0 | ccefce413b236f8cf893c6df337fb4ae26efded0 | 0 | trejkaz/derby,trejkaz/derby,apache/derby,apache/derby,apache/derby,apache/derby,trejkaz/derby | /*
*
* Derby - Class org.apache.derbyTesting.functionTests.tests.lang.XMLTypeAndOpsTest
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package org.apache.derbyTesting.functionTests.tests.lang;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.XML;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.BaseJDBCTestSetup;
import org.apache.derbyTesting.junit.TestConfiguration;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Types;
/**
* XMLTypeAndOpsTest this test is the JUnit equivalent to what used
* to be the "lang/xml_general.sql" test, which was canon-based.
* Since the .sql test had different masters for embedded, JCC, and
* Derby Client, and since it performed some "sed'ing" to ensure
* consistent results across JVMs, it was not sufficient to just
* wrap the test in a JUnit ScriptTestCase (because ScriptTestCase
* doesn't deal with multiple masters nor with sed'ing). Hence the
* creation of this pure JUnit version of the test.
*/
public final class XMLTypeAndOpsTest extends BaseJDBCTestCase {
/* For the test methods in this class, "expRS" refers to a
* two-dimensional array representing an expected result set when
* executing queries. The "rows" and "columns" in this array
* are compard with those from a SQL ResultSet. Note that all
* values are represented as Strings here; we don't actually
* check the *types* of the columns; just their values. This
* is because this test was created from a .sql test, where
* results are similarly treated (i.e. in an ij test with a
* .sql file, the test passes if the values "look the same";
* there's no checking of specific value types for most query
* results. So we do the same for this JUnit test).
*/
/**
* Public constructor required for running test as standalone JUnit.
*/
public XMLTypeAndOpsTest(String name)
{
super(name);
}
/**
* Return a suite that runs a set of tests which are meant to
* be the equivalent to the test cases in the old xml_general.sql.
* But only return such a suite IF the testing classpath has the
* required XML classes. Otherwise just return an empty suite.
*/
public static Test suite()
{
TestSuite suite = new TestSuite("XML Type and Operators Suite\n");
if (!XML.classpathMeetsXMLReqs())
return suite;
/* "false" in the next line means that we will *not* clean the
* database before the embedded and client suites. This ensures
* that we do not remove the objects created by XMLTestSetup.
*/
suite.addTest(
TestConfiguration.defaultSuite(XMLTypeAndOpsTest.class, false));
return (new XMLTestSetup(suite));
}
/**
* Test creation of XML columns.
*/
public void testXMLColCreation() throws Exception
{
// If the column's definition doesn't make sense for XML,
// then we should throw the correct error.
Statement st = createStatement();
assertStatementError("42894", st,
"create table fail1 (i int, x xml default 'oops')");
assertStatementError("42894", st,
"create table fail2 (i int, x xml default 8)");
assertStatementError("42818", st,
"create table fail3 (i int, x xml check (x != 0))");
// These should all work.
st.executeUpdate("create table tc1 (i int, x xml)");
st.executeUpdate("create table tc2 (i int, x xml not null)");
st.executeUpdate("create table tc3 (i int, x xml default null)");
st.executeUpdate("create table tc4 (x2 xml not null)");
st.executeUpdate("alter table tc4 add column x1 xml");
// Cleanup.
st.executeUpdate("drop table tc1");
st.executeUpdate("drop table tc2");
st.executeUpdate("drop table tc3");
st.executeUpdate("drop table tc4");
st.close();
}
/**
* Check insertion of null values into XML columns. This
* test just checks the negative cases--i.e. cases where
* we expect the insertions to fail. The positive cases
* are tested implicitly as part of XMLTestSetup.setUp()
* when we load the test data.
*/
public void testIllegalNullInserts() throws Exception
{
// These should fail because target column is declared
// as non-null.
Statement st = createStatement();
st.executeUpdate("create table tc2 (i int, x xml not null)");
assertStatementError("23502", st, "insert into tc2 values (1, null)");
assertStatementError("23502", st,
"insert into tc2 values (2, cast (null as xml))");
st.executeUpdate("drop table tc2");
st.close();
}
/**
* Test insertion of non-XML values into XML columns. These
* should all fail because such an operation is not allowed.
*/
public void testXMLColsWithNonXMLVals() throws Exception
{
Statement st = createStatement();
assertStatementError("42821", st, "insert into t1 values (3, 'hmm')");
assertStatementError("42821", st, "insert into t1 values (1, 2)");
assertStatementError("42821", st,
" insert into t1 values (1, 123.456)");
assertStatementError("42821", st, "insert into t1 values (1, x'01')");
assertStatementError("42821", st, "insert into t1 values (1, x'ab')");
assertStatementError("42821", st,
"insert into t1 values (1, current date)");
assertStatementError("42821", st,
" insert into t1 values (1, current time)");
assertStatementError("42821", st,
" insert into t1 values (1, current timestamp)");
assertStatementError("42821", st,
" insert into t1 values (1, ('hmm' || 'andstuff'))");
st.close();
}
/**
* Test insertion of XML values into non-XML columns. These
* should all fail because such an operation is not allowed.
*/
public void testNonXMLColsWithXMLVals() throws Exception
{
Statement st = createStatement();
st.executeUpdate(
"create table nonXTable (si smallint, i int, bi bigint, vcb "
+ "varchar (32) for bit data, nu numeric(10,2), f "
+ "float, d double, vc varchar(20), da date, ti time, "
+ "ts timestamp, cl clob, bl blob)");
assertStatementError("42821", st,
"insert into nonXTable (si) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (i) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (bi) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (vcb) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (nu) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (f) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (d) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (vc) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (da) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (ti) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (ts) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (cl) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (bl) values (cast (null as xml))");
// And just to be safe, try to insert a non-null XML
// value. This should fail, too.
assertStatementError("42821", st,
"insert into nonXTable (cl) values (xmlparse(document " +
"'</simp>' preserve whitespace))");
st.executeUpdate("drop table nonXTable");
st.close();
}
/**
* Test casting of values to type XML. These should all
* fail because such casting is not allowed.
*/
public void testXMLCasting() throws Exception
{
Statement st = createStatement();
assertStatementError("42846", st,
"insert into t1 values (1, cast ('hmm' as xml))");
assertStatementError("42846", st,
"insert into t1 values (1, cast (2 as xml))");
assertStatementError("42846", st,
"insert into t1 values (1, cast (123.456 as xml))");
assertStatementError("42846", st,
"insert into t1 values (1, cast (x'01' as xml))");
assertStatementError("42846", st,
"insert into t1 values (1, cast (x'ab' as xml))");
assertStatementError("42846", st,
"insert into t1 values (1, cast (current date as xml))");
assertStatementError("42846", st,
"insert into t1 values (1, cast (current time as xml))");
assertStatementError("42846", st,
"insert into t1 values (1, cast (current timestamp as xml))");
assertStatementError("42846", st,
"insert into t1 values (1, cast (('hmm' || "
+ "'andstuff') as xml))");
// And try to cast an XML value into something else.
// These should fail, too.
st.executeUpdate("create table nonXTable (i int, cl clob)");
assertStatementError("42846", st,
"insert into nonXTable (cl) values (cast ((xmlparse(document " +
"'</simp>' preserve whitespace)) as clob))");
assertStatementError("42846", st,
"insert into nonXTable (i) values (cast ((xmlparse(document " +
"'</simp>' preserve whitespace)) as int))");
st.executeUpdate("drop table nonXTable");
st.close();
}
/**
* Try to use XML values in non-XML operations. These
* should all fail (the only operations allowed with XML
* are the specified XML operations (xmlparse, xmlserialize,
* xmlexists, xmlquery)).
*/
public void testXMLInNonXMLOps() throws Exception
{
Statement st = createStatement();
assertStatementError("42Y95", st, "select i + x from t1");
assertStatementError("42Y95", st, "select i * x from t1");
assertStatementError("42Y95", st, "select i / x from t1");
assertStatementError("42Y95", st, "select i - x from t1");
assertStatementError("42X37", st, "select -x from t1");
assertStatementError("42846", st, "select 'hi' || x from t1");
assertStatementError("42X25", st, "select substr(x, 0) from t1");
assertStatementError("42Y22", st, "select max(x) from t1");
assertStatementError("42Y22", st, "select min(x) from t1");
assertStatementError("42X25", st, "select length(x) from t1");
assertStatementError("42884", st,
"select i from t1 where x like 'hmm'");
st.close();
}
/**
* Test simple comparisons with XML. These should all fail
* because no such comparisons are allowed.
*/
public void testXMLComparisons() throws Exception
{
Statement st = createStatement();
assertStatementError("42818", st, "select i from t1 where x = 'hmm'");
assertStatementError("42818", st, "select i from t1 where x > 0");
assertStatementError("42818", st, "select i from t1 where x < x");
assertStatementError("42818", st,
"select i from t1 where x <> 'some char'");
st.close();
}
/**
* Test additional restrictions on use of XML values.
* These should all fail.
*/
public void testIllegalOps() throws Exception
{
// Indexing/ordering on XML cols is not allowed.
Statement st = createStatement();
assertStatementError("X0X67", st, "create index oops_ix on t1(x)");
assertStatementError("X0X67", st,
"select i from t1 where x is null order by x");
// XML cannot be imported or exported (DERBY-1892).
CallableStatement cSt = prepareCall(
"CALL SYSCS_UTIL.SYSCS_EXPORT_TABLE ("
+ " null, 'T1', 'extinout/xmlexport.del', null, null, null)");
assertStatementError("42Z71", cSt);
cSt = prepareCall(
" CALL SYSCS_UTIL.SYSCS_EXPORT_QUERY("
+ " 'select x from t1', 'extinout/xmlexport.del', null, null, null)");
assertStatementError("42Z71", cSt);
cSt = prepareCall(
" CALL SYSCS_UTIL.SYSCS_IMPORT_TABLE ("
+ " null, 'T1', 'extinout/shouldntmatter.del', null, null, null, 0)");
assertStatementError("XIE0B", cSt);
cSt = prepareCall(
" CALL SYSCS_UTIL.SYSCS_IMPORT_DATA ("
+ " NULL, 'T1', null, '2', 'extinout/shouldntmatter.del', "
+ "null, null, null,0)");
assertStatementError("XIE0B", cSt);
// Done with cSt.
cSt.close();
// XML cannot be used with procedures/functions.
assertStatementError("42962", st,
"create procedure hmmproc (in i int, in x xml)"
+ " parameter style java language java external name "
+ "'hi.there'");
assertStatementError("42962", st,
" create function hmmfunc (i int, x xml) returns int"
+ " parameter style java language java external name "
+ "'hi.there'");
// XML columns cannot be used for global temporary
// tables.
assertStatementError("42962", st,
"declare global temporary table SESSION.xglobal (myx XML)"
+ " not logged on commit preserve rows");
st.close();
}
/**
* Test use of XML columns in a trigger's "SET" clause. Should
* work so long as the target value has type XML.
*/
public void testTriggerSetXML() throws Exception
{
// This should fail.
Statement st = createStatement();
assertStatementError("42821", st,
"create trigger tr2 after insert on t1 for each row "
+ "mode db2sql update t1 set x = 'hmm'");
// This should succeed.
st.executeUpdate("create trigger tr1 after insert on t1 for each row "
+ "mode db2sql update t1 set x = null");
st.executeUpdate(" drop trigger tr1");
st.close();
}
/**
* Various tests for the XMLPARSE operator. Note that this
* test primarily checks the negative cases--i.e. cases where
* we expect the XMLPARSE op to fail. The positive cases
* were tested implicitly as part of XMLTestSetup.setUp()
* when we loaded the test data.
*/
public void testXMLParse() throws Exception
{
// These should fail with various parse errors.
Statement st = createStatement();
assertStatementError("42Z74", st,
"insert into t1 values (1, xmlparse(document "
+ "'<hmm/>' strip whitespace))");
assertStatementError("42Z72", st,
" insert into t1 values (1, xmlparse(document '<hmm/>'))");
assertStatementError("42Z72", st,
" insert into t1 values (1, xmlparse('<hmm/>' "
+ "preserve whitespace))");
assertStatementError("42Z74", st,
" insert into t1 values (1, xmlparse(content "
+ "'<hmm/>' preserve whitespace))");
assertStatementError("42X25", st,
" select xmlparse(document xmlparse(document "
+ "'<hein/>' preserve whitespace) preserve whitespace) from t1");
assertStatementError("42X19", st,
" select i from t1 where xmlparse(document '<hein/>' "
+ "preserve whitespace)");
// This should fail because operand does not constitute
// well-formed XML.
assertStatementError("2200M", st,
" insert into t1 values (1, xmlparse(document "
+ "'<oops>' preserve whitespace))");
// This should fail because use of a parameter for the operand
// requires an explicit CAST to a char type.
assertCompileError("42Z79",
"insert into t1(x) values XMLPARSE(document ? "
+ "preserve whitespace)");
// Creation of a table with a default as XMLPARSE should throw
// an error--use of functions as a default is not allowed
// by the Derby syntax.
assertCompileError("42894",
"create table fail1 (i int, x xml default xmlparse("
+ "document '<my>default col</my>' preserve whitespace))");
// XMLPARSE is valid operand for "is [not] null" so
// this should work (and we should see a row for every
// successful "insert" statement that we executed on T1).
ResultSet rs = st.executeQuery(
" select i from t1 where xmlparse(document '<hein/>' "
+ "preserve whitespace) is not null");
String [] expColNames = new String [] { "I" };
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"1"},
{"2"},
{"4"},
{"3"},
{"5"},
{"6"},
{"7"},
{"8"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Ensure that order by on a table with an XML column in it
// works correctly.
rs = st.executeQuery(
" select i from t1 where xmlparse(document '<hein/>' "
+ "preserve whitespace) is not null order by i");
expColNames = new String [] { "I" };
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1"},
{"2"},
{"3"},
{"4"},
{"5"},
{"6"},
{"7"},
{"8"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Insertions using XMLPARSE with a parameter that is cast
// to a character type should work.
st.execute("create table paramInsert(x xml)");
PreparedStatement pSt = prepareStatement(
"insert into paramInsert values XMLPARSE(document "
+ "cast (? as CLOB) preserve whitespace)");
pSt.setString(1, "<ay>caramba</ay>");
assertUpdateCount(pSt, 1);
pSt.close();
// Run a select to view everything that was inserted.
rs = st.executeQuery("select xmlserialize(x as clob) from t1");
expColNames = new String [] { "1" };
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<update2> document was inserted as part of an "
+ "UPDATE </update2>"},
{null},
{null},
{null},
{"<hmm/>"},
{"<half> <masted> bass </masted> boosted. </half>"},
{"<umm> decl check </umm>"},
{"<lets> <try> this out </try> </lets>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlserialize(x as clob) from paramInsert");
expColNames = new String [] { "1" };
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<ay>caramba</ay>"}
};
// Cleanup.
st.executeUpdate("drop table paramInsert");
st.close();
}
/**
* Test use of the "is [not] null" clause with XML values.
* These should work.
*/
public void testIsNull() throws Exception
{
Statement st = createStatement();
ResultSet rs = st.executeQuery(
"select i from t1 where x is not null");
String [] expColNames = new String [] { "I" };
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"1"},
{"5"},
{"6"},
{"7"},
{"8"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(" select i from t1 where x is null");
expColNames = new String [] { "I" };
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"2"},
{"4"},
{"3"}
};
JDBC.assertFullResultSet(rs, expRS, true);
st.close();
}
/**
* Derby doesn't currently support XML values in a top-level
* result set. So make sure that doesn't work. These should
* all fail.
*/
public void testTopLevelSelect() throws Exception
{
Statement st = createStatement();
st.executeUpdate("create table vcTab (vc varchar(100))");
assertStatementError("42Z71", st, "select x from t1");
assertStatementError("42Z71", st, "select * from t1");
assertStatementError("42Z71", st,
" select xmlparse(document vc preserve whitespace) from vcTab");
assertStatementError("42Z71", st,
" values xmlparse(document '<bye/>' preserve whitespace)");
assertStatementError("42Z71", st,
" values xmlparse(document '<hel' || 'lo/>' preserve "
+ "whitespace)");
st.executeUpdate("drop table vcTab");
st.close();
}
/**
* Various tests for the XMLSERIALIZE operator.
*/
public void testXMLSerialize() throws Exception
{
// Test setup.
Statement st = createStatement();
st.executeUpdate("create table vcTab (vc varchar(100))");
assertUpdateCount(st, 1, "insert into vcTab values ('<hmm/>')");
assertUpdateCount(st, 1, "insert into vcTab values 'no good'");
// These should fail with various parse errors.
assertStatementError("42Z72", st, "select xmlserialize(x) from t1");
assertStatementError("42X01", st, "select xmlserialize(x as) from t1");
assertStatementError("42Z73", st,
" select xmlserialize(x as int) from t1");
assertStatementError("42Z73", st,
" select xmlserialize(x as boolean) from t1");
assertStatementError("42Z73", st,
" select xmlserialize(x as varchar(20) for bit data) from t1");
assertStatementError("42X04", st,
" select xmlserialize(y as char(10)) from t1");
assertStatementError("42X25", st,
" select xmlserialize(xmlserialize(x as clob) as "
+ "clob) from t1");
assertStatementError("42X25", st,
" values xmlserialize('<okay> dokie </okay>' as clob)");
// These should succeed.
ResultSet rs = st.executeQuery("select xmlserialize(x as clob) from t1");
String [] expColNames = new String [] { "1" };
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"<update2> document was inserted as part of an "
+ "UPDATE </update2>"},
{null},
{null},
{null},
{"<hmm/>"},
{"<half> <masted> bass </masted> boosted. </half>"},
{"<umm> decl check </umm>"},
{"<lets> <try> this out </try> </lets>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlserialize(x1 as clob), xmlserialize(x2 as "
+ "clob) from t2");
expColNames = new String [] {"1", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{null, "<notnull/>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlserialize(x as char(100)) from t1");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<update2> document was inserted as part of an "
+ "UPDATE </update2>"},
{null},
{null},
{null},
{"<hmm/>"},
{"<half> <masted> bass </masted> boosted. </half>"},
{"<umm> decl check </umm>"},
{"<lets> <try> this out </try> </lets>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlserialize(x as varchar(300)) from t1");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<update2> document was inserted as part of an "
+ "UPDATE </update2>"},
{null},
{null},
{null},
{"<hmm/>"},
{"<half> <masted> bass </masted> boosted. </half>"},
{"<umm> decl check </umm>"},
{"<lets> <try> this out </try> </lets>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// This should succeed at the XMLPARSE level, but fail
// with parse/truncation errors at the XMLSERIALIZE.
assertStatementError("2200M", st,
"select xmlserialize(xmlparse(document vc preserve "
+ "whitespace) as char(10)) from vcTab");
// These should all fail with truncation errors.
assertStatementError("22001", st,
" select xmlserialize(x as char) from t1");
assertStatementError("22001", st,
" select xmlserialize(x as clob(10)) from t1");
assertStatementError("22001", st,
" select xmlserialize(x as char(1)) from t1");
assertStatementError("22001", st,
" select length(xmlserialize(x as char(1))) from t1");
assertStatementError("22001", st,
" select xmlserialize(x as varchar(1)) from t1");
assertStatementError("22001", st,
" select length(xmlserialize(x as varchar(1))) from t1");
// These checks verify that the XMLSERIALIZE result is the
// correct type.
rs = st.executeQuery("select xmlserialize(x as char(100)) from t1");
ResultSetMetaData rsmd = rs.getMetaData();
assertEquals("Incorrect XMLSERIALIZE result type:",
Types.CHAR, rsmd.getColumnType(1));
rs = st.executeQuery("select xmlserialize(x as varchar(100)) from t1");
rsmd = rs.getMetaData();
assertEquals("Incorrect XMLSERIALIZE result type:",
Types.VARCHAR, rsmd.getColumnType(1));
rs = st.executeQuery("select xmlserialize(x as long varchar) from t1");
rsmd = rs.getMetaData();
assertEquals("Incorrect XMLSERIALIZE result type:",
Types.LONGVARCHAR, rsmd.getColumnType(1));
rs = st.executeQuery("select xmlserialize(x as clob(100)) from t1");
rsmd = rs.getMetaData();
assertEquals("Incorrect XMLSERIALIZE result type:",
Types.CLOB, rsmd.getColumnType(1));
// Cleanup.
rs.close();
st.executeUpdate("drop table vcTab");
st.close();
}
/**
* Various tests with XMLPARSE and XMLSERIALIZE combinations.
*/
public void testXMLParseSerializeCombos() throws Exception
{
// These should fail at the XMLPARSE level.
Statement st = createStatement();
assertStatementError("2200M", st,
"select xmlserialize(xmlparse(document '<hmm>' "
+ "preserve whitespace) as clob) from t1");
assertStatementError("42X25", st,
" select xmlserialize(xmlparse(document x preserve "
+ "whitespace) as char(100)) from t1");
// These should succeed.
ResultSet rs = st.executeQuery(
"select xmlserialize(xmlparse(document '<hmm/>' "
+ "preserve whitespace) as clob) from t1 where i = 1");
String [] expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"<hmm/>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlserialize(xmlparse(document "
+ "xmlserialize(x as clob) preserve whitespace) as "
+ "clob) from t1");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<update2> document was inserted as part of an "
+ "UPDATE </update2>"},
{null},
{null},
{null},
{"<hmm/>"},
{"<half> <masted> bass </masted> boosted. </half>"},
{"<umm> decl check </umm>"},
{"<lets> <try> this out </try> </lets>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"values xmlserialize(xmlparse(document '<okay> dokie "
+ "</okay>' preserve whitespace) as clob)");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<okay> dokie </okay>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i from t1 where xmlparse(document "
+ "xmlserialize(x as clob) preserve whitespace) is not "
+ "null order by i");
expColNames = new String [] {"I"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1"},
{"5"},
{"6"},
{"7"},
{"8"}
};
JDBC.assertFullResultSet(rs, expRS, true);
st.close();
}
/**
* Various tests for the XMLEXISTS operator.
*/
public void testXMLExists() throws Exception
{
// These should fail with various parse errors.
Statement st = createStatement();
assertStatementError("42X01", st,
"select i from t1 where xmlexists(x)");
assertStatementError("42X01", st,
"select i from t1 where xmlexists(i)");
assertStatementError("42X01", st,
"select i from t1 where xmlexists('//*')");
assertStatementError("42X01", st,
"select i from t1 where xmlexists('//*' x)");
assertStatementError("42X01", st,
"select i from t1 where xmlexists('//*' passing x)");
assertStatementError("42Z74", st,
"select i from t1 where xmlexists('//*' passing by value x)");
assertStatementError("42Z77", st,
"select i from t1 where xmlexists('//*' passing by ref i)");
assertStatementError("42Z75", st,
"select i from t1 where xmlexists(i passing by ref x)");
assertStatementError("42Z76", st,
"select i from t1 where xmlexists(i passing by ref x, x)");
// These should succeed.
ResultSet rs = st.executeQuery(
"select i from t1 where xmlexists('//*' passing by ref x)");
String [] expColNames = new String [] {"I"};
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"1"},
{"5"},
{"6"},
{"7"},
{"8"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// This should succeed but return no rows.
rs = st.executeQuery(
"select i from t1 where xmlexists('//person' passing "
+ "by ref x)");
expColNames = new String [] {"I"};
JDBC.assertColumnNames(rs, expColNames);
JDBC.assertDrainResults(rs, 0);
// This should return one row.
rs = st.executeQuery(
"select i from t1 where xmlexists('//lets' passing by ref x)");
expColNames = new String [] {"I"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"8"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// XMLEXISTS should return null if the operand is null.
rs = st.executeQuery(
"select xmlexists('//lets' passing by ref x) from t1");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{null},
{null},
{null},
{"false"},
{"false"},
{"false"},
{"true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//try[text()='' this out '']' "
+ "passing by ref x) from t1");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{null},
{null},
{null},
{"false"},
{"false"},
{"false"},
{"true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//let' passing by ref x) from t1");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{null},
{null},
{null},
{"false"},
{"false"},
{"false"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//try[text()='' this in '']' "
+ "passing by ref x) from t1");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{null},
{null},
{null},
{"false"},
{"false"},
{"false"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Make sure selection of other columns along with XMLEXISTS
// still works.
rs = st.executeQuery(
"select i, xmlexists('//let' passing by ref x) from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "false"},
{"2", null},
{"4", null},
{"3", null},
{"5", "false"},
{"6", "false"},
{"7", "false"},
{"8", "false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i, xmlexists('//lets' passing by ref x) from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "false"},
{"2", null},
{"4", null},
{"3", null},
{"5", "false"},
{"6", "false"},
{"7", "false"},
{"8", "true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// XMLEXISTS should work in a VALUES clause, too.
rs = st.executeQuery(
"values xmlexists('//let' passing by ref "
+ "xmlparse(document '<lets> try this </lets>' "
+ "preserve whitespace))");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"values xmlexists('//lets' passing by ref "
+ "xmlparse(document '<lets> try this </lets>' "
+ "preserve whitespace))");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Simple check for attribute existence.
rs = st.executeQuery(
"values xmlexists('//lets/@doit' passing by ref "
+ "xmlparse(document '<lets doit=\"true\"> try this "
+ "</lets>' preserve whitespace))");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"values xmlexists('//lets/@dot' passing by ref "
+ "xmlparse(document '<lets doit=\"true\"> try this "
+ "</lets>' preserve whitespace))");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// XMLEXISTS in a WHERE clause.
rs = st.executeQuery(
"select xmlserialize(x1 as clob) from t2 where "
+ "xmlexists('//*' passing by ref x1)");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
JDBC.assertDrainResults(rs, 0);
rs = st.executeQuery(
"select xmlserialize(x2 as clob) from t2 where "
+ "xmlexists('//*' passing by ref x2)");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<notnull/>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlserialize(x1 as clob), xmlexists('//*' "
+ "passing by ref xmlparse(document '<badboy/>' "
+ "preserve whitespace)) from t2");
expColNames = new String [] {"1", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{null, "true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlserialize(x1 as clob), "
+ "xmlexists('//goodboy' passing by ref "
+ "xmlparse(document '<badboy/>' preserve whitespace)) from t2");
expColNames = new String [] {"1", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{null, "false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Add some more test tables/data.
st.executeUpdate(
"create table xqExists2 (i int, x1 xml, x2 xml not null)");
assertUpdateCount(st, 1,
" insert into xqExists2 values (1, null, xmlparse(document "
+ "'<ok/>' preserve whitespace))");
rs = st.executeQuery(
"select i, xmlserialize(x1 as char(10)), "
+ "xmlserialize (x2 as char(10)) from xqExists2");
expColNames = new String [] {"I", "2", "3"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", null, "<ok/>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Now run some XMLEXISTS queries on xqExists2 using boolean
// operations ('and', 'or') on the XMLEXISTS result.
rs = st.executeQuery(
"select i from xqExists2 where xmlexists('/ok' passing by "
+ "ref x1) and xmlexists('/ok' passing by ref x2)");
expColNames = new String [] {"I"};
JDBC.assertColumnNames(rs, expColNames);
JDBC.assertDrainResults(rs, 0);
rs = st.executeQuery(
"select i from xqExists2 where xmlexists('/ok' passing by "
+ "ref x1) or xmlexists('/ok' passing by ref x2)");
expColNames = new String [] {"I"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// XMLEXISTS can be used wherever a boolean function is
// allowed, for ex, a check constraint...
st.executeUpdate(
"create table xqExists1 (i int, x xml check "
+ "(xmlexists('//should' passing by ref x)))");
assertUpdateCount(st, 1,
" insert into xqExists1 values (1, xmlparse(document "
+ "'<should/>' preserve whitespace))");
assertStatementError("23513", st,
" insert into xqExists1 values (1, xmlparse(document "
+ "'<shouldnt/>' preserve whitespace))");
rs = st.executeQuery(
"select xmlserialize(x as char(20)) from xqExists1");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<should/>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Do some namespace queries/examples.
st.executeUpdate("create table xqExists3 (i int, x xml)");
assertUpdateCount(st, 1,
" insert into xqExists3 values (1, xmlparse(document '<a:hi "
+ "xmlns:a=\"http://www.hi.there\"/>' preserve whitespace))");
assertUpdateCount(st, 1,
" insert into xqExists3 values (2, xmlparse(document '<b:hi "
+ "xmlns:b=\"http://www.hi.there\"/>' preserve whitespace))");
assertUpdateCount(st, 1,
" insert into xqExists3 values (3, xmlparse(document "
+ "'<a:bye xmlns:a=\"http://www.good.bye\"/>' preserve "
+ "whitespace))");
assertUpdateCount(st, 1,
" insert into xqExists3 values (4, xmlparse(document "
+ "'<b:bye xmlns:b=\"http://www.hi.there\"/>' preserve "
+ "whitespace))");
assertUpdateCount(st, 1,
" insert into xqExists3 values (5, xmlparse(document "
+ "'<hi/>' preserve whitespace))");
rs = st.executeQuery(
"select xmlexists('//child::*[name()=\"none\"]' "
+ "passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{"false"},
{"false"},
{"false"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//child::*[name()=''hi'']' "
+ "passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{"false"},
{"false"},
{"false"},
{"true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//child::*[local-name()=''hi'']' "
+ "passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"true"},
{"true"},
{"false"},
{"false"},
{"true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//child::*[local-name()=''bye'']' "
+ "passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{"false"},
{"true"},
{"true"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select "
+ "xmlexists('//*[namespace::*[string()=''http://www.hi"
+ ".there'']]' passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"true"},
{"true"},
{"false"},
{"true"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select "
+ "xmlexists('//*[namespace::*[string()=''http://www.go"
+ "od.bye'']]' passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{"false"},
{"true"},
{"false"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//child::*[local-name()=''hi'' "
+ "and "
+ "namespace::*[string()=''http://www.hi.there'']]' "
+ "passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"true"},
{"true"},
{"false"},
{"false"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//child::*[local-name()=''bye'' "
+ "and "
+ "namespace::*[string()=''http://www.good.bye'']]' "
+ "passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{"false"},
{"true"},
{"false"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//child::*[local-name()=''bye'' "
+ "and "
+ "namespace::*[string()=''http://www.hi.there'']]' "
+ "passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{"false"},
{"false"},
{"true"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Cleanup.
st.executeUpdate("drop table xqExists1");
st.executeUpdate("drop table xqExists2");
st.executeUpdate("drop table xqExists3");
st.close();
}
/**
* Various tests for the XMLQUERY operator.
*/
public void testXMLQuery() throws Exception
{
// These should fail w/ syntax errors.
Statement st = createStatement();
assertStatementError("42X01", st, "select i, xmlquery('//*') from t1");
assertStatementError("42X01", st,
" select i, xmlquery('//*' passing) from t1");
assertStatementError("42X01", st,
" select i, xmlquery('//*' passing by ref x) from t1");
assertStatementError("42X01", st,
" select i, xmlquery('//*' passing by ref x "
+ "returning sequence) from t1");
assertStatementError("42X01", st,
" select i, xmlquery(passing by ref x empty on empty) from t1");
assertStatementError("42X01", st,
" select i, xmlquery(xmlquery('//*' returning "
+ "sequence empty on empty) as char(75)) from t1");
// These should fail with "not supported" errors.
assertStatementError("42Z74", st,
"select i, xmlquery('//*' passing by ref x returning "
+ "sequence null on empty) from t1");
assertStatementError("42Z74", st,
" select i, xmlquery('//*' passing by ref x "
+ "returning content empty on empty) from t1");
// This should fail because XMLQUERY returns an XML value
// which is not allowed in top-level result set.
assertStatementError("42Z71", st,
"select i, xmlquery('//*' passing by ref x empty on "
+ "empty) from t1");
// These should fail because context item must be XML.
assertStatementError("42Z77", st,
"select i, xmlquery('//*' passing by ref i empty on "
+ "empty) from t1");
assertStatementError("42Z77", st,
" select i, xmlquery('//*' passing by ref 'hello' "
+ "empty on empty) from t1");
assertStatementError("42Z77", st,
" select i, xmlquery('//*' passing by ref cast "
+ "('hello' as clob) empty on empty) from t1");
// This should fail because the function is not recognized
// by Xalan. The failure should be an error from Xalan
// saying what the problem is; it should *NOT* be a NPE,
// which is what we were seeing before DERBY-688 was completed.
assertStatementError("10000", st,
"select i,"
+ " xmlserialize("
+ " xmlquery('data(//@*)' passing by ref x "
+ "returning sequence empty on empty)"
+ " as char(70))"
+ "from t1");
// These should all succeed. Since it's Xalan that's
// actually doing the query evaluation we don't need to
// test very many queries; we just want to make sure we get
// the correct results when there is an empty sequence,
// when the xml context is null, and when there is a
// sequence with one or more nodes/items in it. So we just
// try out some queries and look at the results. The
// selection of queries is random and is not meant to be
// exhaustive.
ResultSet rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('2+2' passing by ref x returning "
+ "sequence empty on empty)"
+ " as char(70))"
+ "from t1");
String [] expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"1", "4"},
{"2", null},
{"4", null},
{"3", null},
{"5", "4"},
{"6", "4"},
{"7", "4"},
{"8", "4"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('./notthere' passing by ref x "
+ "returning sequence empty on empty)"
+ " as char(70))"
+ "from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", ""},
{"2", null},
{"4", null},
{"3", null},
{"5", ""},
{"6", ""},
{"7", ""},
{"8", ""}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('//*' passing by ref x empty on empty)"
+ " as char(70))"
+ "from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "<update2> document was inserted as part of an "
+ "UPDATE </update2>"},
{"2", null},
{"4", null},
{"3", null},
{"5", "<hmm/>"},
{"6", "<half> <masted> bass </masted> boosted. "
+ "</half><masted> bass </masted>"},
{"7", "<umm> decl check </umm>"},
{"8", "<lets> <try> this out </try> </lets><try> this out </try>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('//*[text() = \" bass \"]' passing by "
+ "ref x empty on empty)"
+ " as char(70))"
+ "from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", ""},
{"2", null},
{"4", null},
{"3", null},
{"5", ""},
{"6", "<masted> bass </masted>"},
{"7", ""},
{"8", ""}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('//lets' passing by ref x empty on empty)"
+ " as char(70))"
+ "from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", ""},
{"2", null},
{"4", null},
{"3", null},
{"5", ""},
{"6", ""},
{"7", ""},
{"8", "<lets> <try> this out </try> </lets>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('//text()' passing by ref x empty on empty)"
+ " as char(70))"
+ "from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "document was inserted as part of an UPDATE"},
{"2", null},
{"4", null},
{"3", null},
{"5", ""},
{"6", "bass boosted."},
{"7", "decl check"},
{"8", "this out"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('//try[text()='' this out '']' passing "
+ "by ref x empty on empty)"
+ " as char(70))"
+ "from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", ""},
{"2", null},
{"4", null},
{"3", null},
{"5", ""},
{"6", ""},
{"7", ""},
{"8", "<try> this out </try>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('//try[text()='' this in '']' passing "
+ "by ref x empty on empty)"
+ " as char(70))"
+ "from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", ""},
{"2", null},
{"4", null},
{"3", null},
{"5", ""},
{"6", ""},
{"7", ""},
{"8", ""}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('2+.//try' passing by ref x returning "
+ "sequence empty on empty)"
+ " as char(70))"
+ "from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "NaN"},
{"2", null},
{"4", null},
{"3", null},
{"5", "NaN"},
{"6", "NaN"},
{"7", "NaN"},
{"8", "NaN"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"values ('x', xmlserialize("
+ " xmlquery('//let' passing by ref"
+ " xmlparse(document '<lets> try this </lets>' "
+ "preserve whitespace)"
+ " empty on empty)"
+ "as char(30)))");
expColNames = new String [] {"1", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"x", ""}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"values xmlserialize("
+ " xmlquery('//lets' passing by ref"
+ " xmlparse(document '<lets> try this </lets>' "
+ "preserve whitespace)"
+ " empty on empty)"
+ "as char(30))");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<lets> try this </lets>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
st.close();
}
/* Check insertion of XMLQUERY result into a table. Should
* only allow results that are a sequence of exactly one
* Document node.
*/
public void testXMLQueryInsert() throws Exception
{
// Create test table and data specific to this test.
Statement st = createStatement();
st.executeUpdate("create table xqInsert1 (i int, x xml not null)");
assertUpdateCount(st, 1,
" insert into xqInsert1 values (1, xmlparse(document "
+ "'<should> work as planned </should>' preserve whitespace))");
st.executeUpdate("create table xqInsert2 (i int, x xml default null)");
assertUpdateCount(st, 1,
"insert into xqInsert2 values ("
+ " 9,"
+ " xmlparse(document '<here><is><my "
+ "height=\"4.4\">attribute</my></is></here>' preserve "
+ "whitespace)"
+ ")");
assertUpdateCount(st, 1,
" insert into xqInsert2 values ("
+ " 0,"
+ " xmlparse(document '<there><goes><my "
+ "weight=\"180\">attribute</my></goes></there>' "
+ "preserve whitespace)"
+ ")");
// Show target tables before insertions.
ResultSet rs = st.executeQuery(
"select i, xmlserialize(x as char(75)) from xqInsert1");
String [] expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"1", "<should> work as planned </should>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i, xmlserialize(x as char(75)) from xqInsert2");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"9", "<here><is><my height=\"4.4\">attribute</my></is></here>"},
{"0", "<there><goes><my "
+ "weight=\"180\">attribute</my></goes></there>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// These should all fail because the result of the XMLQUERY
// op is not a valid document (it's either an empty
// sequence, a node that is not a Document node, some
// undefined value, or a sequence with more than one item
// in it).
assertStatementError("2200L", st,
"insert into xqInsert1 (i, x) values ("
+ " 20, "
+ " (select"
+ " xmlquery('./notthere' passing by ref x "
+ "returning sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
assertStatementError("2200L", st,
" insert into xqInsert1 (i, x) values ("
+ " 21,"
+ " (select"
+ " xmlquery('//@*' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
assertStatementError("2200L", st,
" insert into xqInsert1 (i, x) values ("
+ " 22,"
+ " (select"
+ " xmlquery('. + 2' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
assertStatementError("2200L", st,
" insert into xqInsert1 (i, x) values ("
+ " 23,"
+ " (select"
+ " xmlquery('//*' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
assertStatementError("2200L", st,
" insert into xqInsert1 (i, x) values ("
+ " 24,"
+ " (select"
+ " xmlquery('//*[//@*]' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
assertStatementError("2200L", st,
" insert into xqInsert1 (i, x) values ("
+ " 25,"
+ " (select"
+ " xmlquery('//is' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
assertStatementError("2200L", st,
" insert into xqInsert1 (i, x) values ("
+ " 26,"
+ " (select"
+ " xmlquery('//*[@*]' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
// These should succeed.
assertUpdateCount(st, 1,
"insert into xqInsert1 (i, x) values ("
+ " 27,"
+ " (select"
+ " xmlquery('.' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
assertUpdateCount(st, 1,
" insert into xqInsert1 (i, x) values ("
+ " 28,"
+ " (select"
+ " xmlquery('/here/..' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
// Verify results.
rs = st.executeQuery(
"select i, xmlserialize(x as char(75)) from xqInsert1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "<should> work as planned </should>"},
{"27", "<here><is><my height=\"4.4\">attribute</my></is></here>"},
{"28", "<here><is><my height=\"4.4\">attribute</my></is></here>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Next two should _both_ succeed because there's no row
// with i = 100 in xqInsert2, thus the SELECT will return null
// and XMLQUERY operator should never get executed. x will be
// NULL in these cases.
assertUpdateCount(st, 1,
"insert into xqInsert2 (i, x) values ("
+ " 29,"
+ " (select"
+ " xmlquery('2+2' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 100"
+ " )"
+ ")");
assertUpdateCount(st, 1,
" insert into xqInsert2 (i, x) values ("
+ " 30,"
+ " (select"
+ " xmlquery('.' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 100"
+ " )"
+ ")");
// Verify results.
rs = st.executeQuery(
"select i, xmlserialize(x as char(75)) from xqInsert2");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"9", "<here><is><my height=\"4.4\">attribute</my></is></here>"},
{"0", "<there><goes><my "
+ "weight=\"180\">attribute</my></goes></there>"},
{"29", null},
{"30", null}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Cleanup.
st.executeUpdate("drop table xqInsert1");
st.executeUpdate("drop table xqInsert2");
st.close();
}
/* Check updates using XMLQUERY results. Should only allow
* results that constitute a valid DOCUMENT node (i.e. that
* can be parsed by the XMLPARSE operator).
*/
public void testXMLQueryUpdate() throws Exception
{
// Create test table and data.
Statement st = createStatement();
st.executeUpdate("create table xqUpdate (i int, x xml default null)");
assertUpdateCount(st, 2, "insert into xqUpdate (i) values 29, 30");
assertUpdateCount(st, 1,
"insert into xqUpdate values ("
+ " 9,"
+ " xmlparse(document '<here><is><my "
+ "height=\"4.4\">attribute</my></is></here>' preserve "
+ "whitespace)"
+ ")");
// These updates should succeed.
assertUpdateCount(st, 1,
"update xqUpdate"
+ " set x = "
+ " xmlquery('.' passing by ref"
+ " xmlparse(document '<none><here/></none>' "
+ "preserve whitespace)"
+ " returning sequence empty on empty)"
+ "where i = 29");
assertUpdateCount(st, 1,
" update xqUpdate"
+ " set x = "
+ " xmlquery('self::node()[//@height]' passing by ref"
+ " (select"
+ " xmlquery('.' passing by ref x empty on empty)"
+ " from xqUpdate"
+ " where i = 9"
+ " )"
+ " empty on empty)"
+ "where i = 30");
// These should fail because result of XMLQUERY isn't a
// DOCUMENT.
assertStatementError("2200L", st,
"update xqUpdate"
+ " set x = xmlquery('.//*' passing by ref x empty on empty)"
+ "where i = 29");
assertStatementError("2200L", st,
" update xqUpdate"
+ " set x = xmlquery('./notthere' passing by ref x "
+ "empty on empty)"
+ "where i = 30");
assertStatementError("2200L", st,
" update xqUpdate"
+ " set x ="
+ " xmlquery('//*[@weight]' passing by ref"
+ " (select"
+ " xmlquery('.' passing by ref x empty on empty)"
+ " from xqUpdate"
+ " where i = 9"
+ " )"
+ " empty on empty)"
+ "where i = 30");
assertStatementError("2200L", st,
" update xqUpdate"
+ " set x ="
+ " xmlquery('//*/@height' passing by ref"
+ " (select"
+ " xmlquery('.' passing by ref x empty on empty)"
+ " from xqUpdate"
+ " where i = 9"
+ " )"
+ " empty on empty)"
+ "where i = 30");
// Next two should succeed because there's no row with i =
// 100 in xqUpdate and thus xqUpdate should remain unchanged after
// these updates.
assertUpdateCount(st, 0,
"update xqUpdate"
+ " set x = xmlquery('//*' passing by ref x empty on empty)"
+ "where i = 100");
assertUpdateCount(st, 0,
" update xqUpdate"
+ " set x = xmlquery('4+4' passing by ref x empty on empty)"
+ "where i = 100");
// Verify results.
ResultSet rs = st.executeQuery(
"select i, xmlserialize(x as char(75)) from xqUpdate");
String [] expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"29", "<none><here/></none>"},
{"30", "<here><is><my height=\"4.4\">attribute</my></is></here>"},
{"9", "<here><is><my height=\"4.4\">attribute</my></is></here>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Cleanup.
st.executeUpdate("drop table xqUpdate");
st.close();
}
/* Pass results of an XMLQUERY op into another XMLQUERY op.
* Should work so long as results of the first op constitute
* a valid document.
*/
public void testNestedXMLQuery() throws Exception
{
// Should fail because result of inner XMLQUERY op
// isn't a valid document.
Statement st = createStatement();
assertStatementError("2200V", st,
"select i,"
+ " xmlserialize("
+ " xmlquery('//lets/@*' passing by ref"
+ " xmlquery('/okay/text()' passing by ref"
+ " xmlparse(document '<okay><lets "
+ "boki=\"inigo\"/></okay>' preserve whitespace)"
+ " empty on empty)"
+ " empty on empty)"
+ " as char(100))"
+ "from t1 where i > 5");
assertStatementError("2200V", st,
" select i,"
+ " xmlserialize("
+ " xmlquery('.' passing by ref"
+ " xmlquery('//lets' passing by ref"
+ " xmlparse(document '<okay><lets "
+ "boki=\"inigo\"/></okay>' preserve whitespace)"
+ " empty on empty)"
+ " empty on empty)"
+ " as char(100))"
+ "from t1 where i > 5");
assertStatementError("2200V", st,
" select i,"
+ " xmlexists('.' passing by ref"
+ " xmlquery('/okay' passing by ref"
+ " xmlparse(document '<okay><lets "
+ "boki=\"inigo\"/></okay>' preserve whitespace)"
+ " empty on empty)"
+ " )"
+ "from t1 where i > 5");
// Should succeed but result is empty sequence.
ResultSet rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('/not' passing by ref"
+ " xmlquery('.' passing by ref"
+ " xmlparse(document '<okay><lets "
+ "boki=\"inigo\"/></okay>' preserve whitespace)"
+ " empty on empty)"
+ " empty on empty)"
+ " as char(100))"
+ "from t1 where i > 5");
String [] expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"6", ""},
{"7", ""},
{"8", ""}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Should succeed with various results.
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('//lets' passing by ref"
+ " xmlquery('.' passing by ref"
+ " xmlparse(document '<okay><lets "
+ "boki=\"inigo\"/></okay>' preserve whitespace)"
+ " empty on empty)"
+ " empty on empty)"
+ " as char(100))"
+ "from t1 where i > 5");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"6", "<lets boki=\"inigo\"/>"},
{"7", "<lets boki=\"inigo\"/>"},
{"8", "<lets boki=\"inigo\"/>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('string(//@boki)' passing by ref"
+ " xmlquery('/okay/..' passing by ref"
+ " xmlparse(document '<okay><lets "
+ "boki=\"inigo\"/></okay>' preserve whitespace)"
+ " empty on empty)"
+ " empty on empty)"
+ " as char(100))"
+ "from t1 where i > 5");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"6", "inigo"},
{"7", "inigo"},
{"8", "inigo"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('/half/masted/text()' passing by ref"
+ " xmlquery('.' passing by ref x empty on empty)"
+ " empty on empty)"
+ " as char(100))"
+ "from t1 where i = 6");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"6", "bass"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlexists('/half/masted/text()' passing by ref"
+ " xmlquery('.' passing by ref x empty on empty)"
+ " )"
+ "from t1 where i = 6");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"6", "true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
st.close();
}
/**
* DERBY-1759: Serialization of attribute nodes.
*/
public void testAttrSerialization() throws Exception
{
// Create test table and one row of data.
Statement st = createStatement();
st.executeUpdate("create table attserTable (i int, x xml)");
assertUpdateCount(st, 1, "insert into attserTable values (0, null)");
assertUpdateCount(st, 1,
"insert into attserTable values (10,"
+ " xmlparse(document"
+ " '<threeatts first=\"1\" second=\"two\" "
+ "third=\"le 3 trois\"/>'"
+ " preserve whitespace"
+ " ))");
// Echo attserTable rows for reference.
ResultSet rs = st.executeQuery(
"select i, xmlserialize(x as char(75)) from attserTable");
String [] expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"0", null},
{"10", "<threeatts first=\"1\" second=\"two\" third=\"le 3 trois\"/>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// This should fail because XML serialization dictates that
// we throw an error if an attempt is made to serialize a
// sequence that has one or more top-level attributes nodes.
assertStatementError("2200W", st,
"select"
+ " xmlserialize("
+ " xmlquery("
+ " '//@*' passing by ref x empty on empty"
+ " )"
+ " as char(50))"
+ " from attserTable"
+ " where xmlexists('//@*' passing by ref x)");
// Demonstrate that Xalan "string" function only returns
// string value of first attribute and thus cannot be used
// to retrieve a sequence of att values.
rs = st.executeQuery(
"select"
+ " xmlserialize("
+ " xmlquery("
+ " 'string(//@*)'"
+ " passing by ref x empty on empty"
+ " )"
+ " as char(50))"
+ " from attserTable"
+ " where xmlexists('//@*' passing by ref x)");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Xalan doesn't have a function that allows retrieval of a
// sequence of attribute values. One can only retrieve a
// sequence of attribute *nodes*, but since those can't be
// serialized (because of SQL/XML rules) the user has no
// way to get them. The following is a very (VERY) ugly
// two-part workaround that one could use until something
// better is available. First, get the max number of
// attributes in the table.
rs = st.executeQuery(
"select"
+ " max("
+ " cast("
+ " xmlserialize("
+ " xmlquery('count(//@*)' passing by ref x "
+ "empty on empty)"
+ " as char(50))"
+ " as int)"
+ " )"
+ " from attserTable");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"3"}
};
JDBC.assertFullResultSet(rs, expRS, true, false);
// The use of MAX in the previous query throws a warning because
// the table T1 has null values. Just for sanity check for that
// warning if we're in embedded mode (warnings are not returned
// in client/server mode--see DERBY-159).
if (usingEmbedded())
{
SQLWarning sqlWarn = rs.getWarnings();
if (sqlWarn == null)
sqlWarn = st.getWarnings();
if (sqlWarn == null)
sqlWarn = getConnection().getWarnings();
assertTrue("Expected warning but found none.", (sqlWarn != null));
assertSQLState("01003", sqlWarn);
}
rs.close();
// Then use XPath position syntax to retrieve the
// attributes and concatenate them. We need one call to
// string(//@[i]) for every for every i between 1 and the
// value found in the preceding query. In this case we
// know the max is three, so use that.
rs = st.executeQuery(
"select"
+ " xmlserialize("
+ " xmlquery("
+ " 'concat(string(//@*[1]), \" \","
+ " string(//@*[2]), \" \","
+ " string(//@*[3]))'"
+ " passing by ref x empty on empty"
+ " )"
+ " as char(50))"
+ " from attserTable"
+ " where xmlexists('//@*' passing by ref x)");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1 two le 3 trois"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Cleanup.
st.executeUpdate("drop table attserTable");
st.close();
}
/**
* DERBY-1718 create trigger fails when SPS contains XML
* related op.
*/
public void testTriggerSPSWithXML() throws Exception
{
Statement st = createStatement();
st.executeUpdate("create table trigSPS1 (i int, x xml)");
st.executeUpdate("create table trigSPS2 (i int, x xml)");
assertUpdateCount(st, 1,
" insert into trigSPS1 values (1, xmlparse(document "
+ "'<name> john </name>' preserve whitespace))");
st.executeUpdate(
"create trigger tx after insert on trigSPS1 for each "
+ "statement mode db2sql insert into trigSPS2 values "
+ "(1, xmlparse(document '<name> jane </name>' "
+ "preserve whitespace))");
assertUpdateCount(st, 1,
" insert into trigSPS1 values (2, xmlparse(document "
+ "'<name> ally </name>' preserve whitespace))");
ResultSet rs = st.executeQuery(
"select i, xmlserialize(x as varchar(20)) from trigSPS1");
String [] expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"1", "<name> john </name>"},
{"2", "<name> ally </name>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i, xmlserialize(x as varchar(20)) from trigSPS2");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "<name> jane </name>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
assertUpdateCount(st, 2, "insert into trigSPS1 select * from trigSPS1");
rs = st.executeQuery(
"select i, xmlserialize(x as varchar(20)) from trigSPS1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "<name> john </name>"},
{"2", "<name> ally </name>"},
{"1", "<name> john </name>"},
{"2", "<name> ally </name>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i, xmlserialize(x as varchar(20)) from trigSPS2");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "<name> jane </name>"},
{"1", "<name> jane </name>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
st.executeUpdate("drop trigger tx");
assertUpdateCount(st, 4, "delete from trigSPS1");
assertUpdateCount(st, 2, "delete from trigSPS2");
assertUpdateCount(st, 1,
" insert into trigSPS1 values (1, xmlparse(document "
+ "'<name> john </name>' preserve whitespace))");
st.executeUpdate(
"create trigger tx after insert on trigSPS1 for each "
+ "statement mode db2sql insert into trigSPS2 values "
+ "(1, (select xmlquery('.' passing by ref x "
+ "returning sequence empty on empty) from trigSPS1 "
+ "where i = 1))");
assertUpdateCount(st, 1,
" insert into trigSPS1 values (2, xmlparse(document "
+ "'<name> ally </name>' preserve whitespace))");
rs = st.executeQuery(
"select i, xmlserialize(x as varchar(20)) from trigSPS1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "<name> john </name>"},
{"2", "<name> ally </name>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i, xmlserialize(x as varchar(20)) from trigSPS2");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "<name> john </name>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
st.executeUpdate("drop trigger tx");
st.executeUpdate("drop table trigSPS1");
st.executeUpdate("drop table trigSPS2");
st.close();
}
/**
* Test how numeric values returned by XPath queries are formatted.
*/
public void testNumericReturnValues() throws SQLException {
// Array of XPath queries and their expected return values
String[][] queries = {
// Long.MAX_VALUE. We lose some precision.
{ "9223372036854775807", "9223372036854776000" },
// We can also have numbers larger than Long.MAX_VALUE, but we
// don't get higher precision.
{ "9223372036854775807123456789", "9223372036854776000000000000" },
// Expect plain format, not scientific notation like 1.23E-10
{ "123 div 1000000000000", "0.000000000123" },
// Trailing zeros after decimal point should be stripped away
{ "1", "1" },
{ "1.0", "1" },
{ "1.000", "1" },
{ "1.00010", "1.0001" },
// -0 should be normalized to 0
{ "-0", "0" },
{ "-0.0", "0" },
{ "-0.00", "0" },
// Division by zero yields Not A Number or +/- Infinity
{ "0 div 0", "NaN" },
{ "3.14 div 0", "Infinity" },
{ "-3.14 div 0", "-Infinity" },
};
Statement s = createStatement();
for (int i = 0; i < queries.length; i++) {
String xpath = queries[i][0];
String expected = queries[i][1];
String sql = "select xmlserialize(xmlquery('" + xpath +
"' passing by ref x empty on empty) as clob) " +
"from t1 where i = 1";
JDBC.assertSingleValueResultSet(s.executeQuery(sql), expected);
}
}
/**
* Wrapper for the tests in XMLTypeAndOpsTest. We have some
* fixture tables/data that we want to create a single time
* before the tests run and then which we want to clean up
* when the tests complete. This class acts the "wrapper"
* that does this one-time setup and teardown. (Actually,
* we do it two times: once for running in embedded mode
* and once for running in client/server mode--we create an
* instance of this class for each mode.)
*/
private static class XMLTestSetup extends BaseJDBCTestSetup
{
public XMLTestSetup(TestSuite tSuite) {
super(tSuite);
}
/**
* Before running the tests in XMLTypeAndOps we create two
* base tables and insert the common "fixture" data.
*/
public void setUp() throws Exception
{
Connection c = getConnection();
Statement s = c.createStatement();
/* Create test tables as a fixture for this test. Note
* that we're implicitly testing the creation of XML columns
* as part of this setup. All of the following should
* succeed; see testXMLColCreation() for some tests where
* column creation is expected to fail.
*/
s.executeUpdate("create table t1 (i int, x xml)");
s.executeUpdate("create table t2 (x2 xml not null)");
s.executeUpdate("alter table t2 add column x1 xml");
/* Insert test data. Here we're implicitly tesing
* the XMLPARSE operator in situations where it should
* succeed. Negative test cases are tesed in the
* testIllegalNullInserts() and testXMLParse() methods
* of the XMLTypeAndOps class.
*/
// Null values.
assertUpdateCount(s, 1, "insert into t1 values (1, null)");
assertUpdateCount(s, 1,
"insert into t1 values (2, cast (null as xml))");
assertUpdateCount(s, 1, "insert into t1 (i) values (4)");
assertUpdateCount(s, 1, "insert into t1 values (3, default)");
// Non-null values.
assertUpdateCount(s, 1,
"insert into t1 values (5, xmlparse(document "
+ "'<hmm/>' preserve whitespace))");
assertUpdateCount(s, 1,
" insert into t1 values (6, xmlparse(document "
+ "'<half> <masted> bass </masted> boosted. </half>' "
+ "preserve whitespace))");
assertUpdateCount(s, 1,
" insert into t2 (x1, x2) values (null, "
+ "xmlparse(document '<notnull/>' preserve whitespace))");
assertUpdateCount(s, 1,
" insert into t1 values (7, xmlparse(document '<?xml "
+ "version=\"1.0\" encoding= \"UTF-8\"?><umm> decl "
+ "check </umm>' preserve whitespace))");
assertUpdateCount(s, 1,
"insert into t1 values (8, xmlparse(document '<lets> "
+ "<try> this out </try> </lets>' preserve whitespace))");
assertUpdateCount(s, 1,
" update t1 set x = xmlparse(document '<update> "
+ "document was inserted as part of an UPDATE "
+ "</update>' preserve whitespace) where i = 1");
assertUpdateCount(s, 1,
" update t1 set x = xmlparse(document '<update2> "
+ "document was inserted as part of an UPDATE "
+ "</update2>' preserve whitespace) where "
+ "xmlexists('/update' passing by ref x)");
s.close();
c.close();
s = null;
c= null;
}
/**
* For test teardown we just drop the two tables we created in
* test setup and then clean up local objects if needed.
*/
public void tearDown() throws Exception
{
Connection c = getConnection();
Statement s = c.createStatement();
s.executeUpdate("drop table t1");
s.executeUpdate("drop table t2");
s.close();
c.close();
s = null;
c = null;
super.tearDown();
}
}
}
| java/testing/org/apache/derbyTesting/functionTests/tests/lang/XMLTypeAndOpsTest.java | /*
*
* Derby - Class org.apache.derbyTesting.functionTests.tests.lang.XMLTypeAndOpsTest
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package org.apache.derbyTesting.functionTests.tests.lang;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.XML;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.BaseJDBCTestSetup;
import org.apache.derbyTesting.junit.TestConfiguration;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Types;
/**
* XMLTypeAndOpsTest this test is the JUnit equivalent to what used
* to be the "lang/xml_general.sql" test, which was canon-based.
* Since the .sql test had different masters for embedded, JCC, and
* Derby Client, and since it performed some "sed'ing" to ensure
* consistent results across JVMs, it was not sufficient to just
* wrap the test in a JUnit ScriptTestCase (because ScriptTestCase
* doesn't deal with multiple masters nor with sed'ing). Hence the
* creation of this pure JUnit version of the test.
*/
public final class XMLTypeAndOpsTest extends BaseJDBCTestCase {
/* For the test methods in this class, "expRS" refers to a
* two-dimensional array representing an expected result set when
* executing queries. The "rows" and "columns" in this array
* are compard with those from a SQL ResultSet. Note that all
* values are represented as Strings here; we don't actually
* check the *types* of the columns; just their values. This
* is because this test was created from a .sql test, where
* results are similarly treated (i.e. in an ij test with a
* .sql file, the test passes if the values "look the same";
* there's no checking of specific value types for most query
* results. So we do the same for this JUnit test).
*/
/**
* Public constructor required for running test as standalone JUnit.
*/
public XMLTypeAndOpsTest(String name)
{
super(name);
}
/**
* Return a suite that runs a set of tests which are meant to
* be the equivalent to the test cases in the old xml_general.sql.
* But only return such a suite IF the testing classpath has the
* required XML classes. Otherwise just return an empty suite.
*/
public static Test suite()
{
TestSuite suite = new TestSuite("XML Type and Operators Suite\n");
if (!XML.classpathMeetsXMLReqs())
return suite;
/* "false" in the next line means that we will *not* clean the
* database before the embedded and client suites. This ensures
* that we do not remove the objects created by XMLTestSetup.
*/
suite.addTest(
TestConfiguration.defaultSuite(XMLTypeAndOpsTest.class, false));
return (new XMLTestSetup(suite));
}
/**
* Test creation of XML columns.
*/
public void testXMLColCreation() throws Exception
{
// If the column's definition doesn't make sense for XML,
// then we should throw the correct error.
Statement st = createStatement();
assertStatementError("42894", st,
"create table fail1 (i int, x xml default 'oops')");
assertStatementError("42894", st,
"create table fail2 (i int, x xml default 8)");
assertStatementError("42818", st,
"create table fail3 (i int, x xml check (x != 0))");
// These should all work.
st.executeUpdate("create table tc1 (i int, x xml)");
st.executeUpdate("create table tc2 (i int, x xml not null)");
st.executeUpdate("create table tc3 (i int, x xml default null)");
st.executeUpdate("create table tc4 (x2 xml not null)");
st.executeUpdate("alter table tc4 add column x1 xml");
// Cleanup.
st.executeUpdate("drop table tc1");
st.executeUpdate("drop table tc2");
st.executeUpdate("drop table tc3");
st.executeUpdate("drop table tc4");
st.close();
}
/**
* Check insertion of null values into XML columns. This
* test just checks the negative cases--i.e. cases where
* we expect the insertions to fail. The positive cases
* are tested implicitly as part of XMLTestSetup.setUp()
* when we load the test data.
*/
public void testIllegalNullInserts() throws Exception
{
// These should fail because target column is declared
// as non-null.
Statement st = createStatement();
st.executeUpdate("create table tc2 (i int, x xml not null)");
assertStatementError("23502", st, "insert into tc2 values (1, null)");
assertStatementError("23502", st,
"insert into tc2 values (2, cast (null as xml))");
st.executeUpdate("drop table tc2");
st.close();
}
/**
* Test insertion of non-XML values into XML columns. These
* should all fail because such an operation is not allowed.
*/
public void testXMLColsWithNonXMLVals() throws Exception
{
Statement st = createStatement();
assertStatementError("42821", st, "insert into t1 values (3, 'hmm')");
assertStatementError("42821", st, "insert into t1 values (1, 2)");
assertStatementError("42821", st,
" insert into t1 values (1, 123.456)");
assertStatementError("42821", st, "insert into t1 values (1, x'01')");
assertStatementError("42821", st, "insert into t1 values (1, x'ab')");
assertStatementError("42821", st,
"insert into t1 values (1, current date)");
assertStatementError("42821", st,
" insert into t1 values (1, current time)");
assertStatementError("42821", st,
" insert into t1 values (1, current timestamp)");
assertStatementError("42821", st,
" insert into t1 values (1, ('hmm' || 'andstuff'))");
st.close();
}
/**
* Test insertion of XML values into non-XML columns. These
* should all fail because such an operation is not allowed.
*/
public void testNonXMLColsWithXMLVals() throws Exception
{
Statement st = createStatement();
st.executeUpdate(
"create table nonXTable (si smallint, i int, bi bigint, vcb "
+ "varchar (32) for bit data, nu numeric(10,2), f "
+ "float, d double, vc varchar(20), da date, ti time, "
+ "ts timestamp, cl clob, bl blob)");
assertStatementError("42821", st,
"insert into nonXTable (si) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (i) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (bi) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (vcb) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (nu) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (f) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (d) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (vc) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (da) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (ti) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (ts) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (cl) values (cast (null as xml))");
assertStatementError("42821", st,
"insert into nonXTable (bl) values (cast (null as xml))");
// And just to be safe, try to insert a non-null XML
// value. This should fail, too.
assertStatementError("42821", st,
"insert into nonXTable (cl) values (xmlparse(document " +
"'</simp>' preserve whitespace))");
st.executeUpdate("drop table nonXTable");
st.close();
}
/**
* Test casting of values to type XML. These should all
* fail because such casting is not allowed.
*/
public void testXMLCasting() throws Exception
{
Statement st = createStatement();
assertStatementError("42846", st,
"insert into t1 values (1, cast ('hmm' as xml))");
assertStatementError("42846", st,
"insert into t1 values (1, cast (2 as xml))");
assertStatementError("42846", st,
"insert into t1 values (1, cast (123.456 as xml))");
assertStatementError("42846", st,
"insert into t1 values (1, cast (x'01' as xml))");
assertStatementError("42846", st,
"insert into t1 values (1, cast (x'ab' as xml))");
assertStatementError("42846", st,
"insert into t1 values (1, cast (current date as xml))");
assertStatementError("42846", st,
"insert into t1 values (1, cast (current time as xml))");
assertStatementError("42846", st,
"insert into t1 values (1, cast (current timestamp as xml))");
assertStatementError("42846", st,
"insert into t1 values (1, cast (('hmm' || "
+ "'andstuff') as xml))");
// And try to cast an XML value into something else.
// These should fail, too.
st.executeUpdate("create table nonXTable (i int, cl clob)");
assertStatementError("42846", st,
"insert into nonXTable (cl) values (cast ((xmlparse(document " +
"'</simp>' preserve whitespace)) as clob))");
assertStatementError("42846", st,
"insert into nonXTable (i) values (cast ((xmlparse(document " +
"'</simp>' preserve whitespace)) as int))");
st.executeUpdate("drop table nonXTable");
st.close();
}
/**
* Try to use XML values in non-XML operations. These
* should all fail (the only operations allowed with XML
* are the specified XML operations (xmlparse, xmlserialize,
* xmlexists, xmlquery)).
*/
public void testXMLInNonXMLOps() throws Exception
{
Statement st = createStatement();
assertStatementError("42Y95", st, "select i + x from t1");
assertStatementError("42Y95", st, "select i * x from t1");
assertStatementError("42Y95", st, "select i / x from t1");
assertStatementError("42Y95", st, "select i - x from t1");
assertStatementError("42X37", st, "select -x from t1");
assertStatementError("42846", st, "select 'hi' || x from t1");
assertStatementError("42X25", st, "select substr(x, 0) from t1");
assertStatementError("42Y22", st, "select max(x) from t1");
assertStatementError("42Y22", st, "select min(x) from t1");
assertStatementError("42X25", st, "select length(x) from t1");
assertStatementError("42884", st,
"select i from t1 where x like 'hmm'");
st.close();
}
/**
* Test simple comparisons with XML. These should all fail
* because no such comparisons are allowed.
*/
public void testXMLComparisons() throws Exception
{
Statement st = createStatement();
assertStatementError("42818", st, "select i from t1 where x = 'hmm'");
assertStatementError("42818", st, "select i from t1 where x > 0");
assertStatementError("42818", st, "select i from t1 where x < x");
assertStatementError("42818", st,
"select i from t1 where x <> 'some char'");
st.close();
}
/**
* Test additional restrictions on use of XML values.
* These should all fail.
*/
public void testIllegalOps() throws Exception
{
// Indexing/ordering on XML cols is not allowed.
Statement st = createStatement();
assertStatementError("X0X67", st, "create index oops_ix on t1(x)");
assertStatementError("X0X67", st,
"select i from t1 where x is null order by x");
// XML cannot be imported or exported (DERBY-1892).
CallableStatement cSt = prepareCall(
"CALL SYSCS_UTIL.SYSCS_EXPORT_TABLE ("
+ " null, 'T1', 'extinout/xmlexport.del', null, null, null)");
assertStatementError("42Z71", cSt);
cSt = prepareCall(
" CALL SYSCS_UTIL.SYSCS_EXPORT_QUERY("
+ " 'select x from t1', 'extinout/xmlexport.del', null, null, null)");
assertStatementError("42Z71", cSt);
cSt = prepareCall(
" CALL SYSCS_UTIL.SYSCS_IMPORT_TABLE ("
+ " null, 'T1', 'extinout/shouldntmatter.del', null, null, null, 0)");
assertStatementError("XIE0B", cSt);
cSt = prepareCall(
" CALL SYSCS_UTIL.SYSCS_IMPORT_DATA ("
+ " NULL, 'T1', null, '2', 'extinout/shouldntmatter.del', "
+ "null, null, null,0)");
assertStatementError("XIE0B", cSt);
// Done with cSt.
cSt.close();
// XML cannot be used with procedures/functions.
assertStatementError("42962", st,
"create procedure hmmproc (in i int, in x xml)"
+ " parameter style java language java external name "
+ "'hi.there'");
assertStatementError("42962", st,
" create function hmmfunc (i int, x xml) returns int"
+ " parameter style java language java external name "
+ "'hi.there'");
// XML columns cannot be used for global temporary
// tables.
assertStatementError("42962", st,
"declare global temporary table SESSION.xglobal (myx XML)"
+ " not logged on commit preserve rows");
st.close();
}
/**
* Test use of XML columns in a trigger's "SET" clause. Should
* work so long as the target value has type XML.
*/
public void testTriggerSetXML() throws Exception
{
// This should fail.
Statement st = createStatement();
assertStatementError("42821", st,
"create trigger tr2 after insert on t1 for each row "
+ "mode db2sql update t1 set x = 'hmm'");
// This should succeed.
st.executeUpdate("create trigger tr1 after insert on t1 for each row "
+ "mode db2sql update t1 set x = null");
st.executeUpdate(" drop trigger tr1");
st.close();
}
/**
* Various tests for the XMLPARSE operator. Note that this
* test primarily checks the negative cases--i.e. cases where
* we expect the XMLPARSE op to fail. The positive cases
* were tested implicitly as part of XMLTestSetup.setUp()
* when we loaded the test data.
*/
public void testXMLParse() throws Exception
{
// These should fail with various parse errors.
Statement st = createStatement();
assertStatementError("42Z74", st,
"insert into t1 values (1, xmlparse(document "
+ "'<hmm/>' strip whitespace))");
assertStatementError("42Z72", st,
" insert into t1 values (1, xmlparse(document '<hmm/>'))");
assertStatementError("42Z72", st,
" insert into t1 values (1, xmlparse('<hmm/>' "
+ "preserve whitespace))");
assertStatementError("42Z74", st,
" insert into t1 values (1, xmlparse(content "
+ "'<hmm/>' preserve whitespace))");
assertStatementError("42X25", st,
" select xmlparse(document xmlparse(document "
+ "'<hein/>' preserve whitespace) preserve whitespace) from t1");
assertStatementError("42X19", st,
" select i from t1 where xmlparse(document '<hein/>' "
+ "preserve whitespace)");
// This should fail because operand does not constitute
// well-formed XML.
assertStatementError("2200M", st,
" insert into t1 values (1, xmlparse(document "
+ "'<oops>' preserve whitespace))");
// This should fail because use of a parameter for the operand
// requires an explicit CAST to a char type.
assertCompileError("42Z79",
"insert into t1(x) values XMLPARSE(document ? "
+ "preserve whitespace)");
// Creation of a table with a default as XMLPARSE should throw
// an error--use of functions as a default is not allowed
// by the Derby syntax.
assertCompileError("42894",
"create table fail1 (i int, x xml default xmlparse("
+ "document '<my>default col</my>' preserve whitespace))");
// XMLPARSE is valid operand for "is [not] null" so
// this should work (and we should see a row for every
// successful "insert" statement that we executed on T1).
ResultSet rs = st.executeQuery(
" select i from t1 where xmlparse(document '<hein/>' "
+ "preserve whitespace) is not null");
String [] expColNames = new String [] { "I" };
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"1"},
{"2"},
{"4"},
{"3"},
{"5"},
{"6"},
{"7"},
{"8"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Ensure that order by on a table with an XML column in it
// works correctly.
rs = st.executeQuery(
" select i from t1 where xmlparse(document '<hein/>' "
+ "preserve whitespace) is not null order by i");
expColNames = new String [] { "I" };
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1"},
{"2"},
{"3"},
{"4"},
{"5"},
{"6"},
{"7"},
{"8"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Insertions using XMLPARSE with a parameter that is cast
// to a character type should work.
st.execute("create table paramInsert(x xml)");
PreparedStatement pSt = prepareStatement(
"insert into paramInsert values XMLPARSE(document "
+ "cast (? as CLOB) preserve whitespace)");
pSt.setString(1, "<ay>caramba</ay>");
assertUpdateCount(pSt, 1);
pSt.close();
// Run a select to view everything that was inserted.
rs = st.executeQuery("select xmlserialize(x as clob) from t1");
expColNames = new String [] { "1" };
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<update2> document was inserted as part of an "
+ "UPDATE </update2>"},
{null},
{null},
{null},
{"<hmm/>"},
{"<half> <masted> bass </masted> boosted. </half>"},
{"<umm> decl check </umm>"},
{"<lets> <try> this out </try> </lets>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlserialize(x as clob) from paramInsert");
expColNames = new String [] { "1" };
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<ay>caramba</ay>"}
};
// Cleanup.
st.executeUpdate("drop table paramInsert");
st.close();
}
/**
* Test use of the "is [not] null" clause with XML values.
* These should work.
*/
public void testIsNull() throws Exception
{
Statement st = createStatement();
ResultSet rs = st.executeQuery(
"select i from t1 where x is not null");
String [] expColNames = new String [] { "I" };
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"1"},
{"5"},
{"6"},
{"7"},
{"8"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(" select i from t1 where x is null");
expColNames = new String [] { "I" };
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"2"},
{"4"},
{"3"}
};
JDBC.assertFullResultSet(rs, expRS, true);
st.close();
}
/**
* Derby doesn't currently support XML values in a top-level
* result set. So make sure that doesn't work. These should
* all fail.
*/
public void testTopLevelSelect() throws Exception
{
Statement st = createStatement();
st.executeUpdate("create table vcTab (vc varchar(100))");
assertStatementError("42Z71", st, "select x from t1");
assertStatementError("42Z71", st, "select * from t1");
assertStatementError("42Z71", st,
" select xmlparse(document vc preserve whitespace) from vcTab");
assertStatementError("42Z71", st,
" values xmlparse(document '<bye/>' preserve whitespace)");
assertStatementError("42Z71", st,
" values xmlparse(document '<hel' || 'lo/>' preserve "
+ "whitespace)");
st.executeUpdate("drop table vcTab");
st.close();
}
/**
* Various tests for the XMLSERIALIZE operator.
*/
public void testXMLSerialize() throws Exception
{
// Test setup.
Statement st = createStatement();
st.executeUpdate("create table vcTab (vc varchar(100))");
assertUpdateCount(st, 1, "insert into vcTab values ('<hmm/>')");
assertUpdateCount(st, 1, "insert into vcTab values 'no good'");
// These should fail with various parse errors.
assertStatementError("42Z72", st, "select xmlserialize(x) from t1");
assertStatementError("42X01", st, "select xmlserialize(x as) from t1");
assertStatementError("42Z73", st,
" select xmlserialize(x as int) from t1");
assertStatementError("42Z73", st,
" select xmlserialize(x as boolean) from t1");
assertStatementError("42Z73", st,
" select xmlserialize(x as varchar(20) for bit data) from t1");
assertStatementError("42X04", st,
" select xmlserialize(y as char(10)) from t1");
assertStatementError("42X25", st,
" select xmlserialize(xmlserialize(x as clob) as "
+ "clob) from t1");
assertStatementError("42X25", st,
" values xmlserialize('<okay> dokie </okay>' as clob)");
// These should succeed.
ResultSet rs = st.executeQuery("select xmlserialize(x as clob) from t1");
String [] expColNames = new String [] { "1" };
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"<update2> document was inserted as part of an "
+ "UPDATE </update2>"},
{null},
{null},
{null},
{"<hmm/>"},
{"<half> <masted> bass </masted> boosted. </half>"},
{"<umm> decl check </umm>"},
{"<lets> <try> this out </try> </lets>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlserialize(x1 as clob), xmlserialize(x2 as "
+ "clob) from t2");
expColNames = new String [] {"1", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{null, "<notnull/>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlserialize(x as char(100)) from t1");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<update2> document was inserted as part of an "
+ "UPDATE </update2>"},
{null},
{null},
{null},
{"<hmm/>"},
{"<half> <masted> bass </masted> boosted. </half>"},
{"<umm> decl check </umm>"},
{"<lets> <try> this out </try> </lets>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlserialize(x as varchar(300)) from t1");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<update2> document was inserted as part of an "
+ "UPDATE </update2>"},
{null},
{null},
{null},
{"<hmm/>"},
{"<half> <masted> bass </masted> boosted. </half>"},
{"<umm> decl check </umm>"},
{"<lets> <try> this out </try> </lets>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// This should succeed at the XMLPARSE level, but fail
// with parse/truncation errors at the XMLSERIALIZE.
assertStatementError("2200M", st,
"select xmlserialize(xmlparse(document vc preserve "
+ "whitespace) as char(10)) from vcTab");
// These should all fail with truncation errors.
assertStatementError("22001", st,
" select xmlserialize(x as char) from t1");
assertStatementError("22001", st,
" select xmlserialize(x as clob(10)) from t1");
assertStatementError("22001", st,
" select xmlserialize(x as char(1)) from t1");
assertStatementError("22001", st,
" select length(xmlserialize(x as char(1))) from t1");
assertStatementError("22001", st,
" select xmlserialize(x as varchar(1)) from t1");
assertStatementError("22001", st,
" select length(xmlserialize(x as varchar(1))) from t1");
// These checks verify that the XMLSERIALIZE result is the
// correct type.
rs = st.executeQuery("select xmlserialize(x as char(100)) from t1");
ResultSetMetaData rsmd = rs.getMetaData();
assertEquals("Incorrect XMLSERIALIZE result type:",
Types.CHAR, rsmd.getColumnType(1));
rs = st.executeQuery("select xmlserialize(x as varchar(100)) from t1");
rsmd = rs.getMetaData();
assertEquals("Incorrect XMLSERIALIZE result type:",
Types.VARCHAR, rsmd.getColumnType(1));
rs = st.executeQuery("select xmlserialize(x as long varchar) from t1");
rsmd = rs.getMetaData();
assertEquals("Incorrect XMLSERIALIZE result type:",
Types.LONGVARCHAR, rsmd.getColumnType(1));
rs = st.executeQuery("select xmlserialize(x as clob(100)) from t1");
rsmd = rs.getMetaData();
assertEquals("Incorrect XMLSERIALIZE result type:",
Types.CLOB, rsmd.getColumnType(1));
// Cleanup.
rs.close();
st.executeUpdate("drop table vcTab");
st.close();
}
/**
* Various tests with XMLPARSE and XMLSERIALIZE combinations.
*/
public void testXMLParseSerializeCombos() throws Exception
{
// These should fail at the XMLPARSE level.
Statement st = createStatement();
assertStatementError("2200M", st,
"select xmlserialize(xmlparse(document '<hmm>' "
+ "preserve whitespace) as clob) from t1");
assertStatementError("42X25", st,
" select xmlserialize(xmlparse(document x preserve "
+ "whitespace) as char(100)) from t1");
// These should succeed.
ResultSet rs = st.executeQuery(
"select xmlserialize(xmlparse(document '<hmm/>' "
+ "preserve whitespace) as clob) from t1 where i = 1");
String [] expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"<hmm/>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlserialize(xmlparse(document "
+ "xmlserialize(x as clob) preserve whitespace) as "
+ "clob) from t1");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<update2> document was inserted as part of an "
+ "UPDATE </update2>"},
{null},
{null},
{null},
{"<hmm/>"},
{"<half> <masted> bass </masted> boosted. </half>"},
{"<umm> decl check </umm>"},
{"<lets> <try> this out </try> </lets>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"values xmlserialize(xmlparse(document '<okay> dokie "
+ "</okay>' preserve whitespace) as clob)");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<okay> dokie </okay>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i from t1 where xmlparse(document "
+ "xmlserialize(x as clob) preserve whitespace) is not "
+ "null order by i");
expColNames = new String [] {"I"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1"},
{"5"},
{"6"},
{"7"},
{"8"}
};
JDBC.assertFullResultSet(rs, expRS, true);
st.close();
}
/**
* Various tests for the XMLEXISTS operator.
*/
public void testXMLExists() throws Exception
{
// These should fail with various parse errors.
Statement st = createStatement();
assertStatementError("42X01", st,
"select i from t1 where xmlexists(x)");
assertStatementError("42X01", st,
"select i from t1 where xmlexists(i)");
assertStatementError("42X01", st,
"select i from t1 where xmlexists('//*')");
assertStatementError("42X01", st,
"select i from t1 where xmlexists('//*' x)");
assertStatementError("42X01", st,
"select i from t1 where xmlexists('//*' passing x)");
assertStatementError("42Z74", st,
"select i from t1 where xmlexists('//*' passing by value x)");
assertStatementError("42Z77", st,
"select i from t1 where xmlexists('//*' passing by ref i)");
assertStatementError("42Z75", st,
"select i from t1 where xmlexists(i passing by ref x)");
assertStatementError("42Z76", st,
"select i from t1 where xmlexists(i passing by ref x, x)");
// These should succeed.
ResultSet rs = st.executeQuery(
"select i from t1 where xmlexists('//*' passing by ref x)");
String [] expColNames = new String [] {"I"};
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"1"},
{"5"},
{"6"},
{"7"},
{"8"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// This should succeed but return no rows.
rs = st.executeQuery(
"select i from t1 where xmlexists('//person' passing "
+ "by ref x)");
expColNames = new String [] {"I"};
JDBC.assertColumnNames(rs, expColNames);
JDBC.assertDrainResults(rs, 0);
// This should return one row.
rs = st.executeQuery(
"select i from t1 where xmlexists('//lets' passing by ref x)");
expColNames = new String [] {"I"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"8"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// XMLEXISTS should return null if the operand is null.
rs = st.executeQuery(
"select xmlexists('//lets' passing by ref x) from t1");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{null},
{null},
{null},
{"false"},
{"false"},
{"false"},
{"true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//try[text()='' this out '']' "
+ "passing by ref x) from t1");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{null},
{null},
{null},
{"false"},
{"false"},
{"false"},
{"true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//let' passing by ref x) from t1");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{null},
{null},
{null},
{"false"},
{"false"},
{"false"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//try[text()='' this in '']' "
+ "passing by ref x) from t1");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{null},
{null},
{null},
{"false"},
{"false"},
{"false"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Make sure selection of other columns along with XMLEXISTS
// still works.
rs = st.executeQuery(
"select i, xmlexists('//let' passing by ref x) from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "false"},
{"2", null},
{"4", null},
{"3", null},
{"5", "false"},
{"6", "false"},
{"7", "false"},
{"8", "false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i, xmlexists('//lets' passing by ref x) from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "false"},
{"2", null},
{"4", null},
{"3", null},
{"5", "false"},
{"6", "false"},
{"7", "false"},
{"8", "true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// XMLEXISTS should work in a VALUES clause, too.
rs = st.executeQuery(
"values xmlexists('//let' passing by ref "
+ "xmlparse(document '<lets> try this </lets>' "
+ "preserve whitespace))");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"values xmlexists('//lets' passing by ref "
+ "xmlparse(document '<lets> try this </lets>' "
+ "preserve whitespace))");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Simple check for attribute existence.
rs = st.executeQuery(
"values xmlexists('//lets/@doit' passing by ref "
+ "xmlparse(document '<lets doit=\"true\"> try this "
+ "</lets>' preserve whitespace))");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"values xmlexists('//lets/@dot' passing by ref "
+ "xmlparse(document '<lets doit=\"true\"> try this "
+ "</lets>' preserve whitespace))");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// XMLEXISTS in a WHERE clause.
rs = st.executeQuery(
"select xmlserialize(x1 as clob) from t2 where "
+ "xmlexists('//*' passing by ref x1)");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
JDBC.assertDrainResults(rs, 0);
rs = st.executeQuery(
"select xmlserialize(x2 as clob) from t2 where "
+ "xmlexists('//*' passing by ref x2)");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<notnull/>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlserialize(x1 as clob), xmlexists('//*' "
+ "passing by ref xmlparse(document '<badboy/>' "
+ "preserve whitespace)) from t2");
expColNames = new String [] {"1", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{null, "true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlserialize(x1 as clob), "
+ "xmlexists('//goodboy' passing by ref "
+ "xmlparse(document '<badboy/>' preserve whitespace)) from t2");
expColNames = new String [] {"1", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{null, "false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Add some more test tables/data.
st.executeUpdate(
"create table xqExists2 (i int, x1 xml, x2 xml not null)");
assertUpdateCount(st, 1,
" insert into xqExists2 values (1, null, xmlparse(document "
+ "'<ok/>' preserve whitespace))");
rs = st.executeQuery(
"select i, xmlserialize(x1 as char(10)), "
+ "xmlserialize (x2 as char(10)) from xqExists2");
expColNames = new String [] {"I", "2", "3"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", null, "<ok/>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Now run some XMLEXISTS queries on xqExists2 using boolean
// operations ('and', 'or') on the XMLEXISTS result.
rs = st.executeQuery(
"select i from xqExists2 where xmlexists('/ok' passing by "
+ "ref x1) and xmlexists('/ok' passing by ref x2)");
expColNames = new String [] {"I"};
JDBC.assertColumnNames(rs, expColNames);
JDBC.assertDrainResults(rs, 0);
rs = st.executeQuery(
"select i from xqExists2 where xmlexists('/ok' passing by "
+ "ref x1) or xmlexists('/ok' passing by ref x2)");
expColNames = new String [] {"I"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// XMLEXISTS can be used wherever a boolean function is
// allowed, for ex, a check constraint...
st.executeUpdate(
"create table xqExists1 (i int, x xml check "
+ "(xmlexists('//should' passing by ref x)))");
assertUpdateCount(st, 1,
" insert into xqExists1 values (1, xmlparse(document "
+ "'<should/>' preserve whitespace))");
assertStatementError("23513", st,
" insert into xqExists1 values (1, xmlparse(document "
+ "'<shouldnt/>' preserve whitespace))");
rs = st.executeQuery(
"select xmlserialize(x as char(20)) from xqExists1");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<should/>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Do some namespace queries/examples.
st.executeUpdate("create table xqExists3 (i int, x xml)");
assertUpdateCount(st, 1,
" insert into xqExists3 values (1, xmlparse(document '<a:hi "
+ "xmlns:a=\"http://www.hi.there\"/>' preserve whitespace))");
assertUpdateCount(st, 1,
" insert into xqExists3 values (2, xmlparse(document '<b:hi "
+ "xmlns:b=\"http://www.hi.there\"/>' preserve whitespace))");
assertUpdateCount(st, 1,
" insert into xqExists3 values (3, xmlparse(document "
+ "'<a:bye xmlns:a=\"http://www.good.bye\"/>' preserve "
+ "whitespace))");
assertUpdateCount(st, 1,
" insert into xqExists3 values (4, xmlparse(document "
+ "'<b:bye xmlns:b=\"http://www.hi.there\"/>' preserve "
+ "whitespace))");
assertUpdateCount(st, 1,
" insert into xqExists3 values (5, xmlparse(document "
+ "'<hi/>' preserve whitespace))");
rs = st.executeQuery(
"select xmlexists('//child::*[name()=\"none\"]' "
+ "passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{"false"},
{"false"},
{"false"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//child::*[name()=''hi'']' "
+ "passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{"false"},
{"false"},
{"false"},
{"true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//child::*[local-name()=''hi'']' "
+ "passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"true"},
{"true"},
{"false"},
{"false"},
{"true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//child::*[local-name()=''bye'']' "
+ "passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{"false"},
{"true"},
{"true"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select "
+ "xmlexists('//*[namespace::*[string()=''http://www.hi"
+ ".there'']]' passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"true"},
{"true"},
{"false"},
{"true"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select "
+ "xmlexists('//*[namespace::*[string()=''http://www.go"
+ "od.bye'']]' passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{"false"},
{"true"},
{"false"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//child::*[local-name()=''hi'' "
+ "and "
+ "namespace::*[string()=''http://www.hi.there'']]' "
+ "passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"true"},
{"true"},
{"false"},
{"false"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//child::*[local-name()=''bye'' "
+ "and "
+ "namespace::*[string()=''http://www.good.bye'']]' "
+ "passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{"false"},
{"true"},
{"false"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select xmlexists('//child::*[local-name()=''bye'' "
+ "and "
+ "namespace::*[string()=''http://www.hi.there'']]' "
+ "passing by ref x) from xqExists3");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"false"},
{"false"},
{"false"},
{"true"},
{"false"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Cleanup.
st.executeUpdate("drop table xqExists1");
st.executeUpdate("drop table xqExists2");
st.executeUpdate("drop table xqExists3");
st.close();
}
/**
* Various tests for the XMLQUERY operator.
*/
public void testXMLQuery() throws Exception
{
// These should fail w/ syntax errors.
Statement st = createStatement();
assertStatementError("42X01", st, "select i, xmlquery('//*') from t1");
assertStatementError("42X01", st,
" select i, xmlquery('//*' passing) from t1");
assertStatementError("42X01", st,
" select i, xmlquery('//*' passing by ref x) from t1");
assertStatementError("42X01", st,
" select i, xmlquery('//*' passing by ref x "
+ "returning sequence) from t1");
assertStatementError("42X01", st,
" select i, xmlquery(passing by ref x empty on empty) from t1");
assertStatementError("42X01", st,
" select i, xmlquery(xmlquery('//*' returning "
+ "sequence empty on empty) as char(75)) from t1");
// These should fail with "not supported" errors.
assertStatementError("42Z74", st,
"select i, xmlquery('//*' passing by ref x returning "
+ "sequence null on empty) from t1");
assertStatementError("42Z74", st,
" select i, xmlquery('//*' passing by ref x "
+ "returning content empty on empty) from t1");
// This should fail because XMLQUERY returns an XML value
// which is not allowed in top-level result set.
assertStatementError("42Z71", st,
"select i, xmlquery('//*' passing by ref x empty on "
+ "empty) from t1");
// These should fail because context item must be XML.
assertStatementError("42Z77", st,
"select i, xmlquery('//*' passing by ref i empty on "
+ "empty) from t1");
assertStatementError("42Z77", st,
" select i, xmlquery('//*' passing by ref 'hello' "
+ "empty on empty) from t1");
assertStatementError("42Z77", st,
" select i, xmlquery('//*' passing by ref cast "
+ "('hello' as clob) empty on empty) from t1");
// This should fail because the function is not recognized
// by Xalan. The failure should be an error from Xalan
// saying what the problem is; it should *NOT* be a NPE,
// which is what we were seeing before DERBY-688 was completed.
assertStatementError("10000", st,
"select i,"
+ " xmlserialize("
+ " xmlquery('data(//@*)' passing by ref x "
+ "returning sequence empty on empty)"
+ " as char(70))"
+ "from t1");
// These should all succeed. Since it's Xalan that's
// actually doing the query evaluation we don't need to
// test very many queries; we just want to make sure we get
// the correct results when there is an empty sequence,
// when the xml context is null, and when there is a
// sequence with one or more nodes/items in it. So we just
// try out some queries and look at the results. The
// selection of queries is random and is not meant to be
// exhaustive.
ResultSet rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('2+2' passing by ref x returning "
+ "sequence empty on empty)"
+ " as char(70))"
+ "from t1");
String [] expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"1", "4"},
{"2", null},
{"4", null},
{"3", null},
{"5", "4"},
{"6", "4"},
{"7", "4"},
{"8", "4"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('./notthere' passing by ref x "
+ "returning sequence empty on empty)"
+ " as char(70))"
+ "from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", ""},
{"2", null},
{"4", null},
{"3", null},
{"5", ""},
{"6", ""},
{"7", ""},
{"8", ""}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('//*' passing by ref x empty on empty)"
+ " as char(70))"
+ "from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "<update2> document was inserted as part of an "
+ "UPDATE </update2>"},
{"2", null},
{"4", null},
{"3", null},
{"5", "<hmm/>"},
{"6", "<half> <masted> bass </masted> boosted. "
+ "</half><masted> bass </masted>"},
{"7", "<umm> decl check </umm>"},
{"8", "<lets> <try> this out </try> </lets><try> this out </try>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('//*[text() = \" bass \"]' passing by "
+ "ref x empty on empty)"
+ " as char(70))"
+ "from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", ""},
{"2", null},
{"4", null},
{"3", null},
{"5", ""},
{"6", "<masted> bass </masted>"},
{"7", ""},
{"8", ""}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('//lets' passing by ref x empty on empty)"
+ " as char(70))"
+ "from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", ""},
{"2", null},
{"4", null},
{"3", null},
{"5", ""},
{"6", ""},
{"7", ""},
{"8", "<lets> <try> this out </try> </lets>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('//text()' passing by ref x empty on empty)"
+ " as char(70))"
+ "from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "document was inserted as part of an UPDATE"},
{"2", null},
{"4", null},
{"3", null},
{"5", ""},
{"6", "bass boosted."},
{"7", "decl check"},
{"8", "this out"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('//try[text()='' this out '']' passing "
+ "by ref x empty on empty)"
+ " as char(70))"
+ "from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", ""},
{"2", null},
{"4", null},
{"3", null},
{"5", ""},
{"6", ""},
{"7", ""},
{"8", "<try> this out </try>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('//try[text()='' this in '']' passing "
+ "by ref x empty on empty)"
+ " as char(70))"
+ "from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", ""},
{"2", null},
{"4", null},
{"3", null},
{"5", ""},
{"6", ""},
{"7", ""},
{"8", ""}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('2+.//try' passing by ref x returning "
+ "sequence empty on empty)"
+ " as char(70))"
+ "from t1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "NaN"},
{"2", null},
{"4", null},
{"3", null},
{"5", "NaN"},
{"6", "NaN"},
{"7", "NaN"},
{"8", "NaN"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"values ('x', xmlserialize("
+ " xmlquery('//let' passing by ref"
+ " xmlparse(document '<lets> try this </lets>' "
+ "preserve whitespace)"
+ " empty on empty)"
+ "as char(30)))");
expColNames = new String [] {"1", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"x", ""}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"values xmlserialize("
+ " xmlquery('//lets' passing by ref"
+ " xmlparse(document '<lets> try this </lets>' "
+ "preserve whitespace)"
+ " empty on empty)"
+ "as char(30))");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"<lets> try this </lets>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
st.close();
}
/* Check insertion of XMLQUERY result into a table. Should
* only allow results that are a sequence of exactly one
* Document node.
*/
public void testXMLQueryInsert() throws Exception
{
// Create test table and data specific to this test.
Statement st = createStatement();
st.executeUpdate("create table xqInsert1 (i int, x xml not null)");
assertUpdateCount(st, 1,
" insert into xqInsert1 values (1, xmlparse(document "
+ "'<should> work as planned </should>' preserve whitespace))");
st.executeUpdate("create table xqInsert2 (i int, x xml default null)");
assertUpdateCount(st, 1,
"insert into xqInsert2 values ("
+ " 9,"
+ " xmlparse(document '<here><is><my "
+ "height=\"4.4\">attribute</my></is></here>' preserve "
+ "whitespace)"
+ ")");
assertUpdateCount(st, 1,
" insert into xqInsert2 values ("
+ " 0,"
+ " xmlparse(document '<there><goes><my "
+ "weight=\"180\">attribute</my></goes></there>' "
+ "preserve whitespace)"
+ ")");
// Show target tables before insertions.
ResultSet rs = st.executeQuery(
"select i, xmlserialize(x as char(75)) from xqInsert1");
String [] expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"1", "<should> work as planned </should>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i, xmlserialize(x as char(75)) from xqInsert2");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"9", "<here><is><my height=\"4.4\">attribute</my></is></here>"},
{"0", "<there><goes><my "
+ "weight=\"180\">attribute</my></goes></there>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// These should all fail because the result of the XMLQUERY
// op is not a valid document (it's either an empty
// sequence, a node that is not a Document node, some
// undefined value, or a sequence with more than one item
// in it).
assertStatementError("2200L", st,
"insert into xqInsert1 (i, x) values ("
+ " 20, "
+ " (select"
+ " xmlquery('./notthere' passing by ref x "
+ "returning sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
assertStatementError("2200L", st,
" insert into xqInsert1 (i, x) values ("
+ " 21,"
+ " (select"
+ " xmlquery('//@*' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
assertStatementError("2200L", st,
" insert into xqInsert1 (i, x) values ("
+ " 22,"
+ " (select"
+ " xmlquery('. + 2' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
assertStatementError("2200L", st,
" insert into xqInsert1 (i, x) values ("
+ " 23,"
+ " (select"
+ " xmlquery('//*' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
assertStatementError("2200L", st,
" insert into xqInsert1 (i, x) values ("
+ " 24,"
+ " (select"
+ " xmlquery('//*[//@*]' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
assertStatementError("2200L", st,
" insert into xqInsert1 (i, x) values ("
+ " 25,"
+ " (select"
+ " xmlquery('//is' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
assertStatementError("2200L", st,
" insert into xqInsert1 (i, x) values ("
+ " 26,"
+ " (select"
+ " xmlquery('//*[@*]' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
// These should succeed.
assertUpdateCount(st, 1,
"insert into xqInsert1 (i, x) values ("
+ " 27,"
+ " (select"
+ " xmlquery('.' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
assertUpdateCount(st, 1,
" insert into xqInsert1 (i, x) values ("
+ " 28,"
+ " (select"
+ " xmlquery('/here/..' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 9"
+ " )"
+ ")");
// Verify results.
rs = st.executeQuery(
"select i, xmlserialize(x as char(75)) from xqInsert1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "<should> work as planned </should>"},
{"27", "<here><is><my height=\"4.4\">attribute</my></is></here>"},
{"28", "<here><is><my height=\"4.4\">attribute</my></is></here>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Next two should _both_ succeed because there's no row
// with i = 100 in xqInsert2, thus the SELECT will return null
// and XMLQUERY operator should never get executed. x will be
// NULL in these cases.
assertUpdateCount(st, 1,
"insert into xqInsert2 (i, x) values ("
+ " 29,"
+ " (select"
+ " xmlquery('2+2' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 100"
+ " )"
+ ")");
assertUpdateCount(st, 1,
" insert into xqInsert2 (i, x) values ("
+ " 30,"
+ " (select"
+ " xmlquery('.' passing by ref x returning "
+ "sequence empty on empty)"
+ " from xqInsert2 where i = 100"
+ " )"
+ ")");
// Verify results.
rs = st.executeQuery(
"select i, xmlserialize(x as char(75)) from xqInsert2");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"9", "<here><is><my height=\"4.4\">attribute</my></is></here>"},
{"0", "<there><goes><my "
+ "weight=\"180\">attribute</my></goes></there>"},
{"29", null},
{"30", null}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Cleanup.
st.executeUpdate("drop table xqInsert1");
st.executeUpdate("drop table xqInsert2");
st.close();
}
/* Check updates using XMLQUERY results. Should only allow
* results that constitute a valid DOCUMENT node (i.e. that
* can be parsed by the XMLPARSE operator).
*/
public void testXMLQueryUpdate() throws Exception
{
// Create test table and data.
Statement st = createStatement();
st.executeUpdate("create table xqUpdate (i int, x xml default null)");
assertUpdateCount(st, 2, "insert into xqUpdate (i) values 29, 30");
assertUpdateCount(st, 1,
"insert into xqUpdate values ("
+ " 9,"
+ " xmlparse(document '<here><is><my "
+ "height=\"4.4\">attribute</my></is></here>' preserve "
+ "whitespace)"
+ ")");
// These updates should succeed.
assertUpdateCount(st, 1,
"update xqUpdate"
+ " set x = "
+ " xmlquery('.' passing by ref"
+ " xmlparse(document '<none><here/></none>' "
+ "preserve whitespace)"
+ " returning sequence empty on empty)"
+ "where i = 29");
assertUpdateCount(st, 1,
" update xqUpdate"
+ " set x = "
+ " xmlquery('self::node()[//@height]' passing by ref"
+ " (select"
+ " xmlquery('.' passing by ref x empty on empty)"
+ " from xqUpdate"
+ " where i = 9"
+ " )"
+ " empty on empty)"
+ "where i = 30");
// These should fail because result of XMLQUERY isn't a
// DOCUMENT.
assertStatementError("2200L", st,
"update xqUpdate"
+ " set x = xmlquery('.//*' passing by ref x empty on empty)"
+ "where i = 29");
assertStatementError("2200L", st,
" update xqUpdate"
+ " set x = xmlquery('./notthere' passing by ref x "
+ "empty on empty)"
+ "where i = 30");
assertStatementError("2200L", st,
" update xqUpdate"
+ " set x ="
+ " xmlquery('//*[@weight]' passing by ref"
+ " (select"
+ " xmlquery('.' passing by ref x empty on empty)"
+ " from xqUpdate"
+ " where i = 9"
+ " )"
+ " empty on empty)"
+ "where i = 30");
assertStatementError("2200L", st,
" update xqUpdate"
+ " set x ="
+ " xmlquery('//*/@height' passing by ref"
+ " (select"
+ " xmlquery('.' passing by ref x empty on empty)"
+ " from xqUpdate"
+ " where i = 9"
+ " )"
+ " empty on empty)"
+ "where i = 30");
// Next two should succeed because there's no row with i =
// 100 in xqUpdate and thus xqUpdate should remain unchanged after
// these updates.
assertUpdateCount(st, 0,
"update xqUpdate"
+ " set x = xmlquery('//*' passing by ref x empty on empty)"
+ "where i = 100");
assertUpdateCount(st, 0,
" update xqUpdate"
+ " set x = xmlquery('4+4' passing by ref x empty on empty)"
+ "where i = 100");
// Verify results.
ResultSet rs = st.executeQuery(
"select i, xmlserialize(x as char(75)) from xqUpdate");
String [] expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"29", "<none><here/></none>"},
{"30", "<here><is><my height=\"4.4\">attribute</my></is></here>"},
{"9", "<here><is><my height=\"4.4\">attribute</my></is></here>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Cleanup.
st.executeUpdate("drop table xqUpdate");
st.close();
}
/* Pass results of an XMLQUERY op into another XMLQUERY op.
* Should work so long as results of the first op constitute
* a valid document.
*/
public void testNestedXMLQuery() throws Exception
{
// Should fail because result of inner XMLQUERY op
// isn't a valid document.
Statement st = createStatement();
assertStatementError("2200V", st,
"select i,"
+ " xmlserialize("
+ " xmlquery('//lets/@*' passing by ref"
+ " xmlquery('/okay/text()' passing by ref"
+ " xmlparse(document '<okay><lets "
+ "boki=\"inigo\"/></okay>' preserve whitespace)"
+ " empty on empty)"
+ " empty on empty)"
+ " as char(100))"
+ "from t1 where i > 5");
assertStatementError("2200V", st,
" select i,"
+ " xmlserialize("
+ " xmlquery('.' passing by ref"
+ " xmlquery('//lets' passing by ref"
+ " xmlparse(document '<okay><lets "
+ "boki=\"inigo\"/></okay>' preserve whitespace)"
+ " empty on empty)"
+ " empty on empty)"
+ " as char(100))"
+ "from t1 where i > 5");
assertStatementError("2200V", st,
" select i,"
+ " xmlexists('.' passing by ref"
+ " xmlquery('/okay' passing by ref"
+ " xmlparse(document '<okay><lets "
+ "boki=\"inigo\"/></okay>' preserve whitespace)"
+ " empty on empty)"
+ " )"
+ "from t1 where i > 5");
// Should succeed but result is empty sequence.
ResultSet rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('/not' passing by ref"
+ " xmlquery('.' passing by ref"
+ " xmlparse(document '<okay><lets "
+ "boki=\"inigo\"/></okay>' preserve whitespace)"
+ " empty on empty)"
+ " empty on empty)"
+ " as char(100))"
+ "from t1 where i > 5");
String [] expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"6", ""},
{"7", ""},
{"8", ""}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Should succeed with various results.
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('//lets' passing by ref"
+ " xmlquery('.' passing by ref"
+ " xmlparse(document '<okay><lets "
+ "boki=\"inigo\"/></okay>' preserve whitespace)"
+ " empty on empty)"
+ " empty on empty)"
+ " as char(100))"
+ "from t1 where i > 5");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"6", "<lets boki=\"inigo\"/>"},
{"7", "<lets boki=\"inigo\"/>"},
{"8", "<lets boki=\"inigo\"/>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('string(//@boki)' passing by ref"
+ " xmlquery('/okay/..' passing by ref"
+ " xmlparse(document '<okay><lets "
+ "boki=\"inigo\"/></okay>' preserve whitespace)"
+ " empty on empty)"
+ " empty on empty)"
+ " as char(100))"
+ "from t1 where i > 5");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"6", "inigo"},
{"7", "inigo"},
{"8", "inigo"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlserialize("
+ " xmlquery('/half/masted/text()' passing by ref"
+ " xmlquery('.' passing by ref x empty on empty)"
+ " empty on empty)"
+ " as char(100))"
+ "from t1 where i = 6");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"6", "bass"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i,"
+ " xmlexists('/half/masted/text()' passing by ref"
+ " xmlquery('.' passing by ref x empty on empty)"
+ " )"
+ "from t1 where i = 6");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"6", "true"}
};
JDBC.assertFullResultSet(rs, expRS, true);
st.close();
}
/**
* DERBY-1759: Serialization of attribute nodes.
*/
public void testAttrSerialization() throws Exception
{
// Create test table and one row of data.
Statement st = createStatement();
st.executeUpdate("create table attserTable (i int, x xml)");
assertUpdateCount(st, 1, "insert into attserTable values (0, null)");
assertUpdateCount(st, 1,
"insert into attserTable values (10,"
+ " xmlparse(document"
+ " '<threeatts first=\"1\" second=\"two\" "
+ "third=\"le 3 trois\"/>'"
+ " preserve whitespace"
+ " ))");
// Echo attserTable rows for reference.
ResultSet rs = st.executeQuery(
"select i, xmlserialize(x as char(75)) from attserTable");
String [] expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"0", null},
{"10", "<threeatts first=\"1\" second=\"two\" third=\"le 3 trois\"/>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// This should fail because XML serialization dictates that
// we throw an error if an attempt is made to serialize a
// sequence that has one or more top-level attributes nodes.
assertStatementError("2200W", st,
"select"
+ " xmlserialize("
+ " xmlquery("
+ " '//@*' passing by ref x empty on empty"
+ " )"
+ " as char(50))"
+ " from attserTable"
+ " where xmlexists('//@*' passing by ref x)");
// Demonstrate that Xalan "string" function only returns
// string value of first attribute and thus cannot be used
// to retrieve a sequence of att values.
rs = st.executeQuery(
"select"
+ " xmlserialize("
+ " xmlquery("
+ " 'string(//@*)'"
+ " passing by ref x empty on empty"
+ " )"
+ " as char(50))"
+ " from attserTable"
+ " where xmlexists('//@*' passing by ref x)");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Xalan doesn't have a function that allows retrieval of a
// sequence of attribute values. One can only retrieve a
// sequence of attribute *nodes*, but since those can't be
// serialized (because of SQL/XML rules) the user has no
// way to get them. The following is a very (VERY) ugly
// two-part workaround that one could use until something
// better is available. First, get the max number of
// attributes in the table.
rs = st.executeQuery(
"select"
+ " max("
+ " cast("
+ " xmlserialize("
+ " xmlquery('count(//@*)' passing by ref x "
+ "empty on empty)"
+ " as char(50))"
+ " as int)"
+ " )"
+ " from attserTable");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"3"}
};
JDBC.assertFullResultSet(rs, expRS, true, false);
// The use of MAX in the previous query throws a warning because
// the table T1 has null values. Just for sanity check for that
// warning if we're in embedded mode (warnings are not returned
// in client/server mode--see DERBY-159).
if (usingEmbedded())
{
SQLWarning sqlWarn = rs.getWarnings();
if (sqlWarn == null)
sqlWarn = st.getWarnings();
if (sqlWarn == null)
sqlWarn = getConnection().getWarnings();
assertTrue("Expected warning but found none.", (sqlWarn != null));
assertSQLState("01003", sqlWarn);
}
rs.close();
// Then use XPath position syntax to retrieve the
// attributes and concatenate them. We need one call to
// string(//@[i]) for every for every i between 1 and the
// value found in the preceding query. In this case we
// know the max is three, so use that.
rs = st.executeQuery(
"select"
+ " xmlserialize("
+ " xmlquery("
+ " 'concat(string(//@*[1]), \" \","
+ " string(//@*[2]), \" \","
+ " string(//@*[3]))'"
+ " passing by ref x empty on empty"
+ " )"
+ " as char(50))"
+ " from attserTable"
+ " where xmlexists('//@*' passing by ref x)");
expColNames = new String [] {"1"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1 two le 3 trois"}
};
JDBC.assertFullResultSet(rs, expRS, true);
// Cleanup.
st.executeUpdate("drop table attserTable");
st.close();
}
/**
* DERBY-1718 create trigger fails when SPS contains XML
* related op.
*/
public void testTriggerSPSWithXML() throws Exception
{
Statement st = createStatement();
st.executeUpdate("create table trigSPS1 (i int, x xml)");
st.executeUpdate("create table trigSPS2 (i int, x xml)");
assertUpdateCount(st, 1,
" insert into trigSPS1 values (1, xmlparse(document "
+ "'<name> john </name>' preserve whitespace))");
st.executeUpdate(
"create trigger tx after insert on trigSPS1 for each "
+ "statement mode db2sql insert into trigSPS2 values "
+ "(1, xmlparse(document '<name> jane </name>' "
+ "preserve whitespace))");
assertUpdateCount(st, 1,
" insert into trigSPS1 values (2, xmlparse(document "
+ "'<name> ally </name>' preserve whitespace))");
ResultSet rs = st.executeQuery(
"select i, xmlserialize(x as varchar(20)) from trigSPS1");
String [] expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
String [][] expRS = new String [][]
{
{"1", "<name> john </name>"},
{"2", "<name> ally </name>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i, xmlserialize(x as varchar(20)) from trigSPS2");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "<name> jane </name>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
assertUpdateCount(st, 2, "insert into trigSPS1 select * from trigSPS1");
rs = st.executeQuery(
"select i, xmlserialize(x as varchar(20)) from trigSPS1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "<name> john </name>"},
{"2", "<name> ally </name>"},
{"1", "<name> john </name>"},
{"2", "<name> ally </name>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i, xmlserialize(x as varchar(20)) from trigSPS2");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "<name> jane </name>"},
{"1", "<name> jane </name>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
st.executeUpdate("drop trigger tx");
assertUpdateCount(st, 4, "delete from trigSPS1");
assertUpdateCount(st, 2, "delete from trigSPS2");
assertUpdateCount(st, 1,
" insert into trigSPS1 values (1, xmlparse(document "
+ "'<name> john </name>' preserve whitespace))");
st.executeUpdate(
"create trigger tx after insert on trigSPS1 for each "
+ "statement mode db2sql insert into trigSPS2 values "
+ "(1, (select xmlquery('.' passing by ref x "
+ "returning sequence empty on empty) from trigSPS1 "
+ "where i = 1))");
assertUpdateCount(st, 1,
" insert into trigSPS1 values (2, xmlparse(document "
+ "'<name> ally </name>' preserve whitespace))");
rs = st.executeQuery(
"select i, xmlserialize(x as varchar(20)) from trigSPS1");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "<name> john </name>"},
{"2", "<name> ally </name>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
rs = st.executeQuery(
"select i, xmlserialize(x as varchar(20)) from trigSPS2");
expColNames = new String [] {"I", "2"};
JDBC.assertColumnNames(rs, expColNames);
expRS = new String [][]
{
{"1", "<name> john </name>"}
};
JDBC.assertFullResultSet(rs, expRS, true);
st.executeUpdate("drop trigger tx");
st.executeUpdate("drop table trigSPS1");
st.executeUpdate("drop table trigSPS2");
st.close();
}
/**
* Test how numeric values returned by XPath queries are formatted.
*/
public void testNumericReturnValues() throws SQLException {
// Array of XPath queries and their expected return values
String[][] queries = {
// Long.MAX_VALUE. We lose some precision.
{ "9223372036854775807", "9223372036854776000" },
// We can also have numbers larger than Long.MAX_VALUE, but we
// don't get higher precision.
{ "9223372036854775807123456789", "9223372036854776000000000000" },
// Expect plain format, not scientific notation like 1.23E-10
{ "123 div 1000000000000", "0.000000000123" },
// Trailing zeros after decimal point should be stripped away
{ "1", "1" },
{ "1.0", "1" },
{ "1.000", "1" },
{ "1.00010", "1.0001" },
// -0 should be normalized to 0
{ "-0", "0" },
{ "-0.0", "0" },
{ "-0.00", "0" },
};
Statement s = createStatement();
for (int i = 0; i < queries.length; i++) {
String xpath = queries[i][0];
String expected = queries[i][1];
String sql = "select xmlserialize(xmlquery('" + xpath +
"' passing by ref x empty on empty) as clob) " +
"from t1 where i = 1";
JDBC.assertSingleValueResultSet(s.executeQuery(sql), expected);
}
}
/**
* Wrapper for the tests in XMLTypeAndOpsTest. We have some
* fixture tables/data that we want to create a single time
* before the tests run and then which we want to clean up
* when the tests complete. This class acts the "wrapper"
* that does this one-time setup and teardown. (Actually,
* we do it two times: once for running in embedded mode
* and once for running in client/server mode--we create an
* instance of this class for each mode.)
*/
private static class XMLTestSetup extends BaseJDBCTestSetup
{
public XMLTestSetup(TestSuite tSuite) {
super(tSuite);
}
/**
* Before running the tests in XMLTypeAndOps we create two
* base tables and insert the common "fixture" data.
*/
public void setUp() throws Exception
{
Connection c = getConnection();
Statement s = c.createStatement();
/* Create test tables as a fixture for this test. Note
* that we're implicitly testing the creation of XML columns
* as part of this setup. All of the following should
* succeed; see testXMLColCreation() for some tests where
* column creation is expected to fail.
*/
s.executeUpdate("create table t1 (i int, x xml)");
s.executeUpdate("create table t2 (x2 xml not null)");
s.executeUpdate("alter table t2 add column x1 xml");
/* Insert test data. Here we're implicitly tesing
* the XMLPARSE operator in situations where it should
* succeed. Negative test cases are tesed in the
* testIllegalNullInserts() and testXMLParse() methods
* of the XMLTypeAndOps class.
*/
// Null values.
assertUpdateCount(s, 1, "insert into t1 values (1, null)");
assertUpdateCount(s, 1,
"insert into t1 values (2, cast (null as xml))");
assertUpdateCount(s, 1, "insert into t1 (i) values (4)");
assertUpdateCount(s, 1, "insert into t1 values (3, default)");
// Non-null values.
assertUpdateCount(s, 1,
"insert into t1 values (5, xmlparse(document "
+ "'<hmm/>' preserve whitespace))");
assertUpdateCount(s, 1,
" insert into t1 values (6, xmlparse(document "
+ "'<half> <masted> bass </masted> boosted. </half>' "
+ "preserve whitespace))");
assertUpdateCount(s, 1,
" insert into t2 (x1, x2) values (null, "
+ "xmlparse(document '<notnull/>' preserve whitespace))");
assertUpdateCount(s, 1,
" insert into t1 values (7, xmlparse(document '<?xml "
+ "version=\"1.0\" encoding= \"UTF-8\"?><umm> decl "
+ "check </umm>' preserve whitespace))");
assertUpdateCount(s, 1,
"insert into t1 values (8, xmlparse(document '<lets> "
+ "<try> this out </try> </lets>' preserve whitespace))");
assertUpdateCount(s, 1,
" update t1 set x = xmlparse(document '<update> "
+ "document was inserted as part of an UPDATE "
+ "</update>' preserve whitespace) where i = 1");
assertUpdateCount(s, 1,
" update t1 set x = xmlparse(document '<update2> "
+ "document was inserted as part of an UPDATE "
+ "</update2>' preserve whitespace) where "
+ "xmlexists('/update' passing by ref x)");
s.close();
c.close();
s = null;
c= null;
}
/**
* For test teardown we just drop the two tables we created in
* test setup and then clean up local objects if needed.
*/
public void tearDown() throws Exception
{
Connection c = getConnection();
Statement s = c.createStatement();
s.executeUpdate("drop table t1");
s.executeUpdate("drop table t2");
s.close();
c.close();
s = null;
c = null;
super.tearDown();
}
}
}
| DERBY-2739: Test XPath queries that return Infinity or NaN
git-svn-id: 2c06e9c5008124d912b69f0b82df29d4867c0ce2@1054968 13f79535-47bb-0310-9956-ffa450edef68
| java/testing/org/apache/derbyTesting/functionTests/tests/lang/XMLTypeAndOpsTest.java | DERBY-2739: Test XPath queries that return Infinity or NaN |
|
Java | apache-2.0 | c190a33c48f4816c849327304c66cbe41b984dd2 | 0 | kalaspuffar/pdfbox,kalaspuffar/pdfbox,apache/pdfbox,apache/pdfbox | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.pdmodel.font;
import java.io.IOException;
import java.util.Map;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* This will create the correct type of font based on information in the dictionary.
*
* @author <a href="mailto:[email protected]">Ben Litchfield</a>
* @version $Revision: 1.6 $
*/
public class PDFontFactory
{
/**
* private constructor, should only use static methods in this class.
*/
private PDFontFactory()
{
}
/**
* Logger instance.
*/
private static final Log LOG = LogFactory.getLog(PDFontFactory.class);
/**
* This will create the correct font based on information in the dictionary.
*
* @param dic The populated dictionary.
*
* @param fontCache A Map to cache already created fonts
*
* @return The corrent implementation for the font.
*
* @throws IOException If the dictionary is not valid.
*
* @deprecated due to some side effects font caching is no longer supported,
* use {@link #createFont(COSDictionary)} instead
*/
public static PDFont createFont(COSDictionary dic, Map fontCache) throws IOException
{
return createFont(dic);
}
/**
* This will create the correct font based on information in the dictionary.
*
* @param dic The populated dictionary.
*
* @return The corrent implementation for the font.
*
* @throws IOException If the dictionary is not valid.
*/
public static PDFont createFont( COSDictionary dic ) throws IOException
{
PDFont retval = null;
COSName type = (COSName)dic.getDictionaryObject( COSName.TYPE );
if( type != null && !COSName.FONT.equals( type ) )
{
throw new IOException( "Cannot create font if /Type is not /Font. Actual=" +type );
}
COSName subType = (COSName)dic.getDictionaryObject( COSName.SUBTYPE );
if (subType == null)
{
throw new IOException( "Cannot create font as /SubType is not set." );
}
if( subType.equals( COSName.TYPE1) )
{
retval = new PDType1Font( dic );
}
else if( subType.equals( COSName.MM_TYPE1 ) )
{
retval = new PDMMType1Font( dic );
}
else if( subType.equals( COSName.TRUE_TYPE ) )
{
retval = new PDTrueTypeFont( dic );
}
else if( subType.equals( COSName.TYPE3 ) )
{
retval = new PDType3Font( dic );
}
else if( subType.equals( COSName.TYPE0 ) )
{
retval = new PDType0Font( dic );
}
else if( subType.equals( COSName.CID_FONT_TYPE0 ) )
{
retval = new PDCIDFontType0Font( dic );
}
else if( subType.equals( COSName.CID_FONT_TYPE2 ) )
{
retval = new PDCIDFontType2Font( dic );
}
else
{
LOG.warn("Substituting TrueType for unknown font subtype=" + subType.getName());
retval = new PDTrueTypeFont( dic );
}
return retval;
}
}
| pdfbox/src/main/java/org/apache/pdfbox/pdmodel/font/PDFontFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.pdmodel.font;
import java.io.IOException;
import java.util.Map;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* This will create the correct type of font based on information in the dictionary.
*
* @author <a href="mailto:[email protected]">Ben Litchfield</a>
* @version $Revision: 1.6 $
*/
public class PDFontFactory
{
/**
* private constructor, should only use static methods in this class.
*/
private PDFontFactory()
{
}
/**
* Logger instance.
*/
private static final Log LOG = LogFactory.getLog(PDFontFactory.class);
/**
* This will create the correct font based on information in the dictionary.
*
* @param dic The populated dictionary.
*
* @param fontCache A Map to cache already created fonts
*
* @return The corrent implementation for the font.
*
* @throws IOException If the dictionary is not valid.
*
* @deprecated due to some side effects font caching is no longer supported,
* use {@link #createFont(COSDictionary)} instead
*/
public static PDFont createFont(COSDictionary dic, Map fontCache) throws IOException
{
return createFont(dic);
}
/**
* This will create the correct font based on information in the dictionary.
*
* @param dic The populated dictionary.
*
* @return The corrent implementation for the font.
*
* @throws IOException If the dictionary is not valid.
*/
public static PDFont createFont( COSDictionary dic ) throws IOException
{
PDFont retval = null;
COSName type = (COSName)dic.getDictionaryObject( COSName.TYPE );
if( !type.equals( COSName.FONT ) )
{
throw new IOException( "Cannot create font if /Type is not /Font. Actual=" +type );
}
COSName subType = (COSName)dic.getDictionaryObject( COSName.SUBTYPE );
if( subType.equals( COSName.TYPE1) )
{
retval = new PDType1Font( dic );
}
else if( subType.equals( COSName.MM_TYPE1 ) )
{
retval = new PDMMType1Font( dic );
}
else if( subType.equals( COSName.TRUE_TYPE ) )
{
retval = new PDTrueTypeFont( dic );
}
else if( subType.equals( COSName.TYPE3 ) )
{
retval = new PDType3Font( dic );
}
else if( subType.equals( COSName.TYPE0 ) )
{
retval = new PDType0Font( dic );
}
else if( subType.equals( COSName.CID_FONT_TYPE0 ) )
{
retval = new PDCIDFontType0Font( dic );
}
else if( subType.equals( COSName.CID_FONT_TYPE2 ) )
{
retval = new PDCIDFontType2Font( dic );
}
else
{
LOG.warn("Substituting TrueType for unknown font subtype=" +
dic.getDictionaryObject( COSName.SUBTYPE ).toString());
retval = new PDTrueTypeFont( dic );
}
return retval;
}
}
| PDFBOX-1431: avoid NPE if the type FONT is missing as proposed by Gustavo Moreira
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1402971 13f79535-47bb-0310-9956-ffa450edef68
| pdfbox/src/main/java/org/apache/pdfbox/pdmodel/font/PDFontFactory.java | PDFBOX-1431: avoid NPE if the type FONT is missing as proposed by Gustavo Moreira |
|
Java | apache-2.0 | 37cb49f7baedff39e19280f3a780608c9a66f4ca | 0 | drdozer/sbol-data | package uk.ac.ncl.intbio.core.io.rdf;
import java.net.URI;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Stack;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.stream.events.XMLEvent;
import uk.ac.ncl.intbio.core.datatree.*;
import uk.ac.ncl.intbio.core.datatree.Datatree.NamedProperties;
import uk.ac.ncl.intbio.core.datatree.Datatree.NamespaceBindings;
import uk.ac.ncl.intbio.core.io.CoreIoException;
import uk.ac.ncl.intbio.core.io.IoReader;
import uk.ac.ncl.intbio.core.io.IoWriter;
import static uk.ac.ncl.intbio.core.io.rdf.RdfTerms.*;
/**
* The IO layer to read and write {@link DocumentRoot}s using RDF/XML.
* <p>
* Documents are serialised using nesting, in which {@link TopLevelDocument}s embed {@link NestedDocument}s.
* </p>
*
* <p>
* Both {@link TopLevelDocument}s and {@link NestedDocument}s are represented as RDF resources, and
* {@link NamedProperty} objects are serialised as statements for these RDF resources.
* </p>
*/
public class RdfIo{
/**
* Creates an {@link IoWriter} using the given {@link XMLStreamWriter} object.
*
* <p>This {@link IoWriter} provides a method to write {@link DocumentRoot} objects in RDF/XML format.
* During the serialisation, the RDF namespace is added if it is not provided in the {@link NamespaceBinding}s property of a {@link DocumentRoot}.
* </p>
* @param writer The {@link XMLStreamWriter} writer to serialise a {@link DocumentRoot}.
* @return {@link IoWriter}
*/
public IoWriter<QName> createIoWriter(final XMLStreamWriter writer)
{
return new IoWriter<QName>() {
@Override
public void write(DocumentRoot<QName> document) throws CoreIoException {
try
{
writer.writeStartDocument();
writeStartElement(RDF);
setPrefix(rdf);
if(!document.getNamespaceBindings().contains(rdf)) {
writeNamespace(rdf);
}
for(NamespaceBinding nb : document.getNamespaceBindings()) {
setPrefix(nb);
writeNamespace(nb);
}
for (TopLevelDocument<QName> child : document.getTopLevelDocuments())
{
write(child);
}
writer.writeEndElement();
writer.writeEndDocument();
}
catch(XMLStreamException xse)
{
throw new CoreIoException(xse);
}
}
private void write(IdentifiableDocument<QName> doc) throws XMLStreamException {
writeStartElement(doc.getType());
writeAttribute(rdfAbout, doc.getIdentity().toString());
for (NamedProperty<QName> property : doc.getProperties()) {
write(property);
}
writer.writeEndElement();
}
private void write(final NamedProperty<QName> property) {
new PropertyValue.Visitor<QName>() {
@Override
public void visit(NestedDocument<QName> v) throws XMLStreamException {
writeStartElement(property.getName());
write(v);
writer.writeEndElement();
}
@Override
public void visit(Literal<QName> v) throws XMLStreamException {
if(isEmptyElementValue(v)) {
writeEmptyElement(property.getName());
write(v);
} else {
writeStartElement(property.getName());
write(v);
writer.writeEndElement();
}
}
}.visit(property.getValue());
}
private boolean isEmptyElementValue(Literal<QName> literal) {
return /* literal instanceof Literal.QNameLiteral || */ literal instanceof Literal.UriLiteral;
}
private void write(Literal<QName> literal) {
new Literal.Visitor<QName>() {
@Override
public void visit(Literal.StringLiteral<QName> l) throws XMLStreamException {
writer.writeCharacters(l.getValue());
}
@Override
public void visit(Literal.UriLiteral<QName> l) throws XMLStreamException {
writeAttribute(rdfResource, l.getValue().toString());
}
@Override
public void visit(Literal.IntegerLiteral<QName> l) throws XMLStreamException {
writer.writeCharacters(l.getValue().toString());
}
@Override
public void visit(Literal.DoubleLiteral<QName> l) throws XMLStreamException {
writer.writeCharacters(l.getValue().toString());
}
@Override
public void visit(Literal.TypedLiteral<QName> l) throws XMLStreamException {
writer.writeCharacters(l.getValue() + "^^" + l.getType().getPrefix() + ":" + l.getType().getLocalPart());
}
@Override
public void visit(Literal.BooleanLiteral<QName> l) throws XMLStreamException {
writer.writeCharacters(l.getValue().toString());
}
}.visit(literal);
}
private void writeEmptyElement(QName tagName) throws XMLStreamException {
writer.writeEmptyElement(tagName.getPrefix(), tagName.getLocalPart(), tagName.getNamespaceURI());
}
private void writeStartElement(QName tagName) throws XMLStreamException {
writer.writeStartElement(tagName.getPrefix(), tagName.getLocalPart(), tagName.getNamespaceURI());
}
private void setPrefix(NamespaceBinding binding) throws XMLStreamException {
writer.setPrefix(binding.getPrefix(), binding.getNamespaceURI());
}
private void writeNamespace(NamespaceBinding binding) throws XMLStreamException {
writer.writeNamespace(binding.getPrefix(), binding.getNamespaceURI());
}
private void writeAttribute(QName attrName, String attrValue) throws XMLStreamException {
writer.writeAttribute(
attrName.getPrefix(),
attrName.getNamespaceURI(),
attrName.getLocalPart(),
attrValue);
}
};
}
/**
* Creates an {@link IoReader} using the given {@link XMLStreamReader}.
* <p>
* This {@link IoReader} provides a method to read data in RDF/XML format and deserialise it into a {@link DocumentRoot} object.
* </p>
* @param xmlReader The {@link XMLStreamReader} reader to read RDF/XML data.
* @return {@link IoReader}
* @throws XMLStreamException when the underlying reader raises an exception
*/
public IoReader<QName> createIoReader(final XMLStreamReader xmlReader) throws XMLStreamException
{
return new IoReader<QName>() {
@Override
public DocumentRoot<QName> read () throws CoreIoException
{
try {
while (xmlReader.hasNext())
{
int eventType = xmlReader.next();
switch (eventType) {
case XMLEvent.START_ELEMENT:
NamespaceBindings bindings = readBindings();
Datatree.TopLevelDocuments<QName> topLevelDocuments= readTopLevelDocuments();
return Datatree.DocumentRoot(bindings, topLevelDocuments);
}
}
} catch (XMLStreamException e) {
throw new CoreIoException(e);
}
return null;
}
private Datatree.NamespaceBindings readBindings() throws XMLStreamException {
NamespaceBinding[] bindings = new NamespaceBinding[xmlReader.getNamespaceCount()];
for(int i = 0; i < xmlReader.getNamespaceCount(); i++) {
bindings[i] = Datatree.NamespaceBinding(xmlReader.getNamespaceURI(i), xmlReader.getNamespacePrefix(i));
}
return Datatree.NamespaceBindings(bindings);
}
/**
* Used to store documents and properties when reading XML in the readTopLevelDocuments method
*/
private Deque<Object> documentStack=new ArrayDeque<Object>() ;
/**
* Used to store the TopLevelDocument objects in the readTopLevelDocuments method
*/
private List<TopLevelDocument<QName>> topLevelDocuments=null;
/**
* Reads RDF document and returns TopLevelDocuments.
*
* <p>
* Properties and
* documents are stored in a Stack object and populated as more data
* become available The stack object holds one TopLevelDocument at a
* time. Once a TopLevelDocument is read it is added to the
* topLevelDocuments collection. For triples within a
* TopLevelDocument the following rules apply:
* </p>
* Starting tags:
* <p>
* If a triple contains rdf:about attribute it is assumed that the
* tag is the start of a NestedDocument. An empty Nested document is
* added to the stack.
* If a triple contains rdf:resource, a NamedProperty with a URI
* value is created and added to the stack.
* Otherwise a NamedProperty without a value is added to the stack
* </p>
*
* End tags:
* <p>
* For each end tag, an object is taken from the stack.
* If the object is a property The property is removed from the
* stack The XML value (if the value exists) is used to set the
* value of that property. The property is then added to the recent
* document in the stack. This document can be a NestedDocument or a
* TopLevelDocument.
* If the object is a NestedDocument, the document is removed from
* the stack. The property identifying the document in this case is
* the most recent object in the stack and it is also removed from
* the stack. The NestedDocument is then added to the parent
* document (it can be a another NestedDocument or a
* TopLevelDocument using the property relationship. This parent
* document is the most recent object after removing the property.
* If the object is TopLevelDocument, the object is removed from the
* stack and added to the topLevelDocuments collection
* </p>
*
* @return
* @throws XMLStreamException
*/
private Datatree.TopLevelDocuments<QName> readTopLevelDocuments()
throws XMLStreamException {
//Used as a buffer to read XML characters in the readTopLevelDocuments method
StringBuilder currentText=null;
topLevelDocuments = new ArrayList<TopLevelDocument<QName>>();
while (xmlReader.hasNext()) {
int eventType = xmlReader.next();
switch (eventType) {
case XMLEvent.START_ELEMENT:
currentText = new StringBuilder(256);
QName elementURI = Datatree.QName(xmlReader.getNamespaceURI(), xmlReader.getLocalName(), xmlReader.getPrefix());
addToStack(elementURI);
break;
case XMLEvent.END_ELEMENT:
String literalValue = null;
if (currentText != null) {
literalValue = currentText.toString();
currentText = null;
}
updateDocumentInStack(literalValue);
break;
case XMLEvent.CHARACTERS:
String characters = xmlReader.getText();
if (currentText != null) {
currentText.append(characters);
}
break;
}
}
Datatree.TopLevelDocuments<QName> documents = Datatree
.TopLevelDocuments(topLevelDocuments.toArray(new TopLevelDocument[topLevelDocuments.size()]));
return documents;
// return Datatree.<QName> TopLevelDocuments();
}
private void addToStack(QName elementURI) throws XMLStreamException
{
URI identity = null;
URI resourceURI = null;
int attributes = xmlReader.getAttributeCount();
for (int i = 0; i < attributes; ++i)
{
if (rdfAbout.getLocalPart().equals(xmlReader.getAttributeLocalName(i)) && rdfAbout.getNamespaceURI().equals(xmlReader.getAttributeNamespace(i)))
{
identity = URI.create(xmlReader.getAttributeValue(i));
}
if (rdfResource.getLocalPart().equals(xmlReader.getAttributeLocalName(i)) && rdfResource.getNamespaceURI().equals(xmlReader.getAttributeNamespace(i)))
{
resourceURI = URI.create(xmlReader.getAttributeValue(i));
}
}
if (identity != null)
{
Datatree.NamespaceBindings bindings = readBindings();
IdentifiableDocument<QName> document = null;
if (documentStack.isEmpty())
{
document = Datatree.TopLevelDocument(bindings, elementURI, identity);
}
else
{
document = Datatree.NestedDocument(bindings, elementURI, identity);
}
documentStack.push(document);
}
else
{
NamedProperty<QName> property = null;
if (resourceURI != null)
{
property = Datatree.NamedProperty(elementURI, resourceURI);
}
else
{
// TODO Make sure this is ok. The value type is not known yet!
property = Datatree.NamedProperty(elementURI, "");
}
documentStack.push(property);
}
}
private void updateDocumentInStack(String literalValue) throws XMLStreamException
{
// Get the object in the stack
if (!documentStack.isEmpty())
{
Object stackObject = documentStack.pop();
if (stackObject instanceof NamedProperty)
{
NamedProperty<QName> property = (NamedProperty<QName>) stackObject;
// Set its property value
if (literalValue != null && literalValue.length() > 0)
{
property = Datatree.NamedProperty(property.getName(), literalValue);
}
updateDocumentInStackWithProperty(property);
}
else if (stackObject instanceof NestedDocument)
{
NestedDocument<QName> document = (NestedDocument<QName>) stackObject;
// Get the property for the nested document
NamedProperty<QName> property = (NamedProperty<QName>) documentStack
.pop();
property = Datatree.NamedProperty(property.getName(), document);
updateDocumentInStackWithProperty(property);
// Skip the ending of the property tag. The nested
// document is attached to the parent using the property
// already.
while (xmlReader.hasNext())
{
int eventType = xmlReader.next();
if (eventType == XMLEvent.END_ELEMENT)
{
String elementURI = xmlReader.getNamespaceURI() + xmlReader.getLocalName();
if (elementURI.equals(property.getName().getNamespaceURI() + property.getName().getLocalPart()))
{
break;
}
}
}
}
else if (stackObject instanceof TopLevelDocument)
{
topLevelDocuments.add((TopLevelDocument<QName>) stackObject);
}
}
}
private void updateDocumentInStackWithProperty(NamedProperty<QName> property)
{
//Add it to the document in the stack
IdentifiableDocument<QName> documentInStack=(IdentifiableDocument<QName>)documentStack.pop();
documentInStack=addProperty(documentInStack, property);
//Put the document back to the stack
documentStack.push(documentInStack);
}
private IdentifiableDocument<QName> addProperty(
IdentifiableDocument<QName> document, NamedProperty<QName> property)
{
List<NamedProperty<QName>> properties = new ArrayList<>();
if (document.getProperties() == null || document.getProperties().size() == 0)
{
properties = Datatree.NamedProperties(property).getProperties();
}
else
{
properties.addAll(document.getProperties());
// TODO if the Property value is a NestedDocument then add
// the property using the same property key, still works without this though!
properties.add(property);
}
NamedProperty<QName>[] propertyArray = properties.toArray(new NamedProperty[properties.size()]);
NamedProperties<QName> namedProperties = Datatree.NamedProperties(propertyArray);
NamespaceBindings bindings = Datatree.NamespaceBindings(
(NamespaceBinding[]) document.getNamespaceBindings().toArray());
if (document instanceof TopLevelDocument)
{
document = Datatree.TopLevelDocument(bindings,
document.getType(),
document.getIdentity(),
namedProperties);
}
else
{
document = Datatree.NestedDocument(
bindings,
document.getType(),
document.getIdentity(),
namedProperties);
}
return document;
}
};
}
}
| sbol-data-io-RDF/src/main/java/uk/ac/ncl/intbio/core/io/rdf/RdfIo.java | package uk.ac.ncl.intbio.core.io.rdf;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.stream.events.XMLEvent;
import uk.ac.ncl.intbio.core.datatree.*;
import uk.ac.ncl.intbio.core.datatree.Datatree.NamedProperties;
import uk.ac.ncl.intbio.core.datatree.Datatree.NamespaceBindings;
import uk.ac.ncl.intbio.core.io.CoreIoException;
import uk.ac.ncl.intbio.core.io.IoReader;
import uk.ac.ncl.intbio.core.io.IoWriter;
import static uk.ac.ncl.intbio.core.io.rdf.RdfTerms.*;
/**
* The IO layer to read and write {@link DocumentRoot}s using RDF/XML.
* <p>
* Documents are serialised using nesting, in which {@link TopLevelDocument}s embed {@link NestedDocument}s.
* </p>
*
* <p>
* Both {@link TopLevelDocument}s and {@link NestedDocument}s are represented as RDF resources, and
* {@link NamedProperty} objects are serialised as statements for these RDF resources.
* </p>
*/
public class RdfIo{
/**
* Creates an {@link IoWriter} using the given {@link XMLStreamWriter} object.
*
* <p>This {@link IoWriter} provides a method to write {@link DocumentRoot} objects in RDF/XML format.
* During the serialisation, the RDF namespace is added if it is not provided in the {@link NamespaceBinding}s property of a {@link DocumentRoot}.
* </p>
* @param writer The {@link XMLStreamWriter} writer to serialise a {@link DocumentRoot}.
* @return {@link IoWriter}
*/
public IoWriter<QName> createIoWriter(final XMLStreamWriter writer)
{
return new IoWriter<QName>() {
@Override
public void write(DocumentRoot<QName> document) throws CoreIoException {
try
{
writer.writeStartDocument();
writeStartElement(RDF);
setPrefix(rdf);
if(!document.getNamespaceBindings().contains(rdf)) {
writeNamespace(rdf);
}
for(NamespaceBinding nb : document.getNamespaceBindings()) {
setPrefix(nb);
writeNamespace(nb);
}
for (TopLevelDocument<QName> child : document.getTopLevelDocuments())
{
write(child);
}
writer.writeEndElement();
writer.writeEndDocument();
}
catch(XMLStreamException xse)
{
throw new CoreIoException(xse);
}
}
private void write(IdentifiableDocument<QName> doc) throws XMLStreamException {
writeStartElement(doc.getType());
writeAttribute(rdfAbout, doc.getIdentity().toString());
for (NamedProperty<QName> property : doc.getProperties()) {
write(property);
}
writer.writeEndElement();
}
private void write(final NamedProperty<QName> property) {
new PropertyValue.Visitor<QName>() {
@Override
public void visit(NestedDocument<QName> v) throws XMLStreamException {
writeStartElement(property.getName());
write(v);
writer.writeEndElement();
}
@Override
public void visit(Literal<QName> v) throws XMLStreamException {
if(isEmptyElementValue(v)) {
writeEmptyElement(property.getName());
write(v);
} else {
writeStartElement(property.getName());
write(v);
writer.writeEndElement();
}
}
}.visit(property.getValue());
}
private boolean isEmptyElementValue(Literal<QName> literal) {
return /* literal instanceof Literal.QNameLiteral || */ literal instanceof Literal.UriLiteral;
}
private void write(Literal<QName> literal) {
new Literal.Visitor<QName>() {
@Override
public void visit(Literal.StringLiteral<QName> l) throws XMLStreamException {
writer.writeCharacters(l.getValue());
}
@Override
public void visit(Literal.UriLiteral<QName> l) throws XMLStreamException {
writeAttribute(rdfResource, l.getValue().toString());
}
@Override
public void visit(Literal.IntegerLiteral<QName> l) throws XMLStreamException {
writer.writeCharacters(l.getValue().toString());
}
@Override
public void visit(Literal.DoubleLiteral<QName> l) throws XMLStreamException {
writer.writeCharacters(l.getValue().toString());
}
@Override
public void visit(Literal.TypedLiteral<QName> l) throws XMLStreamException {
writer.writeCharacters(l.getValue() + "^^" + l.getType().getPrefix() + ":" + l.getType().getLocalPart());
}
@Override
public void visit(Literal.BooleanLiteral<QName> l) throws XMLStreamException {
writer.writeCharacters(l.getValue().toString());
}
}.visit(literal);
}
private void writeEmptyElement(QName tagName) throws XMLStreamException {
writer.writeEmptyElement(tagName.getPrefix(), tagName.getLocalPart(), tagName.getNamespaceURI());
}
private void writeStartElement(QName tagName) throws XMLStreamException {
writer.writeStartElement(tagName.getPrefix(), tagName.getLocalPart(), tagName.getNamespaceURI());
}
private void setPrefix(NamespaceBinding binding) throws XMLStreamException {
writer.setPrefix(binding.getPrefix(), binding.getNamespaceURI());
}
private void writeNamespace(NamespaceBinding binding) throws XMLStreamException {
writer.writeNamespace(binding.getPrefix(), binding.getNamespaceURI());
}
private void writeAttribute(QName attrName, String attrValue) throws XMLStreamException {
writer.writeAttribute(
attrName.getPrefix(),
attrName.getNamespaceURI(),
attrName.getLocalPart(),
attrValue);
}
};
}
/**
* Creates an {@link IoReader} using the given {@link XMLStreamReader}.
* <p>
* This {@link IoReader} provides a method to read data in RDF/XML format and deserialise it into a {@link DocumentRoot} object.
* </p>
* @param xmlReader The {@link XMLStreamReader} reader to read RDF/XML data.
* @return {@link IoReader}
* @throws XMLStreamException when the underlying reader raises an exception
*/
public IoReader<QName> createIoReader(final XMLStreamReader xmlReader) throws XMLStreamException
{
return new IoReader<QName>() {
@Override
public DocumentRoot<QName> read () throws CoreIoException
{
try {
while (xmlReader.hasNext())
{
int eventType = xmlReader.next();
switch (eventType) {
case XMLEvent.START_ELEMENT:
NamespaceBindings bindings = readBindings();
Datatree.TopLevelDocuments<QName> topLevelDocuments= readTopLevelDocuments();
return Datatree.DocumentRoot(bindings, topLevelDocuments);
}
}
} catch (XMLStreamException e) {
throw new CoreIoException(e);
}
return null;
}
private Datatree.NamespaceBindings readBindings() throws XMLStreamException {
NamespaceBinding[] bindings = new NamespaceBinding[xmlReader.getNamespaceCount()];
for(int i = 0; i < xmlReader.getNamespaceCount(); i++) {
bindings[i] = Datatree.NamespaceBinding(xmlReader.getNamespaceURI(i), xmlReader.getNamespacePrefix(i));
}
return Datatree.NamespaceBindings(bindings);
}
/**
* Used to store documents and properties when reading XML in the readTopLevelDocuments method
*/
private Stack<Object> documentStack=new Stack<Object>() ;
/**
* Used to store the TopLevelDocument objects in the readTopLevelDocuments method
*/
private List<TopLevelDocument<QName>> topLevelDocuments=null;
/**
* Reads RDF document and returns TopLevelDocuments.
*
* <p>
* Properties and
* documents are stored in a Stack object and populated as more data
* become available The stack object holds one TopLevelDocument at a
* time. Once a TopLevelDocument is read it is added to the
* topLevelDocuments collection. For triples within a
* TopLevelDocument the following rules apply:
* </p>
* Starting tags:
* <p>
* If a triple contains rdf:about attribute it is assumed that the
* tag is the start of a NestedDocument. An empty Nested document is
* added to the stack.
* If a triple contains rdf:resource, a NamedProperty with a URI
* value is created and added to the stack.
* Otherwise a NamedProperty without a value is added to the stack
* </p>
*
* End tags:
* <p>
* For each end tag, an object is taken from the stack.
* If the object is a property The property is removed from the
* stack The XML value (if the value exists) is used to set the
* value of that property. The property is then added to the recent
* document in the stack. This document can be a NestedDocument or a
* TopLevelDocument.
* If the object is a NestedDocument, the document is removed from
* the stack. The property identifying the document in this case is
* the most recent object in the stack and it is also removed from
* the stack. The NestedDocument is then added to the parent
* document (it can be a another NestedDocument or a
* TopLevelDocument using the property relationship. This parent
* document is the most recent object after removing the property.
* If the object is TopLevelDocument, the object is removed from the
* stack and added to the topLevelDocuments collection
* </p>
*
* @return
* @throws XMLStreamException
*/
private Datatree.TopLevelDocuments<QName> readTopLevelDocuments()
throws XMLStreamException {
//Used as a buffer to read XML characters in the readTopLevelDocuments method
StringBuilder currentText=null;
topLevelDocuments = new ArrayList<TopLevelDocument<QName>>();
while (xmlReader.hasNext()) {
int eventType = xmlReader.next();
switch (eventType) {
case XMLEvent.START_ELEMENT:
currentText = new StringBuilder(256);
QName elementURI = Datatree.QName(xmlReader.getNamespaceURI(), xmlReader.getLocalName(), xmlReader.getPrefix());
addToStack(elementURI);
break;
case XMLEvent.END_ELEMENT:
String literalValue = null;
if (currentText != null) {
literalValue = currentText.toString();
currentText = null;
}
updateDocumentInStack(literalValue);
break;
case XMLEvent.CHARACTERS:
String characters = xmlReader.getText();
if (currentText != null) {
currentText.append(characters);
}
break;
}
}
Datatree.TopLevelDocuments<QName> documents = Datatree
.TopLevelDocuments(topLevelDocuments.toArray(new TopLevelDocument[topLevelDocuments.size()]));
return documents;
// return Datatree.<QName> TopLevelDocuments();
}
private void addToStack(QName elementURI) throws XMLStreamException
{
URI identity = null;
URI resourceURI = null;
int attributes = xmlReader.getAttributeCount();
for (int i = 0; i < attributes; ++i)
{
if (rdfAbout.getLocalPart().equals(xmlReader.getAttributeLocalName(i)) && rdfAbout.getNamespaceURI().equals(xmlReader.getAttributeNamespace(i)))
{
identity = URI.create(xmlReader.getAttributeValue(i));
}
if (rdfResource.getLocalPart().equals(xmlReader.getAttributeLocalName(i)) && rdfResource.getNamespaceURI().equals(xmlReader.getAttributeNamespace(i)))
{
resourceURI = URI.create(xmlReader.getAttributeValue(i));
}
}
if (identity != null)
{
Datatree.NamespaceBindings bindings = readBindings();
IdentifiableDocument<QName> document = null;
if (documentStack.isEmpty())
{
document = Datatree.TopLevelDocument(bindings, elementURI, identity);
}
else
{
document = Datatree.NestedDocument(bindings, elementURI, identity);
}
documentStack.add(document);
}
else
{
NamedProperty<QName> property = null;
if (resourceURI != null)
{
property = Datatree.NamedProperty(elementURI, resourceURI);
}
else
{
// TODO Make sure this is ok. The value type is not known yet!
property = Datatree.NamedProperty(elementURI, "");
}
documentStack.add(property);
}
}
private void updateDocumentInStack(String literalValue) throws XMLStreamException
{
// Get the object in the stack
if (!documentStack.isEmpty())
{
Object stackObject = documentStack.pop();
if (stackObject instanceof NamedProperty)
{
NamedProperty<QName> property = (NamedProperty<QName>) stackObject;
// Set its property value
if (literalValue != null && literalValue.length() > 0)
{
property = Datatree.NamedProperty(property.getName(), literalValue);
}
updateDocumentInStackWithProperty(property);
}
else if (stackObject instanceof NestedDocument)
{
NestedDocument<QName> document = (NestedDocument<QName>) stackObject;
// Get the property for the nested document
NamedProperty<QName> property = (NamedProperty<QName>) documentStack
.pop();
property = Datatree.NamedProperty(property.getName(), document);
updateDocumentInStackWithProperty(property);
// Skip the ending of the property tag. The nested
// document is attached to the parent using the property
// already.
while (xmlReader.hasNext())
{
int eventType = xmlReader.next();
if (eventType == XMLEvent.END_ELEMENT)
{
String elementURI = xmlReader.getNamespaceURI() + xmlReader.getLocalName();
if (elementURI.equals(property.getName().getNamespaceURI() + property.getName().getLocalPart()))
{
break;
}
}
}
}
else if (stackObject instanceof TopLevelDocument)
{
topLevelDocuments.add((TopLevelDocument<QName>) stackObject);
}
}
}
private void updateDocumentInStackWithProperty(NamedProperty<QName> property)
{
//Add it to the document in the stack
IdentifiableDocument<QName> documentInStack=(IdentifiableDocument<QName>)documentStack.pop();
documentInStack=addProperty(documentInStack, property);
//Put the document back to the stack
documentStack.add(documentInStack);
}
private IdentifiableDocument<QName> addProperty(
IdentifiableDocument<QName> document, NamedProperty<QName> property)
{
List<NamedProperty<QName>> properties = new ArrayList<>();
if (document.getProperties() == null || document.getProperties().size() == 0)
{
properties = Datatree.NamedProperties(property).getProperties();
}
else
{
properties.addAll(document.getProperties());
// TODO if the Property value is a NestedDocument then add
// the property using the same property key, still works without this though!
properties.add(property);
}
NamedProperty<QName>[] propertyArray = properties.toArray(new NamedProperty[properties.size()]);
NamedProperties<QName> namedProperties = Datatree.NamedProperties(propertyArray);
NamespaceBindings bindings = Datatree.NamespaceBindings(
(NamespaceBinding[]) document.getNamespaceBindings().toArray());
if (document instanceof TopLevelDocument)
{
document = Datatree.TopLevelDocument(bindings,
document.getType(),
document.getIdentity(),
namedProperties);
}
else
{
document = Datatree.NestedDocument(
bindings,
document.getType(),
document.getIdentity(),
namedProperties);
}
return document;
}
};
}
}
| Implement Chris' Java9 Fix
| sbol-data-io-RDF/src/main/java/uk/ac/ncl/intbio/core/io/rdf/RdfIo.java | Implement Chris' Java9 Fix |
|
Java | apache-2.0 | 5f86dd202f8cb68d56aab43e06cb55380680b97b | 0 | digipost/signature-api-client-java | /**
* Copyright (C) Posten Norge AS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package no.digipost.signature.client.portal;
import java.util.List;
import java.util.Objects;
import static java.util.Arrays.asList;
public final class SignatureStatus {
/**
* The signer has rejected to sign the document.
*/
public static final SignatureStatus REJECTED = new SignatureStatus("REJECTED");
/**
* This signer has been cancelled by the sender, and will not be able to sign the document.
*/
public static final SignatureStatus CANCELLED = new SignatureStatus("CANCELLED");
/**
* This signer is reserved from receiving documents electronically, and will not receive
* the document for signing.
*/
public static final SignatureStatus RESERVED = new SignatureStatus("RESERVED");
/**
* We were not able to locate any channels (email, SMS) for notifying the signer to sign the document.
*/
public static final SignatureStatus CONTACT_INFORMATION_MISSING = new SignatureStatus("CONTACT_INFORMATION_MISSING");
/**
* The signer has not made a decision to either sign or reject the document within the
* specified time limit,
*/
public static final SignatureStatus EXPIRED = new SignatureStatus("EXPIRED");
/**
* The signer has yet to review the document and decide if she/he wants to sign or
* reject it.
*/
public static final SignatureStatus WAITING = new SignatureStatus("WAITING");
/**
* The signer has successfully signed the document.
*/
public static final SignatureStatus SIGNED = new SignatureStatus("SIGNED");
/**
* The job has reached a state where the status of this signature is not applicable.
* This includes the case where a signer rejects to sign, and thus ending the job in a
* {@link PortalJobStatus#FAILED} state. Any remaining (previously {@link #WAITING})
* signatures are marked as {@link #NOT_APPLICABLE}.
*/
public static final SignatureStatus NOT_APPLICABLE = new SignatureStatus("NOT_APPLICABLE");
private static final List<SignatureStatus> KNOWN_STATUSES = asList(
REJECTED,
CANCELLED,
RESERVED,
CONTACT_INFORMATION_MISSING,
EXPIRED,
WAITING,
SIGNED,
NOT_APPLICABLE
);
private final String identifier;
public SignatureStatus(String identifier) {
this.identifier = identifier;
}
public static SignatureStatus fromXmlType(String xmlSignatureStatus) {
for (SignatureStatus status : KNOWN_STATUSES) {
if (status.is(xmlSignatureStatus)) {
return status;
}
}
return new SignatureStatus(xmlSignatureStatus);
}
private boolean is(String xmlSignatureStatus) {
return this.identifier.equals(xmlSignatureStatus);
}
@Override
public boolean equals(Object o) {
if (o instanceof SignatureStatus) {
SignatureStatus that = (SignatureStatus) o;
return Objects.equals(identifier, that.identifier);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(identifier);
}
@Override
public String toString() {
return identifier;
}
}
| src/main/java/no/digipost/signature/client/portal/SignatureStatus.java | /**
* Copyright (C) Posten Norge AS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package no.digipost.signature.client.portal;
import java.util.List;
import java.util.Objects;
import static java.util.Arrays.asList;
public final class SignatureStatus {
/**
* The signer has rejected to sign the document.
*/
public static final SignatureStatus REJECTED = new SignatureStatus("REJECTED");
/**
* This signer has been cancelled by the sender, and will not be able to sign the document.
*/
public static final SignatureStatus CANCELLED = new SignatureStatus("CANCELLED");
/**
* This signer is reserved from receiving documents electronically, and will not receive
* the document for signing.
*/
public static final SignatureStatus RESERVED = new SignatureStatus("RESERVED");
/**
* We were not able to locate any channels (email, SMS) for notifying the signer to sign the document.
*/
public static final SignatureStatus CONTACT_INFORMATION_MISSING = new SignatureStatus("CONTACT_INFORMATION_MISSING");
/**
* The signer has not made a decision to either sign or reject the document within the
* specified time limit,
*/
public static final SignatureStatus EXPIRED = new SignatureStatus("EXPIRED");
/**
* The signer has yet to review the document and decide if she/he wants to sign or
* reject it.
*/
public static final SignatureStatus WAITING = new SignatureStatus("WAITING");
/**
* The signer has successfully signed the document.
*/
public static final SignatureStatus SIGNED = new SignatureStatus("SIGNED");
/**
* The job has reached a state where the status of this signature is not applicable.
* This includes the case where a signer rejects to sign, and thus ending the job in a
* {@link PortalJobStatus#FAILED} state. Any remaining (previously {@link #WAITING})
* signatures are marked as {@link #NOT_APPLICABLE}.
*/
public static final SignatureStatus NOT_APPLICABLE = new SignatureStatus("NOT_APPLICABLE");
private static final List<SignatureStatus> KNOWN_STATUSES = asList(
REJECTED,
CANCELLED,
RESERVED,
CONTACT_INFORMATION_MISSING,
EXPIRED,
WAITING,
SIGNED,
NOT_APPLICABLE
);
private final String identifier;
public SignatureStatus(String identifier) {
this.identifier = identifier;
}
public static SignatureStatus fromXmlType(String xmlSignatureStatus) {
for (SignatureStatus status : KNOWN_STATUSES) {
if (status.is(xmlSignatureStatus)) {
return status;
}
}
return new SignatureStatus(xmlSignatureStatus);
}
private boolean is(String xmlSignatureStatus) {
return this.identifier.equals(xmlSignatureStatus);
}
@Override
public boolean equals(Object o) {
if (o instanceof SignatureStatus) {
SignatureStatus that = (SignatureStatus) o;
return Objects.equals(identifier, that.identifier);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(identifier);
}
}
| Legger til toString på SignatureStatus | src/main/java/no/digipost/signature/client/portal/SignatureStatus.java | Legger til toString på SignatureStatus |
|
Java | apache-2.0 | 273ac80c7e7eae4827ea91f2b9c93a5a8b006557 | 0 | googleapis/google-http-java-client,googleapis/google-http-java-client,googleapis/google-http-java-client,googleapis/google-http-java-client | /*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http.apache;
import com.google.api.client.util.ByteArrayStreamingContent;
import com.google.api.client.util.StringUtils;
import junit.framework.TestCase;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests {@link ApacheHttpTransport}.
*
* @author Yaniv Inbar
*/
public class ApacheHttpTransportTest extends TestCase {
public void testApacheHttpTransport() {
ApacheHttpTransport transport = new ApacheHttpTransport();
DefaultHttpClient httpClient = (DefaultHttpClient) transport.getHttpClient();
checkDefaultHttpClient(httpClient);
checkHttpClient(httpClient);
}
public void testApacheHttpTransportWithParam() {
ApacheHttpTransport transport = new ApacheHttpTransport(new DefaultHttpClient());
checkHttpClient(transport.getHttpClient());
}
public void testNewDefaultHttpClient() {
checkDefaultHttpClient(ApacheHttpTransport.newDefaultHttpClient());
}
public void testRequestsWithContent() throws Exception {
HttpClient mockClient = mock(HttpClient.class);
HttpResponse mockResponse = mock(HttpResponse.class);
when(mockClient.execute(any(HttpUriRequest.class))).thenReturn(mockResponse);
ApacheHttpTransport transport = new ApacheHttpTransport(mockClient);
// Test GET.
subtestUnsupportedRequestsWithContent(
transport.buildRequest("GET", "http://www.test.url"), "GET");
// Test DELETE.
subtestUnsupportedRequestsWithContent(
transport.buildRequest("DELETE", "http://www.test.url"), "DELETE");
// Test HEAD.
subtestUnsupportedRequestsWithContent(
transport.buildRequest("HEAD", "http://www.test.url"), "HEAD");
// Test PUT.
execute(transport.buildRequest("PUT", "http://www.test.url"));
// Test POST.
execute(transport.buildRequest("POST", "http://www.test.url"));
// Test PATCH.
execute(transport.buildRequest("PATCH", "http://www.test.url"));
}
private void subtestUnsupportedRequestsWithContent(ApacheHttpRequest request, String method)
throws Exception {
try {
execute(request);
fail("expected " + IllegalArgumentException.class);
} catch (IllegalArgumentException e) {
// expected
assertEquals(e.getMessage(),
"Apache HTTP client does not support " + method + " requests with content.");
}
}
private void execute(ApacheHttpRequest request) throws Exception {
byte[] bytes = StringUtils.getBytesUtf8("abc");
request.setStreamingContent(new ByteArrayStreamingContent(bytes));
request.setContentType("text/html");
request.setContentLength(bytes.length);
request.execute();
}
private void checkDefaultHttpClient(DefaultHttpClient client) {
HttpParams params = client.getParams();
assertTrue(client.getConnectionManager() instanceof ThreadSafeClientConnManager);
assertEquals(8192, params.getIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, -1));
DefaultHttpRequestRetryHandler retryHandler =
(DefaultHttpRequestRetryHandler) client.getHttpRequestRetryHandler();
assertEquals(0, retryHandler.getRetryCount());
assertFalse(retryHandler.isRequestSentRetryEnabled());
}
private void checkHttpClient(HttpClient client) {
HttpParams params = client.getParams();
assertFalse(params.getBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true));
assertEquals(HttpVersion.HTTP_1_1, HttpProtocolParams.getVersion(params));
}
}
| google-http-client/src/test/java/com/google/api/client/http/apache/ApacheHttpTransportTest.java | /*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http.apache;
import com.google.api.client.util.ByteArrayStreamingContent;
import com.google.api.client.util.StringUtils;
import junit.framework.TestCase;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Tests {@link ApacheHttpTransport}.
*
* @author Yaniv Inbar
*/
public class ApacheHttpTransportTest extends TestCase {
public void testApacheHttpTransport() {
ApacheHttpTransport transport = new ApacheHttpTransport();
DefaultHttpClient httpClient = (DefaultHttpClient) transport.getHttpClient();
checkDefaultHttpClient(httpClient);
checkHttpClient(httpClient);
}
public void testNewDefaultHttpClient() {
checkDefaultHttpClient(ApacheHttpTransport.newDefaultHttpClient());
}
public void testRequestsWithContent() throws Exception {
HttpClient mockClient = mock(HttpClient.class);
HttpResponse mockResponse = mock(HttpResponse.class);
when(mockClient.execute(any(HttpUriRequest.class))).thenReturn(mockResponse);
ApacheHttpTransport transport = new ApacheHttpTransport(mockClient);
// Test GET.
subtestUnsupportedRequestsWithContent(
transport.buildRequest("GET", "http://www.test.url"), "GET");
// Test DELETE.
subtestUnsupportedRequestsWithContent(
transport.buildRequest("DELETE", "http://www.test.url"), "DELETE");
// Test HEAD.
subtestUnsupportedRequestsWithContent(
transport.buildRequest("HEAD", "http://www.test.url"), "HEAD");
// Test PUT.
execute(transport.buildRequest("PUT", "http://www.test.url"));
// Test POST.
execute(transport.buildRequest("POST", "http://www.test.url"));
// Test PATCH.
execute(transport.buildRequest("PATCH", "http://www.test.url"));
}
private void subtestUnsupportedRequestsWithContent(ApacheHttpRequest request, String method)
throws Exception {
try {
execute(request);
fail("expected " + IllegalArgumentException.class);
} catch (IllegalArgumentException e) {
// expected
assertEquals(e.getMessage(),
"Apache HTTP client does not support " + method + " requests with content.");
}
}
private void execute(ApacheHttpRequest request) throws Exception {
byte[] bytes = StringUtils.getBytesUtf8("abc");
request.setStreamingContent(new ByteArrayStreamingContent(bytes));
request.setContentType("text/html");
request.setContentLength(bytes.length);
request.execute();
}
private void checkDefaultHttpClient(DefaultHttpClient client) {
HttpParams params = client.getParams();
assertTrue(client.getConnectionManager() instanceof ThreadSafeClientConnManager);
assertEquals(8192, params.getIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, -1));
DefaultHttpRequestRetryHandler retryHandler =
(DefaultHttpRequestRetryHandler) client.getHttpRequestRetryHandler();
assertEquals(0, retryHandler.getRetryCount());
assertFalse(retryHandler.isRequestSentRetryEnabled());
}
private void checkHttpClient(HttpClient client) {
HttpParams params = client.getParams();
assertFalse(params.getBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true));
assertEquals(HttpVersion.HTTP_1_1, HttpProtocolParams.getVersion(params));
}
}
| Restore test lost in merge.
| google-http-client/src/test/java/com/google/api/client/http/apache/ApacheHttpTransportTest.java | Restore test lost in merge. |
|
Java | apache-2.0 | db32d69f79dd4ed5cb0aa2eff6f768fa6320aa9c | 0 | gravitee-io/gravitee-gateway,gravitee-io/gateway,gravitee-io/gravitee-gateway,gravitee-io/gateway | /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.gateway.core.policy.impl;
import com.google.common.base.Predicate;
import io.gravitee.gateway.api.policy.PolicyConfiguration;
import io.gravitee.gateway.core.policy.PolicyConfigurationFactory;
import io.gravitee.gateway.core.policy.PolicyDefinition;
import io.gravitee.gateway.core.policy.PolicyFactory;
import org.reflections.ReflectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.Nullable;
import java.lang.reflect.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.reflections.ReflectionUtils.*;
/**
* @author David BRASSELY (brasseld at gmail.com)
*/
public class PolicyFactoryImpl implements PolicyFactory {
private final Logger LOGGER = LoggerFactory.getLogger(PolicyFactoryImpl.class);
@Autowired
private PolicyConfigurationFactory policyConfigurationFactory;
private Map<Class<?>, Constructor<?>> constructorCache = new HashMap<>();
@Override
public Object create(PolicyDefinition policyDefinition, String configuration) {
Class<? extends PolicyConfiguration> policyConfigurationClazz = policyDefinition.configuration();
Class<?> policyClass = policyDefinition.policy();
LOGGER.debug("Create a new policy instance for {}", policyClass.getName());
PolicyConfiguration policyConfiguration = null;
if (policyConfigurationClazz != null) {
if (configuration == null) {
LOGGER.error("A configuration is required for policy {}, returning a null policy", policyDefinition.id());
return null;
} else {
LOGGER.debug("Create policy configuration for policy {}", policyDefinition.id());
policyConfiguration = policyConfigurationFactory.create(policyConfigurationClazz, configuration);
}
}
return createPolicy(policyClass, policyConfiguration);
}
private Object createPolicy(Class<?> policyClass, Object ... args) {
Constructor<?> constr = getConstructor(policyClass);
if (constr != null) {
try {
if (constr.getParameterCount() > 0) {
return constr.newInstance(args);
} else {
return constr.newInstance();
}
} catch (IllegalAccessException | InstantiationException | InvocationTargetException ex) {
LOGGER.error("Unable to instantiate policy {}", policyClass.getName(), ex);
}
}
return null;
}
private Constructor<?> getConstructor(Class<?> policyClass) {
Constructor cons = constructorCache.get(policyClass);
if (cons == null) {
LOGGER.debug("Looking for a constructor to inject policy configuration");
Set<Constructor> constructors =
ReflectionUtils.getConstructors(policyClass,
withModifier(Modifier.PUBLIC),
withParametersAssignableFrom(PolicyConfiguration.class),
withParametersCount(1));
if (constructors.isEmpty()) {
LOGGER.debug("No configuration can be injected for {} because there is no valid constructor. " +
"Using default empty constructor.", policyClass.getName());
try {
cons = policyClass.getConstructor();
} catch (NoSuchMethodException nsme) {
LOGGER.error("Unable to find default empty constructor for {}", policyClass.getName(), nsme);
}
} else if (constructors.size() == 1) {
cons = constructors.iterator().next();
} else {
LOGGER.info("Too much constructors to instantiate policy {}", policyClass.getName());
}
if (cons != null) {
// Put reference in cache
constructorCache.put(policyClass, cons);
}
}
return cons;
}
private <T> T createInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
return clazz.newInstance();
}
public PolicyConfigurationFactory getPolicyConfigurationFactory() {
return policyConfigurationFactory;
}
public void setPolicyConfigurationFactory(PolicyConfigurationFactory policyConfigurationFactory) {
this.policyConfigurationFactory = policyConfigurationFactory;
}
public static Predicate<Member> withParametersAssignableFrom(final Class... types) {
return new Predicate<Member>() {
public boolean apply(@Nullable Member input) {
if (input != null) {
Class<?>[] parameterTypes = parameterTypes(input);
if (parameterTypes.length == types.length) {
for (int i = 0; i < parameterTypes.length; i++) {
if (!types[i].isAssignableFrom(parameterTypes[i]) ||
(parameterTypes[i] == Object.class && types[i] != Object.class)) {
return false;
}
}
return true;
}
}
return false;
}
};
}
private static Class[] parameterTypes(Member member) {
return member != null ?
member.getClass() == Method.class ? ((Method) member).getParameterTypes() :
member.getClass() == Constructor.class ? ((Constructor) member).getParameterTypes() : null : null;
}
}
| gravitee-gateway-core/src/main/java/io/gravitee/gateway/core/policy/impl/PolicyFactoryImpl.java | /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.gateway.core.policy.impl;
import io.gravitee.gateway.api.policy.PolicyConfiguration;
import io.gravitee.gateway.core.policy.PolicyConfigurationFactory;
import io.gravitee.gateway.core.policy.PolicyDefinition;
import io.gravitee.gateway.core.policy.PolicyFactory;
import org.reflections.ReflectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.reflections.ReflectionUtils.*;
/**
* @author David BRASSELY (brasseld at gmail.com)
*/
public class PolicyFactoryImpl implements PolicyFactory {
private final Logger LOGGER = LoggerFactory.getLogger(PolicyFactoryImpl.class);
@Autowired
private PolicyConfigurationFactory policyConfigurationFactory;
private Map<Class<?>, Constructor<?>> constructorCache = new HashMap<>();
@Override
public Object create(PolicyDefinition policyDefinition, String configuration) {
Class<? extends PolicyConfiguration> policyConfigurationClazz = policyDefinition.configuration();
Class<?> policyClass = policyDefinition.policy();
LOGGER.debug("Create a new policy instance for {}", policyClass.getName());
PolicyConfiguration policyConfiguration = null;
if (policyConfigurationClazz != null) {
if (configuration == null) {
LOGGER.error("A configuration is required for policy {}, returning a null policy", policyDefinition.id());
return null;
} else {
LOGGER.debug("Create policy configuration for policy {}", policyDefinition.id());
policyConfiguration = policyConfigurationFactory.create(policyConfigurationClazz, configuration);
}
}
return createPolicy(policyClass, policyConfiguration);
}
private Object createPolicy(Class<?> policyClass, Object ... args) {
Constructor<?> constr = getConstructor(policyClass);
if (constr != null) {
try {
if (constr.getParameterCount() > 0) {
return constr.newInstance(args);
} else {
return constr.newInstance();
}
} catch (IllegalAccessException | InstantiationException | InvocationTargetException ex) {
LOGGER.error("Unable to instantiate policy {}", policyClass.getName(), ex);
}
}
return null;
}
private Constructor<?> getConstructor(Class<?> policyClass) {
Constructor cons = constructorCache.get(policyClass);
if (cons == null) {
LOGGER.debug("Looking for a constructor to inject policy configuration");
Set<Constructor> constructors =
ReflectionUtils.getConstructors(policyClass,
withModifier(Modifier.PUBLIC),
withParametersAssignableTo(PolicyConfiguration.class),
withParametersCount(1));
if (constructors.isEmpty()) {
LOGGER.debug("No configuration can be injected for {} because there is no valid constructor. " +
"Using default empty constructor.", policyClass.getName());
try {
cons = policyClass.getConstructor();
} catch (NoSuchMethodException nsme) {
LOGGER.error("Unable to find default empty constructor for {}", policyClass.getName(), nsme);
}
} else if (constructors.size() == 1) {
cons = constructors.iterator().next();
} else {
LOGGER.info("Too much constructors to instantiate policy {}", policyClass.getName());
}
if (cons != null) {
// Put reference in cache
constructorCache.put(policyClass, cons);
}
}
return cons;
}
private <T> T createInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
return clazz.newInstance();
}
public PolicyConfigurationFactory getPolicyConfigurationFactory() {
return policyConfigurationFactory;
}
public void setPolicyConfigurationFactory(PolicyConfigurationFactory policyConfigurationFactory) {
this.policyConfigurationFactory = policyConfigurationFactory;
}
}
| fix(policy): Looking for policy configuration and subclass using reflection utils
| gravitee-gateway-core/src/main/java/io/gravitee/gateway/core/policy/impl/PolicyFactoryImpl.java | fix(policy): Looking for policy configuration and subclass using reflection utils |
|
Java | apache-2.0 | ac366755b64214d1ef3f87ae5aa39d70793b5994 | 0 | apache/solr,apache/solr,apache/solr,apache/solr,apache/solr | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene.search.grouping;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.MultiDocValues;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.ReaderUtil;
import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.IndexReaderContext;
import org.apache.lucene.index.SlowCompositeReaderWrapper;
import org.apache.lucene.index.Term;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.valuesource.BytesRefFieldSource;
import org.apache.lucene.search.*;
import org.apache.lucene.search.grouping.function.FunctionAllGroupsCollector;
import org.apache.lucene.search.grouping.function.FunctionFirstPassGroupingCollector;
import org.apache.lucene.search.grouping.function.FunctionSecondPassGroupingCollector;
import org.apache.lucene.search.grouping.term.TermAllGroupsCollector;
import org.apache.lucene.search.grouping.term.TermFirstPassGroupingCollector;
import org.apache.lucene.search.grouping.term.TermSecondPassGroupingCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.LuceneTestCase.SuppressCodecs;
import org.apache.lucene.util.TestUtil;
import org.apache.lucene.util.mutable.MutableValue;
import org.apache.lucene.util.mutable.MutableValueStr;
import java.io.IOException;
import java.util.*;
// TODO
// - should test relevance sort too
// - test null
// - test ties
// - test compound sort
@SuppressCodecs({"Lucene40", "Lucene41", "Lucene42"}) // we need missing support... i think?
public class TestGrouping extends LuceneTestCase {
public void testBasic() throws Exception {
String groupField = "author";
FieldType customType = new FieldType();
customType.setStored(true);
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(
random(),
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()));
// 0
Document doc = new Document();
addGroupField(doc, groupField, "author1");
doc.add(new TextField("content", "random text", Field.Store.YES));
doc.add(new Field("id", "1", customType));
w.addDocument(doc);
// 1
doc = new Document();
addGroupField(doc, groupField, "author1");
doc.add(new TextField("content", "some more random text", Field.Store.YES));
doc.add(new Field("id", "2", customType));
w.addDocument(doc);
// 2
doc = new Document();
addGroupField(doc, groupField, "author1");
doc.add(new TextField("content", "some more random textual data", Field.Store.YES));
doc.add(new Field("id", "3", customType));
w.addDocument(doc);
// 3
doc = new Document();
addGroupField(doc, groupField, "author2");
doc.add(new TextField("content", "some random text", Field.Store.YES));
doc.add(new Field("id", "4", customType));
w.addDocument(doc);
// 4
doc = new Document();
addGroupField(doc, groupField, "author3");
doc.add(new TextField("content", "some more random text", Field.Store.YES));
doc.add(new Field("id", "5", customType));
w.addDocument(doc);
// 5
doc = new Document();
addGroupField(doc, groupField, "author3");
doc.add(new TextField("content", "random", Field.Store.YES));
doc.add(new Field("id", "6", customType));
w.addDocument(doc);
// 6 -- no author field
doc = new Document();
doc.add(new TextField("content", "random word stuck in alot of other text", Field.Store.YES));
doc.add(new Field("id", "6", customType));
w.addDocument(doc);
IndexSearcher indexSearcher = newSearcher(w.getReader());
w.shutdown();
final Sort groupSort = Sort.RELEVANCE;
final AbstractFirstPassGroupingCollector<?> c1 = createRandomFirstPassCollector(groupField, groupSort, 10);
indexSearcher.search(new TermQuery(new Term("content", "random")), c1);
final AbstractSecondPassGroupingCollector<?> c2 = createSecondPassCollector(c1, groupField, groupSort, null, 0, 5, true, true, true);
indexSearcher.search(new TermQuery(new Term("content", "random")), c2);
final TopGroups<?> groups = c2.getTopGroups(0);
assertFalse(Float.isNaN(groups.maxScore));
assertEquals(7, groups.totalHitCount);
assertEquals(7, groups.totalGroupedHitCount);
assertEquals(4, groups.groups.length);
// relevance order: 5, 0, 3, 4, 1, 2, 6
// the later a document is added the higher this docId
// value
GroupDocs<?> group = groups.groups[0];
compareGroupValue("author3", group);
assertEquals(2, group.scoreDocs.length);
assertEquals(5, group.scoreDocs[0].doc);
assertEquals(4, group.scoreDocs[1].doc);
assertTrue(group.scoreDocs[0].score > group.scoreDocs[1].score);
group = groups.groups[1];
compareGroupValue("author1", group);
assertEquals(3, group.scoreDocs.length);
assertEquals(0, group.scoreDocs[0].doc);
assertEquals(1, group.scoreDocs[1].doc);
assertEquals(2, group.scoreDocs[2].doc);
assertTrue(group.scoreDocs[0].score > group.scoreDocs[1].score);
assertTrue(group.scoreDocs[1].score > group.scoreDocs[2].score);
group = groups.groups[2];
compareGroupValue("author2", group);
assertEquals(1, group.scoreDocs.length);
assertEquals(3, group.scoreDocs[0].doc);
group = groups.groups[3];
compareGroupValue(null, group);
assertEquals(1, group.scoreDocs.length);
assertEquals(6, group.scoreDocs[0].doc);
indexSearcher.getIndexReader().close();
dir.close();
}
private void addGroupField(Document doc, String groupField, String value) {
doc.add(new SortedDocValuesField(groupField, new BytesRef(value)));
}
private AbstractFirstPassGroupingCollector<?> createRandomFirstPassCollector(String groupField, Sort groupSort, int topDocs) throws IOException {
AbstractFirstPassGroupingCollector<?> selected;
if (random().nextBoolean()) {
ValueSource vs = new BytesRefFieldSource(groupField);
selected = new FunctionFirstPassGroupingCollector(vs, new HashMap<>(), groupSort, topDocs);
} else {
selected = new TermFirstPassGroupingCollector(groupField, groupSort, topDocs);
}
if (VERBOSE) {
System.out.println("Selected implementation: " + selected.getClass().getName());
}
return selected;
}
private AbstractFirstPassGroupingCollector<?> createFirstPassCollector(String groupField, Sort groupSort, int topDocs, AbstractFirstPassGroupingCollector<?> firstPassGroupingCollector) throws IOException {
if (TermFirstPassGroupingCollector.class.isAssignableFrom(firstPassGroupingCollector.getClass())) {
ValueSource vs = new BytesRefFieldSource(groupField);
return new FunctionFirstPassGroupingCollector(vs, new HashMap<>(), groupSort, topDocs);
} else {
return new TermFirstPassGroupingCollector(groupField, groupSort, topDocs);
}
}
@SuppressWarnings({"unchecked","rawtypes"})
private <T> AbstractSecondPassGroupingCollector<T> createSecondPassCollector(AbstractFirstPassGroupingCollector firstPassGroupingCollector,
String groupField,
Sort groupSort,
Sort sortWithinGroup,
int groupOffset,
int maxDocsPerGroup,
boolean getScores,
boolean getMaxScores,
boolean fillSortFields) throws IOException {
if (TermFirstPassGroupingCollector.class.isAssignableFrom(firstPassGroupingCollector.getClass())) {
Collection<SearchGroup<BytesRef>> searchGroups = firstPassGroupingCollector.getTopGroups(groupOffset, fillSortFields);
return (AbstractSecondPassGroupingCollector) new TermSecondPassGroupingCollector(groupField, searchGroups, groupSort, sortWithinGroup, maxDocsPerGroup , getScores, getMaxScores, fillSortFields);
} else {
ValueSource vs = new BytesRefFieldSource(groupField);
Collection<SearchGroup<MutableValue>> searchGroups = firstPassGroupingCollector.getTopGroups(groupOffset, fillSortFields);
return (AbstractSecondPassGroupingCollector) new FunctionSecondPassGroupingCollector(searchGroups, groupSort, sortWithinGroup, maxDocsPerGroup, getScores, getMaxScores, fillSortFields, vs, new HashMap());
}
}
// Basically converts searchGroups from MutableValue to BytesRef if grouping by ValueSource
@SuppressWarnings("unchecked")
private AbstractSecondPassGroupingCollector<?> createSecondPassCollector(AbstractFirstPassGroupingCollector<?> firstPassGroupingCollector,
String groupField,
Collection<SearchGroup<BytesRef>> searchGroups,
Sort groupSort,
Sort sortWithinGroup,
int maxDocsPerGroup,
boolean getScores,
boolean getMaxScores,
boolean fillSortFields) throws IOException {
if (firstPassGroupingCollector.getClass().isAssignableFrom(TermFirstPassGroupingCollector.class)) {
return new TermSecondPassGroupingCollector(groupField, searchGroups, groupSort, sortWithinGroup, maxDocsPerGroup , getScores, getMaxScores, fillSortFields);
} else {
ValueSource vs = new BytesRefFieldSource(groupField);
List<SearchGroup<MutableValue>> mvalSearchGroups = new ArrayList<>(searchGroups.size());
for (SearchGroup<BytesRef> mergedTopGroup : searchGroups) {
SearchGroup<MutableValue> sg = new SearchGroup<>();
MutableValueStr groupValue = new MutableValueStr();
if (mergedTopGroup.groupValue != null) {
groupValue.value = mergedTopGroup.groupValue;
} else {
groupValue.value = new BytesRef();
groupValue.exists = false;
}
sg.groupValue = groupValue;
sg.sortValues = mergedTopGroup.sortValues;
mvalSearchGroups.add(sg);
}
return new FunctionSecondPassGroupingCollector(mvalSearchGroups, groupSort, sortWithinGroup, maxDocsPerGroup, getScores, getMaxScores, fillSortFields, vs, new HashMap<>());
}
}
private AbstractAllGroupsCollector<?> createAllGroupsCollector(AbstractFirstPassGroupingCollector<?> firstPassGroupingCollector,
String groupField) {
if (firstPassGroupingCollector.getClass().isAssignableFrom(TermFirstPassGroupingCollector.class)) {
return new TermAllGroupsCollector(groupField);
} else {
ValueSource vs = new BytesRefFieldSource(groupField);
return new FunctionAllGroupsCollector(vs, new HashMap<>());
}
}
private void compareGroupValue(String expected, GroupDocs<?> group) {
if (expected == null) {
if (group.groupValue == null) {
return;
} else if (group.groupValue.getClass().isAssignableFrom(MutableValueStr.class)) {
return;
} else if (((BytesRef) group.groupValue).length == 0) {
return;
}
fail();
}
if (group.groupValue.getClass().isAssignableFrom(BytesRef.class)) {
assertEquals(new BytesRef(expected), group.groupValue);
} else if (group.groupValue.getClass().isAssignableFrom(MutableValueStr.class)) {
MutableValueStr v = new MutableValueStr();
v.value = new BytesRef(expected);
assertEquals(v, group.groupValue);
} else {
fail();
}
}
private Collection<SearchGroup<BytesRef>> getSearchGroups(AbstractFirstPassGroupingCollector<?> c, int groupOffset, boolean fillFields) {
if (TermFirstPassGroupingCollector.class.isAssignableFrom(c.getClass())) {
return ((TermFirstPassGroupingCollector) c).getTopGroups(groupOffset, fillFields);
} else if (FunctionFirstPassGroupingCollector.class.isAssignableFrom(c.getClass())) {
Collection<SearchGroup<MutableValue>> mutableValueGroups = ((FunctionFirstPassGroupingCollector) c).getTopGroups(groupOffset, fillFields);
if (mutableValueGroups == null) {
return null;
}
List<SearchGroup<BytesRef>> groups = new ArrayList<>(mutableValueGroups.size());
for (SearchGroup<MutableValue> mutableValueGroup : mutableValueGroups) {
SearchGroup<BytesRef> sg = new SearchGroup<>();
sg.groupValue = mutableValueGroup.groupValue.exists() ? ((MutableValueStr) mutableValueGroup.groupValue).value : null;
sg.sortValues = mutableValueGroup.sortValues;
groups.add(sg);
}
return groups;
}
fail();
return null;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private TopGroups<BytesRef> getTopGroups(AbstractSecondPassGroupingCollector c, int withinGroupOffset) {
if (c.getClass().isAssignableFrom(TermSecondPassGroupingCollector.class)) {
return ((TermSecondPassGroupingCollector) c).getTopGroups(withinGroupOffset);
} else if (c.getClass().isAssignableFrom(FunctionSecondPassGroupingCollector.class)) {
TopGroups<MutableValue> mvalTopGroups = ((FunctionSecondPassGroupingCollector) c).getTopGroups(withinGroupOffset);
List<GroupDocs<BytesRef>> groups = new ArrayList<>(mvalTopGroups.groups.length);
for (GroupDocs<MutableValue> mvalGd : mvalTopGroups.groups) {
BytesRef groupValue = mvalGd.groupValue.exists() ? ((MutableValueStr) mvalGd.groupValue).value : null;
groups.add(new GroupDocs<>(Float.NaN, mvalGd.maxScore, mvalGd.totalHits, mvalGd.scoreDocs, groupValue, mvalGd.groupSortValues));
}
return new TopGroups<>(mvalTopGroups.groupSort, mvalTopGroups.withinGroupSort, mvalTopGroups.totalHitCount, mvalTopGroups.totalGroupedHitCount, groups.toArray(new GroupDocs[groups.size()]), Float.NaN);
}
fail();
return null;
}
private static class GroupDoc {
final int id;
final BytesRef group;
final BytesRef sort1;
final BytesRef sort2;
// content must be "realN ..."
final String content;
float score;
float score2;
public GroupDoc(int id, BytesRef group, BytesRef sort1, BytesRef sort2, String content) {
this.id = id;
this.group = group;
this.sort1 = sort1;
this.sort2 = sort2;
this.content = content;
}
}
private Sort getRandomSort() {
final List<SortField> sortFields = new ArrayList<>();
if (random().nextInt(7) == 2) {
sortFields.add(SortField.FIELD_SCORE);
} else {
if (random().nextBoolean()) {
if (random().nextBoolean()) {
sortFields.add(new SortField("sort1", SortField.Type.STRING, random().nextBoolean()));
} else {
sortFields.add(new SortField("sort2", SortField.Type.STRING, random().nextBoolean()));
}
} else if (random().nextBoolean()) {
sortFields.add(new SortField("sort1", SortField.Type.STRING, random().nextBoolean()));
sortFields.add(new SortField("sort2", SortField.Type.STRING, random().nextBoolean()));
}
}
// Break ties:
sortFields.add(new SortField("id", SortField.Type.INT));
return new Sort(sortFields.toArray(new SortField[sortFields.size()]));
}
private Comparator<GroupDoc> getComparator(Sort sort) {
final SortField[] sortFields = sort.getSort();
return new Comparator<GroupDoc>() {
@Override
public int compare(GroupDoc d1, GroupDoc d2) {
for(SortField sf : sortFields) {
final int cmp;
if (sf.getType() == SortField.Type.SCORE) {
if (d1.score > d2.score) {
cmp = -1;
} else if (d1.score < d2.score) {
cmp = 1;
} else {
cmp = 0;
}
} else if (sf.getField().equals("sort1")) {
cmp = d1.sort1.compareTo(d2.sort1);
} else if (sf.getField().equals("sort2")) {
cmp = d1.sort2.compareTo(d2.sort2);
} else {
assertEquals(sf.getField(), "id");
cmp = d1.id - d2.id;
}
if (cmp != 0) {
return sf.getReverse() ? -cmp : cmp;
}
}
// Our sort always fully tie breaks:
fail();
return 0;
}
};
}
@SuppressWarnings({"unchecked","rawtypes"})
private Comparable<?>[] fillFields(GroupDoc d, Sort sort) {
final SortField[] sortFields = sort.getSort();
final Comparable<?>[] fields = new Comparable[sortFields.length];
for(int fieldIDX=0;fieldIDX<sortFields.length;fieldIDX++) {
final Comparable<?> c;
final SortField sf = sortFields[fieldIDX];
if (sf.getType() == SortField.Type.SCORE) {
c = d.score;
} else if (sf.getField().equals("sort1")) {
c = d.sort1;
} else if (sf.getField().equals("sort2")) {
c = d.sort2;
} else {
assertEquals("id", sf.getField());
c = d.id;
}
fields[fieldIDX] = c;
}
return fields;
}
private String groupToString(BytesRef b) {
if (b == null) {
return "null";
} else {
return b.utf8ToString();
}
}
private TopGroups<BytesRef> slowGrouping(GroupDoc[] groupDocs,
String searchTerm,
boolean fillFields,
boolean getScores,
boolean getMaxScores,
boolean doAllGroups,
Sort groupSort,
Sort docSort,
int topNGroups,
int docsPerGroup,
int groupOffset,
int docOffset) {
final Comparator<GroupDoc> groupSortComp = getComparator(groupSort);
Arrays.sort(groupDocs, groupSortComp);
final HashMap<BytesRef,List<GroupDoc>> groups = new HashMap<>();
final List<BytesRef> sortedGroups = new ArrayList<>();
final List<Comparable<?>[]> sortedGroupFields = new ArrayList<>();
int totalHitCount = 0;
Set<BytesRef> knownGroups = new HashSet<>();
//System.out.println("TEST: slowGrouping");
for(GroupDoc d : groupDocs) {
// TODO: would be better to filter by searchTerm before sorting!
if (!d.content.startsWith(searchTerm)) {
continue;
}
totalHitCount++;
//System.out.println(" match id=" + d.id + " score=" + d.score);
if (doAllGroups) {
if (!knownGroups.contains(d.group)) {
knownGroups.add(d.group);
//System.out.println(" add group=" + groupToString(d.group));
}
}
List<GroupDoc> l = groups.get(d.group);
if (l == null) {
//System.out.println(" add sortedGroup=" + groupToString(d.group));
sortedGroups.add(d.group);
if (fillFields) {
sortedGroupFields.add(fillFields(d, groupSort));
}
l = new ArrayList<>();
groups.put(d.group, l);
}
l.add(d);
}
if (groupOffset >= sortedGroups.size()) {
// slice is out of bounds
return null;
}
final int limit = Math.min(groupOffset + topNGroups, groups.size());
final Comparator<GroupDoc> docSortComp = getComparator(docSort);
@SuppressWarnings({"unchecked","rawtypes"})
final GroupDocs<BytesRef>[] result = new GroupDocs[limit-groupOffset];
int totalGroupedHitCount = 0;
for(int idx=groupOffset;idx < limit;idx++) {
final BytesRef group = sortedGroups.get(idx);
final List<GroupDoc> docs = groups.get(group);
totalGroupedHitCount += docs.size();
Collections.sort(docs, docSortComp);
final ScoreDoc[] hits;
if (docs.size() > docOffset) {
final int docIDXLimit = Math.min(docOffset + docsPerGroup, docs.size());
hits = new ScoreDoc[docIDXLimit - docOffset];
for(int docIDX=docOffset; docIDX < docIDXLimit; docIDX++) {
final GroupDoc d = docs.get(docIDX);
final FieldDoc fd;
if (fillFields) {
fd = new FieldDoc(d.id, getScores ? d.score : Float.NaN, fillFields(d, docSort));
} else {
fd = new FieldDoc(d.id, getScores ? d.score : Float.NaN);
}
hits[docIDX-docOffset] = fd;
}
} else {
hits = new ScoreDoc[0];
}
result[idx-groupOffset] = new GroupDocs<>(Float.NaN,
0.0f,
docs.size(),
hits,
group,
fillFields ? sortedGroupFields.get(idx) : null);
}
if (doAllGroups) {
return new TopGroups<>(
new TopGroups<>(groupSort.getSort(), docSort.getSort(), totalHitCount, totalGroupedHitCount, result, Float.NaN),
knownGroups.size()
);
} else {
return new TopGroups<>(groupSort.getSort(), docSort.getSort(), totalHitCount, totalGroupedHitCount, result, Float.NaN);
}
}
private DirectoryReader getDocBlockReader(Directory dir, GroupDoc[] groupDocs) throws IOException {
// Coalesce by group, but in random order:
Collections.shuffle(Arrays.asList(groupDocs), random());
final Map<BytesRef,List<GroupDoc>> groupMap = new HashMap<>();
final List<BytesRef> groupValues = new ArrayList<>();
for(GroupDoc groupDoc : groupDocs) {
if (!groupMap.containsKey(groupDoc.group)) {
groupValues.add(groupDoc.group);
groupMap.put(groupDoc.group, new ArrayList<GroupDoc>());
}
groupMap.get(groupDoc.group).add(groupDoc);
}
RandomIndexWriter w = new RandomIndexWriter(
random(),
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random())));
final List<List<Document>> updateDocs = new ArrayList<>();
FieldType groupEndType = new FieldType(StringField.TYPE_NOT_STORED);
groupEndType.setIndexOptions(IndexOptions.DOCS_ONLY);
groupEndType.setOmitNorms(true);
//System.out.println("TEST: index groups");
for(BytesRef group : groupValues) {
final List<Document> docs = new ArrayList<>();
//System.out.println("TEST: group=" + (group == null ? "null" : group.utf8ToString()));
for(GroupDoc groupValue : groupMap.get(group)) {
Document doc = new Document();
docs.add(doc);
if (groupValue.group != null) {
doc.add(newStringField("group", groupValue.group.utf8ToString(), Field.Store.YES));
doc.add(new SortedDocValuesField("group", BytesRef.deepCopyOf(groupValue.group)));
}
doc.add(newStringField("sort1", groupValue.sort1.utf8ToString(), Field.Store.NO));
doc.add(new SortedDocValuesField("sort1", BytesRef.deepCopyOf(groupValue.sort1)));
doc.add(newStringField("sort2", groupValue.sort2.utf8ToString(), Field.Store.NO));
doc.add(new SortedDocValuesField("sort2", BytesRef.deepCopyOf(groupValue.sort2)));
doc.add(new IntField("id", groupValue.id, Field.Store.NO));
doc.add(new NumericDocValuesField("id", groupValue.id));
doc.add(newTextField("content", groupValue.content, Field.Store.NO));
//System.out.println("TEST: doc content=" + groupValue.content + " group=" + (groupValue.group == null ? "null" : groupValue.group.utf8ToString()) + " sort1=" + groupValue.sort1.utf8ToString() + " id=" + groupValue.id);
}
// So we can pull filter marking last doc in block:
final Field groupEnd = newField("groupend", "x", groupEndType);
docs.get(docs.size()-1).add(groupEnd);
// Add as a doc block:
w.addDocuments(docs);
if (group != null && random().nextInt(7) == 4) {
updateDocs.add(docs);
}
}
for(List<Document> docs : updateDocs) {
// Just replaces docs w/ same docs:
w.updateDocuments(new Term("group", docs.get(0).get("group")), docs);
}
final DirectoryReader r = w.getReader();
w.shutdown();
return r;
}
private static class ShardState {
public final ShardSearcher[] subSearchers;
public final int[] docStarts;
public ShardState(IndexSearcher s) {
final IndexReaderContext ctx = s.getTopReaderContext();
final List<AtomicReaderContext> leaves = ctx.leaves();
subSearchers = new ShardSearcher[leaves.size()];
for(int searcherIDX=0;searcherIDX<subSearchers.length;searcherIDX++) {
subSearchers[searcherIDX] = new ShardSearcher(leaves.get(searcherIDX), ctx);
}
docStarts = new int[subSearchers.length];
for(int subIDX=0;subIDX<docStarts.length;subIDX++) {
docStarts[subIDX] = leaves.get(subIDX).docBase;
//System.out.println("docStarts[" + subIDX + "]=" + docStarts[subIDX]);
}
}
}
public void testRandom() throws Exception {
int numberOfRuns = TestUtil.nextInt(random(), 3, 6);
for (int iter=0; iter<numberOfRuns; iter++) {
if (VERBOSE) {
System.out.println("TEST: iter=" + iter);
}
final int numDocs = TestUtil.nextInt(random(), 100, 1000) * RANDOM_MULTIPLIER;
//final int numDocs = _TestUtil.nextInt(random, 5, 20);
final int numGroups = TestUtil.nextInt(random(), 1, numDocs);
if (VERBOSE) {
System.out.println("TEST: numDocs=" + numDocs + " numGroups=" + numGroups);
}
final List<BytesRef> groups = new ArrayList<>();
for(int i=0;i<numGroups;i++) {
String randomValue;
do {
// B/c of DV based impl we can't see the difference between an empty string and a null value.
// For that reason we don't generate empty string
// groups.
randomValue = TestUtil.randomRealisticUnicodeString(random());
//randomValue = _TestUtil.randomSimpleString(random());
} while ("".equals(randomValue));
groups.add(new BytesRef(randomValue));
}
final String[] contentStrings = new String[TestUtil.nextInt(random(), 2, 20)];
if (VERBOSE) {
System.out.println("TEST: create fake content");
}
for(int contentIDX=0;contentIDX<contentStrings.length;contentIDX++) {
final StringBuilder sb = new StringBuilder();
sb.append("real").append(random().nextInt(3)).append(' ');
final int fakeCount = random().nextInt(10);
for(int fakeIDX=0;fakeIDX<fakeCount;fakeIDX++) {
sb.append("fake ");
}
contentStrings[contentIDX] = sb.toString();
if (VERBOSE) {
System.out.println(" content=" + sb.toString());
}
}
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(
random(),
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random())));
Document doc = new Document();
Document docNoGroup = new Document();
Field idvGroupField = new SortedDocValuesField("group", new BytesRef());
doc.add(idvGroupField);
docNoGroup.add(idvGroupField);
Field group = newStringField("group", "", Field.Store.NO);
doc.add(group);
Field sort1 = new SortedDocValuesField("sort1", new BytesRef());
doc.add(sort1);
docNoGroup.add(sort1);
Field sort2 = new SortedDocValuesField("sort2", new BytesRef());
doc.add(sort2);
docNoGroup.add(sort2);
Field content = newTextField("content", "", Field.Store.NO);
doc.add(content);
docNoGroup.add(content);
IntField id = new IntField("id", 0, Field.Store.NO);
doc.add(id);
NumericDocValuesField idDV = new NumericDocValuesField("id", 0);
doc.add(idDV);
docNoGroup.add(id);
docNoGroup.add(idDV);
final GroupDoc[] groupDocs = new GroupDoc[numDocs];
for(int i=0;i<numDocs;i++) {
final BytesRef groupValue;
if (random().nextInt(24) == 17) {
// So we test the "doc doesn't have the group'd
// field" case:
groupValue = null;
} else {
groupValue = groups.get(random().nextInt(groups.size()));
}
final GroupDoc groupDoc = new GroupDoc(i,
groupValue,
groups.get(random().nextInt(groups.size())),
groups.get(random().nextInt(groups.size())),
contentStrings[random().nextInt(contentStrings.length)]);
if (VERBOSE) {
System.out.println(" doc content=" + groupDoc.content + " id=" + i + " group=" + (groupDoc.group == null ? "null" : groupDoc.group.utf8ToString()) + " sort1=" + groupDoc.sort1.utf8ToString() + " sort2=" + groupDoc.sort2.utf8ToString());
}
groupDocs[i] = groupDoc;
if (groupDoc.group != null) {
group.setStringValue(groupDoc.group.utf8ToString());
idvGroupField.setBytesValue(BytesRef.deepCopyOf(groupDoc.group));
} else {
// TODO: not true
// Must explicitly set empty string, else eg if
// the segment has all docs missing the field then
// we get null back instead of empty BytesRef:
idvGroupField.setBytesValue(new BytesRef());
}
sort1.setBytesValue(BytesRef.deepCopyOf(groupDoc.sort1));
sort2.setBytesValue(BytesRef.deepCopyOf(groupDoc.sort2));
content.setStringValue(groupDoc.content);
id.setIntValue(groupDoc.id);
idDV.setLongValue(groupDoc.id);
if (groupDoc.group == null) {
w.addDocument(docNoGroup);
} else {
w.addDocument(doc);
}
}
final GroupDoc[] groupDocsByID = new GroupDoc[groupDocs.length];
System.arraycopy(groupDocs, 0, groupDocsByID, 0, groupDocs.length);
final DirectoryReader r = w.getReader();
w.shutdown();
final NumericDocValues docIDToID = MultiDocValues.getNumericValues(r, "id");
DirectoryReader rBlocks = null;
Directory dirBlocks = null;
try {
final IndexSearcher s = newSearcher(r);
if (VERBOSE) {
System.out.println("\nTEST: searcher=" + s);
}
final ShardState shards = new ShardState(s);
for(int contentID=0;contentID<3;contentID++) {
final ScoreDoc[] hits = s.search(new TermQuery(new Term("content", "real"+contentID)), numDocs).scoreDocs;
for(ScoreDoc hit : hits) {
final GroupDoc gd = groupDocs[(int) docIDToID.get(hit.doc)];
assertTrue(gd.score == 0.0);
gd.score = hit.score;
assertEquals(gd.id, docIDToID.get(hit.doc));
}
}
for(GroupDoc gd : groupDocs) {
assertTrue(gd.score != 0.0);
}
// Build 2nd index, where docs are added in blocks by
// group, so we can use single pass collector
dirBlocks = newDirectory();
rBlocks = getDocBlockReader(dirBlocks, groupDocs);
final Filter lastDocInBlock = new CachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("groupend", "x"))));
final NumericDocValues docIDToIDBlocks = MultiDocValues.getNumericValues(rBlocks, "id");
final IndexSearcher sBlocks = newSearcher(rBlocks);
final ShardState shardsBlocks = new ShardState(sBlocks);
// ReaderBlocks only increases maxDoc() vs reader, which
// means a monotonic shift in scores, so we can
// reliably remap them w/ Map:
final Map<String,Map<Float,Float>> scoreMap = new HashMap<>();
// Tricky: must separately set .score2, because the doc
// block index was created with possible deletions!
//System.out.println("fixup score2");
for(int contentID=0;contentID<3;contentID++) {
//System.out.println(" term=real" + contentID);
final Map<Float,Float> termScoreMap = new HashMap<>();
scoreMap.put("real"+contentID, termScoreMap);
//System.out.println("term=real" + contentID + " dfold=" + s.docFreq(new Term("content", "real"+contentID)) +
//" dfnew=" + sBlocks.docFreq(new Term("content", "real"+contentID)));
final ScoreDoc[] hits = sBlocks.search(new TermQuery(new Term("content", "real"+contentID)), numDocs).scoreDocs;
for(ScoreDoc hit : hits) {
final GroupDoc gd = groupDocsByID[(int) docIDToIDBlocks.get(hit.doc)];
assertTrue(gd.score2 == 0.0);
gd.score2 = hit.score;
assertEquals(gd.id, docIDToIDBlocks.get(hit.doc));
//System.out.println(" score=" + gd.score + " score2=" + hit.score + " id=" + docIDToIDBlocks.get(hit.doc));
termScoreMap.put(gd.score, gd.score2);
}
}
for(int searchIter=0;searchIter<100;searchIter++) {
if (VERBOSE) {
System.out.println("\nTEST: searchIter=" + searchIter);
}
final String searchTerm = "real" + random().nextInt(3);
final boolean fillFields = random().nextBoolean();
boolean getScores = random().nextBoolean();
final boolean getMaxScores = random().nextBoolean();
final Sort groupSort = getRandomSort();
//final Sort groupSort = new Sort(new SortField[] {new SortField("sort1", SortField.STRING), new SortField("id", SortField.INT)});
// TODO: also test null (= sort by relevance)
final Sort docSort = getRandomSort();
for(SortField sf : docSort.getSort()) {
if (sf.getType() == SortField.Type.SCORE) {
getScores = true;
break;
}
}
for(SortField sf : groupSort.getSort()) {
if (sf.getType() == SortField.Type.SCORE) {
getScores = true;
break;
}
}
final int topNGroups = TestUtil.nextInt(random(), 1, 30);
//final int topNGroups = 10;
final int docsPerGroup = TestUtil.nextInt(random(), 1, 50);
final int groupOffset = TestUtil.nextInt(random(), 0, (topNGroups - 1) / 2);
//final int groupOffset = 0;
final int docOffset = TestUtil.nextInt(random(), 0, docsPerGroup - 1);
//final int docOffset = 0;
final boolean doCache = random().nextBoolean();
final boolean doAllGroups = random().nextBoolean();
if (VERBOSE) {
System.out.println("TEST: groupSort=" + groupSort + " docSort=" + docSort + " searchTerm=" + searchTerm + " dF=" + r.docFreq(new Term("content", searchTerm)) +" dFBlock=" + rBlocks.docFreq(new Term("content", searchTerm)) + " topNGroups=" + topNGroups + " groupOffset=" + groupOffset + " docOffset=" + docOffset + " doCache=" + doCache + " docsPerGroup=" + docsPerGroup + " doAllGroups=" + doAllGroups + " getScores=" + getScores + " getMaxScores=" + getMaxScores);
}
String groupField = "group";
if (VERBOSE) {
System.out.println(" groupField=" + groupField);
}
final AbstractFirstPassGroupingCollector<?> c1 = createRandomFirstPassCollector(groupField, groupSort, groupOffset+topNGroups);
final CachingCollector cCache;
final Collector c;
final AbstractAllGroupsCollector<?> allGroupsCollector;
if (doAllGroups) {
allGroupsCollector = createAllGroupsCollector(c1, groupField);
} else {
allGroupsCollector = null;
}
final boolean useWrappingCollector = random().nextBoolean();
if (doCache) {
final double maxCacheMB = random().nextDouble();
if (VERBOSE) {
System.out.println("TEST: maxCacheMB=" + maxCacheMB);
}
if (useWrappingCollector) {
if (doAllGroups) {
cCache = CachingCollector.create(c1, true, maxCacheMB);
c = MultiCollector.wrap(cCache, allGroupsCollector);
} else {
c = cCache = CachingCollector.create(c1, true, maxCacheMB);
}
} else {
// Collect only into cache, then replay multiple times:
c = cCache = CachingCollector.create(false, true, maxCacheMB);
}
} else {
cCache = null;
if (doAllGroups) {
c = MultiCollector.wrap(c1, allGroupsCollector);
} else {
c = c1;
}
}
// Search top reader:
final Query query = new TermQuery(new Term("content", searchTerm));
s.search(query, c);
if (doCache && !useWrappingCollector) {
if (cCache.isCached()) {
// Replay for first-pass grouping
cCache.replay(c1);
if (doAllGroups) {
// Replay for all groups:
cCache.replay(allGroupsCollector);
}
} else {
// Replay by re-running search:
s.search(query, c1);
if (doAllGroups) {
s.search(query, allGroupsCollector);
}
}
}
// Get 1st pass top groups
final Collection<SearchGroup<BytesRef>> topGroups = getSearchGroups(c1, groupOffset, fillFields);
final TopGroups<BytesRef> groupsResult;
if (VERBOSE) {
System.out.println("TEST: first pass topGroups");
if (topGroups == null) {
System.out.println(" null");
} else {
for (SearchGroup<BytesRef> searchGroup : topGroups) {
System.out.println(" " + (searchGroup.groupValue == null ? "null" : searchGroup.groupValue) + ": " + Arrays.deepToString(searchGroup.sortValues));
}
}
}
// Get 1st pass top groups using shards
ValueHolder<Boolean> idvBasedImplsUsedSharded = new ValueHolder<>(false);
final TopGroups<BytesRef> topGroupsShards = searchShards(s, shards.subSearchers, query, groupSort, docSort,
groupOffset, topNGroups, docOffset, docsPerGroup, getScores, getMaxScores, true, false, idvBasedImplsUsedSharded);
final AbstractSecondPassGroupingCollector<?> c2;
if (topGroups != null) {
if (VERBOSE) {
System.out.println("TEST: topGroups");
for (SearchGroup<BytesRef> searchGroup : topGroups) {
System.out.println(" " + (searchGroup.groupValue == null ? "null" : searchGroup.groupValue.utf8ToString()) + ": " + Arrays.deepToString(searchGroup.sortValues));
}
}
c2 = createSecondPassCollector(c1, groupField, groupSort, docSort, groupOffset, docOffset + docsPerGroup, getScores, getMaxScores, fillFields);
if (doCache) {
if (cCache.isCached()) {
if (VERBOSE) {
System.out.println("TEST: cache is intact");
}
cCache.replay(c2);
} else {
if (VERBOSE) {
System.out.println("TEST: cache was too large");
}
s.search(query, c2);
}
} else {
s.search(query, c2);
}
if (doAllGroups) {
TopGroups<BytesRef> tempTopGroups = getTopGroups(c2, docOffset);
groupsResult = new TopGroups<>(tempTopGroups, allGroupsCollector.getGroupCount());
} else {
groupsResult = getTopGroups(c2, docOffset);
}
} else {
c2 = null;
groupsResult = null;
if (VERBOSE) {
System.out.println("TEST: no results");
}
}
final TopGroups<BytesRef> expectedGroups = slowGrouping(groupDocs, searchTerm, fillFields, getScores, getMaxScores, doAllGroups, groupSort, docSort, topNGroups, docsPerGroup, groupOffset, docOffset);
if (VERBOSE) {
if (expectedGroups == null) {
System.out.println("TEST: no expected groups");
} else {
System.out.println("TEST: expected groups totalGroupedHitCount=" + expectedGroups.totalGroupedHitCount);
for(GroupDocs<BytesRef> gd : expectedGroups.groups) {
System.out.println(" group=" + (gd.groupValue == null ? "null" : gd.groupValue) + " totalHits=" + gd.totalHits + " scoreDocs.len=" + gd.scoreDocs.length);
for(ScoreDoc sd : gd.scoreDocs) {
System.out.println(" id=" + sd.doc + " score=" + sd.score);
}
}
}
if (groupsResult == null) {
System.out.println("TEST: no matched groups");
} else {
System.out.println("TEST: matched groups totalGroupedHitCount=" + groupsResult.totalGroupedHitCount);
for(GroupDocs<BytesRef> gd : groupsResult.groups) {
System.out.println(" group=" + (gd.groupValue == null ? "null" : gd.groupValue) + " totalHits=" + gd.totalHits);
for(ScoreDoc sd : gd.scoreDocs) {
System.out.println(" id=" + docIDToID.get(sd.doc) + " score=" + sd.score);
}
}
if (searchIter == 14) {
for(int docIDX=0;docIDX<s.getIndexReader().maxDoc();docIDX++) {
System.out.println("ID=" + docIDToID.get(docIDX) + " explain=" + s.explain(query, docIDX));
}
}
}
if (topGroupsShards == null) {
System.out.println("TEST: no matched-merged groups");
} else {
System.out.println("TEST: matched-merged groups totalGroupedHitCount=" + topGroupsShards.totalGroupedHitCount);
for(GroupDocs<BytesRef> gd : topGroupsShards.groups) {
System.out.println(" group=" + (gd.groupValue == null ? "null" : gd.groupValue) + " totalHits=" + gd.totalHits);
for(ScoreDoc sd : gd.scoreDocs) {
System.out.println(" id=" + docIDToID.get(sd.doc) + " score=" + sd.score);
}
}
}
}
assertEquals(docIDToID, expectedGroups, groupsResult, true, true, true, getScores, true);
// Confirm merged shards match:
assertEquals(docIDToID, expectedGroups, topGroupsShards, true, false, fillFields, getScores, idvBasedImplsUsedSharded.value);
if (topGroupsShards != null) {
verifyShards(shards.docStarts, topGroupsShards);
}
final boolean needsScores = getScores || getMaxScores || docSort == null;
final BlockGroupingCollector c3 = new BlockGroupingCollector(groupSort, groupOffset+topNGroups, needsScores, lastDocInBlock);
final TermAllGroupsCollector allGroupsCollector2;
final Collector c4;
if (doAllGroups) {
// NOTE: must be "group" and not "group_dv"
// (groupField) because we didn't index doc
// values in the block index:
allGroupsCollector2 = new TermAllGroupsCollector("group");
c4 = MultiCollector.wrap(c3, allGroupsCollector2);
} else {
allGroupsCollector2 = null;
c4 = c3;
}
// Get block grouping result:
sBlocks.search(query, c4);
@SuppressWarnings({"unchecked","rawtypes"})
final TopGroups<BytesRef> tempTopGroupsBlocks = (TopGroups<BytesRef>) c3.getTopGroups(docSort, groupOffset, docOffset, docOffset+docsPerGroup, fillFields);
final TopGroups<BytesRef> groupsResultBlocks;
if (doAllGroups && tempTopGroupsBlocks != null) {
assertEquals((int) tempTopGroupsBlocks.totalGroupCount, allGroupsCollector2.getGroupCount());
groupsResultBlocks = new TopGroups<>(tempTopGroupsBlocks, allGroupsCollector2.getGroupCount());
} else {
groupsResultBlocks = tempTopGroupsBlocks;
}
if (VERBOSE) {
if (groupsResultBlocks == null) {
System.out.println("TEST: no block groups");
} else {
System.out.println("TEST: block groups totalGroupedHitCount=" + groupsResultBlocks.totalGroupedHitCount);
boolean first = true;
for(GroupDocs<BytesRef> gd : groupsResultBlocks.groups) {
System.out.println(" group=" + (gd.groupValue == null ? "null" : gd.groupValue.utf8ToString()) + " totalHits=" + gd.totalHits);
for(ScoreDoc sd : gd.scoreDocs) {
System.out.println(" id=" + docIDToIDBlocks.get(sd.doc) + " score=" + sd.score);
if (first) {
System.out.println("explain: " + sBlocks.explain(query, sd.doc));
first = false;
}
}
}
}
}
// Get shard'd block grouping result:
final TopGroups<BytesRef> topGroupsBlockShards = searchShards(sBlocks, shardsBlocks.subSearchers, query,
groupSort, docSort, groupOffset, topNGroups, docOffset, docsPerGroup, getScores, getMaxScores, false, false, new ValueHolder<>(true));
if (expectedGroups != null) {
// Fixup scores for reader2
for (GroupDocs<?> groupDocsHits : expectedGroups.groups) {
for(ScoreDoc hit : groupDocsHits.scoreDocs) {
final GroupDoc gd = groupDocsByID[hit.doc];
assertEquals(gd.id, hit.doc);
//System.out.println("fixup score " + hit.score + " to " + gd.score2 + " vs " + gd.score);
hit.score = gd.score2;
}
}
final SortField[] sortFields = groupSort.getSort();
final Map<Float,Float> termScoreMap = scoreMap.get(searchTerm);
for(int groupSortIDX=0;groupSortIDX<sortFields.length;groupSortIDX++) {
if (sortFields[groupSortIDX].getType() == SortField.Type.SCORE) {
for (GroupDocs<?> groupDocsHits : expectedGroups.groups) {
if (groupDocsHits.groupSortValues != null) {
//System.out.println("remap " + groupDocsHits.groupSortValues[groupSortIDX] + " to " + termScoreMap.get(groupDocsHits.groupSortValues[groupSortIDX]));
groupDocsHits.groupSortValues[groupSortIDX] = termScoreMap.get(groupDocsHits.groupSortValues[groupSortIDX]);
assertNotNull(groupDocsHits.groupSortValues[groupSortIDX]);
}
}
}
}
final SortField[] docSortFields = docSort.getSort();
for(int docSortIDX=0;docSortIDX<docSortFields.length;docSortIDX++) {
if (docSortFields[docSortIDX].getType() == SortField.Type.SCORE) {
for (GroupDocs<?> groupDocsHits : expectedGroups.groups) {
for(ScoreDoc _hit : groupDocsHits.scoreDocs) {
FieldDoc hit = (FieldDoc) _hit;
if (hit.fields != null) {
hit.fields[docSortIDX] = termScoreMap.get(hit.fields[docSortIDX]);
assertNotNull(hit.fields[docSortIDX]);
}
}
}
}
}
}
assertEquals(docIDToIDBlocks, expectedGroups, groupsResultBlocks, false, true, true, getScores, false);
assertEquals(docIDToIDBlocks, expectedGroups, topGroupsBlockShards, false, false, fillFields, getScores, false);
}
} finally {
QueryUtils.purgeFieldCache(r);
if (rBlocks != null) {
QueryUtils.purgeFieldCache(rBlocks);
}
}
r.close();
dir.close();
rBlocks.close();
dirBlocks.close();
}
}
private void verifyShards(int[] docStarts, TopGroups<BytesRef> topGroups) {
for(GroupDocs<?> group : topGroups.groups) {
for(int hitIDX=0;hitIDX<group.scoreDocs.length;hitIDX++) {
final ScoreDoc sd = group.scoreDocs[hitIDX];
assertEquals("doc=" + sd.doc + " wrong shard",
ReaderUtil.subIndex(sd.doc, docStarts),
sd.shardIndex);
}
}
}
private TopGroups<BytesRef> searchShards(IndexSearcher topSearcher, ShardSearcher[] subSearchers, Query query, Sort groupSort, Sort docSort, int groupOffset, int topNGroups, int docOffset,
int topNDocs, boolean getScores, boolean getMaxScores, boolean canUseIDV, boolean preFlex, ValueHolder<Boolean> usedIdvBasedImpl) throws Exception {
// TODO: swap in caching, all groups collector hereassertEquals(expected.totalHitCount, actual.totalHitCount);
// too...
if (VERBOSE) {
System.out.println("TEST: " + subSearchers.length + " shards: " + Arrays.toString(subSearchers) + " canUseIDV=" + canUseIDV);
}
// Run 1st pass collector to get top groups per shard
final Weight w = topSearcher.createNormalizedWeight(query);
final List<Collection<SearchGroup<BytesRef>>> shardGroups = new ArrayList<>();
List<AbstractFirstPassGroupingCollector<?>> firstPassGroupingCollectors = new ArrayList<>();
AbstractFirstPassGroupingCollector<?> firstPassCollector = null;
boolean shardsCanUseIDV;
if (canUseIDV) {
if (SlowCompositeReaderWrapper.class.isAssignableFrom(subSearchers[0].getIndexReader().getClass())) {
shardsCanUseIDV = false;
} else {
shardsCanUseIDV = !preFlex;
}
} else {
shardsCanUseIDV = false;
}
String groupField = "group";
for(int shardIDX=0;shardIDX<subSearchers.length;shardIDX++) {
// First shard determines whether we use IDV or not;
// all other shards match that:
if (firstPassCollector == null) {
firstPassCollector = createRandomFirstPassCollector(groupField, groupSort, groupOffset + topNGroups);
} else {
firstPassCollector = createFirstPassCollector(groupField, groupSort, groupOffset + topNGroups, firstPassCollector);
}
if (VERBOSE) {
System.out.println(" shard=" + shardIDX + " groupField=" + groupField);
System.out.println(" 1st pass collector=" + firstPassCollector);
}
firstPassGroupingCollectors.add(firstPassCollector);
subSearchers[shardIDX].search(w, firstPassCollector);
final Collection<SearchGroup<BytesRef>> topGroups = getSearchGroups(firstPassCollector, 0, true);
if (topGroups != null) {
if (VERBOSE) {
System.out.println(" shard " + shardIDX + " s=" + subSearchers[shardIDX] + " totalGroupedHitCount=?" + " " + topGroups.size() + " groups:");
for(SearchGroup<BytesRef> group : topGroups) {
System.out.println(" " + groupToString(group.groupValue) + " groupSort=" + Arrays.toString(group.sortValues));
}
}
shardGroups.add(topGroups);
}
}
final Collection<SearchGroup<BytesRef>> mergedTopGroups = SearchGroup.merge(shardGroups, groupOffset, topNGroups, groupSort);
if (VERBOSE) {
System.out.println(" top groups merged:");
if (mergedTopGroups == null) {
System.out.println(" null");
} else {
System.out.println(" " + mergedTopGroups.size() + " top groups:");
for(SearchGroup<BytesRef> group : mergedTopGroups) {
System.out.println(" [" + groupToString(group.groupValue) + "] groupSort=" + Arrays.toString(group.sortValues));
}
}
}
if (mergedTopGroups != null) {
// Now 2nd pass:
@SuppressWarnings({"unchecked","rawtypes"})
final TopGroups<BytesRef>[] shardTopGroups = new TopGroups[subSearchers.length];
for(int shardIDX=0;shardIDX<subSearchers.length;shardIDX++) {
final AbstractSecondPassGroupingCollector<?> secondPassCollector = createSecondPassCollector(firstPassGroupingCollectors.get(shardIDX),
groupField, mergedTopGroups, groupSort, docSort, docOffset + topNDocs, getScores, getMaxScores, true);
subSearchers[shardIDX].search(w, secondPassCollector);
shardTopGroups[shardIDX] = getTopGroups(secondPassCollector, 0);
if (VERBOSE) {
System.out.println(" " + shardTopGroups[shardIDX].groups.length + " shard[" + shardIDX + "] groups:");
for(GroupDocs<BytesRef> group : shardTopGroups[shardIDX].groups) {
System.out.println(" [" + groupToString(group.groupValue) + "] groupSort=" + Arrays.toString(group.groupSortValues) + " numDocs=" + group.scoreDocs.length);
}
}
}
TopGroups<BytesRef> mergedGroups = TopGroups.merge(shardTopGroups, groupSort, docSort, docOffset, topNDocs, TopGroups.ScoreMergeMode.None);
if (VERBOSE) {
System.out.println(" " + mergedGroups.groups.length + " merged groups:");
for(GroupDocs<BytesRef> group : mergedGroups.groups) {
System.out.println(" [" + groupToString(group.groupValue) + "] groupSort=" + Arrays.toString(group.groupSortValues) + " numDocs=" + group.scoreDocs.length);
}
}
return mergedGroups;
} else {
return null;
}
}
private void assertEquals(NumericDocValues docIDtoID, TopGroups<BytesRef> expected, TopGroups<BytesRef> actual, boolean verifyGroupValues, boolean verifyTotalGroupCount, boolean verifySortValues, boolean testScores, boolean idvBasedImplsUsed) {
if (expected == null) {
assertNull(actual);
return;
}
assertNotNull(actual);
assertEquals("expected.groups.length != actual.groups.length", expected.groups.length, actual.groups.length);
assertEquals("expected.totalHitCount != actual.totalHitCount", expected.totalHitCount, actual.totalHitCount);
assertEquals("expected.totalGroupedHitCount != actual.totalGroupedHitCount", expected.totalGroupedHitCount, actual.totalGroupedHitCount);
if (expected.totalGroupCount != null && verifyTotalGroupCount) {
assertEquals("expected.totalGroupCount != actual.totalGroupCount", expected.totalGroupCount, actual.totalGroupCount);
}
for(int groupIDX=0;groupIDX<expected.groups.length;groupIDX++) {
if (VERBOSE) {
System.out.println(" check groupIDX=" + groupIDX);
}
final GroupDocs<BytesRef> expectedGroup = expected.groups[groupIDX];
final GroupDocs<BytesRef> actualGroup = actual.groups[groupIDX];
if (verifyGroupValues) {
if (idvBasedImplsUsed) {
if (actualGroup.groupValue.length == 0) {
assertNull(expectedGroup.groupValue);
} else {
assertEquals(expectedGroup.groupValue, actualGroup.groupValue);
}
} else {
assertEquals(expectedGroup.groupValue, actualGroup.groupValue);
}
}
if (verifySortValues) {
assertArrayEquals(expectedGroup.groupSortValues, actualGroup.groupSortValues);
}
// TODO
// assertEquals(expectedGroup.maxScore, actualGroup.maxScore);
assertEquals(expectedGroup.totalHits, actualGroup.totalHits);
final ScoreDoc[] expectedFDs = expectedGroup.scoreDocs;
final ScoreDoc[] actualFDs = actualGroup.scoreDocs;
assertEquals(expectedFDs.length, actualFDs.length);
for(int docIDX=0;docIDX<expectedFDs.length;docIDX++) {
final FieldDoc expectedFD = (FieldDoc) expectedFDs[docIDX];
final FieldDoc actualFD = (FieldDoc) actualFDs[docIDX];
//System.out.println(" actual doc=" + docIDtoID.get(actualFD.doc) + " score=" + actualFD.score);
assertEquals(expectedFD.doc, docIDtoID.get(actualFD.doc));
if (testScores) {
assertEquals(expectedFD.score, actualFD.score, 0.1);
} else {
// TODO: too anal for now
//assertEquals(Float.NaN, actualFD.score);
}
if (verifySortValues) {
assertArrayEquals(expectedFD.fields, actualFD.fields);
}
}
}
}
private static class ShardSearcher extends IndexSearcher {
private final List<AtomicReaderContext> ctx;
public ShardSearcher(AtomicReaderContext ctx, IndexReaderContext parent) {
super(parent);
this.ctx = Collections.singletonList(ctx);
}
public void search(Weight weight, Collector collector) throws IOException {
search(ctx, weight, collector);
}
@Override
public String toString() {
return "ShardSearcher(" + ctx.get(0).reader() + ")";
}
}
private static class ValueHolder<V> {
V value;
private ValueHolder(V value) {
this.value = value;
}
}
}
| lucene/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.lucene.search.grouping;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.MultiDocValues;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.ReaderUtil;
import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.IndexReaderContext;
import org.apache.lucene.index.SlowCompositeReaderWrapper;
import org.apache.lucene.index.Term;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.valuesource.BytesRefFieldSource;
import org.apache.lucene.search.*;
import org.apache.lucene.search.grouping.function.FunctionAllGroupsCollector;
import org.apache.lucene.search.grouping.function.FunctionFirstPassGroupingCollector;
import org.apache.lucene.search.grouping.function.FunctionSecondPassGroupingCollector;
import org.apache.lucene.search.grouping.term.TermAllGroupsCollector;
import org.apache.lucene.search.grouping.term.TermFirstPassGroupingCollector;
import org.apache.lucene.search.grouping.term.TermSecondPassGroupingCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.LuceneTestCase.SuppressCodecs;
import org.apache.lucene.util.TestUtil;
import org.apache.lucene.util.mutable.MutableValue;
import org.apache.lucene.util.mutable.MutableValueStr;
import java.io.IOException;
import java.util.*;
// TODO
// - should test relevance sort too
// - test null
// - test ties
// - test compound sort
@SuppressCodecs({"Lucene40", "Lucene41", "Lucene42"}) // we need missing support... i think?
public class TestGrouping extends LuceneTestCase {
public void testBasic() throws Exception {
String groupField = "author";
FieldType customType = new FieldType();
customType.setStored(true);
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(
random(),
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy()));
// 0
Document doc = new Document();
addGroupField(doc, groupField, "author1");
doc.add(new TextField("content", "random text", Field.Store.YES));
doc.add(new Field("id", "1", customType));
w.addDocument(doc);
// 1
doc = new Document();
addGroupField(doc, groupField, "author1");
doc.add(new TextField("content", "some more random text", Field.Store.YES));
doc.add(new Field("id", "2", customType));
w.addDocument(doc);
// 2
doc = new Document();
addGroupField(doc, groupField, "author1");
doc.add(new TextField("content", "some more random textual data", Field.Store.YES));
doc.add(new Field("id", "3", customType));
w.addDocument(doc);
// 3
doc = new Document();
addGroupField(doc, groupField, "author2");
doc.add(new TextField("content", "some random text", Field.Store.YES));
doc.add(new Field("id", "4", customType));
w.addDocument(doc);
// 4
doc = new Document();
addGroupField(doc, groupField, "author3");
doc.add(new TextField("content", "some more random text", Field.Store.YES));
doc.add(new Field("id", "5", customType));
w.addDocument(doc);
// 5
doc = new Document();
addGroupField(doc, groupField, "author3");
doc.add(new TextField("content", "random", Field.Store.YES));
doc.add(new Field("id", "6", customType));
w.addDocument(doc);
// 6 -- no author field
doc = new Document();
doc.add(new TextField("content", "random word stuck in alot of other text", Field.Store.YES));
doc.add(new Field("id", "6", customType));
w.addDocument(doc);
IndexSearcher indexSearcher = newSearcher(w.getReader());
w.shutdown();
final Sort groupSort = Sort.RELEVANCE;
final AbstractFirstPassGroupingCollector<?> c1 = createRandomFirstPassCollector(groupField, groupSort, 10);
indexSearcher.search(new TermQuery(new Term("content", "random")), c1);
final AbstractSecondPassGroupingCollector<?> c2 = createSecondPassCollector(c1, groupField, groupSort, null, 0, 5, true, true, true);
indexSearcher.search(new TermQuery(new Term("content", "random")), c2);
final TopGroups<?> groups = c2.getTopGroups(0);
assertFalse(Float.isNaN(groups.maxScore));
assertEquals(7, groups.totalHitCount);
assertEquals(7, groups.totalGroupedHitCount);
assertEquals(4, groups.groups.length);
// relevance order: 5, 0, 3, 4, 1, 2, 6
// the later a document is added the higher this docId
// value
GroupDocs<?> group = groups.groups[0];
compareGroupValue("author3", group);
assertEquals(2, group.scoreDocs.length);
assertEquals(5, group.scoreDocs[0].doc);
assertEquals(4, group.scoreDocs[1].doc);
assertTrue(group.scoreDocs[0].score > group.scoreDocs[1].score);
group = groups.groups[1];
compareGroupValue("author1", group);
assertEquals(3, group.scoreDocs.length);
assertEquals(0, group.scoreDocs[0].doc);
assertEquals(1, group.scoreDocs[1].doc);
assertEquals(2, group.scoreDocs[2].doc);
assertTrue(group.scoreDocs[0].score > group.scoreDocs[1].score);
assertTrue(group.scoreDocs[1].score > group.scoreDocs[2].score);
group = groups.groups[2];
compareGroupValue("author2", group);
assertEquals(1, group.scoreDocs.length);
assertEquals(3, group.scoreDocs[0].doc);
group = groups.groups[3];
compareGroupValue(null, group);
assertEquals(1, group.scoreDocs.length);
assertEquals(6, group.scoreDocs[0].doc);
indexSearcher.getIndexReader().close();
dir.close();
}
private void addGroupField(Document doc, String groupField, String value) {
doc.add(new SortedDocValuesField(groupField, new BytesRef(value)));
}
private AbstractFirstPassGroupingCollector<?> createRandomFirstPassCollector(String groupField, Sort groupSort, int topDocs) throws IOException {
AbstractFirstPassGroupingCollector<?> selected;
if (random().nextBoolean()) {
ValueSource vs = new BytesRefFieldSource(groupField);
selected = new FunctionFirstPassGroupingCollector(vs, new HashMap<>(), groupSort, topDocs);
} else {
selected = new TermFirstPassGroupingCollector(groupField, groupSort, topDocs);
}
if (VERBOSE) {
System.out.println("Selected implementation: " + selected.getClass().getName());
}
return selected;
}
private AbstractFirstPassGroupingCollector<?> createFirstPassCollector(String groupField, Sort groupSort, int topDocs, AbstractFirstPassGroupingCollector<?> firstPassGroupingCollector) throws IOException {
if (TermFirstPassGroupingCollector.class.isAssignableFrom(firstPassGroupingCollector.getClass())) {
ValueSource vs = new BytesRefFieldSource(groupField);
return new FunctionFirstPassGroupingCollector(vs, new HashMap<>(), groupSort, topDocs);
} else {
return new TermFirstPassGroupingCollector(groupField, groupSort, topDocs);
}
}
@SuppressWarnings({"unchecked","rawtypes"})
private <T> AbstractSecondPassGroupingCollector<T> createSecondPassCollector(AbstractFirstPassGroupingCollector firstPassGroupingCollector,
String groupField,
Sort groupSort,
Sort sortWithinGroup,
int groupOffset,
int maxDocsPerGroup,
boolean getScores,
boolean getMaxScores,
boolean fillSortFields) throws IOException {
if (TermFirstPassGroupingCollector.class.isAssignableFrom(firstPassGroupingCollector.getClass())) {
Collection<SearchGroup<BytesRef>> searchGroups = firstPassGroupingCollector.getTopGroups(groupOffset, fillSortFields);
return (AbstractSecondPassGroupingCollector) new TermSecondPassGroupingCollector(groupField, searchGroups, groupSort, sortWithinGroup, maxDocsPerGroup , getScores, getMaxScores, fillSortFields);
} else {
ValueSource vs = new BytesRefFieldSource(groupField);
Collection<SearchGroup<MutableValue>> searchGroups = firstPassGroupingCollector.getTopGroups(groupOffset, fillSortFields);
return (AbstractSecondPassGroupingCollector) new FunctionSecondPassGroupingCollector(searchGroups, groupSort, sortWithinGroup, maxDocsPerGroup, getScores, getMaxScores, fillSortFields, vs, new HashMap());
}
}
// Basically converts searchGroups from MutableValue to BytesRef if grouping by ValueSource
@SuppressWarnings("unchecked")
private AbstractSecondPassGroupingCollector<?> createSecondPassCollector(AbstractFirstPassGroupingCollector<?> firstPassGroupingCollector,
String groupField,
Collection<SearchGroup<BytesRef>> searchGroups,
Sort groupSort,
Sort sortWithinGroup,
int maxDocsPerGroup,
boolean getScores,
boolean getMaxScores,
boolean fillSortFields) throws IOException {
if (firstPassGroupingCollector.getClass().isAssignableFrom(TermFirstPassGroupingCollector.class)) {
return new TermSecondPassGroupingCollector(groupField, searchGroups, groupSort, sortWithinGroup, maxDocsPerGroup , getScores, getMaxScores, fillSortFields);
} else {
ValueSource vs = new BytesRefFieldSource(groupField);
List<SearchGroup<MutableValue>> mvalSearchGroups = new ArrayList<>(searchGroups.size());
for (SearchGroup<BytesRef> mergedTopGroup : searchGroups) {
SearchGroup<MutableValue> sg = new SearchGroup<>();
MutableValueStr groupValue = new MutableValueStr();
if (mergedTopGroup.groupValue != null) {
groupValue.value = mergedTopGroup.groupValue;
} else {
groupValue.value = new BytesRef();
groupValue.exists = false;
}
sg.groupValue = groupValue;
sg.sortValues = mergedTopGroup.sortValues;
mvalSearchGroups.add(sg);
}
return new FunctionSecondPassGroupingCollector(mvalSearchGroups, groupSort, sortWithinGroup, maxDocsPerGroup, getScores, getMaxScores, fillSortFields, vs, new HashMap<>());
}
}
private AbstractAllGroupsCollector<?> createAllGroupsCollector(AbstractFirstPassGroupingCollector<?> firstPassGroupingCollector,
String groupField) {
if (firstPassGroupingCollector.getClass().isAssignableFrom(TermFirstPassGroupingCollector.class)) {
return new TermAllGroupsCollector(groupField);
} else {
ValueSource vs = new BytesRefFieldSource(groupField);
return new FunctionAllGroupsCollector(vs, new HashMap<>());
}
}
private void compareGroupValue(String expected, GroupDocs<?> group) {
if (expected == null) {
if (group.groupValue == null) {
return;
} else if (group.groupValue.getClass().isAssignableFrom(MutableValueStr.class)) {
return;
} else if (((BytesRef) group.groupValue).length == 0) {
return;
}
fail();
}
if (group.groupValue.getClass().isAssignableFrom(BytesRef.class)) {
assertEquals(new BytesRef(expected), group.groupValue);
} else if (group.groupValue.getClass().isAssignableFrom(MutableValueStr.class)) {
MutableValueStr v = new MutableValueStr();
v.value = new BytesRef(expected);
assertEquals(v, group.groupValue);
} else {
fail();
}
}
private Collection<SearchGroup<BytesRef>> getSearchGroups(AbstractFirstPassGroupingCollector<?> c, int groupOffset, boolean fillFields) {
if (TermFirstPassGroupingCollector.class.isAssignableFrom(c.getClass())) {
return ((TermFirstPassGroupingCollector) c).getTopGroups(groupOffset, fillFields);
} else if (FunctionFirstPassGroupingCollector.class.isAssignableFrom(c.getClass())) {
Collection<SearchGroup<MutableValue>> mutableValueGroups = ((FunctionFirstPassGroupingCollector) c).getTopGroups(groupOffset, fillFields);
if (mutableValueGroups == null) {
return null;
}
List<SearchGroup<BytesRef>> groups = new ArrayList<>(mutableValueGroups.size());
for (SearchGroup<MutableValue> mutableValueGroup : mutableValueGroups) {
SearchGroup<BytesRef> sg = new SearchGroup<>();
sg.groupValue = mutableValueGroup.groupValue.exists() ? ((MutableValueStr) mutableValueGroup.groupValue).value : null;
sg.sortValues = mutableValueGroup.sortValues;
groups.add(sg);
}
return groups;
}
fail();
return null;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private TopGroups<BytesRef> getTopGroups(AbstractSecondPassGroupingCollector c, int withinGroupOffset) {
if (c.getClass().isAssignableFrom(TermSecondPassGroupingCollector.class)) {
return ((TermSecondPassGroupingCollector) c).getTopGroups(withinGroupOffset);
} else if (c.getClass().isAssignableFrom(FunctionSecondPassGroupingCollector.class)) {
TopGroups<MutableValue> mvalTopGroups = ((FunctionSecondPassGroupingCollector) c).getTopGroups(withinGroupOffset);
List<GroupDocs<BytesRef>> groups = new ArrayList<>(mvalTopGroups.groups.length);
for (GroupDocs<MutableValue> mvalGd : mvalTopGroups.groups) {
BytesRef groupValue = mvalGd.groupValue.exists() ? ((MutableValueStr) mvalGd.groupValue).value : null;
groups.add(new GroupDocs<>(Float.NaN, mvalGd.maxScore, mvalGd.totalHits, mvalGd.scoreDocs, groupValue, mvalGd.groupSortValues));
}
return new TopGroups<>(mvalTopGroups.groupSort, mvalTopGroups.withinGroupSort, mvalTopGroups.totalHitCount, mvalTopGroups.totalGroupedHitCount, groups.toArray(new GroupDocs[groups.size()]), Float.NaN);
}
fail();
return null;
}
private static class GroupDoc {
final int id;
final BytesRef group;
final BytesRef sort1;
final BytesRef sort2;
// content must be "realN ..."
final String content;
float score;
float score2;
public GroupDoc(int id, BytesRef group, BytesRef sort1, BytesRef sort2, String content) {
this.id = id;
this.group = group;
this.sort1 = sort1;
this.sort2 = sort2;
this.content = content;
}
}
private Sort getRandomSort() {
final List<SortField> sortFields = new ArrayList<>();
if (random().nextInt(7) == 2) {
sortFields.add(SortField.FIELD_SCORE);
} else {
if (random().nextBoolean()) {
if (random().nextBoolean()) {
sortFields.add(new SortField("sort1", SortField.Type.STRING, random().nextBoolean()));
} else {
sortFields.add(new SortField("sort2", SortField.Type.STRING, random().nextBoolean()));
}
} else if (random().nextBoolean()) {
sortFields.add(new SortField("sort1", SortField.Type.STRING, random().nextBoolean()));
sortFields.add(new SortField("sort2", SortField.Type.STRING, random().nextBoolean()));
}
}
// Break ties:
sortFields.add(new SortField("id", SortField.Type.INT));
return new Sort(sortFields.toArray(new SortField[sortFields.size()]));
}
private Comparator<GroupDoc> getComparator(Sort sort) {
final SortField[] sortFields = sort.getSort();
return new Comparator<GroupDoc>() {
@Override
public int compare(GroupDoc d1, GroupDoc d2) {
for(SortField sf : sortFields) {
final int cmp;
if (sf.getType() == SortField.Type.SCORE) {
if (d1.score > d2.score) {
cmp = -1;
} else if (d1.score < d2.score) {
cmp = 1;
} else {
cmp = 0;
}
} else if (sf.getField().equals("sort1")) {
cmp = d1.sort1.compareTo(d2.sort1);
} else if (sf.getField().equals("sort2")) {
cmp = d1.sort2.compareTo(d2.sort2);
} else {
assertEquals(sf.getField(), "id");
cmp = d1.id - d2.id;
}
if (cmp != 0) {
return sf.getReverse() ? -cmp : cmp;
}
}
// Our sort always fully tie breaks:
fail();
return 0;
}
};
}
@SuppressWarnings({"unchecked","rawtypes"})
private Comparable<?>[] fillFields(GroupDoc d, Sort sort) {
final SortField[] sortFields = sort.getSort();
final Comparable<?>[] fields = new Comparable[sortFields.length];
for(int fieldIDX=0;fieldIDX<sortFields.length;fieldIDX++) {
final Comparable<?> c;
final SortField sf = sortFields[fieldIDX];
if (sf.getType() == SortField.Type.SCORE) {
c = d.score;
} else if (sf.getField().equals("sort1")) {
c = d.sort1;
} else if (sf.getField().equals("sort2")) {
c = d.sort2;
} else {
assertEquals("id", sf.getField());
c = d.id;
}
fields[fieldIDX] = c;
}
return fields;
}
private String groupToString(BytesRef b) {
if (b == null) {
return "null";
} else {
return b.utf8ToString();
}
}
private TopGroups<BytesRef> slowGrouping(GroupDoc[] groupDocs,
String searchTerm,
boolean fillFields,
boolean getScores,
boolean getMaxScores,
boolean doAllGroups,
Sort groupSort,
Sort docSort,
int topNGroups,
int docsPerGroup,
int groupOffset,
int docOffset) {
final Comparator<GroupDoc> groupSortComp = getComparator(groupSort);
Arrays.sort(groupDocs, groupSortComp);
final HashMap<BytesRef,List<GroupDoc>> groups = new HashMap<>();
final List<BytesRef> sortedGroups = new ArrayList<>();
final List<Comparable<?>[]> sortedGroupFields = new ArrayList<>();
int totalHitCount = 0;
Set<BytesRef> knownGroups = new HashSet<>();
//System.out.println("TEST: slowGrouping");
for(GroupDoc d : groupDocs) {
// TODO: would be better to filter by searchTerm before sorting!
if (!d.content.startsWith(searchTerm)) {
continue;
}
totalHitCount++;
//System.out.println(" match id=" + d.id + " score=" + d.score);
if (doAllGroups) {
if (!knownGroups.contains(d.group)) {
knownGroups.add(d.group);
//System.out.println(" add group=" + groupToString(d.group));
}
}
List<GroupDoc> l = groups.get(d.group);
if (l == null) {
//System.out.println(" add sortedGroup=" + groupToString(d.group));
sortedGroups.add(d.group);
if (fillFields) {
sortedGroupFields.add(fillFields(d, groupSort));
}
l = new ArrayList<>();
groups.put(d.group, l);
}
l.add(d);
}
if (groupOffset >= sortedGroups.size()) {
// slice is out of bounds
return null;
}
final int limit = Math.min(groupOffset + topNGroups, groups.size());
final Comparator<GroupDoc> docSortComp = getComparator(docSort);
@SuppressWarnings({"unchecked","rawtypes"})
final GroupDocs<BytesRef>[] result = new GroupDocs[limit-groupOffset];
int totalGroupedHitCount = 0;
for(int idx=groupOffset;idx < limit;idx++) {
final BytesRef group = sortedGroups.get(idx);
final List<GroupDoc> docs = groups.get(group);
totalGroupedHitCount += docs.size();
Collections.sort(docs, docSortComp);
final ScoreDoc[] hits;
if (docs.size() > docOffset) {
final int docIDXLimit = Math.min(docOffset + docsPerGroup, docs.size());
hits = new ScoreDoc[docIDXLimit - docOffset];
for(int docIDX=docOffset; docIDX < docIDXLimit; docIDX++) {
final GroupDoc d = docs.get(docIDX);
final FieldDoc fd;
if (fillFields) {
fd = new FieldDoc(d.id, getScores ? d.score : Float.NaN, fillFields(d, docSort));
} else {
fd = new FieldDoc(d.id, getScores ? d.score : Float.NaN);
}
hits[docIDX-docOffset] = fd;
}
} else {
hits = new ScoreDoc[0];
}
result[idx-groupOffset] = new GroupDocs<>(Float.NaN,
0.0f,
docs.size(),
hits,
group,
fillFields ? sortedGroupFields.get(idx) : null);
}
if (doAllGroups) {
return new TopGroups<>(
new TopGroups<>(groupSort.getSort(), docSort.getSort(), totalHitCount, totalGroupedHitCount, result, Float.NaN),
knownGroups.size()
);
} else {
return new TopGroups<>(groupSort.getSort(), docSort.getSort(), totalHitCount, totalGroupedHitCount, result, Float.NaN);
}
}
private DirectoryReader getDocBlockReader(Directory dir, GroupDoc[] groupDocs) throws IOException {
// Coalesce by group, but in random order:
Collections.shuffle(Arrays.asList(groupDocs), random());
final Map<BytesRef,List<GroupDoc>> groupMap = new HashMap<>();
final List<BytesRef> groupValues = new ArrayList<>();
for(GroupDoc groupDoc : groupDocs) {
if (!groupMap.containsKey(groupDoc.group)) {
groupValues.add(groupDoc.group);
groupMap.put(groupDoc.group, new ArrayList<GroupDoc>());
}
groupMap.get(groupDoc.group).add(groupDoc);
}
RandomIndexWriter w = new RandomIndexWriter(
random(),
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random())));
final List<List<Document>> updateDocs = new ArrayList<>();
FieldType groupEndType = new FieldType(StringField.TYPE_NOT_STORED);
groupEndType.setIndexOptions(IndexOptions.DOCS_ONLY);
groupEndType.setOmitNorms(true);
//System.out.println("TEST: index groups");
for(BytesRef group : groupValues) {
final List<Document> docs = new ArrayList<>();
//System.out.println("TEST: group=" + (group == null ? "null" : group.utf8ToString()));
for(GroupDoc groupValue : groupMap.get(group)) {
Document doc = new Document();
docs.add(doc);
if (groupValue.group != null) {
doc.add(newStringField("group", groupValue.group.utf8ToString(), Field.Store.YES));
}
doc.add(newStringField("sort1", groupValue.sort1.utf8ToString(), Field.Store.NO));
doc.add(newStringField("sort2", groupValue.sort2.utf8ToString(), Field.Store.NO));
doc.add(new IntField("id", groupValue.id, Field.Store.NO));
doc.add(newTextField("content", groupValue.content, Field.Store.NO));
//System.out.println("TEST: doc content=" + groupValue.content + " group=" + (groupValue.group == null ? "null" : groupValue.group.utf8ToString()) + " sort1=" + groupValue.sort1.utf8ToString() + " id=" + groupValue.id);
}
// So we can pull filter marking last doc in block:
final Field groupEnd = newField("groupend", "x", groupEndType);
docs.get(docs.size()-1).add(groupEnd);
// Add as a doc block:
w.addDocuments(docs);
if (group != null && random().nextInt(7) == 4) {
updateDocs.add(docs);
}
}
for(List<Document> docs : updateDocs) {
// Just replaces docs w/ same docs:
w.updateDocuments(new Term("group", docs.get(0).get("group")), docs);
}
final DirectoryReader r = w.getReader();
w.shutdown();
return r;
}
private static class ShardState {
public final ShardSearcher[] subSearchers;
public final int[] docStarts;
public ShardState(IndexSearcher s) {
final IndexReaderContext ctx = s.getTopReaderContext();
final List<AtomicReaderContext> leaves = ctx.leaves();
subSearchers = new ShardSearcher[leaves.size()];
for(int searcherIDX=0;searcherIDX<subSearchers.length;searcherIDX++) {
subSearchers[searcherIDX] = new ShardSearcher(leaves.get(searcherIDX), ctx);
}
docStarts = new int[subSearchers.length];
for(int subIDX=0;subIDX<docStarts.length;subIDX++) {
docStarts[subIDX] = leaves.get(subIDX).docBase;
//System.out.println("docStarts[" + subIDX + "]=" + docStarts[subIDX]);
}
}
}
public void testRandom() throws Exception {
int numberOfRuns = TestUtil.nextInt(random(), 3, 6);
for (int iter=0; iter<numberOfRuns; iter++) {
if (VERBOSE) {
System.out.println("TEST: iter=" + iter);
}
final int numDocs = TestUtil.nextInt(random(), 100, 1000) * RANDOM_MULTIPLIER;
//final int numDocs = _TestUtil.nextInt(random, 5, 20);
final int numGroups = TestUtil.nextInt(random(), 1, numDocs);
if (VERBOSE) {
System.out.println("TEST: numDocs=" + numDocs + " numGroups=" + numGroups);
}
final List<BytesRef> groups = new ArrayList<>();
for(int i=0;i<numGroups;i++) {
String randomValue;
do {
// B/c of DV based impl we can't see the difference between an empty string and a null value.
// For that reason we don't generate empty string
// groups.
randomValue = TestUtil.randomRealisticUnicodeString(random());
//randomValue = _TestUtil.randomSimpleString(random());
} while ("".equals(randomValue));
groups.add(new BytesRef(randomValue));
}
final String[] contentStrings = new String[TestUtil.nextInt(random(), 2, 20)];
if (VERBOSE) {
System.out.println("TEST: create fake content");
}
for(int contentIDX=0;contentIDX<contentStrings.length;contentIDX++) {
final StringBuilder sb = new StringBuilder();
sb.append("real").append(random().nextInt(3)).append(' ');
final int fakeCount = random().nextInt(10);
for(int fakeIDX=0;fakeIDX<fakeCount;fakeIDX++) {
sb.append("fake ");
}
contentStrings[contentIDX] = sb.toString();
if (VERBOSE) {
System.out.println(" content=" + sb.toString());
}
}
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(
random(),
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random())));
Document doc = new Document();
Document docNoGroup = new Document();
Field idvGroupField = new SortedDocValuesField("group_dv", new BytesRef());
doc.add(idvGroupField);
docNoGroup.add(idvGroupField);
Field group = newStringField("group", "", Field.Store.NO);
doc.add(group);
Field sort1 = newStringField("sort1", "", Field.Store.NO);
doc.add(sort1);
docNoGroup.add(sort1);
Field sort2 = newStringField("sort2", "", Field.Store.NO);
doc.add(sort2);
docNoGroup.add(sort2);
Field content = newTextField("content", "", Field.Store.NO);
doc.add(content);
docNoGroup.add(content);
IntField id = new IntField("id", 0, Field.Store.NO);
doc.add(id);
NumericDocValuesField idDV = new NumericDocValuesField("id", 0);
doc.add(idDV);
docNoGroup.add(id);
docNoGroup.add(idDV);
final GroupDoc[] groupDocs = new GroupDoc[numDocs];
for(int i=0;i<numDocs;i++) {
final BytesRef groupValue;
if (random().nextInt(24) == 17) {
// So we test the "doc doesn't have the group'd
// field" case:
groupValue = null;
} else {
groupValue = groups.get(random().nextInt(groups.size()));
}
final GroupDoc groupDoc = new GroupDoc(i,
groupValue,
groups.get(random().nextInt(groups.size())),
groups.get(random().nextInt(groups.size())),
contentStrings[random().nextInt(contentStrings.length)]);
if (VERBOSE) {
System.out.println(" doc content=" + groupDoc.content + " id=" + i + " group=" + (groupDoc.group == null ? "null" : groupDoc.group.utf8ToString()) + " sort1=" + groupDoc.sort1.utf8ToString() + " sort2=" + groupDoc.sort2.utf8ToString());
}
groupDocs[i] = groupDoc;
if (groupDoc.group != null) {
group.setStringValue(groupDoc.group.utf8ToString());
idvGroupField.setBytesValue(BytesRef.deepCopyOf(groupDoc.group));
} else {
// TODO: not true
// Must explicitly set empty string, else eg if
// the segment has all docs missing the field then
// we get null back instead of empty BytesRef:
idvGroupField.setBytesValue(new BytesRef());
}
sort1.setStringValue(groupDoc.sort1.utf8ToString());
sort2.setStringValue(groupDoc.sort2.utf8ToString());
content.setStringValue(groupDoc.content);
id.setIntValue(groupDoc.id);
idDV.setLongValue(groupDoc.id);
if (groupDoc.group == null) {
w.addDocument(docNoGroup);
} else {
w.addDocument(doc);
}
}
final GroupDoc[] groupDocsByID = new GroupDoc[groupDocs.length];
System.arraycopy(groupDocs, 0, groupDocsByID, 0, groupDocs.length);
final DirectoryReader r = w.getReader();
w.shutdown();
final NumericDocValues docIDToID = MultiDocValues.getNumericValues(r, "id");
DirectoryReader rBlocks = null;
Directory dirBlocks = null;
try {
final IndexSearcher s = newSearcher(r);
if (VERBOSE) {
System.out.println("\nTEST: searcher=" + s);
}
final ShardState shards = new ShardState(s);
for(int contentID=0;contentID<3;contentID++) {
final ScoreDoc[] hits = s.search(new TermQuery(new Term("content", "real"+contentID)), numDocs).scoreDocs;
for(ScoreDoc hit : hits) {
final GroupDoc gd = groupDocs[(int) docIDToID.get(hit.doc)];
assertTrue(gd.score == 0.0);
gd.score = hit.score;
assertEquals(gd.id, docIDToID.get(hit.doc));
}
}
for(GroupDoc gd : groupDocs) {
assertTrue(gd.score != 0.0);
}
// Build 2nd index, where docs are added in blocks by
// group, so we can use single pass collector
dirBlocks = newDirectory();
rBlocks = getDocBlockReader(dirBlocks, groupDocs);
final Filter lastDocInBlock = new CachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("groupend", "x"))));
final NumericDocValues docIDToIDBlocks = MultiDocValues.getNumericValues(rBlocks, "id");
final IndexSearcher sBlocks = newSearcher(rBlocks);
final ShardState shardsBlocks = new ShardState(sBlocks);
// ReaderBlocks only increases maxDoc() vs reader, which
// means a monotonic shift in scores, so we can
// reliably remap them w/ Map:
final Map<String,Map<Float,Float>> scoreMap = new HashMap<>();
// Tricky: must separately set .score2, because the doc
// block index was created with possible deletions!
//System.out.println("fixup score2");
for(int contentID=0;contentID<3;contentID++) {
//System.out.println(" term=real" + contentID);
final Map<Float,Float> termScoreMap = new HashMap<>();
scoreMap.put("real"+contentID, termScoreMap);
//System.out.println("term=real" + contentID + " dfold=" + s.docFreq(new Term("content", "real"+contentID)) +
//" dfnew=" + sBlocks.docFreq(new Term("content", "real"+contentID)));
final ScoreDoc[] hits = sBlocks.search(new TermQuery(new Term("content", "real"+contentID)), numDocs).scoreDocs;
for(ScoreDoc hit : hits) {
final GroupDoc gd = groupDocsByID[(int) docIDToIDBlocks.get(hit.doc)];
assertTrue(gd.score2 == 0.0);
gd.score2 = hit.score;
assertEquals(gd.id, docIDToIDBlocks.get(hit.doc));
//System.out.println(" score=" + gd.score + " score2=" + hit.score + " id=" + docIDToIDBlocks.get(hit.doc));
termScoreMap.put(gd.score, gd.score2);
}
}
for(int searchIter=0;searchIter<100;searchIter++) {
if (VERBOSE) {
System.out.println("\nTEST: searchIter=" + searchIter);
}
final String searchTerm = "real" + random().nextInt(3);
final boolean fillFields = random().nextBoolean();
boolean getScores = random().nextBoolean();
final boolean getMaxScores = random().nextBoolean();
final Sort groupSort = getRandomSort();
//final Sort groupSort = new Sort(new SortField[] {new SortField("sort1", SortField.STRING), new SortField("id", SortField.INT)});
// TODO: also test null (= sort by relevance)
final Sort docSort = getRandomSort();
for(SortField sf : docSort.getSort()) {
if (sf.getType() == SortField.Type.SCORE) {
getScores = true;
break;
}
}
for(SortField sf : groupSort.getSort()) {
if (sf.getType() == SortField.Type.SCORE) {
getScores = true;
break;
}
}
final int topNGroups = TestUtil.nextInt(random(), 1, 30);
//final int topNGroups = 10;
final int docsPerGroup = TestUtil.nextInt(random(), 1, 50);
final int groupOffset = TestUtil.nextInt(random(), 0, (topNGroups - 1) / 2);
//final int groupOffset = 0;
final int docOffset = TestUtil.nextInt(random(), 0, docsPerGroup - 1);
//final int docOffset = 0;
final boolean doCache = random().nextBoolean();
final boolean doAllGroups = random().nextBoolean();
if (VERBOSE) {
System.out.println("TEST: groupSort=" + groupSort + " docSort=" + docSort + " searchTerm=" + searchTerm + " dF=" + r.docFreq(new Term("content", searchTerm)) +" dFBlock=" + rBlocks.docFreq(new Term("content", searchTerm)) + " topNGroups=" + topNGroups + " groupOffset=" + groupOffset + " docOffset=" + docOffset + " doCache=" + doCache + " docsPerGroup=" + docsPerGroup + " doAllGroups=" + doAllGroups + " getScores=" + getScores + " getMaxScores=" + getMaxScores);
}
String groupField = "group_dv";
if (VERBOSE) {
System.out.println(" groupField=" + groupField);
}
final AbstractFirstPassGroupingCollector<?> c1 = createRandomFirstPassCollector(groupField, groupSort, groupOffset+topNGroups);
final CachingCollector cCache;
final Collector c;
final AbstractAllGroupsCollector<?> allGroupsCollector;
if (doAllGroups) {
allGroupsCollector = createAllGroupsCollector(c1, groupField);
} else {
allGroupsCollector = null;
}
final boolean useWrappingCollector = random().nextBoolean();
if (doCache) {
final double maxCacheMB = random().nextDouble();
if (VERBOSE) {
System.out.println("TEST: maxCacheMB=" + maxCacheMB);
}
if (useWrappingCollector) {
if (doAllGroups) {
cCache = CachingCollector.create(c1, true, maxCacheMB);
c = MultiCollector.wrap(cCache, allGroupsCollector);
} else {
c = cCache = CachingCollector.create(c1, true, maxCacheMB);
}
} else {
// Collect only into cache, then replay multiple times:
c = cCache = CachingCollector.create(false, true, maxCacheMB);
}
} else {
cCache = null;
if (doAllGroups) {
c = MultiCollector.wrap(c1, allGroupsCollector);
} else {
c = c1;
}
}
// Search top reader:
final Query query = new TermQuery(new Term("content", searchTerm));
s.search(query, c);
if (doCache && !useWrappingCollector) {
if (cCache.isCached()) {
// Replay for first-pass grouping
cCache.replay(c1);
if (doAllGroups) {
// Replay for all groups:
cCache.replay(allGroupsCollector);
}
} else {
// Replay by re-running search:
s.search(query, c1);
if (doAllGroups) {
s.search(query, allGroupsCollector);
}
}
}
// Get 1st pass top groups
final Collection<SearchGroup<BytesRef>> topGroups = getSearchGroups(c1, groupOffset, fillFields);
final TopGroups<BytesRef> groupsResult;
if (VERBOSE) {
System.out.println("TEST: first pass topGroups");
if (topGroups == null) {
System.out.println(" null");
} else {
for (SearchGroup<BytesRef> searchGroup : topGroups) {
System.out.println(" " + (searchGroup.groupValue == null ? "null" : searchGroup.groupValue) + ": " + Arrays.deepToString(searchGroup.sortValues));
}
}
}
// Get 1st pass top groups using shards
ValueHolder<Boolean> idvBasedImplsUsedSharded = new ValueHolder<>(false);
final TopGroups<BytesRef> topGroupsShards = searchShards(s, shards.subSearchers, query, groupSort, docSort,
groupOffset, topNGroups, docOffset, docsPerGroup, getScores, getMaxScores, true, false, idvBasedImplsUsedSharded);
final AbstractSecondPassGroupingCollector<?> c2;
if (topGroups != null) {
if (VERBOSE) {
System.out.println("TEST: topGroups");
for (SearchGroup<BytesRef> searchGroup : topGroups) {
System.out.println(" " + (searchGroup.groupValue == null ? "null" : searchGroup.groupValue.utf8ToString()) + ": " + Arrays.deepToString(searchGroup.sortValues));
}
}
c2 = createSecondPassCollector(c1, groupField, groupSort, docSort, groupOffset, docOffset + docsPerGroup, getScores, getMaxScores, fillFields);
if (doCache) {
if (cCache.isCached()) {
if (VERBOSE) {
System.out.println("TEST: cache is intact");
}
cCache.replay(c2);
} else {
if (VERBOSE) {
System.out.println("TEST: cache was too large");
}
s.search(query, c2);
}
} else {
s.search(query, c2);
}
if (doAllGroups) {
TopGroups<BytesRef> tempTopGroups = getTopGroups(c2, docOffset);
groupsResult = new TopGroups<>(tempTopGroups, allGroupsCollector.getGroupCount());
} else {
groupsResult = getTopGroups(c2, docOffset);
}
} else {
c2 = null;
groupsResult = null;
if (VERBOSE) {
System.out.println("TEST: no results");
}
}
final TopGroups<BytesRef> expectedGroups = slowGrouping(groupDocs, searchTerm, fillFields, getScores, getMaxScores, doAllGroups, groupSort, docSort, topNGroups, docsPerGroup, groupOffset, docOffset);
if (VERBOSE) {
if (expectedGroups == null) {
System.out.println("TEST: no expected groups");
} else {
System.out.println("TEST: expected groups totalGroupedHitCount=" + expectedGroups.totalGroupedHitCount);
for(GroupDocs<BytesRef> gd : expectedGroups.groups) {
System.out.println(" group=" + (gd.groupValue == null ? "null" : gd.groupValue) + " totalHits=" + gd.totalHits + " scoreDocs.len=" + gd.scoreDocs.length);
for(ScoreDoc sd : gd.scoreDocs) {
System.out.println(" id=" + sd.doc + " score=" + sd.score);
}
}
}
if (groupsResult == null) {
System.out.println("TEST: no matched groups");
} else {
System.out.println("TEST: matched groups totalGroupedHitCount=" + groupsResult.totalGroupedHitCount);
for(GroupDocs<BytesRef> gd : groupsResult.groups) {
System.out.println(" group=" + (gd.groupValue == null ? "null" : gd.groupValue) + " totalHits=" + gd.totalHits);
for(ScoreDoc sd : gd.scoreDocs) {
System.out.println(" id=" + docIDToID.get(sd.doc) + " score=" + sd.score);
}
}
if (searchIter == 14) {
for(int docIDX=0;docIDX<s.getIndexReader().maxDoc();docIDX++) {
System.out.println("ID=" + docIDToID.get(docIDX) + " explain=" + s.explain(query, docIDX));
}
}
}
if (topGroupsShards == null) {
System.out.println("TEST: no matched-merged groups");
} else {
System.out.println("TEST: matched-merged groups totalGroupedHitCount=" + topGroupsShards.totalGroupedHitCount);
for(GroupDocs<BytesRef> gd : topGroupsShards.groups) {
System.out.println(" group=" + (gd.groupValue == null ? "null" : gd.groupValue) + " totalHits=" + gd.totalHits);
for(ScoreDoc sd : gd.scoreDocs) {
System.out.println(" id=" + docIDToID.get(sd.doc) + " score=" + sd.score);
}
}
}
}
assertEquals(docIDToID, expectedGroups, groupsResult, true, true, true, getScores, groupField.endsWith("_dv"));
// Confirm merged shards match:
assertEquals(docIDToID, expectedGroups, topGroupsShards, true, false, fillFields, getScores, idvBasedImplsUsedSharded.value);
if (topGroupsShards != null) {
verifyShards(shards.docStarts, topGroupsShards);
}
final boolean needsScores = getScores || getMaxScores || docSort == null;
final BlockGroupingCollector c3 = new BlockGroupingCollector(groupSort, groupOffset+topNGroups, needsScores, lastDocInBlock);
final TermAllGroupsCollector allGroupsCollector2;
final Collector c4;
if (doAllGroups) {
// NOTE: must be "group" and not "group_dv"
// (groupField) because we didn't index doc
// values in the block index:
allGroupsCollector2 = new TermAllGroupsCollector("group");
c4 = MultiCollector.wrap(c3, allGroupsCollector2);
} else {
allGroupsCollector2 = null;
c4 = c3;
}
// Get block grouping result:
sBlocks.search(query, c4);
@SuppressWarnings({"unchecked","rawtypes"})
final TopGroups<BytesRef> tempTopGroupsBlocks = (TopGroups<BytesRef>) c3.getTopGroups(docSort, groupOffset, docOffset, docOffset+docsPerGroup, fillFields);
final TopGroups<BytesRef> groupsResultBlocks;
if (doAllGroups && tempTopGroupsBlocks != null) {
assertEquals((int) tempTopGroupsBlocks.totalGroupCount, allGroupsCollector2.getGroupCount());
groupsResultBlocks = new TopGroups<>(tempTopGroupsBlocks, allGroupsCollector2.getGroupCount());
} else {
groupsResultBlocks = tempTopGroupsBlocks;
}
if (VERBOSE) {
if (groupsResultBlocks == null) {
System.out.println("TEST: no block groups");
} else {
System.out.println("TEST: block groups totalGroupedHitCount=" + groupsResultBlocks.totalGroupedHitCount);
boolean first = true;
for(GroupDocs<BytesRef> gd : groupsResultBlocks.groups) {
System.out.println(" group=" + (gd.groupValue == null ? "null" : gd.groupValue.utf8ToString()) + " totalHits=" + gd.totalHits);
for(ScoreDoc sd : gd.scoreDocs) {
System.out.println(" id=" + docIDToIDBlocks.get(sd.doc) + " score=" + sd.score);
if (first) {
System.out.println("explain: " + sBlocks.explain(query, sd.doc));
first = false;
}
}
}
}
}
// Get shard'd block grouping result:
// Block index does not index DocValues so we pass
// false for canUseIDV:
final TopGroups<BytesRef> topGroupsBlockShards = searchShards(sBlocks, shardsBlocks.subSearchers, query,
groupSort, docSort, groupOffset, topNGroups, docOffset, docsPerGroup, getScores, getMaxScores, false, false, new ValueHolder<>(false));
if (expectedGroups != null) {
// Fixup scores for reader2
for (GroupDocs<?> groupDocsHits : expectedGroups.groups) {
for(ScoreDoc hit : groupDocsHits.scoreDocs) {
final GroupDoc gd = groupDocsByID[hit.doc];
assertEquals(gd.id, hit.doc);
//System.out.println("fixup score " + hit.score + " to " + gd.score2 + " vs " + gd.score);
hit.score = gd.score2;
}
}
final SortField[] sortFields = groupSort.getSort();
final Map<Float,Float> termScoreMap = scoreMap.get(searchTerm);
for(int groupSortIDX=0;groupSortIDX<sortFields.length;groupSortIDX++) {
if (sortFields[groupSortIDX].getType() == SortField.Type.SCORE) {
for (GroupDocs<?> groupDocsHits : expectedGroups.groups) {
if (groupDocsHits.groupSortValues != null) {
//System.out.println("remap " + groupDocsHits.groupSortValues[groupSortIDX] + " to " + termScoreMap.get(groupDocsHits.groupSortValues[groupSortIDX]));
groupDocsHits.groupSortValues[groupSortIDX] = termScoreMap.get(groupDocsHits.groupSortValues[groupSortIDX]);
assertNotNull(groupDocsHits.groupSortValues[groupSortIDX]);
}
}
}
}
final SortField[] docSortFields = docSort.getSort();
for(int docSortIDX=0;docSortIDX<docSortFields.length;docSortIDX++) {
if (docSortFields[docSortIDX].getType() == SortField.Type.SCORE) {
for (GroupDocs<?> groupDocsHits : expectedGroups.groups) {
for(ScoreDoc _hit : groupDocsHits.scoreDocs) {
FieldDoc hit = (FieldDoc) _hit;
if (hit.fields != null) {
hit.fields[docSortIDX] = termScoreMap.get(hit.fields[docSortIDX]);
assertNotNull(hit.fields[docSortIDX]);
}
}
}
}
}
}
assertEquals(docIDToIDBlocks, expectedGroups, groupsResultBlocks, false, true, true, getScores, false);
assertEquals(docIDToIDBlocks, expectedGroups, topGroupsBlockShards, false, false, fillFields, getScores, false);
}
} finally {
QueryUtils.purgeFieldCache(r);
if (rBlocks != null) {
QueryUtils.purgeFieldCache(rBlocks);
}
}
r.close();
dir.close();
rBlocks.close();
dirBlocks.close();
}
}
private void verifyShards(int[] docStarts, TopGroups<BytesRef> topGroups) {
for(GroupDocs<?> group : topGroups.groups) {
for(int hitIDX=0;hitIDX<group.scoreDocs.length;hitIDX++) {
final ScoreDoc sd = group.scoreDocs[hitIDX];
assertEquals("doc=" + sd.doc + " wrong shard",
ReaderUtil.subIndex(sd.doc, docStarts),
sd.shardIndex);
}
}
}
private TopGroups<BytesRef> searchShards(IndexSearcher topSearcher, ShardSearcher[] subSearchers, Query query, Sort groupSort, Sort docSort, int groupOffset, int topNGroups, int docOffset,
int topNDocs, boolean getScores, boolean getMaxScores, boolean canUseIDV, boolean preFlex, ValueHolder<Boolean> usedIdvBasedImpl) throws Exception {
// TODO: swap in caching, all groups collector hereassertEquals(expected.totalHitCount, actual.totalHitCount);
// too...
if (VERBOSE) {
System.out.println("TEST: " + subSearchers.length + " shards: " + Arrays.toString(subSearchers) + " canUseIDV=" + canUseIDV);
}
// Run 1st pass collector to get top groups per shard
final Weight w = topSearcher.createNormalizedWeight(query);
final List<Collection<SearchGroup<BytesRef>>> shardGroups = new ArrayList<>();
List<AbstractFirstPassGroupingCollector<?>> firstPassGroupingCollectors = new ArrayList<>();
AbstractFirstPassGroupingCollector<?> firstPassCollector = null;
boolean shardsCanUseIDV;
if (canUseIDV) {
if (SlowCompositeReaderWrapper.class.isAssignableFrom(subSearchers[0].getIndexReader().getClass())) {
shardsCanUseIDV = false;
} else {
shardsCanUseIDV = !preFlex;
}
} else {
shardsCanUseIDV = false;
}
String groupField = "group";
if (shardsCanUseIDV && random().nextBoolean()) {
groupField += "_dv";
usedIdvBasedImpl.value = true;
}
for(int shardIDX=0;shardIDX<subSearchers.length;shardIDX++) {
// First shard determines whether we use IDV or not;
// all other shards match that:
if (firstPassCollector == null) {
firstPassCollector = createRandomFirstPassCollector(groupField, groupSort, groupOffset + topNGroups);
} else {
firstPassCollector = createFirstPassCollector(groupField, groupSort, groupOffset + topNGroups, firstPassCollector);
}
if (VERBOSE) {
System.out.println(" shard=" + shardIDX + " groupField=" + groupField);
System.out.println(" 1st pass collector=" + firstPassCollector);
}
firstPassGroupingCollectors.add(firstPassCollector);
subSearchers[shardIDX].search(w, firstPassCollector);
final Collection<SearchGroup<BytesRef>> topGroups = getSearchGroups(firstPassCollector, 0, true);
if (topGroups != null) {
if (VERBOSE) {
System.out.println(" shard " + shardIDX + " s=" + subSearchers[shardIDX] + " totalGroupedHitCount=?" + " " + topGroups.size() + " groups:");
for(SearchGroup<BytesRef> group : topGroups) {
System.out.println(" " + groupToString(group.groupValue) + " groupSort=" + Arrays.toString(group.sortValues));
}
}
shardGroups.add(topGroups);
}
}
final Collection<SearchGroup<BytesRef>> mergedTopGroups = SearchGroup.merge(shardGroups, groupOffset, topNGroups, groupSort);
if (VERBOSE) {
System.out.println(" top groups merged:");
if (mergedTopGroups == null) {
System.out.println(" null");
} else {
System.out.println(" " + mergedTopGroups.size() + " top groups:");
for(SearchGroup<BytesRef> group : mergedTopGroups) {
System.out.println(" [" + groupToString(group.groupValue) + "] groupSort=" + Arrays.toString(group.sortValues));
}
}
}
if (mergedTopGroups != null) {
// Now 2nd pass:
@SuppressWarnings({"unchecked","rawtypes"})
final TopGroups<BytesRef>[] shardTopGroups = new TopGroups[subSearchers.length];
for(int shardIDX=0;shardIDX<subSearchers.length;shardIDX++) {
final AbstractSecondPassGroupingCollector<?> secondPassCollector = createSecondPassCollector(firstPassGroupingCollectors.get(shardIDX),
groupField, mergedTopGroups, groupSort, docSort, docOffset + topNDocs, getScores, getMaxScores, true);
subSearchers[shardIDX].search(w, secondPassCollector);
shardTopGroups[shardIDX] = getTopGroups(secondPassCollector, 0);
if (VERBOSE) {
System.out.println(" " + shardTopGroups[shardIDX].groups.length + " shard[" + shardIDX + "] groups:");
for(GroupDocs<BytesRef> group : shardTopGroups[shardIDX].groups) {
System.out.println(" [" + groupToString(group.groupValue) + "] groupSort=" + Arrays.toString(group.groupSortValues) + " numDocs=" + group.scoreDocs.length);
}
}
}
TopGroups<BytesRef> mergedGroups = TopGroups.merge(shardTopGroups, groupSort, docSort, docOffset, topNDocs, TopGroups.ScoreMergeMode.None);
if (VERBOSE) {
System.out.println(" " + mergedGroups.groups.length + " merged groups:");
for(GroupDocs<BytesRef> group : mergedGroups.groups) {
System.out.println(" [" + groupToString(group.groupValue) + "] groupSort=" + Arrays.toString(group.groupSortValues) + " numDocs=" + group.scoreDocs.length);
}
}
return mergedGroups;
} else {
return null;
}
}
private void assertEquals(NumericDocValues docIDtoID, TopGroups<BytesRef> expected, TopGroups<BytesRef> actual, boolean verifyGroupValues, boolean verifyTotalGroupCount, boolean verifySortValues, boolean testScores, boolean idvBasedImplsUsed) {
if (expected == null) {
assertNull(actual);
return;
}
assertNotNull(actual);
assertEquals("expected.groups.length != actual.groups.length", expected.groups.length, actual.groups.length);
assertEquals("expected.totalHitCount != actual.totalHitCount", expected.totalHitCount, actual.totalHitCount);
assertEquals("expected.totalGroupedHitCount != actual.totalGroupedHitCount", expected.totalGroupedHitCount, actual.totalGroupedHitCount);
if (expected.totalGroupCount != null && verifyTotalGroupCount) {
assertEquals("expected.totalGroupCount != actual.totalGroupCount", expected.totalGroupCount, actual.totalGroupCount);
}
for(int groupIDX=0;groupIDX<expected.groups.length;groupIDX++) {
if (VERBOSE) {
System.out.println(" check groupIDX=" + groupIDX);
}
final GroupDocs<BytesRef> expectedGroup = expected.groups[groupIDX];
final GroupDocs<BytesRef> actualGroup = actual.groups[groupIDX];
if (verifyGroupValues) {
if (idvBasedImplsUsed) {
if (actualGroup.groupValue.length == 0) {
assertNull(expectedGroup.groupValue);
} else {
assertEquals(expectedGroup.groupValue, actualGroup.groupValue);
}
} else {
assertEquals(expectedGroup.groupValue, actualGroup.groupValue);
}
}
if (verifySortValues) {
assertArrayEquals(expectedGroup.groupSortValues, actualGroup.groupSortValues);
}
// TODO
// assertEquals(expectedGroup.maxScore, actualGroup.maxScore);
assertEquals(expectedGroup.totalHits, actualGroup.totalHits);
final ScoreDoc[] expectedFDs = expectedGroup.scoreDocs;
final ScoreDoc[] actualFDs = actualGroup.scoreDocs;
assertEquals(expectedFDs.length, actualFDs.length);
for(int docIDX=0;docIDX<expectedFDs.length;docIDX++) {
final FieldDoc expectedFD = (FieldDoc) expectedFDs[docIDX];
final FieldDoc actualFD = (FieldDoc) actualFDs[docIDX];
//System.out.println(" actual doc=" + docIDtoID.get(actualFD.doc) + " score=" + actualFD.score);
assertEquals(expectedFD.doc, docIDtoID.get(actualFD.doc));
if (testScores) {
assertEquals(expectedFD.score, actualFD.score, 0.1);
} else {
// TODO: too anal for now
//assertEquals(Float.NaN, actualFD.score);
}
if (verifySortValues) {
assertArrayEquals(expectedFD.fields, actualFD.fields);
}
}
}
}
private static class ShardSearcher extends IndexSearcher {
private final List<AtomicReaderContext> ctx;
public ShardSearcher(AtomicReaderContext ctx, IndexReaderContext parent) {
super(parent);
this.ctx = Collections.singletonList(ctx);
}
public void search(Weight weight, Collector collector) throws IOException {
search(ctx, weight, collector);
}
@Override
public String toString() {
return "ShardSearcher(" + ctx.get(0).reader() + ")";
}
}
private static class ValueHolder<V> {
V value;
private ValueHolder(V value) {
this.value = value;
}
}
}
| progress on testrandom... i think
git-svn-id: ef9b7dcfbde82e7b8a1a36a680e226e6d25ceb28@1593794 13f79535-47bb-0310-9956-ffa450edef68
| lucene/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java | progress on testrandom... i think |
|
Java | apache-2.0 | cd03fa587869831c7596612ebf76e335c34064e8 | 0 | kubatatami/JudoNetworking | package com.github.kubatatami.judonetworking.stateful;
import com.github.kubatatami.judonetworking.AsyncResult;
import com.github.kubatatami.judonetworking.CacheInfo;
import com.github.kubatatami.judonetworking.callbacks.AsyncResultCallback;
import com.github.kubatatami.judonetworking.callbacks.Callback;
import com.github.kubatatami.judonetworking.callbacks.DecoratorCallback;
import com.github.kubatatami.judonetworking.exceptions.JudoException;
public final class StatefulCallback<T> extends DecoratorCallback<T> implements Stateful<Callback<T>> {
private AsyncResult asyncResult;
private final int id;
private final String who;
private int progress;
private boolean consume = false;
private boolean finishedSuccessfully = false;
private T data;
private JudoException exception;
public StatefulCallback(StatefulController controller, Callback<T> callback, boolean active) {
this(controller, callback.getClass().hashCode(), callback, active);
}
public StatefulCallback(StatefulController controller, int id, Callback<T> callback, boolean active) {
super(active ? callback : null);
this.id = id;
this.who = controller.getWho();
StatefulCache.addStatefulCallback(who, id, this);
}
@Override
public final void onStart(CacheInfo cacheInfo, AsyncResult asyncResult) {
this.asyncResult = asyncResult;
consume = false;
finishedSuccessfully = false;
data = null;
exception = null;
super.onStart(cacheInfo, asyncResult);
}
@Override
public void onFinish() {
super.onFinish();
if (internalCallback != null) {
StatefulCache.endStatefulCallback(who, id);
consume = true;
}
}
@Override
public void onProgress(int progress) {
super.onProgress(progress);
this.progress = progress;
}
@Override
public void onSuccess(T result) {
this.data = result;
this.finishedSuccessfully = true;
super.onSuccess(result);
}
@Override
public void tryCancel() {
if (asyncResult != null) {
asyncResult.cancel();
consume = true;
}
}
@Override
public void setCallback(Callback<T> callback) {
this.internalCallback = callback;
if (callback != null) {
if (callback instanceof AsyncResultCallback) {
((AsyncResultCallback) callback).setAsyncResult(asyncResult);
}
if (progress > 0) {
callback.onProgress(progress);
}
if (!consume) {
if (finishedSuccessfully) {
this.internalCallback.onSuccess(data);
onFinish();
} else if (exception != null) {
this.internalCallback.onError(exception);
onFinish();
}
}
}
}
} | base/src/main/java/com/github/kubatatami/judonetworking/stateful/StatefulCallback.java | package com.github.kubatatami.judonetworking.stateful;
import com.github.kubatatami.judonetworking.AsyncResult;
import com.github.kubatatami.judonetworking.CacheInfo;
import com.github.kubatatami.judonetworking.callbacks.AsyncResultCallback;
import com.github.kubatatami.judonetworking.callbacks.Callback;
import com.github.kubatatami.judonetworking.callbacks.DecoratorCallback;
import com.github.kubatatami.judonetworking.exceptions.JudoException;
public final class StatefulCallback<T> extends DecoratorCallback<T> implements Stateful<Callback<T>> {
private AsyncResult asyncResult;
private final int id;
private final String who;
private int progress;
private boolean consume = false;
private T data;
private JudoException exception;
public StatefulCallback(StatefulController controller, Callback<T> callback, boolean active) {
this(controller, callback.getClass().hashCode(), callback, active);
}
public StatefulCallback(StatefulController controller, int id, Callback<T> callback, boolean active) {
super(active ? callback : null);
this.id = id;
this.who = controller.getWho();
StatefulCache.addStatefulCallback(who, id, this);
}
@Override
public final void onStart(CacheInfo cacheInfo, AsyncResult asyncResult) {
this.asyncResult = asyncResult;
consume = false;
data = null;
exception = null;
super.onStart(cacheInfo, asyncResult);
}
@Override
public void onFinish() {
super.onFinish();
if (internalCallback != null) {
StatefulCache.endStatefulCallback(who, id);
consume = true;
}
}
@Override
public void onProgress(int progress) {
super.onProgress(progress);
this.progress = progress;
}
@Override
public void onSuccess(T result) {
this.data = result;
super.onSuccess(result);
}
@Override
public void tryCancel() {
if (asyncResult != null) {
asyncResult.cancel();
consume = true;
}
}
@Override
public void setCallback(Callback<T> callback) {
this.internalCallback = callback;
if (callback != null) {
if (callback instanceof AsyncResultCallback) {
((AsyncResultCallback) callback).setAsyncResult(asyncResult);
}
if (progress > 0) {
callback.onProgress(progress);
}
if (!consume) {
if (data != null) {
this.internalCallback.onSuccess(data);
onFinish();
} else if (exception != null) {
this.internalCallback.onError(exception);
onFinish();
}
}
}
}
} | bug fix
| base/src/main/java/com/github/kubatatami/judonetworking/stateful/StatefulCallback.java | bug fix |
|
Java | apache-2.0 | d11be8cc0e0aea450dffcc68f6b66a1e7489338a | 0 | macrozheng/mall,macrozheng/mall | package com.macro.mall.security.component;
import cn.hutool.json.JSONUtil;
import com.macro.mall.common.api.CommonResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 自定义返回结果:未登录或登录过期
* Created by macro on 2018/5/14.
*/
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Cache-Control","no-cache");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().println(JSONUtil.parse(CommonResult.unauthorized(authException.getMessage())));
response.getWriter().flush();
}
}
| mall-security/src/main/java/com/macro/mall/security/component/RestAuthenticationEntryPoint.java | package com.macro.mall.security.component;
import cn.hutool.json.JSONUtil;
import com.macro.mall.common.api.CommonResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 自定义返回结果:未登录或登录过期
* Created by macro on 2018/5/14.
*/
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().println(JSONUtil.parse(CommonResult.unauthorized(authException.getMessage())));
response.getWriter().flush();
}
}
| 跨域问题修复
| mall-security/src/main/java/com/macro/mall/security/component/RestAuthenticationEntryPoint.java | 跨域问题修复 |
|
Java | apache-2.0 | 934ecb2f45458660263d1ee47aeb7d0cd4596026 | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.ex;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.util.ArrayUtilRt;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Merges multiple inspections settings {@link #getSourceToolNames()} into another one {@link #getMergedToolName()}.
*
* Used to preserve backward compatibility when merging several inspections into one, or replacing an inspection with a different
* inspection. An inspection merger keeps existing @SuppressWarnings annotations working. It can also avoid the need to modify user
* inspection profiles, because a new inspection can take one or more old inspection’s settings, without the user needing to configure
* it again.
*
* {@see com.intellij.codeInspection.ex.InspectionElementsMergerBase} to provide more fine control over xml
*/
public abstract class InspectionElementsMerger {
public static final ExtensionPointName<InspectionElementsMerger> EP_NAME = ExtensionPointName.create("com.intellij.inspectionElementsMerger");
private static Map<String, InspectionElementsMerger> ourMergers;
private static final ConcurrentMap<String, InspectionElementsMerger> ourAdditionalMergers = new ConcurrentHashMap<>();
static {
EP_NAME.addChangeListener(InspectionElementsMerger::resetMergers, null);
}
private static synchronized void resetMergers() {
ourMergers = null;
}
@Nullable
public static InspectionElementsMerger getMerger(@NotNull String shortName) {
InspectionElementsMerger additionalMerger = ourAdditionalMergers.get(shortName);
return additionalMerger == null ? getMergers().get(shortName) : additionalMerger;
}
private static synchronized Map<String, InspectionElementsMerger> getMergers() {
if (ourMergers == null) {
Map<String, InspectionElementsMerger> mergers = new HashMap<>();
for (InspectionElementsMerger merger : EP_NAME.getExtensionList()) {
mergers.put(merger.getMergedToolName(), merger);
}
return ourMergers = mergers;
}
return ourMergers;
}
static void addMerger(@NotNull String shortName, @NotNull InspectionElementsMerger merger) {
ourAdditionalMergers.put(shortName, merger);
}
/**
* @return shortName of the new merged inspection.
*/
@Contract(pure = true)
@NotNull
public abstract String getMergedToolName();
/**
* @return the shortNames of the inspections whose settings needs to be merged.
*
* when one of toolNames doesn't present in the profile, default settings for that tool are expected, e.g. by default the result would be enabled with min severity WARNING
*/
@Contract(pure = true)
public abstract String @NotNull [] getSourceToolNames();
/**
* The ids to check for suppression.
* If this returns an empty string array, the result of getSourceToolNames() is used instead.
* @return the suppressIds of the merged inspections.
*/
@Contract(pure = true)
public String @NotNull [] getSuppressIds() {
return ArrayUtilRt.EMPTY_STRING_ARRAY;
}
/**
* @param id suppress id in code
* @return new merged tool name
* null if merger is not found
*/
public static String getMergedToolName(@NotNull String id) {
for (InspectionElementsMerger merger : EP_NAME.getExtensionList()) {
for (String sourceToolName : merger.getSourceToolNames()) {
if (id.equals(sourceToolName)) {
return merger.getMergedToolName();
}
}
for (String suppressId : merger.getSuppressIds()) {
if (id.equals(suppressId)) {
return merger.getMergedToolName();
}
}
}
return null;
}
}
| platform/analysis-api/src/com/intellij/codeInspection/ex/InspectionElementsMerger.java | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.ex;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.util.ArrayUtilRt;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Merges multiple inspections settings {@link #getSourceToolNames()} into another one {@link #getMergedToolName()}
*
* {@see com.intellij.codeInspection.ex.InspectionElementsMergerBase} to provide more fine control over xml
*/
public abstract class InspectionElementsMerger {
public static final ExtensionPointName<InspectionElementsMerger> EP_NAME = ExtensionPointName.create("com.intellij.inspectionElementsMerger");
private static Map<String, InspectionElementsMerger> ourMergers;
private static final ConcurrentMap<String, InspectionElementsMerger> ourAdditionalMergers = new ConcurrentHashMap<>();
static {
EP_NAME.addChangeListener(InspectionElementsMerger::resetMergers, null);
}
private static synchronized void resetMergers() {
ourMergers = null;
}
@Nullable
public static InspectionElementsMerger getMerger(@NotNull String shortName) {
InspectionElementsMerger additionalMerger = ourAdditionalMergers.get(shortName);
return additionalMerger == null ? getMergers().get(shortName) : additionalMerger;
}
private static synchronized Map<String, InspectionElementsMerger> getMergers() {
if (ourMergers == null) {
Map<String, InspectionElementsMerger> mergers = new HashMap<>();
for (InspectionElementsMerger merger : EP_NAME.getExtensionList()) {
mergers.put(merger.getMergedToolName(), merger);
}
return ourMergers = mergers;
}
return ourMergers;
}
static void addMerger(@NotNull String shortName, @NotNull InspectionElementsMerger merger) {
ourAdditionalMergers.put(shortName, merger);
}
/**
* @return shortName of the new merged inspection.
*/
@Contract(pure = true)
@NotNull
public abstract String getMergedToolName();
/**
* @return the shortNames of the inspections whose settings needs to be merged.
*
* when one of toolNames doesn't present in the profile, default settings for that tool are expected, e.g. by default the result would be enabled with min severity WARNING
*/
@Contract(pure = true)
public abstract String @NotNull [] getSourceToolNames();
/**
* The ids to check for suppression.
* If this returns an empty string array, the result of getSourceToolNames() is used instead.
* @return the suppressIds of the merged inspections.
*/
@Contract(pure = true)
public String @NotNull [] getSuppressIds() {
return ArrayUtilRt.EMPTY_STRING_ARRAY;
}
/**
* @param id suppress id in code
* @return new merged tool name
* null if merger is not found
*/
public static String getMergedToolName(@NotNull String id) {
for (InspectionElementsMerger merger : EP_NAME.getExtensionList()) {
for (String sourceToolName : merger.getSourceToolNames()) {
if (id.equals(sourceToolName)) {
return merger.getMergedToolName();
}
}
for (String suppressId : merger.getSuppressIds()) {
if (id.equals(suppressId)) {
return merger.getMergedToolName();
}
}
}
return null;
}
}
| add javadoc explanation
GitOrigin-RevId: a5c28a8883385ce0dfb0e542cb3078de486d8d03 | platform/analysis-api/src/com/intellij/codeInspection/ex/InspectionElementsMerger.java | add javadoc explanation |
|
Java | apache-2.0 | 4e1f00999f216f57b2be43be2a5fa840dff742f6 | 0 | Arcnor/bladecoder-adventure-engine,bladecoder/bladecoder-adventure-engine,bladecoder/bladecoder-adventure-engine,Arcnor/bladecoder-adventure-engine,Arcnor/bladecoder-adventure-engine,Arcnor/bladecoder-adventure-engine | /*******************************************************************************
* Copyright 2014 Rafael Garcia Moreno.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.bladecoder.engineeditor.ui;
import java.text.MessageFormat;
import org.w3c.dom.Element;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.bladecoder.engineeditor.Ctx;
import com.bladecoder.engineeditor.model.BaseDocument;
import com.bladecoder.engineeditor.ui.components.CellRenderer;
import com.bladecoder.engineeditor.ui.components.EditElementDialog;
import com.bladecoder.engineeditor.ui.components.ElementList;
public class VerbList extends ElementList {
public static final String VERBS[] = { "lookat", "pickup", "talkto", "use", "leave", "enter", "exit", "init",
"test", "custom" };
private ActionList actionList;
public VerbList(Skin skin) {
super(skin, true);
actionList = new ActionList(skin);
// addActor(actionList);
row();
add(actionList).expand().fill();
list.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
addActions();
}
});
list.setCellRenderer(listCellRenderer);
}
@Override
protected EditElementDialog getEditElementDialogInstance(Element e) {
return new EditVerbDialog(skin, doc, parent, e);
}
@Override
public void addElements(BaseDocument doc, Element parent, String tag) {
super.addElements(doc, parent, tag);
addActions();
}
@Override
protected void delete() {
super.delete();
// Clear actions here because change event doesn't call when deleting the last element
if(list.getSelectedIndex() == -1)
addActions();
}
private void addActions() {
int pos = list.getSelectedIndex();
Element v = null;
if (pos != -1) {
v = list.getItems().get(pos);
}
actionList.addElements(doc, v, "action");
}
// -------------------------------------------------------------------------
// ListCellRenderer
// -------------------------------------------------------------------------
private final CellRenderer<Element> listCellRenderer = new CellRenderer<Element>() {
@Override
protected String getCellTitle(Element e) {
return e.getAttribute("id");
}
@Override
protected String getCellSubTitle(Element e) {
String state = e.getAttribute("state");
String target = e.getAttribute("target");
StringBuilder sb = new StringBuilder();
if (!state.isEmpty())
sb.append("when ").append(state);
if (!target.isEmpty())
sb.append(" with target '").append(target).append("'");
return sb.toString();
}
@Override
public TextureRegion getCellImage(Element e) {
boolean custom = true;
String verbName = e.getAttribute("id");
for(String v:VERBS) {
if(v.equals(verbName)) {
custom = false;
break;
}
}
String iconName = MessageFormat.format("ic_{0}", e.getAttribute("id"));
TextureRegion image = null;
if(!custom)
image = Ctx.assetManager.getIcon(iconName);
else
image = Ctx.assetManager.getIcon("ic_custom");
return image;
}
@Override
protected boolean hasSubtitle() {
return true;
}
@Override
protected boolean hasImage() {
return true;
}
};
}
| adventure-composer/src/main/java/com/bladecoder/engineeditor/ui/VerbList.java | /*******************************************************************************
* Copyright 2014 Rafael Garcia Moreno.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.bladecoder.engineeditor.ui;
import java.text.MessageFormat;
import org.w3c.dom.Element;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.bladecoder.engineeditor.Ctx;
import com.bladecoder.engineeditor.model.BaseDocument;
import com.bladecoder.engineeditor.ui.components.CellRenderer;
import com.bladecoder.engineeditor.ui.components.EditElementDialog;
import com.bladecoder.engineeditor.ui.components.ElementList;
public class VerbList extends ElementList {
public static final String VERBS[] = { "lookat", "pickup", "talkto", "use", "leave", "enter", "exit", "init",
"test", "custom" };
private ActionList actionList;
public VerbList(Skin skin) {
super(skin, true);
actionList = new ActionList(skin);
// addActor(actionList);
row();
add(actionList).expand().fill();
list.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
addActions();
}
});
list.setCellRenderer(listCellRenderer);
}
@Override
protected EditElementDialog getEditElementDialogInstance(Element e) {
return new EditVerbDialog(skin, doc, parent, e);
}
@Override
public void addElements(BaseDocument doc, Element parent, String tag) {
super.addElements(doc, parent, tag);
addActions();
}
private void addActions() {
int pos = list.getSelectedIndex();
Element v = null;
if (pos != -1) {
v = list.getItems().get(pos);
}
actionList.addElements(doc, v, "action");
}
// -------------------------------------------------------------------------
// ListCellRenderer
// -------------------------------------------------------------------------
private final CellRenderer<Element> listCellRenderer = new CellRenderer<Element>() {
@Override
protected String getCellTitle(Element e) {
return e.getAttribute("id");
}
@Override
protected String getCellSubTitle(Element e) {
String state = e.getAttribute("state");
String target = e.getAttribute("target");
StringBuilder sb = new StringBuilder();
if (!state.isEmpty())
sb.append("when ").append(state);
if (!target.isEmpty())
sb.append(" with target '").append(target).append("'");
return sb.toString();
}
@Override
public TextureRegion getCellImage(Element e) {
boolean custom = true;
String verbName = e.getAttribute("id");
for(String v:VERBS) {
if(v.equals(verbName)) {
custom = false;
break;
}
}
String iconName = MessageFormat.format("ic_{0}", e.getAttribute("id"));
TextureRegion image = null;
if(!custom)
image = Ctx.assetManager.getIcon(iconName);
else
image = Ctx.assetManager.getIcon("ic_custom");
return image;
}
@Override
protected boolean hasSubtitle() {
return true;
}
@Override
protected boolean hasImage() {
return true;
}
};
}
| fix: clear action list when deleting last verb in the verblist | adventure-composer/src/main/java/com/bladecoder/engineeditor/ui/VerbList.java | fix: clear action list when deleting last verb in the verblist |
|
Java | apache-2.0 | 34f1668801cbaadd2b7627d1c221abff2fa86a12 | 0 | whumph/sakai,ouit0408/sakai,clhedrick/sakai,hackbuteer59/sakai,kwedoff1/sakai,conder/sakai,OpenCollabZA/sakai,colczr/sakai,conder/sakai,wfuedu/sakai,liubo404/sakai,puramshetty/sakai,puramshetty/sakai,frasese/sakai,noondaysun/sakai,clhedrick/sakai,Fudan-University/sakai,liubo404/sakai,whumph/sakai,joserabal/sakai,ouit0408/sakai,clhedrick/sakai,noondaysun/sakai,bzhouduke123/sakai,duke-compsci290-spring2016/sakai,frasese/sakai,willkara/sakai,OpenCollabZA/sakai,whumph/sakai,introp-software/sakai,hackbuteer59/sakai,ktakacs/sakai,hackbuteer59/sakai,tl-its-umich-edu/sakai,conder/sakai,Fudan-University/sakai,joserabal/sakai,lorenamgUMU/sakai,tl-its-umich-edu/sakai,puramshetty/sakai,puramshetty/sakai,Fudan-University/sakai,zqian/sakai,puramshetty/sakai,clhedrick/sakai,kingmook/sakai,surya-janani/sakai,kwedoff1/sakai,duke-compsci290-spring2016/sakai,kingmook/sakai,introp-software/sakai,bkirschn/sakai,wfuedu/sakai,udayg/sakai,OpenCollabZA/sakai,colczr/sakai,bzhouduke123/sakai,udayg/sakai,Fudan-University/sakai,noondaysun/sakai,surya-janani/sakai,kingmook/sakai,wfuedu/sakai,pushyamig/sakai,ktakacs/sakai,clhedrick/sakai,ouit0408/sakai,conder/sakai,buckett/sakai-gitflow,kwedoff1/sakai,udayg/sakai,noondaysun/sakai,puramshetty/sakai,bkirschn/sakai,rodriguezdevera/sakai,rodriguezdevera/sakai,tl-its-umich-edu/sakai,surya-janani/sakai,bkirschn/sakai,pushyamig/sakai,OpenCollabZA/sakai,ktakacs/sakai,OpenCollabZA/sakai,kwedoff1/sakai,surya-janani/sakai,hackbuteer59/sakai,udayg/sakai,duke-compsci290-spring2016/sakai,ktakacs/sakai,willkara/sakai,hackbuteer59/sakai,introp-software/sakai,rodriguezdevera/sakai,joserabal/sakai,tl-its-umich-edu/sakai,bzhouduke123/sakai,ouit0408/sakai,wfuedu/sakai,liubo404/sakai,bzhouduke123/sakai,lorenamgUMU/sakai,OpenCollabZA/sakai,surya-janani/sakai,colczr/sakai,ktakacs/sakai,wfuedu/sakai,buckett/sakai-gitflow,joserabal/sakai,rodriguezdevera/sakai,duke-compsci290-spring2016/sakai,hackbuteer59/sakai,whumph/sakai,puramshetty/sakai,kingmook/sakai,joserabal/sakai,tl-its-umich-edu/sakai,willkara/sakai,rodriguezdevera/sakai,tl-its-umich-edu/sakai,surya-janani/sakai,buckett/sakai-gitflow,zqian/sakai,lorenamgUMU/sakai,udayg/sakai,zqian/sakai,whumph/sakai,zqian/sakai,colczr/sakai,Fudan-University/sakai,joserabal/sakai,bkirschn/sakai,Fudan-University/sakai,bkirschn/sakai,ouit0408/sakai,ouit0408/sakai,liubo404/sakai,kingmook/sakai,conder/sakai,zqian/sakai,introp-software/sakai,whumph/sakai,puramshetty/sakai,clhedrick/sakai,tl-its-umich-edu/sakai,frasese/sakai,pushyamig/sakai,introp-software/sakai,willkara/sakai,Fudan-University/sakai,introp-software/sakai,clhedrick/sakai,surya-janani/sakai,lorenamgUMU/sakai,liubo404/sakai,udayg/sakai,duke-compsci290-spring2016/sakai,bkirschn/sakai,willkara/sakai,liubo404/sakai,frasese/sakai,kwedoff1/sakai,noondaysun/sakai,kwedoff1/sakai,colczr/sakai,surya-janani/sakai,kwedoff1/sakai,bkirschn/sakai,buckett/sakai-gitflow,hackbuteer59/sakai,introp-software/sakai,whumph/sakai,pushyamig/sakai,willkara/sakai,kwedoff1/sakai,duke-compsci290-spring2016/sakai,wfuedu/sakai,bzhouduke123/sakai,willkara/sakai,joserabal/sakai,udayg/sakai,lorenamgUMU/sakai,pushyamig/sakai,bzhouduke123/sakai,rodriguezdevera/sakai,conder/sakai,bzhouduke123/sakai,pushyamig/sakai,wfuedu/sakai,kingmook/sakai,introp-software/sakai,OpenCollabZA/sakai,frasese/sakai,buckett/sakai-gitflow,duke-compsci290-spring2016/sakai,zqian/sakai,noondaysun/sakai,ktakacs/sakai,lorenamgUMU/sakai,colczr/sakai,kingmook/sakai,buckett/sakai-gitflow,buckett/sakai-gitflow,frasese/sakai,ouit0408/sakai,liubo404/sakai,colczr/sakai,clhedrick/sakai,buckett/sakai-gitflow,ktakacs/sakai,bzhouduke123/sakai,wfuedu/sakai,zqian/sakai,udayg/sakai,pushyamig/sakai,ktakacs/sakai,willkara/sakai,bkirschn/sakai,frasese/sakai,lorenamgUMU/sakai,ouit0408/sakai,Fudan-University/sakai,duke-compsci290-spring2016/sakai,colczr/sakai,noondaysun/sakai,conder/sakai,OpenCollabZA/sakai,zqian/sakai,conder/sakai,tl-its-umich-edu/sakai,whumph/sakai,hackbuteer59/sakai,noondaysun/sakai,rodriguezdevera/sakai,kingmook/sakai,lorenamgUMU/sakai,joserabal/sakai,pushyamig/sakai,liubo404/sakai,frasese/sakai,rodriguezdevera/sakai | /**
* Copyright (c) 2008-2012 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.osedu.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sakaiproject.profile2.util;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.imageio.ImageIO;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.imgscalr.Scalr;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.ResourceLoader;
public class ProfileUtils {
private static final Logger log = Logger.getLogger(ProfileUtils.class);
/**
* Check content type against allowed types. only JPEG,GIF and PNG are support at the moment
*
* @param contentType string of the content type determined by some image parser
*/
public static boolean checkContentTypeForProfileImage(String contentType) {
ArrayList<String> allowedTypes = new ArrayList<String>();
allowedTypes.add("image/jpeg");
allowedTypes.add("image/gif");
allowedTypes.add("image/png");
//Adding MIME types that Internet Explorer returns PRFL-98
allowedTypes.add("image/x-png");
allowedTypes.add("image/pjpeg");
allowedTypes.add("image/jpg");
//add more here as required, BUT also add them below.
//You will need to check ImageIO for the informal names.
if(allowedTypes.contains(contentType)) {
return true;
}
return false;
}
/**
* Helper to get the informal format name that is used by ImageIO.
* We have access to the mimetype so we can map them.
*
* <p>If no valid mapping is found, it will default to "jpg".
*
* @param mimeType the mimetype of the original image, eg image/jpeg
*/
public static String getInformalFormatForMimeType(String mimeType){
Map<String,String> formats = new HashMap<String,String>();
formats.put("image/jpeg", "jpg");
formats.put("image/gif", "gif");
formats.put("image/png", "png");
formats.put("image/x-png", "png");
formats.put("image/pjpeg", "jpg");
formats.put("image/jpg", "jpg");
String format = formats.get(mimeType);
if(format != null) {
return format;
}
return "jpg";
}
/**
* Scale an image so it is fit within a give width and height, whilst maintaining its original proportions
*
* @param imageData bytes of the original image
* @param maxSize maximum dimension in px
*/
public static byte[] scaleImage(byte[] imageData, int maxSize, String mimeType) {
InputStream in = null;
byte[] scaledImageBytes = null;
try {
//convert original image to inputstream
in = new ByteArrayInputStream(imageData);
//original buffered image
BufferedImage originalImage = ImageIO.read(in);
//scale the image using the imgscalr library
BufferedImage scaledImage = Scalr.resize(originalImage, maxSize);
//convert BufferedImage to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(scaledImage, getInformalFormatForMimeType(mimeType), baos);
baos.flush();
scaledImageBytes = baos.toByteArray();
baos.close();
} catch (Exception e) {
log.error("Scaling image failed.", e);
}
finally {
if (in != null) {
try {
in.close();
log.debug("Image stream closed.");
}
catch (IOException e) {
log.error("Error closing image stream: ", e);
}
}
}
return scaledImageBytes;
}
/**
* Convert a Date into a String according to format, or, if format
* is set to null, do a current locale based conversion.
*
* @param date date to convert
* @param format format in SimpleDateFormat syntax. Set to null to force as locale based conversion.
*/
public static String convertDateToString(Date date, String format) {
if(date == null || "".equals(format)) {
throw new IllegalArgumentException("Null Argument in Profile.convertDateToString()");
}
String dateStr = null;
if(format != null) {
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
dateStr = dateFormat.format(date);
} else {
// Since no specific format has been specced, we use the user's locale.
Locale userLocale = (new ResourceLoader()).getLocale();
DateFormat formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, userLocale);
dateStr = formatter.format(date);
}
if(log.isDebugEnabled()) {
log.debug("Profile.convertDateToString(): Input date: " + date.toString());
log.debug("Profile.convertDateToString(): Converted date string: " + dateStr);
}
return dateStr;
}
/**
* Convert a string into a Date object (reverse of above
*
* @param dateStr date string to convert
* @param format format of the input date in SimpleDateFormat syntax
*/
public static Date convertStringToDate(String dateStr, String format) {
if("".equals(dateStr) || "".equals(format)) {
throw new IllegalArgumentException("Null Argument in Profile.convertStringToDate()");
}
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
try {
Date date = dateFormat.parse(dateStr);
log.debug("Profile.convertStringToDate(): Input date string: " + dateStr);
log.debug("Profile.convertStringToDate(): Converted date: " + date.toString());
return date;
} catch (ParseException e) {
log.error("Profile.convertStringToDate() failed. " + e.getClass() + ": " + e.getMessage());
return null;
}
}
/**
* Strip the year from a given date (actually just sets it to 1)
*
* @param date original date
* @return
*/
public static Date stripYear(Date date){
return DateUtils.setYears(date, 1);
}
/**
* Get the localised name of the day (ie Monday for en, Maandag for nl)
* @param day int according to Calendar.DAY_OF_WEEK
* @param locale locale to render dayname in
* @return
*/
public static String getDayName(int day, Locale locale) {
//localised daynames
String dayNames[] = new DateFormatSymbols(locale).getWeekdays();
String dayName = null;
try {
dayName = dayNames[day];
} catch (Exception e) {
log.error("Profile.getDayName() failed. " + e.getClass() + ": " + e.getMessage());
}
return dayName;
}
/**
* Convert a string to propercase. ie This Is Proper Text
* @param input string to be formatted
* @return
*/
public static String toProperCase(String input) {
return WordUtils.capitalizeFully(input);
}
/**
* Convert a date into a field like "just then, 2 minutes ago, 4 hours ago, yesterday, on sunday, etc"
*
* @param date date to convert
*/
public static String convertDateForStatus(Date date) {
//current time
Calendar currentCal = Calendar.getInstance();
long currentTimeMillis = currentCal.getTimeInMillis();
//posting time
long postingTimeMillis = date.getTime();
//difference
int diff = (int)(currentTimeMillis - postingTimeMillis);
Locale locale = getUserPreferredLocale();
//System.out.println("currentDate:" + currentTimeMillis);
//System.out.println("postingDate:" + postingTimeMillis);
//System.out.println("diff:" + diff);
int MILLIS_IN_SECOND = 1000;
int MILLIS_IN_MINUTE = 1000 * 60;
int MILLIS_IN_HOUR = 1000 * 60 * 60;
int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
int MILLIS_IN_WEEK = 1000 * 60 * 60 * 24 * 7;
if(diff < MILLIS_IN_SECOND) {
//less than a second
return Messages.getString("Label.just_then");
} else if (diff < MILLIS_IN_MINUTE) {
//less than a minute, calc seconds
int numSeconds = diff/MILLIS_IN_SECOND;
if(numSeconds == 1) {
//one sec
return Messages.getString("Label.second_ago", new Object[] {numSeconds});
} else {
//more than one sec
return Messages.getString("Label.seconds_ago", new Object[] {numSeconds});
}
} else if (diff < MILLIS_IN_HOUR) {
//less than an hour, calc minutes
int numMinutes = diff/MILLIS_IN_MINUTE;
if(numMinutes == 1) {
//one minute
return Messages.getString("Label.minute_ago", new Object[] {numMinutes});
} else {
//more than one minute
return Messages.getString("Label.minutes_ago", new Object[] {numMinutes});
}
} else if (diff < MILLIS_IN_DAY) {
//less than a day, calc hours
int numHours = diff/MILLIS_IN_HOUR;
if(numHours == 1) {
//one hour
return Messages.getString("Label.hour_ago", new Object[] {numHours});
} else {
//more than one hour
return Messages.getString("Label.hours_ago", new Object[] {numHours});
}
} else if (diff < MILLIS_IN_WEEK) {
//less than a week, calculate days
int numDays = diff/MILLIS_IN_DAY;
//now calculate which day it was
if(numDays == 1) {
return Messages.getString("Label.yesterday");
} else {
//set calendar and get day of week
Calendar postingCal = Calendar.getInstance();
postingCal.setTimeInMillis(postingTimeMillis);
int postingDay = postingCal.get(Calendar.DAY_OF_WEEK);
//set to localised value: 'on Wednesday' for example
String dayName = getDayName(postingDay,locale);
if(dayName != null) {
return Messages.getString("Label.on", new Object[] {toProperCase(dayName)});
}
}
} else {
//over a week ago, we want it blank though.
}
return null;
}
/**
* Gets the users preferred locale, either from the user's session or Sakai preferences and returns it
* This depends on Sakai's ResourceLoader.
*
* @return
*/
public static Locale getUserPreferredLocale() {
ResourceLoader rl = new ResourceLoader();
return rl.getLocale();
}
/**
* Creates a full profile event reference for a given reference
* @param ref
* @return
*/
public static String createEventRef(String ref) {
return "/profile/"+ref;
}
/**
* Method for getting a value from a map based on the given key, but if it does not exist, use the given default
* @param map
* @param key
* @param defaultValue
* @return
*/
public static Object getValueFromMapOrDefault(Map<?,?> map, Object key, Object defaultValue) {
return (map.containsKey(key) ? map.get(key) : defaultValue);
}
/**
* Method to chop a String into it's parts based on the separator and return as a List. Useful for multi valued Sakai properties
* @param str the String to split
* @param separator separator character
* @return
*/
public static List<String> getListFromString(String str, char separator) {
String[] items = StringUtils.split(str, separator);
return Arrays.asList(items);
}
/**
* Processes HTML and escapes evils tags like <script>, also converts newlines to proper HTML breaks.
* @param s
* @return
*/
public static String processHtml(String s){
return FormattedText.processFormattedText(s, new StringBuilder(), true, false);
}
/**
* Strips string of HTML and returns plain text.
*
* @param s
* @return
*/
public static String stripHtml(String s) {
return FormattedText.convertFormattedTextToPlaintext(s);
}
/**
* Strips string of HTML, escaping anything that is left to return plain text.
*
* <p>Deals better with poorly formed HTML than just stripHtml and is best for XSS protection, not for storing actual data.
*
* @param s The string to process
* @return
*/
public static String stripAndCleanHtml(String s) {
//Attempt to strip HTML. This doesn't work on poorly formatted HTML though
String stripped = FormattedText.convertFormattedTextToPlaintext(s);
//so we escape anything that is left
return StringEscapeUtils.escapeHtml(stripped);
}
/**
* Trims text to the given maximum number of displayed characters.
* Supports HTML and preserves formatting.
*
* @param s the string
* @param maxNumOfChars num chars to keep. If HTML, it's the number of content chars, ignoring tags.
* @param isHtml is the string HTML?
* @return
*/
public static String truncate(String s, int maxNumOfChars, boolean isHtml) {
if (StringUtils.isBlank(s)) {
return "";
}
//html
if(isHtml) {
StringBuilder trimmedHtml = new StringBuilder();
FormattedText.trimFormattedText(s, maxNumOfChars, trimmedHtml);
return trimmedHtml.toString();
}
//plain text
return StringUtils.substring(s, 0, maxNumOfChars);
}
/**
* Trims and abbreviates text to the given maximum number of displayed
* characters (less 3 characters, in case "..." must be appended).
* Supports HTML and preserves formatting.
*
* @param s the string
* @param maxNumOfChars num chars to keep. If HTML, it's the number of content chars, ignoring tags.
* @param isHtml is the string HTML?
* @return
*/
public static String truncateAndAbbreviate(String s, int maxNumOfChars, boolean isHtml) {
if (StringUtils.isBlank(s)) {
return "";
}
//html
if(isHtml) {
StringBuilder trimmedHtml = new StringBuilder();
boolean trimmed = FormattedText.trimFormattedText(s, maxNumOfChars - 3, trimmedHtml);
if (trimmed) {
int index = trimmedHtml.lastIndexOf("</");
if (-1 != index) {
trimmedHtml.insert(index, "...");
} else {
trimmedHtml.append("...");
}
}
return trimmedHtml.toString();
}
//plain text
return StringUtils.abbreviate(s, maxNumOfChars);
}
/**
* Generate a UUID
* @return
*/
public static String generateUuid() {
UUID uuid = UUID.randomUUID();
return uuid.toString();
}
/**
* Returns the SkypeMe URL for the specified Skype username.
*
* @param skypeUsername
* @return the SkypeMe URL for the specified Skype username.
*/
public static String getSkypeMeURL(String skypeUsername) {
return "skype:" + skypeUsername + "?call";
}
/**
* Remove duplicates from a list, order is not retained.
*
* @param list list of objects to clean
*/
public static <T> void removeDuplicates(List<T> list){
Set<T> set = new HashSet<T>();
set.addAll(list);
list.clear();
list.addAll(set);
}
/**
* Remove duplicates from a list, order is retained.
*
* @param list list of objects to clean
*/
public static <T> void removeDuplicatesWithOrder(List<T> list) {
Set<T> set = new HashSet<T> ();
List<T> newList = new ArrayList<T>();
for(T e: list) {
if (set.add(e)) {
newList.add(e);
}
}
list.clear();
list.addAll(newList);
}
/**
* Calculate an MD5 hash of a string
* @param s String to hash
* @return MD5 hash as a String
*/
public static String calculateMD5(String s){
return DigestUtils.md5Hex(s);
}
/**
* Creates a square avatar image by taking a segment out of the centre of the original image and resizing to the appropriate dimensions
*
* @param imageData original bytes of the image
* @param mimeType mimetype of image
* @return
*/
public static byte[] createAvatar(byte[] imageData, String mimeType) {
InputStream in = null;
byte[] outputBytes = null;
try {
//convert original image to inputstream
in = new ByteArrayInputStream(imageData);
//original buffered image
BufferedImage originalImage = ImageIO.read(in);
//OPTION 1
//determine the smaller side of the image and use that as the size of the cropped square
//to be taken out of the centre
//then resize to the avatar size =80 square.
int smallestSide = originalImage.getWidth();
if(originalImage.getHeight() < originalImage.getWidth()) {
smallestSide = originalImage.getHeight();
}
if(log.isDebugEnabled()){
log.debug("smallestSide:" + smallestSide);
}
int startX = (originalImage.getWidth() / 2) - (smallestSide/2);
int startY = (originalImage.getHeight() / 2) - (smallestSide/2);
//OPTION 2 (unused)
//determine a percentage of the original image which we want to keep, say 90%.
//then figure out the dimensions of the box and crop to that.
//then resize to the avatar size =80 square.
//int percentWidth = (originalImage.getWidth() / 100) * 90;
//int startX = (originalImage.getWidth() / 2) - (percentWidth/2);
//int percentHeight = (originalImage.getHeight() / 100) * 90;
//int startY = (originalImage.getHeight() / 2) - (percentHeight/2);
//log.debug("percentWidth:" + percentWidth);
//log.debug("percentHeight:" + percentHeight);
//so it is square, we can only use one dimension for both side, so choose the smaller one
//int croppedSize = percentWidth;
//if(percentHeight < percentWidth) {
// croppedSize = percentHeight;
//}
//log.debug("croppedSize:" + croppedSize);
if(log.isDebugEnabled()){
log.debug("originalImage.getWidth():" + originalImage.getWidth());
log.debug("originalImage.getHeight():" + originalImage.getHeight());
log.debug("startX:" + startX);
log.debug("startY:" + startY);
}
//crop to these bounds and starting positions
BufferedImage croppedImage = Scalr.crop(originalImage, startX, startY, smallestSide, smallestSide);
//now resize it to the desired avatar size
BufferedImage scaledImage = Scalr.resize(croppedImage, 80);
//convert BufferedImage to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(scaledImage, getInformalFormatForMimeType(mimeType), baos);
baos.flush();
outputBytes = baos.toByteArray();
baos.close();
} catch (Exception e) {
log.error("Cropping and scaling image failed.", e);
}
finally {
if (in != null) {
try {
in.close();
log.debug("Image stream closed.");
}
catch (IOException e) {
log.error("Error closing image stream: ", e);
}
}
}
return outputBytes;
}
}
| profile2/util/src/java/org/sakaiproject/profile2/util/ProfileUtils.java | /**
* Copyright (c) 2008-2012 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.osedu.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sakaiproject.profile2.util;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.imageio.ImageIO;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.imgscalr.Scalr;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.ResourceLoader;
public class ProfileUtils {
private static final Logger log = Logger.getLogger(ProfileUtils.class);
/**
* Check content type against allowed types. only JPEG,GIF and PNG are support at the moment
*
* @param contentType string of the content type determined by some image parser
*/
public static boolean checkContentTypeForProfileImage(String contentType) {
ArrayList<String> allowedTypes = new ArrayList<String>();
allowedTypes.add("image/jpeg");
allowedTypes.add("image/gif");
allowedTypes.add("image/png");
//Adding MIME types that Internet Explorer returns PRFL-98
allowedTypes.add("image/x-png");
allowedTypes.add("image/pjpeg");
allowedTypes.add("image/jpg");
//add more here as required, BUT also add them below.
//You will need to check ImageIO for the informal names.
if(allowedTypes.contains(contentType)) {
return true;
}
return false;
}
/**
* Helper to get the informal format name that is used by ImageIO.
* We have access to the mimetype so we can map them.
*
* <p>If no valid mapping is found, it will default to "jpg".
*
* @param mimeType the mimetype of the original image, eg image/jpeg
*/
public static String getInformalFormatForMimeType(String mimeType){
Map<String,String> formats = new HashMap<String,String>();
formats.put("image/jpeg", "jpg");
formats.put("image/gif", "gif");
formats.put("image/png", "png");
formats.put("image/x-png", "png");
formats.put("image/pjpeg", "jpg");
formats.put("image/jpg", "jpg");
String format = formats.get(mimeType);
if(format != null) {
return format;
}
return "jpg";
}
/**
* Scale an image so it is fit within a give width and height, whilst maintaining its original proportions
*
* @param imageData bytes of the original image
* @param maxSize maximum dimension in px
*/
public static byte[] scaleImage(byte[] imageData, int maxSize, String mimeType) {
InputStream in = null;
byte[] scaledImageBytes = null;
try {
//convert original image to inputstream
in = new ByteArrayInputStream(imageData);
//original buffered image
BufferedImage originalImage = ImageIO.read(in);
//scale the image using the imgscalr library
BufferedImage scaledImage = Scalr.resize(originalImage, maxSize);
//convert BufferedImage to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(scaledImage, getInformalFormatForMimeType(mimeType), baos);
baos.flush();
scaledImageBytes = baos.toByteArray();
baos.close();
} catch (Exception e) {
log.error("Scaling image failed.", e);
}
finally {
if (in != null) {
try {
in.close();
log.debug("Image stream closed.");
}
catch (IOException e) {
log.error("Error closing image stream: ", e);
}
}
}
return scaledImageBytes;
}
/**
* Convert a Date into a String according to format
*
* @param date date to convert
* @param format format in SimpleDateFormat syntax
*/
public static String convertDateToString(Date date, String format) {
if(date == null || "".equals(format)) {
throw new IllegalArgumentException("Null Argument in Profile.convertDateToString()");
}
String dateStr = null;
if(format != null) {
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
dateStr = dateFormat.format(date);
} else {
// Since no specific format has been specced, we use the user's locale.
Locale userLocale = (new ResourceLoader()).getLocale();
DateFormat formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, userLocale);
dateStr = formatter.format(date);
}
if(log.isDebugEnabled()) {
log.debug("Profile.convertDateToString(): Input date: " + date.toString());
log.debug("Profile.convertDateToString(): Converted date string: " + dateStr);
}
return dateStr;
}
/**
* Convert a string into a Date object (reverse of above
*
* @param dateStr date string to convert
* @param format format of the input date in SimpleDateFormat syntax
*/
public static Date convertStringToDate(String dateStr, String format) {
if("".equals(dateStr) || "".equals(format)) {
throw new IllegalArgumentException("Null Argument in Profile.convertStringToDate()");
}
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
try {
Date date = dateFormat.parse(dateStr);
log.debug("Profile.convertStringToDate(): Input date string: " + dateStr);
log.debug("Profile.convertStringToDate(): Converted date: " + date.toString());
return date;
} catch (ParseException e) {
log.error("Profile.convertStringToDate() failed. " + e.getClass() + ": " + e.getMessage());
return null;
}
}
/**
* Strip the year from a given date (actually just sets it to 1)
*
* @param date original date
* @return
*/
public static Date stripYear(Date date){
return DateUtils.setYears(date, 1);
}
/**
* Get the localised name of the day (ie Monday for en, Maandag for nl)
* @param day int according to Calendar.DAY_OF_WEEK
* @param locale locale to render dayname in
* @return
*/
public static String getDayName(int day, Locale locale) {
//localised daynames
String dayNames[] = new DateFormatSymbols(locale).getWeekdays();
String dayName = null;
try {
dayName = dayNames[day];
} catch (Exception e) {
log.error("Profile.getDayName() failed. " + e.getClass() + ": " + e.getMessage());
}
return dayName;
}
/**
* Convert a string to propercase. ie This Is Proper Text
* @param input string to be formatted
* @return
*/
public static String toProperCase(String input) {
return WordUtils.capitalizeFully(input);
}
/**
* Convert a date into a field like "just then, 2 minutes ago, 4 hours ago, yesterday, on sunday, etc"
*
* @param date date to convert
*/
public static String convertDateForStatus(Date date) {
//current time
Calendar currentCal = Calendar.getInstance();
long currentTimeMillis = currentCal.getTimeInMillis();
//posting time
long postingTimeMillis = date.getTime();
//difference
int diff = (int)(currentTimeMillis - postingTimeMillis);
Locale locale = getUserPreferredLocale();
//System.out.println("currentDate:" + currentTimeMillis);
//System.out.println("postingDate:" + postingTimeMillis);
//System.out.println("diff:" + diff);
int MILLIS_IN_SECOND = 1000;
int MILLIS_IN_MINUTE = 1000 * 60;
int MILLIS_IN_HOUR = 1000 * 60 * 60;
int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
int MILLIS_IN_WEEK = 1000 * 60 * 60 * 24 * 7;
if(diff < MILLIS_IN_SECOND) {
//less than a second
return Messages.getString("Label.just_then");
} else if (diff < MILLIS_IN_MINUTE) {
//less than a minute, calc seconds
int numSeconds = diff/MILLIS_IN_SECOND;
if(numSeconds == 1) {
//one sec
return Messages.getString("Label.second_ago", new Object[] {numSeconds});
} else {
//more than one sec
return Messages.getString("Label.seconds_ago", new Object[] {numSeconds});
}
} else if (diff < MILLIS_IN_HOUR) {
//less than an hour, calc minutes
int numMinutes = diff/MILLIS_IN_MINUTE;
if(numMinutes == 1) {
//one minute
return Messages.getString("Label.minute_ago", new Object[] {numMinutes});
} else {
//more than one minute
return Messages.getString("Label.minutes_ago", new Object[] {numMinutes});
}
} else if (diff < MILLIS_IN_DAY) {
//less than a day, calc hours
int numHours = diff/MILLIS_IN_HOUR;
if(numHours == 1) {
//one hour
return Messages.getString("Label.hour_ago", new Object[] {numHours});
} else {
//more than one hour
return Messages.getString("Label.hours_ago", new Object[] {numHours});
}
} else if (diff < MILLIS_IN_WEEK) {
//less than a week, calculate days
int numDays = diff/MILLIS_IN_DAY;
//now calculate which day it was
if(numDays == 1) {
return Messages.getString("Label.yesterday");
} else {
//set calendar and get day of week
Calendar postingCal = Calendar.getInstance();
postingCal.setTimeInMillis(postingTimeMillis);
int postingDay = postingCal.get(Calendar.DAY_OF_WEEK);
//set to localised value: 'on Wednesday' for example
String dayName = getDayName(postingDay,locale);
if(dayName != null) {
return Messages.getString("Label.on", new Object[] {toProperCase(dayName)});
}
}
} else {
//over a week ago, we want it blank though.
}
return null;
}
/**
* Gets the users preferred locale, either from the user's session or Sakai preferences and returns it
* This depends on Sakai's ResourceLoader.
*
* @return
*/
public static Locale getUserPreferredLocale() {
ResourceLoader rl = new ResourceLoader();
return rl.getLocale();
}
/**
* Creates a full profile event reference for a given reference
* @param ref
* @return
*/
public static String createEventRef(String ref) {
return "/profile/"+ref;
}
/**
* Method for getting a value from a map based on the given key, but if it does not exist, use the given default
* @param map
* @param key
* @param defaultValue
* @return
*/
public static Object getValueFromMapOrDefault(Map<?,?> map, Object key, Object defaultValue) {
return (map.containsKey(key) ? map.get(key) : defaultValue);
}
/**
* Method to chop a String into it's parts based on the separator and return as a List. Useful for multi valued Sakai properties
* @param str the String to split
* @param separator separator character
* @return
*/
public static List<String> getListFromString(String str, char separator) {
String[] items = StringUtils.split(str, separator);
return Arrays.asList(items);
}
/**
* Processes HTML and escapes evils tags like <script>, also converts newlines to proper HTML breaks.
* @param s
* @return
*/
public static String processHtml(String s){
return FormattedText.processFormattedText(s, new StringBuilder(), true, false);
}
/**
* Strips string of HTML and returns plain text.
*
* @param s
* @return
*/
public static String stripHtml(String s) {
return FormattedText.convertFormattedTextToPlaintext(s);
}
/**
* Strips string of HTML, escaping anything that is left to return plain text.
*
* <p>Deals better with poorly formed HTML than just stripHtml and is best for XSS protection, not for storing actual data.
*
* @param s The string to process
* @return
*/
public static String stripAndCleanHtml(String s) {
//Attempt to strip HTML. This doesn't work on poorly formatted HTML though
String stripped = FormattedText.convertFormattedTextToPlaintext(s);
//so we escape anything that is left
return StringEscapeUtils.escapeHtml(stripped);
}
/**
* Trims text to the given maximum number of displayed characters.
* Supports HTML and preserves formatting.
*
* @param s the string
* @param maxNumOfChars num chars to keep. If HTML, it's the number of content chars, ignoring tags.
* @param isHtml is the string HTML?
* @return
*/
public static String truncate(String s, int maxNumOfChars, boolean isHtml) {
if (StringUtils.isBlank(s)) {
return "";
}
//html
if(isHtml) {
StringBuilder trimmedHtml = new StringBuilder();
FormattedText.trimFormattedText(s, maxNumOfChars, trimmedHtml);
return trimmedHtml.toString();
}
//plain text
return StringUtils.substring(s, 0, maxNumOfChars);
}
/**
* Trims and abbreviates text to the given maximum number of displayed
* characters (less 3 characters, in case "..." must be appended).
* Supports HTML and preserves formatting.
*
* @param s the string
* @param maxNumOfChars num chars to keep. If HTML, it's the number of content chars, ignoring tags.
* @param isHtml is the string HTML?
* @return
*/
public static String truncateAndAbbreviate(String s, int maxNumOfChars, boolean isHtml) {
if (StringUtils.isBlank(s)) {
return "";
}
//html
if(isHtml) {
StringBuilder trimmedHtml = new StringBuilder();
boolean trimmed = FormattedText.trimFormattedText(s, maxNumOfChars - 3, trimmedHtml);
if (trimmed) {
int index = trimmedHtml.lastIndexOf("</");
if (-1 != index) {
trimmedHtml.insert(index, "...");
} else {
trimmedHtml.append("...");
}
}
return trimmedHtml.toString();
}
//plain text
return StringUtils.abbreviate(s, maxNumOfChars);
}
/**
* Generate a UUID
* @return
*/
public static String generateUuid() {
UUID uuid = UUID.randomUUID();
return uuid.toString();
}
/**
* Returns the SkypeMe URL for the specified Skype username.
*
* @param skypeUsername
* @return the SkypeMe URL for the specified Skype username.
*/
public static String getSkypeMeURL(String skypeUsername) {
return "skype:" + skypeUsername + "?call";
}
/**
* Remove duplicates from a list, order is not retained.
*
* @param list list of objects to clean
*/
public static <T> void removeDuplicates(List<T> list){
Set<T> set = new HashSet<T>();
set.addAll(list);
list.clear();
list.addAll(set);
}
/**
* Remove duplicates from a list, order is retained.
*
* @param list list of objects to clean
*/
public static <T> void removeDuplicatesWithOrder(List<T> list) {
Set<T> set = new HashSet<T> ();
List<T> newList = new ArrayList<T>();
for(T e: list) {
if (set.add(e)) {
newList.add(e);
}
}
list.clear();
list.addAll(newList);
}
/**
* Calculate an MD5 hash of a string
* @param s String to hash
* @return MD5 hash as a String
*/
public static String calculateMD5(String s){
return DigestUtils.md5Hex(s);
}
/**
* Creates a square avatar image by taking a segment out of the centre of the original image and resizing to the appropriate dimensions
*
* @param imageData original bytes of the image
* @param mimeType mimetype of image
* @return
*/
public static byte[] createAvatar(byte[] imageData, String mimeType) {
InputStream in = null;
byte[] outputBytes = null;
try {
//convert original image to inputstream
in = new ByteArrayInputStream(imageData);
//original buffered image
BufferedImage originalImage = ImageIO.read(in);
//OPTION 1
//determine the smaller side of the image and use that as the size of the cropped square
//to be taken out of the centre
//then resize to the avatar size =80 square.
int smallestSide = originalImage.getWidth();
if(originalImage.getHeight() < originalImage.getWidth()) {
smallestSide = originalImage.getHeight();
}
if(log.isDebugEnabled()){
log.debug("smallestSide:" + smallestSide);
}
int startX = (originalImage.getWidth() / 2) - (smallestSide/2);
int startY = (originalImage.getHeight() / 2) - (smallestSide/2);
//OPTION 2 (unused)
//determine a percentage of the original image which we want to keep, say 90%.
//then figure out the dimensions of the box and crop to that.
//then resize to the avatar size =80 square.
//int percentWidth = (originalImage.getWidth() / 100) * 90;
//int startX = (originalImage.getWidth() / 2) - (percentWidth/2);
//int percentHeight = (originalImage.getHeight() / 100) * 90;
//int startY = (originalImage.getHeight() / 2) - (percentHeight/2);
//log.debug("percentWidth:" + percentWidth);
//log.debug("percentHeight:" + percentHeight);
//so it is square, we can only use one dimension for both side, so choose the smaller one
//int croppedSize = percentWidth;
//if(percentHeight < percentWidth) {
// croppedSize = percentHeight;
//}
//log.debug("croppedSize:" + croppedSize);
if(log.isDebugEnabled()){
log.debug("originalImage.getWidth():" + originalImage.getWidth());
log.debug("originalImage.getHeight():" + originalImage.getHeight());
log.debug("startX:" + startX);
log.debug("startY:" + startY);
}
//crop to these bounds and starting positions
BufferedImage croppedImage = Scalr.crop(originalImage, startX, startY, smallestSide, smallestSide);
//now resize it to the desired avatar size
BufferedImage scaledImage = Scalr.resize(croppedImage, 80);
//convert BufferedImage to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(scaledImage, getInformalFormatForMimeType(mimeType), baos);
baos.flush();
outputBytes = baos.toByteArray();
baos.close();
} catch (Exception e) {
log.error("Cropping and scaling image failed.", e);
}
finally {
if (in != null) {
try {
in.close();
log.debug("Image stream closed.");
}
catch (IOException e) {
log.error("Error closing image stream: ", e);
}
}
}
return outputBytes;
}
}
| PRFL-434
Updated the comment on ProfileUtils.convertDateToString.
git-svn-id: 30a950ac960002fda4f107a8e0f4b5b25bfa9e10@116796 66ffb92e-73f9-0310-93c1-f5514f145a0a
| profile2/util/src/java/org/sakaiproject/profile2/util/ProfileUtils.java | PRFL-434 |
|
Java | apache-2.0 | a546b89686f7a048254e2bf2a8e5c18511686972 | 0 | eFaps/eFaps-WebApp,eFaps/eFaps-WebApp,eFaps/eFaps-WebApp | /*
* Copyright 2003 - 2010 The eFaps Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package org.efaps.ui.wicket.models.objects;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import org.apache.wicket.PageParameters;
import org.apache.wicket.RestartResponseException;
import org.efaps.admin.AbstractAdminObject;
import org.efaps.admin.datamodel.Attribute;
import org.efaps.admin.datamodel.Type;
import org.efaps.admin.datamodel.ui.FieldValue;
import org.efaps.admin.dbproperty.DBProperties;
import org.efaps.admin.event.EventDefinition;
import org.efaps.admin.event.EventType;
import org.efaps.admin.event.Parameter.ParameterValues;
import org.efaps.admin.event.Return;
import org.efaps.admin.event.Return.ReturnValues;
import org.efaps.admin.ui.AbstractCommand;
import org.efaps.admin.ui.AbstractCommand.SortDirection;
import org.efaps.admin.ui.AbstractUserInterfaceObject.TargetMode;
import org.efaps.admin.ui.Image;
import org.efaps.admin.ui.Menu;
import org.efaps.admin.ui.Table;
import org.efaps.admin.ui.field.Field;
import org.efaps.admin.ui.field.Field.Display;
import org.efaps.beans.ValueList;
import org.efaps.beans.valueparser.ParseException;
import org.efaps.beans.valueparser.ValueParser;
import org.efaps.db.Context;
import org.efaps.db.Instance;
import org.efaps.db.MultiPrintQuery;
import org.efaps.db.PrintQuery;
import org.efaps.ui.wicket.models.cell.UIStructurBrowserTableCell;
import org.efaps.ui.wicket.pages.error.ErrorPage;
import org.efaps.util.EFapsException;
import org.efaps.util.RequestHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is used to provide the Model for the StructurBrowser for eFpas. <br>
* It is used in tow different cases. In one case it is a TreeTable, where the
* Table will be provided with additional information in columns. In the other
* case a Tree only.<br>
* The concept of this class is to provide a Model which connects through the
* eFaps-kernel to the eFaps-DataBase and turn it to a Standard TreeModel from
* <code>javax.swing.tree</code>. which will be used from the Component to
* render the Tree and the Table. This leads to a very similar behavior of the
* WebApp GUI to a swing GUI. <br>
* This model works asyncron. That means only the actually in the GUI rendered
* Nodes (and Columns) will be retrieved from the eFaps-DataBase. The next level
* in a tree will be retrieved on the expand of a TreeNode. To achieve this and
* to be able to render expand-links for every node it will only be checked if
* it is a potential parent (if it has children). In the case of expanding this
* Node the children will be retrieved and rendered.<br>
* To access the eFaps-Database a esjp is used, which will be used in five
* different cases. To distinguish the use of the esjp some extra Parameters
* will be passed to the esjp when calling it.
*
* @author The eFaps Team
* @version $Id$
*/
public class UIStructurBrowser
extends AbstractUIPageObject
{
/**
* Enum is used to set for this UIStructurBrowser which status of execution
* it is in.
*/
public enum ExecutionStatus {
/** Method addChildren is executed. */
ADDCHILDREN,
/** Method addChildren is executed. */
ALLOWSCHILDREN,
/** Method checkForChildren is executed. */
CHECKFORCHILDREN,
/** Method is creating a new folder. */
CHECKHIDECOLUMN4ROW,
/**
* Method is called after the insert etc. of a new node in edit mode to
* get a JavaScript that will be appended to the AjaxTarget. In this
* Step the values for the StructurBrowsers also can be altered.
* @see {@link UIStructurBrowser.#setValuesFromUI(Map, DefaultMutableTreeNode)setValuesFromUI}
*/
GETJAVASCRIPT4TARGET,
/** Method execute is executed. */
EXECUTE,
/** Method sort is executed. */
SORT;
}
/**
* Static part of the key to get the Information stored in the session
* in relation to this StruturBrowser.
*/
public static final String USERSESSIONKEY = "eFapsUIStructurBrowser";
/**
* Logging instance used in this class.
*/
private static final Logger LOG = LoggerFactory.getLogger(UIStructurBrowser.class);
/**
* Needed for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* The instance variable stores the UUID for the table which must be shown.
*
* @see #getTable
*/
private UUID tableuuid;
/**
* This instance variable holds if this StructurBrowserModel can have
* children at all.
*/
private boolean allowChilds;
/**
* This instance variable holds if this StructurBrowserModel is a
* parent, this is needed because, first it will be only determined if a
* node is a potential parent, and later on the childs will be retrieved
* from the eFaps-DataBase.
*
* @see #isParent()
*/
private boolean parent;
/**
* This instance variable holds the childs of this StructurBrowserModel.
*/
private final List<UIStructurBrowser> childs = new ArrayList<UIStructurBrowser>();
/**
* Holds the columns in case of a TableTree.
*/
private final List<UIStructurBrowserTableCell> columns = new ArrayList<UIStructurBrowserTableCell>();
/**
* Holds the label of the Node which will be presented in the GUI.
*
* @see #toString()
* @see #getLabel()
* @see #setLabel(String)
* @see #requeryLabel()
*/
private String label;
/**
* Holds the Name of the Field the StructurBrowser should be in, in case of
* a TableTree.
*/
private String browserFieldName;
/**
* Holds the headers for the Table, in case of a TableTree.
*/
private final List<UITableHeader> headers = new ArrayList<UITableHeader>();
/**
* Holds the SortDirection for the Headers.
*/
private SortDirection sortDirection = SortDirection.ASCENDING;
/**
* This instance variable holds, if this StructurBrowserModel is the Root of
* a tree.
*/
private final boolean root;
/**
* Holds the Value for the Label as it is difined in the DBProperties.
*/
private String valueLabel;
/**
* Contains the url for the Image that will be presented in GUI.
*/
private String image;
/**
* this instrance variable is used as a <b>TriState</b>, to determine if the
* Model should show the direction of this Model as Child in comparisment to
* the parent.<br>
* The tristate is used as follows: <li><b>null</b>: no direction will be
* shown</li> <li><b>true</b>: an arrow showing downwards, will be rendered</li>
* <li><b>false</b>: an arrow showing upwards, will be rendered</li>
*/
private Boolean direction = null;
/**
* Stores the actual execution status.
*/
private ExecutionStatus executionStatus;
/**
* Is this model expanded.
*/
private boolean expanded;
/**
* The index of the column containing the browser.
*/
private int browserFieldIndex;
/**
* This Row is used in case of edit to create new empty rows for the root.
*/
private UIStructurBrowser emptyRow;
/**
* If true the tree is always expanded and the inks for expand and
* collapse will not work.
*/
private boolean forceExpanded = false;
/**
* Stores if the StructurBrowser should show CheckBoxes.
*/
private boolean showCheckBoxes = false;
/**
* Constructor.
*
* @param _parameters Page parameters
* @throws EFapsException on error
*/
public UIStructurBrowser(final PageParameters _parameters)
throws EFapsException
{
super(_parameters);
this.root = true;
initialise();
}
/**
* Standard constructor, if called this StructurBrowserModel will be defined
* as root.
*
* @param _commandUUID UUID of the calling command
* @param _instanceKey oid
* @throws EFapsException on error
*
*/
public UIStructurBrowser(final UUID _commandUUID,
final String _instanceKey)
throws EFapsException
{
this(_commandUUID, _instanceKey, true, SortDirection.ASCENDING);
}
/**
* Internal constructor, it is used to set that this StructurBrowserModel is
* not a root.
*
* @param _commandUUID UUID of the command
* @param _instanceKey OID
* @param _root is this STrtucturbrowser the root
* @param _sortdirection sort direction
* @throws EFapsException on error
*/
protected UIStructurBrowser(final UUID _commandUUID,
final String _instanceKey,
final boolean _root,
final SortDirection _sortdirection)
throws EFapsException
{
super(_commandUUID, _instanceKey);
this.root = _root;
if (isRoot()) {
this.allowChilds = true;
}
this.sortDirection = _sortdirection;
initialise();
}
/**
* Internal method to call a constructor, it is used to set that this
* StructurBrowserModel is not a root.
*
* @param _instance Instance
* @param _strucBrwsr StructurBrowser the values will be copied from
* @return UIStructurBrowser
* @throws EFapsException on error
*/
protected UIStructurBrowser getNewStructurBrowser(final Instance _instance,
final UIStructurBrowser _strucBrwsr)
throws EFapsException
{
final UUID uuid;
if (_strucBrwsr.getTable() == null) {
uuid = Menu.getTypeTreeMenu(_instance.getType()).getUUID();
} else {
uuid = _strucBrwsr.getCommandUUID();
}
return new UIStructurBrowser(uuid, _instance == null ? null : _instance.getKey(), false,
_strucBrwsr.getSortDirection());
}
/**
* Method used to initialize this StructurBrowserModel.
*
* @throws EFapsException on error
*/
protected void initialise()
throws EFapsException
{
final AbstractCommand command = getCommand();
if ((command != null) && (command.getTargetTable() != null)) {
this.tableuuid = command.getTargetTable().getUUID();
this.browserFieldName = command.getTargetStructurBrowserField();
this.showCheckBoxes = command.isTargetShowCheckBoxes();
} else if (getInstance() != null) {
final String tmplabel = Menu.getTypeTreeMenu(getInstance().getType()).getLabel();
this.valueLabel = DBProperties.getProperty(tmplabel);
}
}
/**
* This method should be called to actually execute this
* StructurBrowserModel, that means to retrieve the values from the
* eFaps-DataBase, create the TreeModel etc. This method actually calls
* depending if we have a Tree or a TreeTabel the Methodes
* {@link #executeTree(List)} or {@link #executeTreeTable(List)}
*
* @see #executeTree(List)
* @see #executeTreeTable(List)
*/
@Override
@SuppressWarnings("unchecked")
public void execute()
{
setExecutionStatus(UIStructurBrowser.ExecutionStatus.EXECUTE);
List<Return> ret;
try {
if (this.tableuuid == null) {
final Map<Instance, Boolean> map = new LinkedHashMap<Instance, Boolean>();
map.put(getInstance(), null);
executeTree(map, false);
} else {
final Map<Instance, Boolean> map = new LinkedHashMap<Instance, Boolean>();
if (!isCreateMode()) {
ret = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.CLASS, this,
ParameterValues.INSTANCE, getInstance());
map.putAll((Map<Instance, Boolean>) ret.get(0).get(ReturnValues.VALUES));
}
executeTreeTable(map, false);
}
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
}
/**
* This method is called in case of a Tree from the {@link #execute()}method
* to fill this StructurBrowserModel with live.
*
* @param _map List of Object
* @param _expand inside an expand
*/
protected void executeTree(final Map<Instance, Boolean> _map,
final boolean _expand)
{
try {
final List<Instance> instances = new ArrayList<Instance>();
for (final Instance inst : _map.keySet()) {
instances.add(inst);
}
final ValueParser parser = new ValueParser(new StringReader(this.valueLabel));
final ValueList valuelist = parser.ExpressionString();
final MultiPrintQuery print = new MultiPrintQuery(instances);
valuelist.makeSelect(print);
print.execute();
while (print.next()) {
Object value = null;
final Instance instance = print.getCurrentInstance();
value = valuelist.makeString(getInstance(), print, getMode());
final UIStructurBrowser child = getNewStructurBrowser(instance, this);
this.childs.add(child);
child.setDirection(_map.get(instance));
child.setLabel(value.toString());
child.setAllowChilds(checkForAllowChilds(instance));
if (isAllowChilds()) {
child.setParent(checkForChildren(instance));
}
child.setImage(Image.getTypeIcon(instance.getType()) != null ? Image.getTypeIcon(instance.getType())
.getUrl() : null);
}
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
} catch (final ParseException e) {
throw new RestartResponseException(new ErrorPage(e));
}
sortModel();
expand(_expand);
super.setInitialized(true);
}
/**
* This method is called in case of a TreeTable from the {@link #execute()}
* method to fill this StructurBrowserModel with live.
*
* @param _map List of Objects
* @param _expand inside an expand
*/
protected void executeTreeTable(final Map<Instance, Boolean> _map,
final boolean _expand)
{
try {
final List<Instance> instances = new ArrayList<Instance>();
for (final Instance inst : _map.keySet()) {
instances.add(inst);
}
// evaluate for all expressions in the table
final MultiPrintQuery print = new MultiPrintQuery(instances);
Type type = instances.isEmpty() ? null : instances.get(0).getType();
for (final Field field : getTable().getFields()) {
Attribute attr = null;
if (field.hasAccess(getMode(), getInstance())
&& !field.isNoneDisplay(getMode()) && !field.isHiddenDisplay(getMode())) {
if (_map.size() > 0) {
if (field.getSelect() != null) {
print.addSelect(field.getSelect());
} else if (field.getAttribute() != null) {
print.addAttribute(field.getAttribute());
} else if (field.getPhrase() != null) {
print.addPhrase(field.getName(), field.getPhrase());
}
if (field.getSelectAlternateOID() != null) {
print.addSelect(field.getSelectAlternateOID());
}
}
if (field.getAttribute() != null && type != null) {
attr = type.getAttribute(field.getAttribute());
}
if (isRoot()) {
this.headers.add(new UITableHeader(field, this.sortDirection, attr));
}
}
}
boolean row4Create = false;
if (!print.execute()) {
row4Create = isCreateMode();
type = getTypeFromEvent();
}
Attribute attr = null;
while (print.next() || row4Create) {
Instance instance = print.getCurrentInstance();
final UIStructurBrowser child = getNewStructurBrowser(instance, this);
child.setDirection(_map.get(instance));
for (final Field field : getTable().getFields()) {
if (field.hasAccess(getMode(), getInstance())
&& !field.isNoneDisplay(getMode()) && !field.isHiddenDisplay(getMode())) {
Object value = null;
if (row4Create) {
if (field.getAttribute() != null && type != null) {
attr = type.getAttribute(field.getAttribute());
}
} else {
//the previous field might have set the different instance
if (field.getSelectAlternateOID() == null) {
instance = print.getCurrentInstance();
} else {
instance = Instance.get(print.<String>getSelect(field.getSelectAlternateOID()));
}
if (field.getSelect() != null) {
value = print.getSelect(field.getSelect());
attr = print.getAttribute4Select(field.getSelect());
} else if (field.getAttribute() != null) {
value = print.getAttribute(field.getAttribute());
attr = print.getAttribute4Attribute(field.getAttribute());
} else if (field.getPhrase() != null) {
value = print.getPhrase(field.getName());
}
}
final FieldValue fieldvalue = new FieldValue(field, attr, value, instance, getInstance());
String strValue;
String htmlTitle;
if (value != null || row4Create || isEditMode()) {
if ((isCreateMode() || isEditMode()) && field.isEditableDisplay(getMode())) {
strValue = fieldvalue.getEditHtml(getMode());
htmlTitle = fieldvalue.getStringValue(getMode());
} else if (field.isHiddenDisplay(getMode())) {
strValue = fieldvalue.getHiddenHtml(getMode());
htmlTitle = "";
} else {
strValue = fieldvalue.getReadOnlyHtml(getMode());
htmlTitle = fieldvalue.getStringValue(getMode());
}
} else {
strValue = "";
htmlTitle = "";
}
String icon = field.getIcon();
if (field.isShowTypeIcon()) {
final Image cellIcon = Image.getTypeIcon(instance.getType());
if (cellIcon != null) {
icon = cellIcon.getUrl();
}
}
final UIStructurBrowserTableCell cell = new UIStructurBrowserTableCell(child, fieldvalue,
instance, strValue, htmlTitle, icon);
if (field.getName().equals(this.browserFieldName)) {
child.setLabel(strValue);
child.setAllowChilds(checkForAllowChilds(instance));
if (child.isAllowChilds()) {
child.setParent(checkForChildren(instance));
}
if (row4Create) {
child.setImage(Image.getTypeIcon(type) != null
? Image.getTypeIcon(type).getUrl() : null);
} else {
child.setImage(Image.getTypeIcon(instance.getType()) != null ? Image.getTypeIcon(
instance.getType()).getUrl() : null);
}
cell.setBrowserField(true);
child.browserFieldIndex = child.getColumns().size();
}
child.getColumns().add(cell);
}
}
if (this.root && row4Create) {
this.emptyRow = child;
} else if (this.root && isEditMode() && this.emptyRow == null) {
this.emptyRow = child;
this.childs.add(child);
} else {
this.childs.add(child);
}
row4Create = false;
child.checkHideColumn4Row();
}
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
sortModel();
expand(_expand);
super.setInitialized(true);
}
/**
* Expand the tree with the information from the Session.
* @param _expand is this inside an expand
*/
@SuppressWarnings("unchecked")
protected void expand(final boolean _expand)
{
try {
// only if the element was opened the first time e.g. reload etc.
if ((isRoot() || _expand)
&& (Context.getThreadContext().containsSessionAttribute(getCacheKey()) || this.forceExpanded)) {
final Map<String, Boolean> sessMap = (Map<String, Boolean>) Context
.getThreadContext().getSessionAttribute(getCacheKey());
for (final UIStructurBrowser uiChild : this.childs) {
if (sessMap == null || sessMap.containsKey(uiChild.getInstanceKey())) {
final Boolean expandedTmp = sessMap == null ? true : sessMap.get(uiChild.getInstanceKey());
if (expandedTmp != null && expandedTmp && uiChild.isParent()) {
uiChild.setExecutionStatus(UIStructurBrowser.ExecutionStatus.ADDCHILDREN);
final List<Return> ret = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE,
ParameterValues.INSTANCE, uiChild.getInstance(),
ParameterValues.CLASS, uiChild);
final Map<Instance, Boolean> map = (Map<Instance, Boolean>) ret.get(0).get(
ReturnValues.VALUES);
uiChild.setExpanded(true);
if (uiChild.tableuuid == null) {
uiChild.executeTree(map, true);
} else {
uiChild.executeTreeTable(map, true);
}
}
}
}
}
} catch (final EFapsException e) {
UIStructurBrowser.LOG.error("Error retreiving Session info for StruturBrowser from Command with UUID: {}",
getCommandUUID(), e);
}
}
/**
* Method to sort the data of this model. It calls an esjp for sorting.
*/
protected void sortModel()
{
setExecutionStatus(UIStructurBrowser.ExecutionStatus.SORT);
try {
getCommand().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.CLASS, this);
if (getSortDirection() == SortDirection.DESCENDING) {
Collections.reverse(this.childs);
}
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
}
/**
* Method to sort this model and all child models.
*/
public void sort()
{
sortModel();
for (final UIStructurBrowser child : this.childs) {
child.sort();
}
}
/**
* @return UIStructurBrowser
* @throws EFapsException on error
*/
public UIStructurBrowser getClone4New()
throws EFapsException
{
final UIStructurBrowser parentTmp;
if (this.root) {
parentTmp = this.emptyRow;
} else {
parentTmp = this;
}
final UIStructurBrowser ret = getNewStructurBrowser(null, parentTmp);
ret.initialise();
for (final UIStructurBrowserTableCell col : parentTmp.columns) {
final FieldValue fieldValue = new FieldValue(col.getField(), col.getAttribute(), null, null, null);
final String htmlValue;
if (col.getDisplay().equals(Display.EDITABLE)) {
htmlValue = fieldValue.getEditHtml(getMode());
} else {
htmlValue = fieldValue.getReadOnlyHtml(getMode());
}
final String htmlTitle = fieldValue.getStringValue(getMode());
final UIStructurBrowserTableCell newCol = new UIStructurBrowserTableCell(ret, fieldValue, null,
htmlValue, htmlTitle, "");
newCol.setBrowserField(col.isBrowserField());
ret.setBrowserFieldIndex(parentTmp.getBrowserFieldIndex());
ret.getColumns().add(newCol);
}
return ret;
}
/**
* Getter method for the instance variable {@link #forceExpanded}.
*
* @return value of instance variable {@link #forceExpanded}
*/
public boolean isForceExpanded()
{
return this.forceExpanded;
}
/**
* Setter method for instance variable {@link #forceExpanded}.
*
* @param _forceExpanded value for instance variable {@link #forceExpanded}
*/
protected void setForceExpanded(final boolean _forceExpanded)
{
this.forceExpanded = _forceExpanded;
}
/**
* Getter method for the instance variable {@link #allowChilds}.
*
* @return value of instance variable {@link #allowChilds}
*/
public boolean isAllowChilds()
{
return this.allowChilds;
}
/**
* Setter method for instance variable {@link #allowChilds}.
*
* @param _allowChilds value for instance variable {@link #allowChilds}
*/
public void setAllowChilds(final boolean _allowChilds)
{
this.allowChilds = _allowChilds;
}
/**
* Method used to evaluate the type for this table from the connected
* events.
*
* @return type if found
* @throws EFapsException on error
*/
protected Type getTypeFromEvent()
throws EFapsException
{
final List<EventDefinition> events = getObject4Event().getEvents(EventType.UI_TABLE_EVALUATE);
String typeName = null;
if (events.size() > 1) {
throw new EFapsException(this.getClass(), "execute4NoInstance.moreThanOneEvaluate");
} else {
final EventDefinition event = events.get(0);
if (event.getProperty("Types") != null) {
typeName = event.getProperty("Types").split(";")[0];
}
}
return Type.get(typeName);
}
/**
* Method is called from the StructurBrowser in edit mode before rendering
* the columns for row to be able to hide the columns for different rows by
* setting the cell model to hide.
*/
public void checkHideColumn4Row()
{
setExecutionStatus(UIStructurBrowser.ExecutionStatus.CHECKHIDECOLUMN4ROW);
try {
getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE,
ParameterValues.INSTANCE, getInstance(),
ParameterValues.CLASS, this);
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
}
/**
* This method should be called to add children to a Node in the Tree.<br>
* e.g. in a standard implementation the children would be added to the Tree
* on the expand-Event of the tree. The children a retrieved from an esjp
* with the EventType UI_TABLE_EVALUATE.
*
* @param _parent the DefaultMutableTreeNode the new children should be
* added
*/
@SuppressWarnings("unchecked")
public void addChildren(final DefaultMutableTreeNode _parent)
{
setExecutionStatus(UIStructurBrowser.ExecutionStatus.ADDCHILDREN);
_parent.removeAllChildren();
List<Return> ret;
try {
ret = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.INSTANCE, getInstance(),
ParameterValues.CLASS, this);
final Map<Instance, Boolean> map = (Map<Instance, Boolean>) ret.get(0).get(ReturnValues.VALUES);
if (this.tableuuid == null) {
executeTree(map, false);
} else {
executeTreeTable(map, false);
}
addNode(_parent, this.childs);
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
}
/**
* This method is used to check if a node has potential children.
*
* @param _instance Instance of a Node to be checked
* @return true if this Node has children, else false
*/
protected boolean checkForAllowChilds(final Instance _instance)
{
setExecutionStatus(UIStructurBrowser.ExecutionStatus.ALLOWSCHILDREN);
try {
final List<Return> ret = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE,
ParameterValues.INSTANCE, _instance,
ParameterValues.CLASS, this);
return ret.isEmpty() ? false : ret.get(0).get(ReturnValues.TRUE) != null;
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
}
/**
* This method is used to check if a node has potential children.
*
* @param _instance Instance of a Node to be checked
* @return true if this Node has children, else false
*/
protected boolean checkForChildren(final Instance _instance)
{
setExecutionStatus(UIStructurBrowser.ExecutionStatus.CHECKFORCHILDREN);
try {
final List<Return> ret = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE,
ParameterValues.INSTANCE, _instance,
ParameterValues.CLASS, this);
return ret.isEmpty() ? false : ret.get(0).get(ReturnValues.TRUE) != null;
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
}
/**
* Method is called from the StructurBrowser in edit mode from
* {@link #setValuesFromUI(Map, DefaultMutableTreeNode)} to get
* additional JavaScript to be appended to the AjaxTarget.
* @param _parameters Parameter as send from the UserInterface
* @return JavaScript for the UserInterface
*/
protected String getJavaScript4Target(final Map<String, String[]> _parameters)
{
String ret;
setExecutionStatus(UIStructurBrowser.ExecutionStatus.GETJAVASCRIPT4TARGET);
try {
final List<Return> retList = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE,
ParameterValues.INSTANCE, getInstance(),
ParameterValues.CLASS, this,
ParameterValues.PARAMETERS, _parameters);
ret = (String) retList.get(0).get(ReturnValues.SNIPLETT);
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
return ret;
}
/**
* This is the getter method for the instance variable {@link #parent}.
*
* @return value of instance variable {@link #parent}
*/
private boolean isParent()
{
return this.parent;
}
/**
* This is the setter method for the instance variable {@link #parent}.
*
* @param _parent the parent to set
*/
public void setParent(final boolean _parent)
{
this.parent = _parent;
}
/**
* Method to reset the Model.
*
* @see org.efaps.ui.wicket.models.AbstractModel#resetModel()
*/
@Override
public void resetModel()
{
this.childs.clear();
}
/**
* This is the getter method for the instance variable {@link #table}.
*
* @return value of instance variable {@link #table}
* @see #table
*/
public Table getTable()
{
return Table.get(this.tableuuid);
}
/**
* Has this StructurBrowserModel childs.
*
* @return true if has children, else false
*/
public boolean hasChilds()
{
return !this.childs.isEmpty();
}
/**
* Get the TreeModel used in the Component to construct the actual tree.
*
* @see #addNode(DefaultMutableTreeNode, List)
* @return TreeModel of this StructurBrowseModel
*/
public TreeModel getTreeModel()
{
DefaultTreeModel model = null;
final DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(this);
rootNode.setAllowsChildren(true);
if (this.childs.size() > 0) {
addNode(rootNode, this.childs);
}
model = new DefaultTreeModel(rootNode);
model.setAsksAllowsChildren(true);
return model;
}
/**
* Recursive method used to fill the TreeModel.
*
* @see #getTreeModel()
* @param _parent ParentNode children should be added
* @param _childs to be added as childs
*/
private void addNode(final DefaultMutableTreeNode _parent,
final List<UIStructurBrowser> _childs)
{
for (final UIStructurBrowser child : _childs) {
final DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child);
_parent.add(childNode);
if (child.hasChilds()) {
addNode(childNode, child.getChilds());
} else if (child.isParent()) {
childNode.setAllowsChildren(true);
childNode.add(new BogusNode());
}
childNode.setAllowsChildren(child.isAllowChilds());
}
}
/**
* @param _parameters Parameter as send from the UserInterface
* @param _node Node the _parameters were send from
* @throws EFapsException on error
* @return JavaScript for the UserInterface
*/
public String setValuesFromUI(final Map<String, String[]> _parameters,
final DefaultMutableTreeNode _node)
throws EFapsException
{
final Enumeration<?> preOrdEnum = ((DefaultMutableTreeNode) _node.getRoot()).preorderEnumeration();
int i = 0;
while (preOrdEnum.hasMoreElements()) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode) preOrdEnum.nextElement();
if (!node.isRoot()) {
final UIStructurBrowser uiObject = (UIStructurBrowser) node.getUserObject();
for (final UIStructurBrowserTableCell cell : uiObject.getColumns()) {
final String[] values = _parameters.get(cell.getName());
if (cell.isAutoComplete()) {
final String[] autoValues = _parameters.get(cell.getName() + "AutoComplete");
cell.setCellTitle(autoValues[i]);
cell.setInstanceKey(values[i]);
} else {
if (values != null) {
cell.setValueFromUI(values[i]);
}
}
}
i++;
}
}
return getJavaScript4Target(_parameters);
}
/**
* Get the Value of a Column identified by the index of the Column.
*
* @param _index index of the Column
* @return String with the Value of the Column
*/
public UIStructurBrowserTableCell getColumnValue(final int _index)
{
return this.columns.isEmpty() ? null : this.columns.get(_index);
}
/**
* This is the setter method for the instance variable {@link #label}.
*
* @param _label the label to set
*/
private void setLabel(final String _label)
{
this.label = _label;
}
/**
* This is the getter method for the instance variable {@link #columns}.
*
* @return value of instance variable {@link #columns}
*/
public List<UIStructurBrowserTableCell> getColumns()
{
return this.columns;
}
/**
* Setter method for instance variable {@link #browserFieldName}.
*
* @param _browserFieldName value for instance variable {@link #browserFieldName}
*/
protected void setBrowserFieldName(final String _browserFieldName)
{
this.browserFieldName = _browserFieldName;
}
/**
* Setter method for instance variable {@link #tableuuid}.
*
* @param _tableuuid value for instance variable {@link #tableuuid}
*/
protected void setTableuuid(final UUID _tableuuid)
{
this.tableuuid = _tableuuid;
}
/**
* Setter method for instance variable {@link #browserFieldIndex}.
*
* @param _browserFieldIndex value for instance variable {@link #browserFieldIndex}
*/
protected void setBrowserFieldIndex(final int _browserFieldIndex)
{
this.browserFieldIndex = _browserFieldIndex;
}
/**
* Getter method for the instance variable {@link #browserFieldIndex}.
*
* @return value of instance variable {@link #browserFieldIndex}
*/
public int getBrowserFieldIndex()
{
return this.browserFieldIndex;
}
/**
* This is the getter method for the instance variable
* {@link #browserFieldName}.
*
* @return value of instance variable {@link #browserFieldName}
*/
public String getBrowserFieldName()
{
return this.browserFieldName;
}
/**
* This is the getter method for the instance variable {@link #headers}.
*
* @return value of instance variable {@link #headers}
*/
public List<UITableHeader> getHeaders()
{
return this.headers;
}
/**
* This is the getter method for the instance variable {@link #image}.
*
* @return value of instance variable {@link #image}
*/
public String getImage()
{
return this.image;
}
/**
* This is the setter method for the instance variable {@link #image}.
*
* @param _url the url of the image to set
*/
private void setImage(final String _url)
{
if (_url != null) {
this.image = RequestHandler.replaceMacrosInUrl(_url);
}
}
/**
* This is the getter method for the instance variable {@link #direction}.
*
* @return value of instance variable {@link #direction}
*/
public Boolean getDirection()
{
return this.direction;
}
/**
* This is the setter method for the instance variable {@link #direction}.
*
* @param _direction the direction to set
*/
public void setDirection(final Boolean _direction)
{
this.direction = _direction;
}
/**
* Getter method for instance variable {@link #executionStatus}.
*
* @return value of instance variable {@link #executionStatus}
*/
public ExecutionStatus getExecutionStatus()
{
return this.executionStatus;
}
/**
* This method is updating the Label, by querying the eFaps-DataBase.
*/
public void requeryLabel()
{
try {
final ValueParser parser = new ValueParser(new StringReader(this.valueLabel));
final ValueList valList = parser.ExpressionString();
final PrintQuery print = new PrintQuery(getInstance());
valList.makeSelect(print);
if (print.execute()) {
setLabel(valList.makeString(getInstance(), print, getMode()).toString());
}
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
} catch (final ParseException e) {
throw new RestartResponseException(new ErrorPage(e));
}
}
/**
* Method to add a new BogusNode to the given Node.
*
* @param _parent Parent a BogusNode should be added
*/
public void addBogusNode(final DefaultMutableTreeNode _parent)
{
_parent.add(new BogusNode());
}
/**
* Getter method for instance variable {@link #childs}.
*
* @return value of instance variable {@link #childs}
*/
public List<UIStructurBrowser> getChilds()
{
return this.childs;
}
/**
* Getter method for instance variable {@link #label}.
*
* @return value of instance variable {@link #label}
*/
public String getLabel()
{
return this.label;
}
/**
* Getter method for instance variable {@link #sortDirection}.
*
* @return value of instance variable {@link #sortDirection}
*/
public SortDirection getSortDirection()
{
return this.sortDirection;
}
/**
* Setter method for instance variable {@link #sortDirection} and for all
* children also.
*
* @param _sortDirection value for instance variable {@link #sortDirection}
*/
public void setSortDirection(final SortDirection _sortDirection)
{
this.sortDirection = _sortDirection;
for (final UIStructurBrowser child : this.childs) {
child.setSortDirection(_sortDirection);
}
}
/**
* Getter method for instance variable {@link #expanded}.
*
* @return value of instance variable {@link #expanded}
*/
public boolean isExpanded()
{
return this.expanded;
}
/**
* Setter method for instance variable {@link #expanded}.
*
* @param _expanded value for instance variable {@link #expanded}
*/
public void setExpanded(final boolean _expanded)
{
this.expanded = _expanded;
storeInSession();
}
/**
* This method generates the Key for a UserAttribute by using the UUID of
* the Command and the given static part, so that for every StruturBrowser a
* unique key for expand etc, is created.
*
* @return String with the key
*/
public String getCacheKey()
{
return super.getCommandUUID() + "-" + UIStructurBrowser.USERSESSIONKEY;
}
/**
* Store the Information in the Session.
*/
@SuppressWarnings("unchecked")
private void storeInSession()
{
try {
if (!getMode().equals(TargetMode.CREATE)) {
final Map<String, Boolean> sessMap;
if (Context.getThreadContext().containsSessionAttribute(getCacheKey())) {
sessMap = (Map<String, Boolean>) Context.getThreadContext().getSessionAttribute(getCacheKey());
} else {
sessMap = new HashMap<String, Boolean>();
}
sessMap.put(getInstanceKey(), isExpanded());
Context.getThreadContext().setSessionAttribute(getCacheKey(), sessMap);
}
} catch (final EFapsException e) {
UIStructurBrowser.LOG.error("Error storing Session info for StruturBrowser called by Command with UUID: {}",
getCommandUUID(), e);
}
}
/**
* Setter method for instance variable {@link #executionStatus}.
*
* @param _executionStatus value for instance variable {@link #executionStatus}
*/
protected void setExecutionStatus(final ExecutionStatus _executionStatus)
{
this.executionStatus = _executionStatus;
}
/**
* Get the Admin Object that contains the events that must be executed.
*
* @return the Admin Object that contains the events to be executed
*/
protected AbstractAdminObject getObject4Event()
{
return this.getCommand();
}
/**
* Getter method for the instance variable {@link #root}.
*
* @return value of instance variable {@link #root}
*/
public boolean isRoot()
{
return this.root;
}
/**
* @return <i>true</i> if the check boxes must be shown, other <i>false</i>
* is returned.
* @see #showCheckBoxes
*/
public boolean isShowCheckBoxes()
{
boolean ret;
if (super.isSubmit() && !isCreateMode()) {
ret = true;
} else {
ret = this.showCheckBoxes;
}
return ret;
}
/**
* Setter method for instance variable {@link #showCheckBoxes}.
*
* @param _showCheckBoxes value for instance variable {@link #showCheckBoxes}
*/
protected void setShowCheckBoxes(final boolean _showCheckBoxes)
{
this.showCheckBoxes = _showCheckBoxes;
}
/**
* In create or edit mode this StructurBrowser is editable.
*
* @return is this StructurBrowser editable.
*/
public boolean isEditable()
{
return isCreateMode() || isEditMode();
}
/**
* (non-Javadoc).
*
* @see org.apache.wicket.model.Model#toString()
* @return label
*/
@Override
public String toString()
{
return this.label;
}
/**
* This class is used to add a ChildNode under a ParentNode, if the
* ParentNode actually has some children. By using this class it then can
* very easy be distinguished between Nodes which where expanded and Nodes
* which still need to be expanded.
*
*/
public class BogusNode
extends DefaultMutableTreeNode
{
/**
* Needed for serialization.
*/
private static final long serialVersionUID = 1L;
}
}
| src/main/java/org/efaps/ui/wicket/models/objects/UIStructurBrowser.java | /*
* Copyright 2003 - 2010 The eFaps Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package org.efaps.ui.wicket.models.objects;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import org.apache.wicket.PageParameters;
import org.apache.wicket.RestartResponseException;
import org.efaps.admin.AbstractAdminObject;
import org.efaps.admin.datamodel.Attribute;
import org.efaps.admin.datamodel.Type;
import org.efaps.admin.datamodel.ui.FieldValue;
import org.efaps.admin.dbproperty.DBProperties;
import org.efaps.admin.event.EventDefinition;
import org.efaps.admin.event.EventType;
import org.efaps.admin.event.Parameter.ParameterValues;
import org.efaps.admin.event.Return;
import org.efaps.admin.event.Return.ReturnValues;
import org.efaps.admin.ui.AbstractCommand;
import org.efaps.admin.ui.AbstractCommand.SortDirection;
import org.efaps.admin.ui.AbstractUserInterfaceObject.TargetMode;
import org.efaps.admin.ui.Image;
import org.efaps.admin.ui.Menu;
import org.efaps.admin.ui.Table;
import org.efaps.admin.ui.field.Field;
import org.efaps.admin.ui.field.Field.Display;
import org.efaps.beans.ValueList;
import org.efaps.beans.valueparser.ParseException;
import org.efaps.beans.valueparser.ValueParser;
import org.efaps.db.Context;
import org.efaps.db.Instance;
import org.efaps.db.MultiPrintQuery;
import org.efaps.db.PrintQuery;
import org.efaps.ui.wicket.models.cell.UIStructurBrowserTableCell;
import org.efaps.ui.wicket.pages.error.ErrorPage;
import org.efaps.util.EFapsException;
import org.efaps.util.RequestHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is used to provide the Model for the StructurBrowser for eFpas. <br>
* It is used in tow different cases. In one case it is a TreeTable, where the
* Table will be provided with additional information in columns. In the other
* case a Tree only.<br>
* The concept of this class is to provide a Model which connects through the
* eFaps-kernel to the eFaps-DataBase and turn it to a Standard TreeModel from
* <code>javax.swing.tree</code>. which will be used from the Component to
* render the Tree and the Table. This leads to a very similar behavior of the
* WebApp GUI to a swing GUI. <br>
* This model works asyncron. That means only the actually in the GUI rendered
* Nodes (and Columns) will be retrieved from the eFaps-DataBase. The next level
* in a tree will be retrieved on the expand of a TreeNode. To achieve this and
* to be able to render expand-links for every node it will only be checked if
* it is a potential parent (if it has children). In the case of expanding this
* Node the children will be retrieved and rendered.<br>
* To access the eFaps-Database a esjp is used, which will be used in five
* different cases. To distinguish the use of the esjp some extra Parameters
* will be passed to the esjp when calling it.
*
* @author The eFaps Team
* @version $Id$
*/
public class UIStructurBrowser
extends AbstractUIPageObject
{
/**
* Enum is used to set for this UIStructurBrowser which status of execution
* it is in.
*/
public enum ExecutionStatus {
/** Method addChildren is executed. */
ADDCHILDREN,
/** Method addChildren is executed. */
ALLOWSCHILDREN,
/** Method checkForChildren is executed. */
CHECKFORCHILDREN,
/** Method is creating a new folder. */
CHECKHIDECOLUMN4ROW,
/**
* Method is called after the insert etc. of a new node in edit mode to
* get a JavaScript that will be appended to the AjaxTarget. In this
* Step the values for the StructurBrowsers also can be altered.
* @see {@link UIStructurBrowser.#setValuesFromUI(Map, DefaultMutableTreeNode)setValuesFromUI}
*/
GETJAVASCRIPT4TARGET,
/** Method execute is executed. */
EXECUTE,
/** Method sort is executed. */
SORT;
}
/**
* Static part of the key to get the Information stored in the session
* in relation to this StruturBrowser.
*/
public static final String USERSESSIONKEY = "eFapsUIStructurBrowser";
/**
* Logging instance used in this class.
*/
private static final Logger LOG = LoggerFactory.getLogger(UIStructurBrowser.class);
/**
* Needed for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* The instance variable stores the UUID for the table which must be shown.
*
* @see #getTable
*/
private UUID tableuuid;
/**
* This instance variable holds if this StructurBrowserModel can have
* children at all.
*/
private boolean allowChilds;
/**
* This instance variable holds if this StructurBrowserModel is a
* parent, this is needed because, first it will be only determined if a
* node is a potential parent, and later on the childs will be retrieved
* from the eFaps-DataBase.
*
* @see #isParent()
*/
private boolean parent;
/**
* This instance variable holds the childs of this StructurBrowserModel.
*/
private final List<UIStructurBrowser> childs = new ArrayList<UIStructurBrowser>();
/**
* Holds the columns in case of a TableTree.
*/
private final List<UIStructurBrowserTableCell> columns = new ArrayList<UIStructurBrowserTableCell>();
/**
* Holds the label of the Node which will be presented in the GUI.
*
* @see #toString()
* @see #getLabel()
* @see #setLabel(String)
* @see #requeryLabel()
*/
private String label;
/**
* Holds the Name of the Field the StructurBrowser should be in, in case of
* a TableTree.
*/
private String browserFieldName;
/**
* Holds the headers for the Table, in case of a TableTree.
*/
private final List<UITableHeader> headers = new ArrayList<UITableHeader>();
/**
* Holds the SortDirection for the Headers.
*/
private SortDirection sortDirection = SortDirection.ASCENDING;
/**
* This instance variable holds, if this StructurBrowserModel is the Root of
* a tree.
*/
private final boolean root;
/**
* Holds the Value for the Label as it is difined in the DBProperties.
*/
private String valueLabel;
/**
* Contains the url for the Image that will be presented in GUI.
*/
private String image;
/**
* this instrance variable is used as a <b>TriState</b>, to determine if the
* Model should show the direction of this Model as Child in comparisment to
* the parent.<br>
* The tristate is used as follows: <li><b>null</b>: no direction will be
* shown</li> <li><b>true</b>: an arrow showing downwards, will be rendered</li>
* <li><b>false</b>: an arrow showing upwards, will be rendered</li>
*/
private Boolean direction = null;
/**
* Stores the actual execution status.
*/
private ExecutionStatus executionStatus;
/**
* Is this model expanded.
*/
private boolean expanded;
/**
* The index of the column containing the browser.
*/
private int browserFieldIndex;
/**
* This Row is used in case of edit to create new empty rows for the root.
*/
private UIStructurBrowser emptyRow;
/**
* If true the tree is always expanded and the inks for expand and
* collapse will not work.
*/
private boolean forceExpanded = false;
/**
* Stores if the StructurBrowser should show CheckBoxes.
*/
private boolean showCheckBoxes = false;
/**
* Constructor.
*
* @param _parameters Page parameters
* @throws EFapsException on error
*/
public UIStructurBrowser(final PageParameters _parameters)
throws EFapsException
{
super(_parameters);
this.root = true;
initialise();
}
/**
* Standard constructor, if called this StructurBrowserModel will be defined
* as root.
*
* @param _commandUUID UUID of the calling command
* @param _instanceKey oid
* @throws EFapsException on error
*
*/
public UIStructurBrowser(final UUID _commandUUID,
final String _instanceKey)
throws EFapsException
{
this(_commandUUID, _instanceKey, true, SortDirection.ASCENDING);
}
/**
* Internal constructor, it is used to set that this StructurBrowserModel is
* not a root.
*
* @param _commandUUID UUID of the command
* @param _instanceKey OID
* @param _root is this STrtucturbrowser the root
* @param _sortdirection sort direction
* @throws EFapsException on error
*/
protected UIStructurBrowser(final UUID _commandUUID,
final String _instanceKey,
final boolean _root,
final SortDirection _sortdirection)
throws EFapsException
{
super(_commandUUID, _instanceKey);
this.root = _root;
if (isRoot()) {
this.allowChilds = true;
}
this.sortDirection = _sortdirection;
initialise();
}
/**
* Internal method to call a constructor, it is used to set that this
* StructurBrowserModel is not a root.
*
* @param _instance Instance
* @param _strucBrwsr StructurBrowser the values will be copied from
* @return UIStructurBrowser
* @throws EFapsException on error
*/
protected UIStructurBrowser getNewStructurBrowser(final Instance _instance,
final UIStructurBrowser _strucBrwsr)
throws EFapsException
{
final UUID uuid;
if (_strucBrwsr.getTable() == null) {
uuid = Menu.getTypeTreeMenu(_instance.getType()).getUUID();
} else {
uuid = _strucBrwsr.getCommandUUID();
}
return new UIStructurBrowser(uuid, _instance == null ? null : _instance.getKey(), false,
_strucBrwsr.getSortDirection());
}
/**
* Method used to initialize this StructurBrowserModel.
*
* @throws EFapsException on error
*/
protected void initialise()
throws EFapsException
{
final AbstractCommand command = getCommand();
if ((command != null) && (command.getTargetTable() != null)) {
this.tableuuid = command.getTargetTable().getUUID();
this.browserFieldName = command.getTargetStructurBrowserField();
this.showCheckBoxes = command.isTargetShowCheckBoxes();
} else if (getInstance() != null) {
final String tmplabel = Menu.getTypeTreeMenu(getInstance().getType()).getLabel();
this.valueLabel = DBProperties.getProperty(tmplabel);
}
}
/**
* This method should be called to actually execute this
* StructurBrowserModel, that means to retrieve the values from the
* eFaps-DataBase, create the TreeModel etc. This method actually calls
* depending if we have a Tree or a TreeTabel the Methodes
* {@link #executeTree(List)} or {@link #executeTreeTable(List)}
*
* @see #executeTree(List)
* @see #executeTreeTable(List)
*/
@Override
@SuppressWarnings("unchecked")
public void execute()
{
setExecutionStatus(UIStructurBrowser.ExecutionStatus.EXECUTE);
List<Return> ret;
try {
if (this.tableuuid == null) {
final Map<Instance, Boolean> map = new LinkedHashMap<Instance, Boolean>();
map.put(getInstance(), null);
executeTree(map, false);
} else {
final Map<Instance, Boolean> map = new LinkedHashMap<Instance, Boolean>();
if (!isCreateMode()) {
ret = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.CLASS, this,
ParameterValues.INSTANCE, getInstance());
map.putAll((Map<Instance, Boolean>) ret.get(0).get(ReturnValues.VALUES));
}
executeTreeTable(map, false);
}
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
}
/**
* This method is called in case of a Tree from the {@link #execute()}method
* to fill this StructurBrowserModel with live.
*
* @param _map List of Object
* @param _expand inside an expand
*/
protected void executeTree(final Map<Instance, Boolean> _map,
final boolean _expand)
{
try {
final List<Instance> instances = new ArrayList<Instance>();
for (final Instance inst : _map.keySet()) {
instances.add(inst);
}
final ValueParser parser = new ValueParser(new StringReader(this.valueLabel));
final ValueList valuelist = parser.ExpressionString();
final MultiPrintQuery print = new MultiPrintQuery(instances);
valuelist.makeSelect(print);
print.execute();
while (print.next()) {
Object value = null;
final Instance instance = print.getCurrentInstance();
value = valuelist.makeString(getInstance(), print, getMode());
final UIStructurBrowser child = getNewStructurBrowser(instance, this);
this.childs.add(child);
child.setDirection(_map.get(instance));
child.setLabel(value.toString());
child.setParent(checkForChildren(instance));
child.setImage(Image.getTypeIcon(instance.getType()) != null ? Image.getTypeIcon(instance.getType())
.getUrl() : null);
}
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
} catch (final ParseException e) {
throw new RestartResponseException(new ErrorPage(e));
}
sortModel();
expand(_expand);
super.setInitialized(true);
}
/**
* This method is called in case of a TreeTable from the {@link #execute()}
* method to fill this StructurBrowserModel with live.
*
* @param _map List of Objects
* @param _expand inside an expand
*/
protected void executeTreeTable(final Map<Instance, Boolean> _map,
final boolean _expand)
{
try {
final List<Instance> instances = new ArrayList<Instance>();
for (final Instance inst : _map.keySet()) {
instances.add(inst);
}
// evaluate for all expressions in the table
final MultiPrintQuery print = new MultiPrintQuery(instances);
Type type = instances.isEmpty() ? null : instances.get(0).getType();
for (final Field field : getTable().getFields()) {
Attribute attr = null;
if (field.hasAccess(getMode(), getInstance())
&& !field.isNoneDisplay(getMode()) && !field.isHiddenDisplay(getMode())) {
if (_map.size() > 0) {
if (field.getSelect() != null) {
print.addSelect(field.getSelect());
} else if (field.getAttribute() != null) {
print.addAttribute(field.getAttribute());
} else if (field.getPhrase() != null) {
print.addPhrase(field.getName(), field.getPhrase());
}
if (field.getSelectAlternateOID() != null) {
print.addSelect(field.getSelectAlternateOID());
}
}
if (field.getAttribute() != null && type != null) {
attr = type.getAttribute(field.getAttribute());
}
if (isRoot()) {
this.headers.add(new UITableHeader(field, this.sortDirection, attr));
}
}
}
boolean row4Create = false;
if (!print.execute()) {
row4Create = isCreateMode();
type = getTypeFromEvent();
}
Attribute attr = null;
while (print.next() || row4Create) {
Instance instance = print.getCurrentInstance();
final UIStructurBrowser child = getNewStructurBrowser(instance, this);
child.setDirection(_map.get(instance));
for (final Field field : getTable().getFields()) {
if (field.hasAccess(getMode(), getInstance())
&& !field.isNoneDisplay(getMode()) && !field.isHiddenDisplay(getMode())) {
Object value = null;
if (row4Create) {
if (field.getAttribute() != null && type != null) {
attr = type.getAttribute(field.getAttribute());
}
} else {
//the previous field might have set the different instance
if (field.getSelectAlternateOID() == null) {
instance = print.getCurrentInstance();
} else {
instance = Instance.get(print.<String>getSelect(field.getSelectAlternateOID()));
}
if (field.getSelect() != null) {
value = print.getSelect(field.getSelect());
attr = print.getAttribute4Select(field.getSelect());
} else if (field.getAttribute() != null) {
value = print.getAttribute(field.getAttribute());
attr = print.getAttribute4Attribute(field.getAttribute());
} else if (field.getPhrase() != null) {
value = print.getPhrase(field.getName());
}
}
final FieldValue fieldvalue = new FieldValue(field, attr, value, instance, getInstance());
String strValue;
String htmlTitle;
if (value != null || row4Create || isEditMode()) {
if ((isCreateMode() || isEditMode()) && field.isEditableDisplay(getMode())) {
strValue = fieldvalue.getEditHtml(getMode());
htmlTitle = fieldvalue.getStringValue(getMode());
} else if (field.isHiddenDisplay(getMode())) {
strValue = fieldvalue.getHiddenHtml(getMode());
htmlTitle = "";
} else {
strValue = fieldvalue.getReadOnlyHtml(getMode());
htmlTitle = fieldvalue.getStringValue(getMode());
}
} else {
strValue = "";
htmlTitle = "";
}
String icon = field.getIcon();
if (field.isShowTypeIcon()) {
final Image cellIcon = Image.getTypeIcon(instance.getType());
if (cellIcon != null) {
icon = cellIcon.getUrl();
}
}
final UIStructurBrowserTableCell cell = new UIStructurBrowserTableCell(child, fieldvalue,
instance, strValue, htmlTitle, icon);
if (field.getName().equals(this.browserFieldName)) {
child.setLabel(strValue);
child.setAllowChilds(checkForAllowChilds(instance));
if (child.isAllowChilds()) {
child.setParent(checkForChildren(instance));
}
if (row4Create) {
child.setImage(Image.getTypeIcon(type) != null
? Image.getTypeIcon(type).getUrl() : null);
} else {
child.setImage(Image.getTypeIcon(instance.getType()) != null ? Image.getTypeIcon(
instance.getType()).getUrl() : null);
}
cell.setBrowserField(true);
child.browserFieldIndex = child.getColumns().size();
}
child.getColumns().add(cell);
}
}
if (this.root && row4Create) {
this.emptyRow = child;
} else if (this.root && isEditMode() && this.emptyRow == null) {
this.emptyRow = child;
this.childs.add(child);
} else {
this.childs.add(child);
}
row4Create = false;
child.checkHideColumn4Row();
}
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
sortModel();
expand(_expand);
super.setInitialized(true);
}
/**
* Expand the tree with the information from the Session.
* @param _expand is this inside an expand
*/
@SuppressWarnings("unchecked")
protected void expand(final boolean _expand)
{
try {
// only if the element was opened the first time e.g. reload etc.
if ((isRoot() || _expand)
&& (Context.getThreadContext().containsSessionAttribute(getCacheKey()) || this.forceExpanded)) {
final Map<String, Boolean> sessMap = (Map<String, Boolean>) Context
.getThreadContext().getSessionAttribute(getCacheKey());
for (final UIStructurBrowser uiChild : this.childs) {
if (sessMap == null || sessMap.containsKey(uiChild.getInstanceKey())) {
final Boolean expandedTmp = sessMap == null ? true : sessMap.get(uiChild.getInstanceKey());
if (expandedTmp != null && expandedTmp && uiChild.isParent()) {
uiChild.setExecutionStatus(UIStructurBrowser.ExecutionStatus.ADDCHILDREN);
final List<Return> ret = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE,
ParameterValues.INSTANCE, uiChild.getInstance(),
ParameterValues.CLASS, uiChild);
final Map<Instance, Boolean> map = (Map<Instance, Boolean>) ret.get(0).get(
ReturnValues.VALUES);
uiChild.setExpanded(true);
if (uiChild.tableuuid == null) {
uiChild.executeTree(map, true);
} else {
uiChild.executeTreeTable(map, true);
}
}
}
}
}
} catch (final EFapsException e) {
UIStructurBrowser.LOG.error("Error retreiving Session info for StruturBrowser from Command with UUID: {}",
getCommandUUID(), e);
}
}
/**
* Method to sort the data of this model. It calls an esjp for sorting.
*/
protected void sortModel()
{
setExecutionStatus(UIStructurBrowser.ExecutionStatus.SORT);
try {
getCommand().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.CLASS, this);
if (getSortDirection() == SortDirection.DESCENDING) {
Collections.reverse(this.childs);
}
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
}
/**
* Method to sort this model and all child models.
*/
public void sort()
{
sortModel();
for (final UIStructurBrowser child : this.childs) {
child.sort();
}
}
/**
* @return UIStructurBrowser
* @throws EFapsException on error
*/
public UIStructurBrowser getClone4New()
throws EFapsException
{
final UIStructurBrowser parentTmp;
if (this.root) {
parentTmp = this.emptyRow;
} else {
parentTmp = this;
}
final UIStructurBrowser ret = getNewStructurBrowser(null, parentTmp);
ret.initialise();
for (final UIStructurBrowserTableCell col : parentTmp.columns) {
final FieldValue fieldValue = new FieldValue(col.getField(), col.getAttribute(), null, null, null);
final String htmlValue;
if (col.getDisplay().equals(Display.EDITABLE)) {
htmlValue = fieldValue.getEditHtml(getMode());
} else {
htmlValue = fieldValue.getReadOnlyHtml(getMode());
}
final String htmlTitle = fieldValue.getStringValue(getMode());
final UIStructurBrowserTableCell newCol = new UIStructurBrowserTableCell(ret, fieldValue, null,
htmlValue, htmlTitle, "");
newCol.setBrowserField(col.isBrowserField());
ret.setBrowserFieldIndex(parentTmp.getBrowserFieldIndex());
ret.getColumns().add(newCol);
}
return ret;
}
/**
* Getter method for the instance variable {@link #forceExpanded}.
*
* @return value of instance variable {@link #forceExpanded}
*/
public boolean isForceExpanded()
{
return this.forceExpanded;
}
/**
* Setter method for instance variable {@link #forceExpanded}.
*
* @param _forceExpanded value for instance variable {@link #forceExpanded}
*/
protected void setForceExpanded(final boolean _forceExpanded)
{
this.forceExpanded = _forceExpanded;
}
/**
* Getter method for the instance variable {@link #allowChilds}.
*
* @return value of instance variable {@link #allowChilds}
*/
public boolean isAllowChilds()
{
return this.allowChilds;
}
/**
* Setter method for instance variable {@link #allowChilds}.
*
* @param _allowChilds value for instance variable {@link #allowChilds}
*/
public void setAllowChilds(final boolean _allowChilds)
{
this.allowChilds = _allowChilds;
}
/**
* Method used to evaluate the type for this table from the connected
* events.
*
* @return type if found
* @throws EFapsException on error
*/
protected Type getTypeFromEvent()
throws EFapsException
{
final List<EventDefinition> events = getObject4Event().getEvents(EventType.UI_TABLE_EVALUATE);
String typeName = null;
if (events.size() > 1) {
throw new EFapsException(this.getClass(), "execute4NoInstance.moreThanOneEvaluate");
} else {
final EventDefinition event = events.get(0);
if (event.getProperty("Types") != null) {
typeName = event.getProperty("Types").split(";")[0];
}
}
return Type.get(typeName);
}
/**
* Method is called from the StructurBrowser in edit mode before rendering
* the columns for row to be able to hide the columns for different rows by
* setting the cell model to hide.
*/
public void checkHideColumn4Row()
{
setExecutionStatus(UIStructurBrowser.ExecutionStatus.CHECKHIDECOLUMN4ROW);
try {
getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE,
ParameterValues.INSTANCE, getInstance(),
ParameterValues.CLASS, this);
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
}
/**
* This method should be called to add children to a Node in the Tree.<br>
* e.g. in a standard implementation the children would be added to the Tree
* on the expand-Event of the tree. The children a retrieved from an esjp
* with the EventType UI_TABLE_EVALUATE.
*
* @param _parent the DefaultMutableTreeNode the new children should be
* added
*/
@SuppressWarnings("unchecked")
public void addChildren(final DefaultMutableTreeNode _parent)
{
setExecutionStatus(UIStructurBrowser.ExecutionStatus.ADDCHILDREN);
_parent.removeAllChildren();
List<Return> ret;
try {
ret = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.INSTANCE, getInstance(),
ParameterValues.CLASS, this);
final Map<Instance, Boolean> map = (Map<Instance, Boolean>) ret.get(0).get(ReturnValues.VALUES);
if (this.tableuuid == null) {
executeTree(map, false);
} else {
executeTreeTable(map, false);
}
addNode(_parent, this.childs);
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
}
/**
* This method is used to check if a node has potential children.
*
* @param _instance Instance of a Node to be checked
* @return true if this Node has children, else false
*/
protected boolean checkForAllowChilds(final Instance _instance)
{
setExecutionStatus(UIStructurBrowser.ExecutionStatus.ALLOWSCHILDREN);
try {
final List<Return> ret = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE,
ParameterValues.INSTANCE, _instance,
ParameterValues.CLASS, this);
return ret.isEmpty() ? false : ret.get(0).get(ReturnValues.TRUE) != null;
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
}
/**
* This method is used to check if a node has potential children.
*
* @param _instance Instance of a Node to be checked
* @return true if this Node has children, else false
*/
protected boolean checkForChildren(final Instance _instance)
{
setExecutionStatus(UIStructurBrowser.ExecutionStatus.CHECKFORCHILDREN);
try {
final List<Return> ret = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE,
ParameterValues.INSTANCE, _instance,
ParameterValues.CLASS, this);
return ret.isEmpty() ? false : ret.get(0).get(ReturnValues.TRUE) != null;
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
}
/**
* Method is called from the StructurBrowser in edit mode from
* {@link #setValuesFromUI(Map, DefaultMutableTreeNode)} to get
* additional JavaScript to be appended to the AjaxTarget.
* @param _parameters Parameter as send from the UserInterface
* @return JavaScript for the UserInterface
*/
protected String getJavaScript4Target(final Map<String, String[]> _parameters)
{
String ret;
setExecutionStatus(UIStructurBrowser.ExecutionStatus.GETJAVASCRIPT4TARGET);
try {
final List<Return> retList = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE,
ParameterValues.INSTANCE, getInstance(),
ParameterValues.CLASS, this,
ParameterValues.PARAMETERS, _parameters);
ret = (String) retList.get(0).get(ReturnValues.SNIPLETT);
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
return ret;
}
/**
* This is the getter method for the instance variable {@link #parent}.
*
* @return value of instance variable {@link #parent}
*/
private boolean isParent()
{
return this.parent;
}
/**
* This is the setter method for the instance variable {@link #parent}.
*
* @param _parent the parent to set
*/
public void setParent(final boolean _parent)
{
this.parent = _parent;
}
/**
* Method to reset the Model.
*
* @see org.efaps.ui.wicket.models.AbstractModel#resetModel()
*/
@Override
public void resetModel()
{
this.childs.clear();
}
/**
* This is the getter method for the instance variable {@link #table}.
*
* @return value of instance variable {@link #table}
* @see #table
*/
public Table getTable()
{
return Table.get(this.tableuuid);
}
/**
* Has this StructurBrowserModel childs.
*
* @return true if has children, else false
*/
public boolean hasChilds()
{
return !this.childs.isEmpty();
}
/**
* Get the TreeModel used in the Component to construct the actual tree.
*
* @see #addNode(DefaultMutableTreeNode, List)
* @return TreeModel of this StructurBrowseModel
*/
public TreeModel getTreeModel()
{
DefaultTreeModel model = null;
final DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(this);
rootNode.setAllowsChildren(true);
if (this.childs.size() > 0) {
addNode(rootNode, this.childs);
}
model = new DefaultTreeModel(rootNode);
model.setAsksAllowsChildren(true);
return model;
}
/**
* Recursive method used to fill the TreeModel.
*
* @see #getTreeModel()
* @param _parent ParentNode children should be added
* @param _childs to be added as childs
*/
private void addNode(final DefaultMutableTreeNode _parent,
final List<UIStructurBrowser> _childs)
{
for (final UIStructurBrowser child : _childs) {
final DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child);
_parent.add(childNode);
if (child.hasChilds()) {
addNode(childNode, child.getChilds());
} else if (child.isParent()) {
childNode.setAllowsChildren(true);
childNode.add(new BogusNode());
}
childNode.setAllowsChildren(child.isAllowChilds());
}
}
/**
* @param _parameters Parameter as send from the UserInterface
* @param _node Node the _parameters were send from
* @throws EFapsException on error
* @return JavaScript for the UserInterface
*/
public String setValuesFromUI(final Map<String, String[]> _parameters,
final DefaultMutableTreeNode _node)
throws EFapsException
{
final Enumeration<?> preOrdEnum = ((DefaultMutableTreeNode) _node.getRoot()).preorderEnumeration();
int i = 0;
while (preOrdEnum.hasMoreElements()) {
final DefaultMutableTreeNode node = (DefaultMutableTreeNode) preOrdEnum.nextElement();
if (!node.isRoot()) {
final UIStructurBrowser uiObject = (UIStructurBrowser) node.getUserObject();
for (final UIStructurBrowserTableCell cell : uiObject.getColumns()) {
final String[] values = _parameters.get(cell.getName());
if (cell.isAutoComplete()) {
final String[] autoValues = _parameters.get(cell.getName() + "AutoComplete");
cell.setCellTitle(autoValues[i]);
cell.setInstanceKey(values[i]);
} else {
if (values != null) {
cell.setValueFromUI(values[i]);
}
}
}
i++;
}
}
return getJavaScript4Target(_parameters);
}
/**
* Get the Value of a Column identified by the index of the Column.
*
* @param _index index of the Column
* @return String with the Value of the Column
*/
public UIStructurBrowserTableCell getColumnValue(final int _index)
{
return this.columns.isEmpty() ? null : this.columns.get(_index);
}
/**
* This is the setter method for the instance variable {@link #label}.
*
* @param _label the label to set
*/
private void setLabel(final String _label)
{
this.label = _label;
}
/**
* This is the getter method for the instance variable {@link #columns}.
*
* @return value of instance variable {@link #columns}
*/
public List<UIStructurBrowserTableCell> getColumns()
{
return this.columns;
}
/**
* Setter method for instance variable {@link #browserFieldName}.
*
* @param _browserFieldName value for instance variable {@link #browserFieldName}
*/
protected void setBrowserFieldName(final String _browserFieldName)
{
this.browserFieldName = _browserFieldName;
}
/**
* Setter method for instance variable {@link #tableuuid}.
*
* @param _tableuuid value for instance variable {@link #tableuuid}
*/
protected void setTableuuid(final UUID _tableuuid)
{
this.tableuuid = _tableuuid;
}
/**
* Setter method for instance variable {@link #browserFieldIndex}.
*
* @param _browserFieldIndex value for instance variable {@link #browserFieldIndex}
*/
protected void setBrowserFieldIndex(final int _browserFieldIndex)
{
this.browserFieldIndex = _browserFieldIndex;
}
/**
* Getter method for the instance variable {@link #browserFieldIndex}.
*
* @return value of instance variable {@link #browserFieldIndex}
*/
public int getBrowserFieldIndex()
{
return this.browserFieldIndex;
}
/**
* This is the getter method for the instance variable
* {@link #browserFieldName}.
*
* @return value of instance variable {@link #browserFieldName}
*/
public String getBrowserFieldName()
{
return this.browserFieldName;
}
/**
* This is the getter method for the instance variable {@link #headers}.
*
* @return value of instance variable {@link #headers}
*/
public List<UITableHeader> getHeaders()
{
return this.headers;
}
/**
* This is the getter method for the instance variable {@link #image}.
*
* @return value of instance variable {@link #image}
*/
public String getImage()
{
return this.image;
}
/**
* This is the setter method for the instance variable {@link #image}.
*
* @param _url the url of the image to set
*/
private void setImage(final String _url)
{
if (_url != null) {
this.image = RequestHandler.replaceMacrosInUrl(_url);
}
}
/**
* This is the getter method for the instance variable {@link #direction}.
*
* @return value of instance variable {@link #direction}
*/
public Boolean getDirection()
{
return this.direction;
}
/**
* This is the setter method for the instance variable {@link #direction}.
*
* @param _direction the direction to set
*/
public void setDirection(final Boolean _direction)
{
this.direction = _direction;
}
/**
* Getter method for instance variable {@link #executionStatus}.
*
* @return value of instance variable {@link #executionStatus}
*/
public ExecutionStatus getExecutionStatus()
{
return this.executionStatus;
}
/**
* This method is updating the Label, by querying the eFaps-DataBase.
*/
public void requeryLabel()
{
try {
final ValueParser parser = new ValueParser(new StringReader(this.valueLabel));
final ValueList valList = parser.ExpressionString();
final PrintQuery print = new PrintQuery(getInstance());
valList.makeSelect(print);
if (print.execute()) {
setLabel(valList.makeString(getInstance(), print, getMode()).toString());
}
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
} catch (final ParseException e) {
throw new RestartResponseException(new ErrorPage(e));
}
}
/**
* Method to add a new BogusNode to the given Node.
*
* @param _parent Parent a BogusNode should be added
*/
public void addBogusNode(final DefaultMutableTreeNode _parent)
{
_parent.add(new BogusNode());
}
/**
* Getter method for instance variable {@link #childs}.
*
* @return value of instance variable {@link #childs}
*/
public List<UIStructurBrowser> getChilds()
{
return this.childs;
}
/**
* Getter method for instance variable {@link #label}.
*
* @return value of instance variable {@link #label}
*/
public String getLabel()
{
return this.label;
}
/**
* Getter method for instance variable {@link #sortDirection}.
*
* @return value of instance variable {@link #sortDirection}
*/
public SortDirection getSortDirection()
{
return this.sortDirection;
}
/**
* Setter method for instance variable {@link #sortDirection} and for all
* children also.
*
* @param _sortDirection value for instance variable {@link #sortDirection}
*/
public void setSortDirection(final SortDirection _sortDirection)
{
this.sortDirection = _sortDirection;
for (final UIStructurBrowser child : this.childs) {
child.setSortDirection(_sortDirection);
}
}
/**
* Getter method for instance variable {@link #expanded}.
*
* @return value of instance variable {@link #expanded}
*/
public boolean isExpanded()
{
return this.expanded;
}
/**
* Setter method for instance variable {@link #expanded}.
*
* @param _expanded value for instance variable {@link #expanded}
*/
public void setExpanded(final boolean _expanded)
{
this.expanded = _expanded;
storeInSession();
}
/**
* This method generates the Key for a UserAttribute by using the UUID of
* the Command and the given static part, so that for every StruturBrowser a
* unique key for expand etc, is created.
*
* @return String with the key
*/
public String getCacheKey()
{
return super.getCommandUUID() + "-" + UIStructurBrowser.USERSESSIONKEY;
}
/**
* Store the Information in the Session.
*/
@SuppressWarnings("unchecked")
private void storeInSession()
{
try {
if (!getMode().equals(TargetMode.CREATE)) {
final Map<String, Boolean> sessMap;
if (Context.getThreadContext().containsSessionAttribute(getCacheKey())) {
sessMap = (Map<String, Boolean>) Context.getThreadContext().getSessionAttribute(getCacheKey());
} else {
sessMap = new HashMap<String, Boolean>();
}
sessMap.put(getInstanceKey(), isExpanded());
Context.getThreadContext().setSessionAttribute(getCacheKey(), sessMap);
}
} catch (final EFapsException e) {
UIStructurBrowser.LOG.error("Error storing Session info for StruturBrowser called by Command with UUID: {}",
getCommandUUID(), e);
}
}
/**
* Setter method for instance variable {@link #executionStatus}.
*
* @param _executionStatus value for instance variable {@link #executionStatus}
*/
protected void setExecutionStatus(final ExecutionStatus _executionStatus)
{
this.executionStatus = _executionStatus;
}
/**
* Get the Admin Object that contains the events that must be executed.
*
* @return the Admin Object that contains the events to be executed
*/
protected AbstractAdminObject getObject4Event()
{
return this.getCommand();
}
/**
* Getter method for the instance variable {@link #root}.
*
* @return value of instance variable {@link #root}
*/
public boolean isRoot()
{
return this.root;
}
/**
* @return <i>true</i> if the check boxes must be shown, other <i>false</i>
* is returned.
* @see #showCheckBoxes
*/
public boolean isShowCheckBoxes()
{
boolean ret;
if (super.isSubmit() && !isCreateMode()) {
ret = true;
} else {
ret = this.showCheckBoxes;
}
return ret;
}
/**
* Setter method for instance variable {@link #showCheckBoxes}.
*
* @param _showCheckBoxes value for instance variable {@link #showCheckBoxes}
*/
protected void setShowCheckBoxes(final boolean _showCheckBoxes)
{
this.showCheckBoxes = _showCheckBoxes;
}
/**
* In create or edit mode this StructurBrowser is editable.
*
* @return is this StructurBrowser editable.
*/
public boolean isEditable()
{
return isCreateMode() || isEditMode();
}
/**
* (non-Javadoc).
*
* @see org.apache.wicket.model.Model#toString()
* @return label
*/
@Override
public String toString()
{
return this.label;
}
/**
* This class is used to add a ChildNode under a ParentNode, if the
* ParentNode actually has some children. By using this class it then can
* very easy be distinguished between Nodes which where expanded and Nodes
* which still need to be expanded.
*
*/
public class BogusNode
extends DefaultMutableTreeNode
{
/**
* Needed for serialization.
*/
private static final long serialVersionUID = 1L;
}
}
| - missing check for allowing of children in StructurBrowser
git-svn-id: 6de479fac40b5ab7fd12e267df1fa0a7a72510c4@6011 fee104cc-1dfa-8c0f-632d-d3b7e6b59fb0
| src/main/java/org/efaps/ui/wicket/models/objects/UIStructurBrowser.java | - missing check for allowing of children in StructurBrowser |
|
Java | apache-2.0 | 18b463bcac3a60e83a5ebfbdffcebf4ce95508de | 0 | huyunkai/StickyListHeaders,tomoyuki28jp/StickyListHeaders,jmiguel2902/StickyListHeaders,NewComerBH/StickyListHeaders,denispyr/StickyListHeaders,chwnFlyPig/StickyListHeaders,CyanogenMod/android_external_emilsjolander_stickylistheaders,lxhxhlw/StickyListHeaders,msdgwzhy6/StickyListHeaders,pacificIT/StickyListHeaders,maxi182/StickyListHeaders,AndrewGeorge/StickyListHeaders,paul0952710801/StickyListHeaders,selmanon/StickyListHeaders,xiazhenshui/StickyListHeaders,DenisMondon/StickyListHeaders,neonaldo/StickyListHeaders,emilsjolander/StickyListHeaders,wisavalite/StickyListHeaders,jianxiansining/StickyListHeaders,huy510cnt/Sticky_ListHeaders,yunfengsa/StickyListHeaders,wlrhnh-David/StickyListHeaders,sam-yr/StickyListHeaders,silent-nischal/StickyListHeaders,emnrd-ito/StickyListHeaders,hgl888/StickyListHeaders,LivioGama/StickyListHeaders,Akylas/StickyListHeaders,VictorS-Zhao/StickyListHeaders,nilesh14/FMC,mtotschnig/StickyListHeaders,hejunbinlan/StickyListHeaders,jaohoang/StickyListHeaders,mrljdx/StickyListHeaders,b-cuts/StickyListHeaders,littlezan/StickyListHeaders,wswenyue/StickyListHeaders,dongzhouT/StickyListHeaders,peterdocter/StickyListHeaders | package se.emilsjolander.stickylistheaders;
import se.emilsjolander.stickylistheaders.WrapperViewList.LifeCycleListener;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.SectionIndexer;
/**
* Even though this is a FrameLayout subclass we it is called a
* ListView. This is because of 2 reasons. 1. It acts like as ListView
* 2. It used to be a ListView subclass and i did not was to change to
* name causing compatibility errors.
*
* @author Emil Sjlander
*/
public class StickyListHeadersListView extends FrameLayout {
public interface OnHeaderClickListener {
public void onHeaderClick(StickyListHeadersListView l, View header, int itemPosition, long headerId,
boolean currentlySticky);
}
/* --- Children --- */
private WrapperViewList mList;
private View mHeader;
/* --- Header state --- */
private Long mHeaderId;
// used to not have to call getHeaderId() all the time
private Integer mHeaderPosition;
private Integer mHeaderOffset;
/* --- Delegates --- */
private OnScrollListener mOnScrollListenerDelegate;
/* --- Settings --- */
private boolean mAreHeadersSticky = true;
private boolean mClippingToPadding = true;
private boolean mIsDrawingListUnderStickyHeader = true;
private int mPaddingLeft = 0;
private int mPaddingTop = 0;
private int mPaddingRight = 0;
private int mPaddingBottom = 0;
/* --- Other --- */
private AdapterWrapper mAdapter;
private OnHeaderClickListener mOnHeaderClickListener;
private Drawable mDivider;
private int mDividerHeight;
private AdapterWrapperDataSetObserver mDataSetObserver;
public StickyListHeadersListView(Context context) {
this(context, null);
}
public StickyListHeadersListView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public StickyListHeadersListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Initialize the list
mList = new WrapperViewList(context);
mDivider = mList.getDivider();
mDividerHeight = mList.getDividerHeight();
// null out divider, dividers are handled by adapter so they look good
// with headers
mList.setDivider(null);
mList.setDividerHeight(0);
mList.setLifeCycleListener(new WrapperViewListLifeCycleListener());
mList.setOnScrollListener(new WrapperListScrollListener());
addView(mList);
if (attrs != null) {
TypedArray a = context.getTheme()
.obtainStyledAttributes(attrs, R.styleable.StickyListHeadersListView, 0, 0);
try {
// Android attributes
if (a.hasValue(R.styleable.StickyListHeadersListView_android_padding)) {
int padding = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_padding, 0);
mPaddingLeft = padding;
mPaddingTop = padding;
mPaddingRight = padding;
mPaddingBottom = padding;
} else {
mPaddingLeft = a
.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingLeft, 0);
mPaddingTop = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingTop, 0);
mPaddingRight = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingRight,
0);
mPaddingBottom = a.getDimensionPixelSize(
R.styleable.StickyListHeadersListView_android_paddingBottom, 0);
}
setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
// Set clip to padding on the list and reset value to default on
// wrapper
mClippingToPadding = a.getBoolean(R.styleable.StickyListHeadersListView_android_clipToPadding, true);
super.setClipToPadding(true);
mList.setClipToPadding(mClippingToPadding);
// ListView attributes
mList.setFadingEdgeLength(a.getDimensionPixelSize(
R.styleable.StickyListHeadersListView_android_fadingEdgeLength,
mList.getVerticalFadingEdgeLength()));
final int fadingEdge = a.getInt(R.styleable.StickyListHeadersListView_android_requiresFadingEdge, 0);
if (fadingEdge == 0x00001000) {
mList.setVerticalFadingEdgeEnabled(false);
mList.setHorizontalFadingEdgeEnabled(true);
} else if (fadingEdge == 0x00002000) {
mList.setVerticalFadingEdgeEnabled(true);
mList.setHorizontalFadingEdgeEnabled(false);
} else {
mList.setVerticalFadingEdgeEnabled(false);
mList.setHorizontalFadingEdgeEnabled(false);
}
mList.setCacheColorHint(a.getColor(R.styleable.StickyListHeadersListView_android_cacheColorHint,
mList.getCacheColorHint()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mList.setChoiceMode(a.getInt(R.styleable.StickyListHeadersListView_android_choiceMode,
mList.getChoiceMode()));
}
mList.setDrawSelectorOnTop(a.getBoolean(
R.styleable.StickyListHeadersListView_android_drawSelectorOnTop, false));
mList.setFastScrollEnabled(a.getBoolean(
R.styleable.StickyListHeadersListView_android_fastScrollEnabled, mList.isFastScrollEnabled()));
mList.setScrollBarStyle(a.getInt(R.styleable.StickyListHeadersListView_android_scrollbarStyle, 0));
final Drawable selector = a.getDrawable(R.styleable.StickyListHeadersListView_android_listSelector);
if (selector != null) {
mList.setSelector(selector);
}
mList.setScrollingCacheEnabled(a.getBoolean(
R.styleable.StickyListHeadersListView_android_scrollingCache, mList.isScrollingCacheEnabled()));
final Drawable divider = a.getDrawable(R.styleable.StickyListHeadersListView_android_divider);
if (divider != null) {
mDivider = divider;
}
mDividerHeight = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_dividerHeight, mDividerHeight);
// StickyListHeaders attributes
mAreHeadersSticky = a.getBoolean(R.styleable.StickyListHeadersListView_hasStickyHeaders, true);
mIsDrawingListUnderStickyHeader = a.getBoolean(
R.styleable.StickyListHeadersListView_isDrawingListUnderStickyHeader, true);
} finally {
a.recycle();
}
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
mList.layout(mPaddingLeft, 0, mList.getMeasuredWidth() + mPaddingLeft, getHeight());
if (mHeader != null) {
MarginLayoutParams lp = (MarginLayoutParams) mHeader.getLayoutParams();
int headerTop = lp.topMargin + (mClippingToPadding ? mPaddingTop : 0);
// The left parameter must for some reason be set to 0.
// I think it should be set to mPaddingLeft but apparently not
mHeader.layout(0, headerTop, mHeader.getMeasuredWidth(), headerTop + mHeader.getMeasuredHeight());
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
// Only draw the list here.
// The header should be drawn right after the lists children are drawn.
// This is done so that the header is above the list items
// but below the list decorators (scroll bars etc).
drawChild(canvas, mList, 0);
}
// Reset values tied the header. also remove header form layout
// This is called in response to the data set or the adapter changing
private void clearHeader() {
if (mHeader != null) {
removeView(mHeader);
mHeader = null;
mHeaderId = null;
mHeaderPosition = null;
mHeaderOffset = null;
// reset the top clipping length
mList.setTopClippingLength(0);
updateHeaderVisibilities();
}
}
private void updateOrClearHeader(int firstVisiblePosition) {
final int adapterCount = mAdapter == null ? 0 : mAdapter.getCount();
if (adapterCount == 0 || !mAreHeadersSticky) {
return;
}
final int headerViewCount = mList.getHeaderViewsCount();
final int realFirstVisibleItem = firstVisiblePosition - headerViewCount;
// It is not a mistake to call getFirstVisiblePosition() here.
// Most of the time getFixedFirstVisibleItem() should be called
// but that does not work great together with getChildAt()
final boolean isFirstViewBelowTop = mList.getFirstVisiblePosition() == 0 && mList.getChildAt(0).getTop() > 0;
final boolean isFirstVisibleItemOutsideAdapterRange = realFirstVisibleItem > adapterCount - 1
|| realFirstVisibleItem < 0;
final boolean doesListHaveChildren = mList.getChildCount() != 0;
if (!doesListHaveChildren || isFirstVisibleItemOutsideAdapterRange || isFirstViewBelowTop) {
clearHeader();
return;
}
updateHeader(realFirstVisibleItem);
}
private void updateHeader(int firstVisiblePosition) {
// check if there is a new header should be sticky
if (mHeaderPosition == null || mHeaderPosition != firstVisiblePosition) {
mHeaderPosition = firstVisiblePosition;
final long headerId = mAdapter.getHeaderId(firstVisiblePosition);
if (mHeaderId == null || mHeaderId != headerId) {
mHeaderId = headerId;
final View header = mAdapter.getHeaderView(mHeaderPosition, mHeader, this);
if (mHeader != header) {
if (header == null) {
throw new NullPointerException("header may not be null");
}
swapHeader(header);
}
ViewGroup.LayoutParams lp = mHeader.getLayoutParams();
if (lp.height == ViewGroup.LayoutParams.MATCH_PARENT) {
lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
mHeader.setLayoutParams(lp);
}
// measure the header
final int width = getWidth();
final int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
final int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
measureChild(mHeader, parentWidthMeasureSpec, parentHeightMeasureSpec);
// Reset mHeaderOffset to null ensuring
// that it will be set on the header and
// not skipped for performance reasons.
mHeaderOffset = null;
}
}
int headerOffset = 0;
// Calculate new header offset
// Skip looking at the first view. it never matters because it always
// results in a headerOffset = 0
int headerBottom = mHeader.getMeasuredHeight() + (mClippingToPadding ? mPaddingTop : 0);
for (int i = 0; i < mList.getChildCount(); i++) {
final View child = mList.getChildAt(i);
final boolean doesChildHaveHeader = child instanceof WrapperView && ((WrapperView) child).hasHeader();
final boolean isChildFooter = mList.containsFooterView(child);
if (child.getTop() >= (mClippingToPadding ? mPaddingTop : 0) && (doesChildHaveHeader || isChildFooter)) {
headerOffset = Math.min(child.getTop() - headerBottom, 0);
break;
}
}
setHeaderOffet(headerOffset);
if (!mIsDrawingListUnderStickyHeader) {
mList.setTopClippingLength(mHeader.getMeasuredHeight() + mHeaderOffset);
}
updateHeaderVisibilities();
}
private void swapHeader(View newHeader) {
if (mHeader != null) {
removeView(mHeader);
}
mHeader = newHeader;
addView(mHeader);
mHeader.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mOnHeaderClickListener != null) {
mOnHeaderClickListener.onHeaderClick(StickyListHeadersListView.this, mHeader, mHeaderPosition,
mHeaderId, true);
}
}
});
}
// hides the headers in the list under the sticky header.
// Makes sure the other ones are showing
private void updateHeaderVisibilities() {
int top;
if (mHeader != null) {
top = mHeader.getMeasuredHeight() + (mHeaderOffset != null ? mHeaderOffset : 0);
} else {
top = mClippingToPadding ? mPaddingTop : 0;
}
int childCount = mList.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = mList.getChildAt(i);
if (child instanceof WrapperView) {
WrapperView wrapperViewChild = (WrapperView) child;
if (wrapperViewChild.hasHeader()) {
View childHeader = wrapperViewChild.mHeader;
if (wrapperViewChild.getTop() < top) {
if (childHeader.getVisibility() != View.INVISIBLE) {
childHeader.setVisibility(View.INVISIBLE);
}
} else {
if (childHeader.getVisibility() != View.VISIBLE) {
childHeader.setVisibility(View.VISIBLE);
}
}
}
}
}
}
// Wrapper around setting the header offset in different ways depending on
// the API version
@SuppressLint("NewApi")
private void setHeaderOffet(int offset) {
if (mHeaderOffset == null || mHeaderOffset != offset) {
mHeaderOffset = offset;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mHeader.setTranslationY(mHeaderOffset);
} else {
MarginLayoutParams params = (MarginLayoutParams) mHeader.getLayoutParams();
params.topMargin = mHeaderOffset;
mHeader.setLayoutParams(params);
}
}
}
private class AdapterWrapperDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
clearHeader();
}
@Override
public void onInvalidated() {
clearHeader();
}
}
private class WrapperListScrollListener implements OnScrollListener {
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (mOnScrollListenerDelegate != null) {
mOnScrollListenerDelegate.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (mOnScrollListenerDelegate != null) {
mOnScrollListenerDelegate.onScrollStateChanged(view, scrollState);
}
}
}
private class WrapperViewListLifeCycleListener implements LifeCycleListener {
@Override
public void onDispatchDrawOccurred(Canvas canvas) {
// onScroll is not called often at all before froyo
// therefor we need to update the header here as well.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
if (mHeader != null) {
if (mClippingToPadding) {
canvas.save();
canvas.clipRect(0, mPaddingTop, getRight(), getBottom());
drawChild(canvas, mHeader, 0);
canvas.restore();
} else {
drawChild(canvas, mHeader, 0);
}
}
}
}
private class AdapterWrapperHeaderClickHandler implements AdapterWrapper.OnHeaderClickListener {
@Override
public void onHeaderClick(View header, int itemPosition, long headerId) {
mOnHeaderClickListener.onHeaderClick(StickyListHeadersListView.this, header, itemPosition, headerId, false);
}
}
private boolean isStartOfSection(int position) {
return position == 0 || mAdapter.getHeaderId(position) == mAdapter.getHeaderId(position - 1);
}
private int getHeaderOverlap(int position) {
boolean isStartOfSection = isStartOfSection(position);
if (!isStartOfSection) {
View header = mAdapter.getView(position, null, mList);
final int width = getWidth();
final int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
final int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
measureChild(header, parentWidthMeasureSpec, parentHeightMeasureSpec);
return header.getMeasuredHeight();
}
return 0;
}
/* ---------- StickyListHeaders specific API ---------- */
public void setAreHeadersSticky(boolean areHeadersSticky) {
mAreHeadersSticky = areHeadersSticky;
if (!areHeadersSticky) {
clearHeader();
} else {
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
// invalidating the list will trigger dispatchDraw()
mList.invalidate();
}
public boolean areHeadersSticky() {
return mAreHeadersSticky;
}
/**
* Use areHeadersSticky() method instead
*/
@Deprecated
public boolean getAreHeadersSticky() {
return areHeadersSticky();
}
public void setDrawingListUnderStickyHeader(boolean drawingListUnderStickyHeader) {
mIsDrawingListUnderStickyHeader = drawingListUnderStickyHeader;
// reset the top clipping length
mList.setTopClippingLength(0);
}
public boolean isDrawingListUnderStickyHeader() {
return mIsDrawingListUnderStickyHeader;
}
public void setOnHeaderClickListener(OnHeaderClickListener onHeaderClickListener) {
mOnHeaderClickListener = onHeaderClickListener;
if (mAdapter != null) {
if (mOnHeaderClickListener != null) {
mAdapter.setOnHeaderClickListener(new AdapterWrapperHeaderClickHandler());
} else {
mAdapter.setOnHeaderClickListener(null);
}
}
}
public View getListChildAt(int index) {
return mList.getChildAt(index);
}
public int getListChildCount() {
return mList.getChildCount();
}
/**
* Use the method with extreme caution!!
* Changing any values on the underlying ListView might break everything.
*
* @return the ListView backing this view.
*/
public ListView getWrappedList() {
return mList;
}
/* ---------- ListView delegate methods ---------- */
public void setAdapter(StickyListHeadersAdapter adapter) {
if (adapter == null) {
mList.setAdapter(null);
clearHeader();
return;
}
if (mAdapter != null) {
mAdapter.unregisterDataSetObserver(mDataSetObserver);
}
if (adapter instanceof SectionIndexer) {
mAdapter = new SectionIndexerAdapterWrapper(getContext(), adapter);
} else {
mAdapter = new AdapterWrapper(getContext(), adapter);
}
mDataSetObserver = new AdapterWrapperDataSetObserver();
mAdapter.registerDataSetObserver(mDataSetObserver);
if (mOnHeaderClickListener != null) {
mAdapter.setOnHeaderClickListener(new AdapterWrapperHeaderClickHandler());
} else {
mAdapter.setOnHeaderClickListener(null);
}
mAdapter.setDivider(mDivider, mDividerHeight);
mList.setAdapter(mAdapter);
clearHeader();
}
public StickyListHeadersAdapter getAdapter() {
return mAdapter == null ? null : mAdapter.mDelegate;
}
public void setDivider(Drawable divider) {
mDivider = divider;
if (mAdapter != null) {
mAdapter.setDivider(mDivider, mDividerHeight);
}
}
public void setDividerHeight(int dividerHeight) {
mDividerHeight = dividerHeight;
if (mAdapter != null) {
mAdapter.setDivider(mDivider, mDividerHeight);
}
}
public Drawable getDivider() {
return mDivider;
}
public int getDividerHeight() {
return mDividerHeight;
}
public void setOnScrollListener(OnScrollListener onScrollListener) {
mOnScrollListenerDelegate = onScrollListener;
}
public void setOnItemClickListener(OnItemClickListener listener) {
mList.setOnItemClickListener(listener);
}
public void setOnItemLongClickListener(OnItemLongClickListener listener) {
mList.setOnItemLongClickListener(listener);
}
public void addHeaderView(View v) {
mList.addHeaderView(v);
}
public void removeHeaderView(View v) {
mList.removeHeaderView(v);
}
public int getHeaderViewsCount() {
return mList.getHeaderViewsCount();
}
public void addFooterView(View v) {
mList.addFooterView(v);
}
public void removeFooterView(View v) {
mList.removeFooterView(v);
}
public int getFooterViewsCount() {
return mList.getFooterViewsCount();
}
public void setEmptyView(View v) {
mList.setEmptyView(v);
}
public View getEmptyView() {
return mList.getEmptyView();
}
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollBy(int distance, int duration) {
requireSdkVersion(Build.VERSION_CODES.FROYO);
mList.smoothScrollBy(distance, duration);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollByOffset(int offset) {
requireSdkVersion(Build.VERSION_CODES.HONEYCOMB);
mList.smoothScrollByOffset(offset);
}
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollToPosition(int position) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
mList.smoothScrollToPosition(position);
} else {
int offset = mAdapter == null ? 0 : getHeaderOverlap(position);
mList.smoothScrollToPositionFromTop(position, offset);
}
}
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollToPosition(int position, int boundPosition) {
requireSdkVersion(Build.VERSION_CODES.FROYO);
mList.smoothScrollToPosition(position, boundPosition);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollToPositionFromTop(int position, int offset) {
requireSdkVersion(Build.VERSION_CODES.HONEYCOMB);
offset += mAdapter == null ? 0 : getHeaderOverlap(position);
mList.smoothScrollToPositionFromTop(position, offset);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollToPositionFromTop(int position, int offset, int duration) {
requireSdkVersion(Build.VERSION_CODES.HONEYCOMB);
offset += mAdapter == null ? 0 : getHeaderOverlap(position);
mList.smoothScrollToPositionFromTop(position, offset, duration);
}
public void setSelection(int position) {
mList.setSelection(position);
}
public void setSelectionAfterHeaderView() {
mList.setSelectionAfterHeaderView();
}
public void setSelectionFromTop(int position, int y) {
mList.setSelectionFromTop(position, y);
}
public void setSelector(Drawable sel) {
mList.setSelector(sel);
}
public void setSelector(int resID) {
mList.setSelector(resID);
}
public int getFirstVisiblePosition() {
return mList.getFirstVisiblePosition();
}
public int getLastVisiblePosition() {
return mList.getLastVisiblePosition();
}
public void setChoiceMode(int choiceMode) {
mList.setChoiceMode(choiceMode);
}
public void setItemChecked(int position, boolean value) {
mList.setItemChecked(position, value);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public int getCheckedItemCount() {
requireSdkVersion(Build.VERSION_CODES.HONEYCOMB);
return mList.getCheckedItemCount();
}
@TargetApi(Build.VERSION_CODES.FROYO)
public long[] getCheckedItemIds() {
requireSdkVersion(Build.VERSION_CODES.FROYO);
return mList.getCheckedItemIds();
}
public int getCheckedItemPosition() {
return mList.getCheckedItemPosition();
}
public SparseBooleanArray getCheckedItemPositions() {
return mList.getCheckedItemPositions();
}
public int getCount() {
return mList.getCount();
}
public Object getItemAtPosition(int position) {
return mList.getItemAtPosition(position);
}
public long getItemIdAtPosition(int position) {
return mList.getItemIdAtPosition(position);
}
@Override
public void setClipToPadding(boolean clipToPadding) {
if (mList != null) {
mList.setClipToPadding(clipToPadding);
}
mClippingToPadding = clipToPadding;
}
@Override
public void setPadding(int left, int top, int right, int bottom) {
mPaddingLeft = left;
mPaddingTop = top;
mPaddingRight = right;
mPaddingBottom = bottom;
// Set left/right paddings on the wrapper and top/bottom on the
// list to support the clip to padding flag
super.setPadding(left, 0, right, 0);
if (mList != null) {
mList.setPadding(0, top, 0, bottom);
}
}
@Override
public int getPaddingLeft() {
return mPaddingLeft;
}
@Override
public int getPaddingTop() {
return mPaddingTop;
}
@Override
public int getPaddingRight() {
return mPaddingRight;
}
@Override
public int getPaddingBottom() {
return mPaddingBottom;
}
public void setFastScrollEnabled(boolean fastScrollEnabled) {
mList.setFastScrollEnabled(fastScrollEnabled);
}
private void requireSdkVersion(int versionCode) {
if (Build.VERSION.SDK_INT < versionCode) {
throw new ApiLevelTooLowException(versionCode);
}
}
public int getPositionForView(View view){
return mList.getPositionForView(view);
}
}
| library/src/se/emilsjolander/stickylistheaders/StickyListHeadersListView.java | package se.emilsjolander.stickylistheaders;
import se.emilsjolander.stickylistheaders.WrapperViewList.LifeCycleListener;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.SectionIndexer;
/**
* Even though this is a FrameLayout subclass we it is called a
* ListView. This is because of 2 reasons. 1. It acts like as ListView
* 2. It used to be a ListView subclass and i did not was to change to
* name causing compatibility errors.
*
* @author Emil Sjlander
*/
public class StickyListHeadersListView extends FrameLayout {
public interface OnHeaderClickListener {
public void onHeaderClick(StickyListHeadersListView l, View header, int itemPosition, long headerId,
boolean currentlySticky);
}
/* --- Children --- */
private WrapperViewList mList;
private View mHeader;
/* --- Header state --- */
private Long mHeaderId;
// used to not have to call getHeaderId() all the time
private Integer mHeaderPosition;
private Integer mHeaderOffset;
/* --- Delegates --- */
private OnScrollListener mOnScrollListenerDelegate;
/* --- Settings --- */
private boolean mAreHeadersSticky = true;
private boolean mClippingToPadding = true;
private boolean mIsDrawingListUnderStickyHeader = true;
private int mPaddingLeft = 0;
private int mPaddingTop = 0;
private int mPaddingRight = 0;
private int mPaddingBottom = 0;
/* --- Other --- */
private AdapterWrapper mAdapter;
private OnHeaderClickListener mOnHeaderClickListener;
private Drawable mDivider;
private int mDividerHeight;
private AdapterWrapperDataSetObserver mDataSetObserver;
public StickyListHeadersListView(Context context) {
this(context, null);
}
public StickyListHeadersListView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public StickyListHeadersListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Initialize the list
mList = new WrapperViewList(context);
mDivider = mList.getDivider();
mDividerHeight = mList.getDividerHeight();
// null out divider, dividers are handled by adapter so they look good
// with headers
mList.setDivider(null);
mList.setDividerHeight(0);
mList.setLifeCycleListener(new WrapperViewListLifeCycleListener());
mList.setOnScrollListener(new WrapperListScrollListener());
addView(mList);
if (attrs != null) {
TypedArray a = context.getTheme()
.obtainStyledAttributes(attrs, R.styleable.StickyListHeadersListView, 0, 0);
try {
// Android attributes
if (a.hasValue(R.styleable.StickyListHeadersListView_android_padding)) {
int padding = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_padding, 0);
mPaddingLeft = padding;
mPaddingTop = padding;
mPaddingRight = padding;
mPaddingBottom = padding;
} else {
mPaddingLeft = a
.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingLeft, 0);
mPaddingTop = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingTop, 0);
mPaddingRight = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingRight,
0);
mPaddingBottom = a.getDimensionPixelSize(
R.styleable.StickyListHeadersListView_android_paddingBottom, 0);
}
setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
// Set clip to padding on the list and reset value to default on
// wrapper
mClippingToPadding = a.getBoolean(R.styleable.StickyListHeadersListView_android_clipToPadding, true);
super.setClipToPadding(true);
mList.setClipToPadding(mClippingToPadding);
// ListView attributes
mList.setFadingEdgeLength(a.getDimensionPixelSize(
R.styleable.StickyListHeadersListView_android_fadingEdgeLength,
mList.getVerticalFadingEdgeLength()));
final int fadingEdge = a.getInt(R.styleable.StickyListHeadersListView_android_requiresFadingEdge, 0);
if (fadingEdge == 0x00001000) {
mList.setVerticalFadingEdgeEnabled(false);
mList.setHorizontalFadingEdgeEnabled(true);
} else if (fadingEdge == 0x00002000) {
mList.setVerticalFadingEdgeEnabled(true);
mList.setHorizontalFadingEdgeEnabled(false);
} else {
mList.setVerticalFadingEdgeEnabled(false);
mList.setHorizontalFadingEdgeEnabled(false);
}
mList.setCacheColorHint(a.getColor(R.styleable.StickyListHeadersListView_android_cacheColorHint,
mList.getCacheColorHint()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mList.setChoiceMode(a.getInt(R.styleable.StickyListHeadersListView_android_choiceMode,
mList.getChoiceMode()));
}
mList.setDrawSelectorOnTop(a.getBoolean(
R.styleable.StickyListHeadersListView_android_drawSelectorOnTop, false));
mList.setFastScrollEnabled(a.getBoolean(
R.styleable.StickyListHeadersListView_android_fastScrollEnabled, mList.isFastScrollEnabled()));
mList.setScrollBarStyle(a.getInt(R.styleable.StickyListHeadersListView_android_scrollbarStyle, 0));
final Drawable selector = a.getDrawable(R.styleable.StickyListHeadersListView_android_listSelector);
if (selector != null) {
mList.setSelector(selector);
}
mList.setScrollingCacheEnabled(a.getBoolean(
R.styleable.StickyListHeadersListView_android_scrollingCache, mList.isScrollingCacheEnabled()));
final Drawable divider = a.getDrawable(R.styleable.StickyListHeadersListView_android_divider);
if (divider != null) {
mDivider = divider;
}
mDividerHeight = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_dividerHeight, mDividerHeight);
// StickyListHeaders attributes
mAreHeadersSticky = a.getBoolean(R.styleable.StickyListHeadersListView_hasStickyHeaders, true);
mIsDrawingListUnderStickyHeader = a.getBoolean(
R.styleable.StickyListHeadersListView_isDrawingListUnderStickyHeader, true);
} finally {
a.recycle();
}
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
mList.layout(mPaddingLeft, 0, mList.getMeasuredWidth() + mPaddingLeft, getHeight());
if (mHeader != null) {
MarginLayoutParams lp = (MarginLayoutParams) mHeader.getLayoutParams();
int headerTop = lp.topMargin + (mClippingToPadding ? mPaddingTop : 0);
// The left parameter must for some reason be set to 0.
// I think it should be set to mPaddingLeft but apparently not
mHeader.layout(0, headerTop, mHeader.getMeasuredWidth(), headerTop + mHeader.getMeasuredHeight());
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
// Only draw the list here.
// The header should be drawn right after the lists children are drawn.
// This is done so that the header is above the list items
// but below the list decorators (scroll bars etc).
drawChild(canvas, mList, 0);
}
// Reset values tied the header. also remove header form layout
// This is called in response to the data set or the adapter changing
private void clearHeader() {
if (mHeader != null) {
removeView(mHeader);
mHeader = null;
mHeaderId = null;
mHeaderPosition = null;
mHeaderOffset = null;
// reset the top clipping length
mList.setTopClippingLength(0);
updateHeaderVisibilities();
}
}
private void updateOrClearHeader(int firstVisiblePosition) {
final int adapterCount = mAdapter == null ? 0 : mAdapter.getCount();
if (adapterCount == 0 || !mAreHeadersSticky) {
return;
}
final int headerViewCount = mList.getHeaderViewsCount();
final int realFirstVisibleItem = firstVisiblePosition - headerViewCount;
// It is not a mistake to call getFirstVisiblePosition() here.
// Most of the time getFixedFirstVisibleItem() should be called
// but that does not work great together with getChildAt()
final boolean isFirstViewBelowTop = mList.getFirstVisiblePosition() == 0 && mList.getChildAt(0).getTop() > 0;
final boolean isFirstVisibleItemOutsideAdapterRange = realFirstVisibleItem > adapterCount - 1
|| realFirstVisibleItem < 0;
final boolean doesListHaveChildren = mList.getChildCount() != 0;
if (!doesListHaveChildren || isFirstVisibleItemOutsideAdapterRange || isFirstViewBelowTop) {
clearHeader();
return;
}
updateHeader(realFirstVisibleItem);
}
private void updateHeader(int firstVisiblePosition) {
// check if there is a new header should be sticky
if (mHeaderPosition == null || mHeaderPosition != firstVisiblePosition) {
mHeaderPosition = firstVisiblePosition;
final long headerId = mAdapter.getHeaderId(firstVisiblePosition);
if (mHeaderId == null || mHeaderId != headerId) {
mHeaderId = headerId;
final View header = mAdapter.getHeaderView(mHeaderPosition, mHeader, this);
if (mHeader != header) {
if (header == null) {
throw new NullPointerException("header may not be null");
}
swapHeader(header);
}
ViewGroup.LayoutParams lp = mHeader.getLayoutParams();
if (lp.height == ViewGroup.LayoutParams.MATCH_PARENT) {
lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
mHeader.setLayoutParams(lp);
}
// measure the header
final int width = getWidth();
final int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
final int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
measureChild(mHeader, parentWidthMeasureSpec, parentHeightMeasureSpec);
// Reset mHeaderOffset to null ensuring
// that it will be set on the header and
// not skipped for performance reasons.
mHeaderOffset = null;
}
}
int headerOffset = 0;
// Calculate new header offset
// Skip looking at the first view. it never matters because it always
// results in a headerOffset = 0
int headerBottom = mHeader.getMeasuredHeight() + (mClippingToPadding ? mPaddingTop : 0);
for (int i = 0; i < mList.getChildCount(); i++) {
final View child = mList.getChildAt(i);
final boolean doesChildHaveHeader = child instanceof WrapperView && ((WrapperView) child).hasHeader();
final boolean isChildFooter = mList.containsFooterView(child);
if (child.getTop() >= (mClippingToPadding ? mPaddingTop : 0) && (doesChildHaveHeader || isChildFooter)) {
headerOffset = Math.min(child.getTop() - headerBottom, 0);
break;
}
}
setHeaderOffet(headerOffset);
if (!mIsDrawingListUnderStickyHeader) {
mList.setTopClippingLength(mHeader.getMeasuredHeight() + mHeaderOffset);
}
updateHeaderVisibilities();
}
private void swapHeader(View newHeader) {
if (mHeader != null) {
removeView(mHeader);
}
mHeader = newHeader;
addView(mHeader);
mHeader.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mOnHeaderClickListener != null) {
mOnHeaderClickListener.onHeaderClick(StickyListHeadersListView.this, mHeader, mHeaderPosition,
mHeaderId, true);
}
}
});
}
// hides the headers in the list under the sticky header.
// Makes sure the other ones are showing
private void updateHeaderVisibilities() {
int top;
if (mHeader != null) {
top = mHeader.getMeasuredHeight() + (mHeaderOffset != null ? mHeaderOffset : 0);
} else {
top = mClippingToPadding ? mPaddingTop : 0;
}
int childCount = mList.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = mList.getChildAt(i);
if (child instanceof WrapperView) {
WrapperView wrapperViewChild = (WrapperView) child;
if (wrapperViewChild.hasHeader()) {
View childHeader = wrapperViewChild.mHeader;
if (wrapperViewChild.getTop() < top) {
if (childHeader.getVisibility() != View.INVISIBLE) {
childHeader.setVisibility(View.INVISIBLE);
}
} else {
if (childHeader.getVisibility() != View.VISIBLE) {
childHeader.setVisibility(View.VISIBLE);
}
}
}
}
}
}
// Wrapper around setting the header offset in different ways depending on
// the API version
@SuppressLint("NewApi")
private void setHeaderOffet(int offset) {
if (mHeaderOffset == null || mHeaderOffset != offset) {
mHeaderOffset = offset;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mHeader.setTranslationY(mHeaderOffset);
} else {
MarginLayoutParams params = (MarginLayoutParams) mHeader.getLayoutParams();
params.topMargin = mHeaderOffset;
mHeader.setLayoutParams(params);
}
}
}
private class AdapterWrapperDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
clearHeader();
}
@Override
public void onInvalidated() {
clearHeader();
}
}
private class WrapperListScrollListener implements OnScrollListener {
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (mOnScrollListenerDelegate != null) {
mOnScrollListenerDelegate.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (mOnScrollListenerDelegate != null) {
mOnScrollListenerDelegate.onScrollStateChanged(view, scrollState);
}
}
}
private class WrapperViewListLifeCycleListener implements LifeCycleListener {
@Override
public void onDispatchDrawOccurred(Canvas canvas) {
// onScroll is not called often at all before froyo
// therefor we need to update the header here as well.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
if (mHeader != null) {
if (mClippingToPadding) {
canvas.save();
canvas.clipRect(0, mPaddingTop, getRight(), getBottom());
drawChild(canvas, mHeader, 0);
canvas.restore();
} else {
drawChild(canvas, mHeader, 0);
}
}
}
}
private class AdapterWrapperHeaderClickHandler implements AdapterWrapper.OnHeaderClickListener {
@Override
public void onHeaderClick(View header, int itemPosition, long headerId) {
mOnHeaderClickListener.onHeaderClick(StickyListHeadersListView.this, header, itemPosition, headerId, false);
}
}
private boolean isStartOfSection(int position) {
return position == 0 || mAdapter.getHeaderId(position) == mAdapter.getHeaderId(position - 1);
}
private int getHeaderOverlap(int position) {
boolean isStartOfSection = isStartOfSection(position);
if (!isStartOfSection) {
View header = mAdapter.getView(position, null, mList);
final int width = getWidth();
final int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
final int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
measureChild(header, parentWidthMeasureSpec, parentHeightMeasureSpec);
return header.getMeasuredHeight();
}
return 0;
}
/* ---------- StickyListHeaders specific API ---------- */
public void setAreHeadersSticky(boolean areHeadersSticky) {
mAreHeadersSticky = areHeadersSticky;
if (!areHeadersSticky) {
clearHeader();
} else {
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
// invalidating the list will trigger dispatchDraw()
mList.invalidate();
}
public boolean areHeadersSticky() {
return mAreHeadersSticky;
}
/**
* Use areHeadersSticky() method instead
*/
@Deprecated
public boolean getAreHeadersSticky() {
return areHeadersSticky();
}
public void setDrawingListUnderStickyHeader(boolean drawingListUnderStickyHeader) {
mIsDrawingListUnderStickyHeader = drawingListUnderStickyHeader;
// reset the top clipping length
mList.setTopClippingLength(0);
}
public boolean isDrawingListUnderStickyHeader() {
return mIsDrawingListUnderStickyHeader;
}
public void setOnHeaderClickListener(OnHeaderClickListener onHeaderClickListener) {
mOnHeaderClickListener = onHeaderClickListener;
if (mAdapter != null) {
if (mOnHeaderClickListener != null) {
mAdapter.setOnHeaderClickListener(new AdapterWrapperHeaderClickHandler());
} else {
mAdapter.setOnHeaderClickListener(null);
}
}
}
public View getListChildAt(int index) {
return mList.getChildAt(index);
}
public int getListChildCount() {
return mList.getChildCount();
}
/**
* Use the method with extreme caution!!
* Changing any values on the underlying ListView might break everything.
*
* @return the ListView backing this view.
*/
public ListView getWrappedList() {
return mList;
}
/* ---------- ListView delegate methods ---------- */
public void setAdapter(StickyListHeadersAdapter adapter) {
if (adapter == null) {
mList.setAdapter(null);
clearHeader();
return;
}
if (mAdapter != null) {
mAdapter.unregisterDataSetObserver(mDataSetObserver);
}
if (adapter instanceof SectionIndexer) {
mAdapter = new SectionIndexerAdapterWrapper(getContext(), adapter);
} else {
mAdapter = new AdapterWrapper(getContext(), adapter);
}
mDataSetObserver = new AdapterWrapperDataSetObserver();
mAdapter.registerDataSetObserver(mDataSetObserver);
if (mOnHeaderClickListener != null) {
mAdapter.setOnHeaderClickListener(new AdapterWrapperHeaderClickHandler());
} else {
mAdapter.setOnHeaderClickListener(null);
}
mAdapter.setDivider(mDivider, mDividerHeight);
mList.setAdapter(mAdapter);
clearHeader();
}
public StickyListHeadersAdapter getAdapter() {
return mAdapter == null ? null : mAdapter.mDelegate;
}
public void setDivider(Drawable divider) {
mDivider = divider;
if (mAdapter != null) {
mAdapter.setDivider(mDivider, mDividerHeight);
}
}
public void setDividerHeight(int dividerHeight) {
mDividerHeight = dividerHeight;
if (mAdapter != null) {
mAdapter.setDivider(mDivider, mDividerHeight);
}
}
public Drawable getDivider() {
return mDivider;
}
public int getDividerHeight() {
return mDividerHeight;
}
public void setOnScrollListener(OnScrollListener onScrollListener) {
mOnScrollListenerDelegate = onScrollListener;
}
public void setOnItemClickListener(OnItemClickListener listener) {
mList.setOnItemClickListener(listener);
}
public void addHeaderView(View v) {
mList.addHeaderView(v);
}
public void removeHeaderView(View v) {
mList.removeHeaderView(v);
}
public int getHeaderViewsCount() {
return mList.getHeaderViewsCount();
}
public void addFooterView(View v) {
mList.addFooterView(v);
}
public void removeFooterView(View v) {
mList.removeFooterView(v);
}
public int getFooterViewsCount() {
return mList.getFooterViewsCount();
}
public void setEmptyView(View v) {
mList.setEmptyView(v);
}
public View getEmptyView() {
return mList.getEmptyView();
}
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollBy(int distance, int duration) {
requireSdkVersion(Build.VERSION_CODES.FROYO);
mList.smoothScrollBy(distance, duration);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollByOffset(int offset) {
requireSdkVersion(Build.VERSION_CODES.HONEYCOMB);
mList.smoothScrollByOffset(offset);
}
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollToPosition(int position) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
mList.smoothScrollToPosition(position);
} else {
int offset = mAdapter == null ? 0 : getHeaderOverlap(position);
mList.smoothScrollToPositionFromTop(position, offset);
}
}
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollToPosition(int position, int boundPosition) {
requireSdkVersion(Build.VERSION_CODES.FROYO);
mList.smoothScrollToPosition(position, boundPosition);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollToPositionFromTop(int position, int offset) {
requireSdkVersion(Build.VERSION_CODES.HONEYCOMB);
offset += mAdapter == null ? 0 : getHeaderOverlap(position);
mList.smoothScrollToPositionFromTop(position, offset);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollToPositionFromTop(int position, int offset, int duration) {
requireSdkVersion(Build.VERSION_CODES.HONEYCOMB);
offset += mAdapter == null ? 0 : getHeaderOverlap(position);
mList.smoothScrollToPositionFromTop(position, offset, duration);
}
public void setSelection(int position) {
mList.setSelection(position);
}
public void setSelectionAfterHeaderView() {
mList.setSelectionAfterHeaderView();
}
public void setSelectionFromTop(int position, int y) {
mList.setSelectionFromTop(position, y);
}
public void setSelector(Drawable sel) {
mList.setSelector(sel);
}
public void setSelector(int resID) {
mList.setSelector(resID);
}
public int getFirstVisiblePosition() {
return mList.getFirstVisiblePosition();
}
public int getLastVisiblePosition() {
return mList.getLastVisiblePosition();
}
public void setChoiceMode(int choiceMode) {
mList.setChoiceMode(choiceMode);
}
public void setItemChecked(int position, boolean value) {
mList.setItemChecked(position, value);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public int getCheckedItemCount() {
requireSdkVersion(Build.VERSION_CODES.HONEYCOMB);
return mList.getCheckedItemCount();
}
@TargetApi(Build.VERSION_CODES.FROYO)
public long[] getCheckedItemIds() {
requireSdkVersion(Build.VERSION_CODES.FROYO);
return mList.getCheckedItemIds();
}
public int getCheckedItemPosition() {
return mList.getCheckedItemPosition();
}
public SparseBooleanArray getCheckedItemPositions() {
return mList.getCheckedItemPositions();
}
public int getCount() {
return mList.getCount();
}
public Object getItemAtPosition(int position) {
return mList.getItemAtPosition(position);
}
public long getItemIdAtPosition(int position) {
return mList.getItemIdAtPosition(position);
}
@Override
public void setClipToPadding(boolean clipToPadding) {
if (mList != null) {
mList.setClipToPadding(clipToPadding);
}
mClippingToPadding = clipToPadding;
}
@Override
public void setPadding(int left, int top, int right, int bottom) {
mPaddingLeft = left;
mPaddingTop = top;
mPaddingRight = right;
mPaddingBottom = bottom;
// Set left/right paddings on the wrapper and top/bottom on the
// list to support the clip to padding flag
super.setPadding(left, 0, right, 0);
if (mList != null) {
mList.setPadding(0, top, 0, bottom);
}
}
@Override
public int getPaddingLeft() {
return mPaddingLeft;
}
@Override
public int getPaddingTop() {
return mPaddingTop;
}
@Override
public int getPaddingRight() {
return mPaddingRight;
}
@Override
public int getPaddingBottom() {
return mPaddingBottom;
}
public void setFastScrollEnabled(boolean fastScrollEnabled) {
mList.setFastScrollEnabled(fastScrollEnabled);
}
private void requireSdkVersion(int versionCode) {
if (Build.VERSION.SDK_INT < versionCode) {
throw new ApiLevelTooLowException(versionCode);
}
}
public int getPositionForView(View view){
return mList.getPositionForView(view);
}
}
| fixes #188
| library/src/se/emilsjolander/stickylistheaders/StickyListHeadersListView.java | fixes #188 |
|
Java | apache-2.0 | aa5eeac19368a6f4cf5d8090c344ba0f78c536f0 | 0 | andrhamm/Singularity,andrhamm/Singularity,grepsr/Singularity,hs-jenkins-bot/Singularity,andrhamm/Singularity,hs-jenkins-bot/Singularity,grepsr/Singularity,grepsr/Singularity,grepsr/Singularity,HubSpot/Singularity,HubSpot/Singularity,HubSpot/Singularity,andrhamm/Singularity,grepsr/Singularity,HubSpot/Singularity,grepsr/Singularity,HubSpot/Singularity,hs-jenkins-bot/Singularity,hs-jenkins-bot/Singularity,andrhamm/Singularity,hs-jenkins-bot/Singularity | package com.hubspot.singularity.scheduler;
import com.google.inject.AbstractModule;
import com.google.inject.Scopes;
import com.hubspot.singularity.data.history.SingularityHistoryPurger;
public class SingularitySchedulerModule extends AbstractModule {
@Override
protected void configure() {
bind(SingularityHealthchecker.class).in(Scopes.SINGLETON);
bind(SingularityNewTaskChecker.class).in(Scopes.SINGLETON);
bind(SingularityCleanupPoller.class).in(Scopes.SINGLETON);
bind(SingularityExpiringUserActionPoller.class).in(Scopes.SINGLETON);
bind(SingularityHistoryPurger.class).in(Scopes.SINGLETON);
bind(SingularityDeadSlavePoller.class).in(Scopes.SINGLETON);
bind(SingularityCooldownPoller.class).in(Scopes.SINGLETON);
bind(SingularityDeployPoller.class).in(Scopes.SINGLETON);
bind(SingularityCooldownPoller.class).in(Scopes.SINGLETON);
bind(SingularityDeployPoller.class).in(Scopes.SINGLETON);
bind(SingularitySchedulerPoller.class).in(Scopes.SINGLETON);
bind(SingularityScheduledJobPoller.class).in(Scopes.SINGLETON);
bind(SingularityTaskShellCommandDispatchPoller.class).in(Scopes.SINGLETON);
bind(SingularityTaskReconciliationPoller.class).in(Scopes.SINGLETON);
bind(SingularityScheduler.class).in(Scopes.SINGLETON);
bind(SingularityCooldownChecker.class).in(Scopes.SINGLETON);
bind(SingularityDeployChecker.class).in(Scopes.SINGLETON);
bind(SingularityCleaner.class).in(Scopes.SINGLETON);
bind(SingularityCooldown.class).in(Scopes.SINGLETON);
bind(SingularityDeployHealthHelper.class).in(Scopes.SINGLETON);
bind(SingularityCooldown.class).in(Scopes.SINGLETON);
bind(SingularityHealthchecker.class).in(Scopes.SINGLETON);
bind(SingularityNewTaskChecker.class).in(Scopes.SINGLETON);
bind(SingularityTaskReconciliation.class).in(Scopes.SINGLETON);
bind(SingularitySchedulerPriority.class).in(Scopes.SINGLETON);
bind(SingularityMailPoller.class).in(Scopes.SINGLETON);
bind(SingularitySchedulerStateCache.class);
}
}
| SingularityService/src/main/java/com/hubspot/singularity/scheduler/SingularitySchedulerModule.java | package com.hubspot.singularity.scheduler;
import com.google.inject.AbstractModule;
import com.google.inject.Scopes;
import com.hubspot.singularity.data.history.SingularityHistoryPurger;
public class SingularitySchedulerModule extends AbstractModule {
@Override
protected void configure() {
bind(SingularityHealthchecker.class).in(Scopes.SINGLETON);
bind(SingularityNewTaskChecker.class).in(Scopes.SINGLETON);
bind(SingularityCleanupPoller.class).in(Scopes.SINGLETON);
bind(SingularityExpiringUserActionPoller.class).in(Scopes.SINGLETON);
bind(SingularityHistoryPurger.class).in(Scopes.SINGLETON);
bind(SingularityDeadSlavePoller.class).in(Scopes.SINGLETON);
bind(SingularityCooldownPoller.class).in(Scopes.SINGLETON);
bind(SingularityDeployPoller.class).in(Scopes.SINGLETON);
bind(SingularityCooldownPoller.class).in(Scopes.SINGLETON);
bind(SingularityDeployPoller.class).in(Scopes.SINGLETON);
bind(SingularitySchedulerPoller.class).in(Scopes.SINGLETON);
bind(SingularityScheduledJobPoller.class).in(Scopes.SINGLETON);
bind(SingularityTaskShellCommandDispatchPoller.class).in(Scopes.SINGLETON);
bind(SingularityTaskReconciliationPoller.class).in(Scopes.SINGLETON);
bind(SingularityScheduler.class).in(Scopes.SINGLETON);
bind(SingularityCooldownChecker.class).in(Scopes.SINGLETON);
bind(SingularityDeployChecker.class).in(Scopes.SINGLETON);
bind(SingularityCleaner.class).in(Scopes.SINGLETON);
bind(SingularityCooldown.class).in(Scopes.SINGLETON);
bind(SingularityDeployHealthHelper.class).in(Scopes.SINGLETON);
bind(SingularityCooldown.class).in(Scopes.SINGLETON);
bind(SingularityHealthchecker.class).in(Scopes.SINGLETON);
bind(SingularityNewTaskChecker.class).in(Scopes.SINGLETON);
bind(SingularityTaskReconciliation.class).in(Scopes.SINGLETON);
bind(SingularitySchedulerPriority.class).in(Scopes.SINGLETON);
bind(SingularitySchedulerStateCache.class);
}
}
| bind this
| SingularityService/src/main/java/com/hubspot/singularity/scheduler/SingularitySchedulerModule.java | bind this |
|
Java | apache-2.0 | 47d4abec7912e7b5e34bd832d68df32b117b94ac | 0 | Donnerbart/hazelcast,Donnerbart/hazelcast,emrahkocaman/hazelcast,tkountis/hazelcast,juanavelez/hazelcast,juanavelez/hazelcast,mesutcelik/hazelcast,tkountis/hazelcast,mesutcelik/hazelcast,tufangorel/hazelcast,tombujok/hazelcast,dbrimley/hazelcast,mdogan/hazelcast,lmjacksoniii/hazelcast,Donnerbart/hazelcast,emre-aydin/hazelcast,mdogan/hazelcast,tombujok/hazelcast,emrahkocaman/hazelcast,emre-aydin/hazelcast,dsukhoroslov/hazelcast,dbrimley/hazelcast,mesutcelik/hazelcast,lmjacksoniii/hazelcast,dbrimley/hazelcast,tkountis/hazelcast,emre-aydin/hazelcast,dsukhoroslov/hazelcast,tufangorel/hazelcast,mdogan/hazelcast,tufangorel/hazelcast | package com.hazelcast.spi.impl.operationservice.impl;
import com.hazelcast.config.Config;
import com.hazelcast.core.ExecutionCallback;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ICompletableFuture;
import com.hazelcast.core.OperationTimeoutException;
import com.hazelcast.spi.OperationService;
import com.hazelcast.spi.properties.GroupProperty;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class Invocation_TimeoutTest extends HazelcastTestSupport {
private final static Object RESPONSE = "someresponse";
/**
* Tests if the get is called with a timeout, and the operation takes more time to execute then the timeout, that the call
* fails with a TimeoutException.
*/
@Test
public void whenGetTimeout_thenTimeoutException() throws InterruptedException, ExecutionException, TimeoutException {
Config config = new Config();
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
Future future = opService.invokeOnPartition(
null,
new SlowOperation(SECONDS.toMillis(10), RESPONSE),
getPartitionId(remote));
try {
future.get(1, SECONDS);
fail();
} catch (TimeoutException ignored) {
}
// so even though the previous get failed with a timeout, the future can still provide a valid result.
assertEquals(RESPONSE, future.get());
}
@Test
public void whenMultipleThreadsCallGetOnSameLongRunningOperation() throws ExecutionException, InterruptedException {
long callTimeout = 5000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeout);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
final Future future = opService.invokeOnPartition(
null,
new SlowOperation(callTimeout * 3, RESPONSE),
getPartitionId(remote));
List<Future> futures = new LinkedList<Future>();
for (int k = 0; k < 10; k++) {
futures.add(spawn(new Callable<Object>() {
@Override
public Object call() throws Exception {
return future.get();
}
}));
}
for (Future sf : futures) {
assertEquals(RESPONSE, sf.get());
}
}
// ==================== long running operation ===============================================================================
// Tests that a long running operation is not going to give any problems.
//
// When an operation is running for a long time, so a much longer time than the call timeout and heartbeat time, due to
// the heartbeats being detected, the call will not timeout and returns a valid response.
// ===========================================================================================================================
@Test
public void sync_whenLongRunningOperation() throws InterruptedException, ExecutionException, TimeoutException {
long callTimeout = 5000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeout);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
Future future = opService.invokeOnPartition(
null,
new SlowOperation(6 * callTimeout, RESPONSE),
getPartitionId(remote));
Object result = future.get(120, SECONDS);
assertEquals(RESPONSE, result);
}
@Test
public void async_whenLongRunningOperation() throws InterruptedException, ExecutionException, TimeoutException {
long callTimeout = 5000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeout);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
ICompletableFuture<Object> future = opService.invokeOnPartition(
null,
new SlowOperation(6 * callTimeout, RESPONSE),
getPartitionId(remote));
final ExecutionCallback<Object> callback = getExecutionCallbackMock();
future.andThen(callback);
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
verify(callback).onResponse(RESPONSE);
}
});
}
// ==================== operation heartbeat timeout ==========================================================================
// This test verifies that an Invocation is going to timeout when no heartbeat is received.
//
// This is simulated by executing an void operation (an operation that doesn't send a response). After the execution of this
// operation, no heartbeats will be received since it has executed successfully. So eventually the heartbeat timeout should
// kick in.
// ===========================================================================================================================
@Test
public void sync_whenHeartbeatTimeout_thenOperationTimeoutException() throws Exception {
long callTimeoutMs = 5000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeoutMs);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
Future future = opService.invokeOnPartition(
null,
new VoidOperation(),
getPartitionId(remote));
try {
future.get(5 * callTimeoutMs, MILLISECONDS);
fail();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
assertInstanceOf(OperationTimeoutException.class, cause);
assertTrue(cause.getMessage(), cause.getMessage().contains("operation-heartbeat-timeout"));
}
}
@Test
public void async_whenHeartbeatTimeout_thenOperationTimeoutException() throws Exception {
long callTimeoutMs = 1000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeoutMs);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
ICompletableFuture<Object> future = opService.invokeOnPartition(
null,
new VoidOperation(),
getPartitionId(remote));
ExecutionCallback<Object> callback = getExecutionCallbackMock();
future.andThen(callback);
assertEventuallyFailsWithHeartbeatTimeout(callback);
}
// ==================== eventually operation heartbeat timeout ===============================================================
// This test verifies that an Invocation is going to timeout when initially there was a heartbeat, but eventually this
// heartbeat stops
//
// This is done by creating a void operation that runs for an extended period and on completion, the void operation doesn't
// send a response.
// ===========================================================================================================================
@Test
public void sync_whenEventuallyHeartbeatTimeout_thenOperationTimeoutException() throws Exception {
long callTimeoutMs = 5000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeoutMs);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
Future future = opService.invokeOnPartition(
null,
new VoidOperation(callTimeoutMs * 5),
getPartitionId(remote));
try {
future.get(10 * callTimeoutMs, MILLISECONDS);
fail();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
assertInstanceOf(OperationTimeoutException.class, cause);
assertTrue(cause.getMessage(), cause.getMessage().contains("operation-heartbeat-timeout"));
}
}
@Test
public void async_whenEventuallyHeartbeatTimeout_thenOperationTimeoutException() throws Exception {
long callTimeoutMs = 5000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeoutMs);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
ICompletableFuture<Object> future = opService.invokeOnPartition(
null,
new VoidOperation(callTimeoutMs * 5),
getPartitionId(remote));
final ExecutionCallback<Object> callback = getExecutionCallbackMock();
future.andThen(callback);
assertEventuallyFailsWithHeartbeatTimeout(callback);
}
// ==================== operation call timeout ===============================================================================
// This test verifies that an operation doesn't get executed after its timeout expires. This is done by
// executing an operation in front of the operation that takes a lot of time to execute.
// ===========================================================================================================================
@Test
@Ignore //https://github.com/hazelcast/hazelcast/issues/7932
public void sync_whenCallTimeout_thenOperationTimeoutException() throws Exception {
long callTimeoutMs = 60000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeoutMs);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
int partitionId = getPartitionId(remote);
opService.invokeOnPartition(new SlowOperation(callTimeoutMs * 2).setPartitionId(partitionId));
Future future = opService.invokeOnPartition(new DummyOperation().setPartitionId(partitionId));
try {
future.get(3 * callTimeoutMs, MILLISECONDS);
fail();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
assertInstanceOf(OperationTimeoutException.class, cause);
assertTrue(cause.getMessage(), cause.getMessage().contains("operation-call-timeout"));
}
}
@Test
@Ignore //https://github.com/hazelcast/hazelcast/issues/7932
public void async_whenCallTimeout_thenOperationTimeoutException() throws Exception {
long callTimeoutMs = 60000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeoutMs);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
int partitionId = getPartitionId(remote);
opService.invokeOnPartition(new SlowOperation(callTimeoutMs * 2).setPartitionId(partitionId));
ICompletableFuture<Object> future = opService.invokeOnPartition(new DummyOperation().setPartitionId(partitionId));
ExecutionCallback<Object> callback = getExecutionCallbackMock();
future.andThen(callback);
assertEventuallyFailsWithCallTimeout(callback);
}
@SuppressWarnings("unchecked")
private static ExecutionCallback<Object> getExecutionCallbackMock() {
return mock(ExecutionCallback.class);
}
private static void assertEventuallyFailsWithHeartbeatTimeout(final ExecutionCallback callback) {
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
ArgumentCaptor<Throwable> argument = ArgumentCaptor.forClass(Throwable.class);
verify(callback).onFailure(argument.capture());
Throwable cause = argument.getValue();
assertInstanceOf(OperationTimeoutException.class, cause);
assertTrue(cause.getMessage(), cause.getMessage().contains("operation-heartbeat-timeout"));
}
});
}
private static void assertEventuallyFailsWithCallTimeout(final ExecutionCallback callback) {
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
ArgumentCaptor<Throwable> argument = ArgumentCaptor.forClass(Throwable.class);
verify(callback).onFailure(argument.capture());
Throwable cause = argument.getValue();
assertInstanceOf(OperationTimeoutException.class, cause);
assertTrue(cause.getMessage(), cause.getMessage().contains("operation-call-timeout"));
}
});
}
}
| hazelcast/src/test/java/com/hazelcast/spi/impl/operationservice/impl/Invocation_TimeoutTest.java | package com.hazelcast.spi.impl.operationservice.impl;
import com.hazelcast.config.Config;
import com.hazelcast.core.ExecutionCallback;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ICompletableFuture;
import com.hazelcast.core.OperationTimeoutException;
import com.hazelcast.spi.OperationService;
import com.hazelcast.spi.properties.GroupProperty;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class Invocation_TimeoutTest extends HazelcastTestSupport {
private final static Object RESPONSE = "someresponse";
/**
* Tests if the get is called with a timeout, and the operation takes more time to execute then the timeout, that the call
* fails with a TimeoutException.
*/
@Test
public void whenGetTimeout_thenTimeoutException() throws InterruptedException, ExecutionException, TimeoutException {
Config config = new Config();
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
Future future = opService.invokeOnPartition(
null,
new SlowOperation(SECONDS.toMillis(10), RESPONSE),
getPartitionId(remote));
try {
future.get(1, SECONDS);
fail();
} catch (TimeoutException ignored) {
}
// so even though the previous get failed with a timeout, the future can still provide a valid result.
assertEquals(RESPONSE, future.get());
}
@Test
public void whenMultipleThreadsCallGetOnSameLongRunningOperation() throws ExecutionException, InterruptedException {
long callTimeout = 5000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeout);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
final Future future = opService.invokeOnPartition(
null,
new SlowOperation(callTimeout * 3, RESPONSE),
getPartitionId(remote));
List<Future> futures = new LinkedList<Future>();
for (int k = 0; k < 10; k++) {
futures.add(spawn(new Callable<Object>() {
@Override
public Object call() throws Exception {
return future.get();
}
}));
}
for (Future sf : futures) {
assertEquals(RESPONSE, sf.get());
}
}
// ==================== long running operation ===============================================================================
// Tests that a long running operation is not going to give any problems.
//
// When an operation is running for a long time, so a much longer time than the call timeout and heartbeat time, due to
// the heartbeats being detected, the call will not timeout and returns a valid response.
// ===========================================================================================================================
@Test
public void sync_whenLongRunningOperation() throws InterruptedException, ExecutionException, TimeoutException {
long callTimeout = 5000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeout);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
Future future = opService.invokeOnPartition(
null,
new SlowOperation(6 * callTimeout, RESPONSE),
getPartitionId(remote));
Object result = future.get(120, SECONDS);
assertEquals(RESPONSE, result);
}
@Test
public void async_whenLongRunningOperation() throws InterruptedException, ExecutionException, TimeoutException {
long callTimeout = 5000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeout);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
ICompletableFuture<Object> future = opService.invokeOnPartition(
null,
new SlowOperation(6 * callTimeout, RESPONSE),
getPartitionId(remote));
final ExecutionCallback<Object> callback = getExecutionCallbackMock();
future.andThen(callback);
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
verify(callback).onResponse(RESPONSE);
}
});
}
// ==================== operation heartbeat timeout ==========================================================================
// This test verifies that an Invocation is going to timeout when no heartbeat is received.
//
// This is simulated by executing an void operation (an operation that doesn't send a response). After the execution of this
// operation, no heartbeats will be received since it has executed successfully. So eventually the heartbeat timeout should
// kick in.
// ===========================================================================================================================
@Test
public void sync_whenHeartbeatTimeout_thenOperationTimeoutException() throws Exception {
long callTimeoutMs = 5000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeoutMs);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
Future future = opService.invokeOnPartition(
null,
new VoidOperation(),
getPartitionId(remote));
try {
future.get(5 * callTimeoutMs, MILLISECONDS);
fail();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
assertInstanceOf(OperationTimeoutException.class, cause);
assertTrue(cause.getMessage(), cause.getMessage().contains("operation-heartbeat-timeout"));
}
}
@Test
public void async_whenHeartbeatTimeout_thenOperationTimeoutException() throws Exception {
long callTimeoutMs = 1000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeoutMs);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
ICompletableFuture<Object> future = opService.invokeOnPartition(
null,
new VoidOperation(),
getPartitionId(remote));
ExecutionCallback<Object> callback = getExecutionCallbackMock();
future.andThen(callback);
assertEventuallyFailsWithHeartbeatTimeout(callback);
}
// ==================== eventually operation heartbeat timeout ===============================================================
// This test verifies that an Invocation is going to timeout when initially there was a heartbeat, but eventually this
// heartbeat stops
//
// This is done by creating a void operation that runs for an extended period and on completion, the void operation doesn't
// send a response.
// ===========================================================================================================================
@Test
public void sync_whenEventuallyHeartbeatTimeout_thenOperationTimeoutException() throws Exception {
long callTimeoutMs = 5000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeoutMs);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
Future future = opService.invokeOnPartition(
null,
new VoidOperation(callTimeoutMs * 5),
getPartitionId(remote));
try {
future.get(10 * callTimeoutMs, MILLISECONDS);
fail();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
assertInstanceOf(OperationTimeoutException.class, cause);
assertTrue(cause.getMessage(), cause.getMessage().contains("operation-heartbeat-timeout"));
}
}
@Test
public void async_whenEventuallyHeartbeatTimeout_thenOperationTimeoutException() throws Exception {
long callTimeoutMs = 5000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeoutMs);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
ICompletableFuture<Object> future = opService.invokeOnPartition(
null,
new VoidOperation(callTimeoutMs * 5),
getPartitionId(remote));
final ExecutionCallback<Object> callback = getExecutionCallbackMock();
future.andThen(callback);
assertEventuallyFailsWithHeartbeatTimeout(callback);
}
// ==================== operation call timeout ===============================================================================
// This test verifies that an operation doesn't get executed after its timeout expires. This is done by
// executing an operation in front of the operation that takes a lot of time to execute.
// ===========================================================================================================================
@Test
public void sync_whenCallTimeout_thenOperationTimeoutException() throws Exception {
long callTimeoutMs = 60000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeoutMs);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
int partitionId = getPartitionId(remote);
opService.invokeOnPartition(new SlowOperation(callTimeoutMs * 2).setPartitionId(partitionId));
Future future = opService.invokeOnPartition(new DummyOperation().setPartitionId(partitionId));
try {
future.get(3 * callTimeoutMs, MILLISECONDS);
fail();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
assertInstanceOf(OperationTimeoutException.class, cause);
assertTrue(cause.getMessage(), cause.getMessage().contains("operation-call-timeout"));
}
}
@Test
public void async_whenCallTimeout_thenOperationTimeoutException() throws Exception {
long callTimeoutMs = 60000;
Config config = new Config().setProperty(GroupProperty.OPERATION_CALL_TIMEOUT_MILLIS.getName(), "" + callTimeoutMs);
TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory(2);
HazelcastInstance local = factory.newHazelcastInstance(config);
HazelcastInstance remote = factory.newHazelcastInstance(config);
warmUpPartitions(local, remote);
OperationService opService = getOperationService(local);
int partitionId = getPartitionId(remote);
opService.invokeOnPartition(new SlowOperation(callTimeoutMs * 2).setPartitionId(partitionId));
ICompletableFuture<Object> future = opService.invokeOnPartition(new DummyOperation().setPartitionId(partitionId));
ExecutionCallback<Object> callback = getExecutionCallbackMock();
future.andThen(callback);
assertEventuallyFailsWithCallTimeout(callback);
}
@SuppressWarnings("unchecked")
private static ExecutionCallback<Object> getExecutionCallbackMock() {
return mock(ExecutionCallback.class);
}
private static void assertEventuallyFailsWithHeartbeatTimeout(final ExecutionCallback callback) {
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
ArgumentCaptor<Throwable> argument = ArgumentCaptor.forClass(Throwable.class);
verify(callback).onFailure(argument.capture());
Throwable cause = argument.getValue();
assertInstanceOf(OperationTimeoutException.class, cause);
assertTrue(cause.getMessage(), cause.getMessage().contains("operation-heartbeat-timeout"));
}
});
}
private static void assertEventuallyFailsWithCallTimeout(final ExecutionCallback callback) {
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
ArgumentCaptor<Throwable> argument = ArgumentCaptor.forClass(Throwable.class);
verify(callback).onFailure(argument.capture());
Throwable cause = argument.getValue();
assertInstanceOf(OperationTimeoutException.class, cause);
assertTrue(cause.getMessage(), cause.getMessage().contains("operation-call-timeout"));
}
});
}
}
| ignored #7932
| hazelcast/src/test/java/com/hazelcast/spi/impl/operationservice/impl/Invocation_TimeoutTest.java | ignored #7932 |
|
Java | apache-2.0 | eaf09c48139172e6e6ae8e621ae53b266fb7bc55 | 0 | rankinc/Resteasy,awhitford/Resteasy,psakar/Resteasy,rankinc/Resteasy,awhitford/Resteasy,psakar/Resteasy,rankinc/Resteasy,awhitford/Resteasy,psakar/Resteasy,rankinc/Resteasy,awhitford/Resteasy,psakar/Resteasy,awhitford/Resteasy | package org.jboss.resteasy.core;
import org.jboss.resteasy.specimpl.BuiltResponse;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ServerResponse extends BuiltResponse
{
public ServerResponse()
{
}
public ServerResponse(Object entity, int status, Headers<Object> metadata)
{
this.setEntity(entity);
this.status = status;
this.metadata = metadata;
}
public ServerResponse(BuiltResponse response)
{
this.setEntity(response.getEntity());
this.setAnnotations(response.getAnnotations());
this.setStatus(response.getStatus());
this.setMetadata(response.getMetadata());
this.setEntityClass(response.getEntityClass());
this.setGenericType(response.getGenericType());
}
}
| jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ServerResponse.java | package org.jboss.resteasy.core;
import org.jboss.resteasy.specimpl.BuiltResponse;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ServerResponse extends BuiltResponse
{
public ServerResponse()
{
}
public ServerResponse(Object entity, int status, Headers<Object> metadata)
{
this.entity = entity;
this.status = status;
this.metadata = metadata;
}
public ServerResponse(BuiltResponse response)
{
this.setEntity(response.getEntity());
this.setAnnotations(response.getAnnotations());
this.setStatus(response.getStatus());
this.setMetadata(response.getMetadata());
this.setEntityClass(response.getEntityClass());
this.setGenericType(response.getGenericType());
}
}
| ServerResponse not setting entityClass
The constructor of ServerResponse that takes an entity as an argument
doesn't set the entityClass.
| jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ServerResponse.java | ServerResponse not setting entityClass |
|
Java | apache-2.0 | b04a12d39f5acc42f9dca247d2463d365dcabb41 | 0 | dhirajsb/fabric8,opensourceconsultant/fuse,chirino/fabric8,janstey/fabric8,chirino/fabric8v2,janstey/fuse,gnodet/fuse,jboss-fuse/fuse,migue/fabric8,sobkowiak/fabric8,gashcrumb/fabric8,joelschuster/fuse,rhuss/fabric8,rajdavies/fabric8,jludvice/fabric8,avano/fabric8,tadayosi/fuse,janstey/fuse,rhuss/fabric8,jboss-fuse/fuse,rajdavies/fabric8,chirino/fabric8v2,mwringe/fabric8,janstey/fuse,hekonsek/fabric8,migue/fabric8,mwringe/fabric8,gashcrumb/fabric8,ffang/fuse-1,punkhorn/fabric8,punkhorn/fabric8,dhirajsb/fuse,EricWittmann/fabric8,janstey/fuse-1,aslakknutsen/fabric8,PhilHardwick/fabric8,punkhorn/fuse,chirino/fuse,sobkowiak/fabric8,jimmidyson/fabric8,aslakknutsen/fabric8,jludvice/fabric8,rajdavies/fabric8,jimmidyson/fabric8,opensourceconsultant/fuse,gashcrumb/fabric8,dhirajsb/fabric8,tadayosi/fuse,cunningt/fuse,christian-posta/fabric8,sobkowiak/fuse,chirino/fabric8v2,dhirajsb/fabric8,rmarting/fuse,zmhassan/fabric8,jonathanchristison/fabric8,cunningt/fuse,PhilHardwick/fabric8,migue/fabric8,janstey/fuse,rmarting/fuse,chirino/fuse,KurtStam/fabric8,jonathanchristison/fabric8,jimmidyson/fabric8,dejanb/fuse,jonathanchristison/fabric8,joelschuster/fuse,EricWittmann/fabric8,janstey/fabric8,rajdavies/fabric8,KurtStam/fabric8,dhirajsb/fabric8,opensourceconsultant/fuse,mwringe/fabric8,rhuss/fabric8,zmhassan/fabric8,joelschuster/fuse,EricWittmann/fabric8,chirino/fabric8v2,rnc/fabric8,avano/fabric8,sobkowiak/fabric8,mwringe/fabric8,hekonsek/fabric8,christian-posta/fabric8,chirino/fabric8,avano/fabric8,PhilHardwick/fabric8,jludvice/fabric8,chirino/fabric8,gashcrumb/fabric8,dejanb/fuse,jboss-fuse/fuse,sobkowiak/fuse,rhuss/fabric8,jimmidyson/fabric8,jludvice/fabric8,EricWittmann/fabric8,hekonsek/fabric8,gnodet/fuse,ffang/fuse-1,dejanb/fuse,rmarting/fuse,zmhassan/fabric8,KurtStam/fabric8,migue/fabric8,hekonsek/fabric8,janstey/fuse-1,dhirajsb/fuse,ffang/fuse-1,aslakknutsen/fabric8,jimmidyson/fabric8,gnodet/fuse,punkhorn/fuse,christian-posta/fabric8,janstey/fuse-1,rnc/fabric8,rnc/fabric8,rnc/fabric8,janstey/fabric8,hekonsek/fabric8,KurtStam/fabric8,rnc/fabric8,PhilHardwick/fabric8,sobkowiak/fabric8,zmhassan/fabric8,jonathanchristison/fabric8,punkhorn/fabric8,christian-posta/fabric8,punkhorn/fabric8,avano/fabric8,chirino/fabric8,gnodet/fuse | /**
* Copyright (C) FuseSource, Inc.
* http://fusesource.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fusesource.fabric.boot.commands;
import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;
import org.apache.felix.gogo.commands.Option;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import org.apache.zookeeper.KeeperException;
import org.fusesource.fabric.internal.FabricConstants;
import org.fusesource.fabric.utils.BundleUtils;
import org.fusesource.fabric.zookeeper.IZKClient;
import org.fusesource.fabric.zookeeper.ZkDefs;
import org.fusesource.fabric.zookeeper.ZkPath;
import org.linkedin.util.clock.Timespan;
import org.linkedin.zookeeper.client.ZKClient;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.service.cm.ConfigurationAdmin;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
@Command(name = "join", scope = "fabric", description = "Join a container to an existing fabric", detailedDescription = "classpath:join.txt")
public class Join extends OsgiCommandSupport implements org.fusesource.fabric.boot.commands.service.Join {
ConfigurationAdmin configurationAdmin;
private IZKClient zooKeeper;
private String version = ZkDefs.DEFAULT_VERSION;
private BundleContext bundleContext;
@Option(name = "-n", aliases = "--non-managed", multiValued = false, description = "Flag to keep the container non managed")
private boolean nonManaged;
@Option(name = "-f", aliases = "--force", multiValued = false, description = "Forces the use of container name.")
private boolean force;
@Argument(required = true, index = 0, multiValued = false, description = "Zookeeper URL")
private String zookeeperUrl;
@Argument(required = false, index = 1, multiValued = false, description = "Container name to use in fabric; by default a karaf name will be used")
private String containerName;
@Override
protected Object doExecute() throws Exception {
String oldName = System.getProperty("karaf.name");
if (containerName == null) {
containerName = oldName;
}
if (!containerName.equals(oldName)) {
if (force || permissionToRenameContainer()) {
if (!registerContainer(containerName, force)) {
System.err.print("A container with the name: " + containerName + " is already member of the cluster. You can use the --container-name option to specify a different name.");
return null;
}
System.setProperty("karaf.name", containerName);
System.setProperty("zookeeper.url", zookeeperUrl);
//Rename the container
File file = new File(System.getProperty("karaf.base") + "/etc/system.properties");
org.apache.felix.utils.properties.Properties props = new org.apache.felix.utils.properties.Properties(file);
props.put("karaf.name", containerName);
props.put("zookeeper.url", zookeeperUrl);
props.save();
//Install required bundles
if (!nonManaged) {
installBundles();
}
org.osgi.service.cm.Configuration config = configurationAdmin.getConfiguration("org.fusesource.fabric.zookeeper");
Properties properties = new Properties();
properties.put("zookeeper.url", zookeeperUrl);
config.setBundleLocation(null);
config.update(properties);
//Restart the container
System.setProperty("karaf.restart", "true");
System.setProperty("karaf.restart.clean", "false");
bundleContext.getBundle(0).stop();
return null;
} else {
return null;
}
} else {
if (!registerContainer(containerName, force)) {
System.err.println("A container with the name: " + containerName + " is already member of the cluster. You can use the --container-name option to specify a different name.");
return null;
}
org.osgi.service.cm.Configuration config = configurationAdmin.getConfiguration("org.fusesource.fabric.zookeeper");
Properties properties = new Properties();
properties.put("zookeeper.url", zookeeperUrl);
config.setBundleLocation(null);
config.update(properties);
installBundles();
return null;
}
}
/**
* Checks if there is an existing container using the same name.
*
* @param name
* @return
* @throws InterruptedException
* @throws KeeperException
*/
private boolean registerContainer(String name, boolean force) throws InterruptedException, KeeperException {
boolean exists = false;
ZKClient zkClient = null;
try {
zkClient = new ZKClient(zookeeperUrl, Timespan.ONE_MINUTE, null);
zkClient.start();
zkClient.waitForStart();
exists = zkClient.exists(ZkPath.CONTAINER.getPath(name)) != null;
if (!exists || force) {
ZkPath.createContainerPaths(zkClient, containerName, version);
}
} finally {
if (zkClient != null) {
zkClient.destroy();
}
}
return !exists || force;
}
/**
* Asks the users permission to restart the container.
*
* @return
* @throws IOException
*/
private boolean permissionToRenameContainer() throws IOException {
for (; ; ) {
StringBuffer sb = new StringBuffer();
System.err.println("You are about to change the container name. This action will restart the container.");
System.err.println("The local shell will automatically restart, but ssh connections will be terminated.");
System.err.println("The container will automatically join: " + zookeeperUrl + " the cluster after it restarts.");
System.err.print("Do you wish to proceed (yes/no):");
System.err.flush();
for (; ; ) {
int c = session.getKeyboard().read();
if (c < 0) {
return false;
}
System.err.print((char) c);
if (c == '\r' || c == '\n') {
break;
}
sb.append((char) c);
}
String str = sb.toString();
if ("yes".equals(str)) {
return true;
}
if ("no".equals(str)) {
return false;
}
}
}
public void installBundles() throws BundleException {
Bundle bundleFabricJaas = BundleUtils.findOrInstallBundle(bundleContext, "org.fusesource.fabric.fabric-jaas",
"mvn:org.fusesource.fabric/fabric-jaas/" + FabricConstants.FABRIC_VERSION);
Bundle bundleFabricCommands = BundleUtils.findOrInstallBundle(bundleContext, "org.fusesource.fabric.fabric-commands",
"mvn:org.fusesource.fabric/fabric-commands/" + FabricConstants.FABRIC_VERSION);
bundleFabricJaas.start();
bundleFabricCommands.start();
if (!nonManaged) {
Bundle bundleFabricConfigAdmin = BundleUtils.findOrInstallBundle(bundleContext, "org.fusesource.fabric.fabric-configadmin",
"mvn:org.fusesource.fabric/fabric-configadmin/" + FabricConstants.FABRIC_VERSION);
Bundle bundleFabricAgent = BundleUtils.findOrInstallBundle(bundleContext, "org.fusesource.fabric.fabric-agent",
"mvn:org.fusesource.fabric/fabric-agent/" + FabricConstants.FABRIC_VERSION);
bundleFabricConfigAdmin.start();
bundleFabricAgent.start();
}
}
@Override
public Object run() throws Exception {
return doExecute();
}
@Override
public void setConfigurationAdmin(ConfigurationAdmin configurationAdmin) {
this.configurationAdmin = configurationAdmin;
}
@Override
public void setZooKeeper(IZKClient zooKeeper) {
this.zooKeeper = zooKeeper;
}
@Override
public String getVersion() {
return version;
}
@Override
public void setVersion(String version) {
this.version = version;
}
@Override
public String getZookeeperUrl() {
return zookeeperUrl;
}
@Override
public void setZookeeperUrl(String zookeeperUrl) {
this.zookeeperUrl = zookeeperUrl;
}
public BundleContext getBundleContext() {
return bundleContext;
}
public void setBundleContext(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
}
| fabric/fabric-boot-commands/src/main/java/org/fusesource/fabric/boot/commands/Join.java | /**
* Copyright (C) FuseSource, Inc.
* http://fusesource.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fusesource.fabric.boot.commands;
import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;
import org.apache.felix.gogo.commands.Option;
import org.apache.felix.service.command.CommandProcessor;
import org.apache.karaf.shell.console.OsgiCommandSupport;
import org.apache.zookeeper.KeeperException;
import org.fusesource.fabric.internal.FabricConstants;
import org.fusesource.fabric.utils.BundleUtils;
import org.fusesource.fabric.zookeeper.IZKClient;
import org.fusesource.fabric.zookeeper.ZkDefs;
import org.fusesource.fabric.zookeeper.ZkPath;
import org.linkedin.util.clock.Timespan;
import org.linkedin.zookeeper.client.ZKClient;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.util.tracker.ServiceTracker;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
@Command(name = "join", scope = "fabric", description = "Join a container to an existing fabric", detailedDescription = "classpath:join.txt")
public class Join extends OsgiCommandSupport implements org.fusesource.fabric.boot.commands.service.Join {
ConfigurationAdmin configurationAdmin;
private IZKClient zooKeeper;
private String version = ZkDefs.DEFAULT_VERSION;
private BundleContext bundleContext;
@Option(name = "-n", aliases = "--non-managed", multiValued = false, description = "Flag to keep the container non managed")
private boolean nonManaged;
@Argument(required = true, index = 0, multiValued = false, description = "Zookeeper URL")
private String zookeeperUrl;
@Argument(required = false, index = 1, multiValued = false, description = "Container name to use in fabric; by default a karaf name will be used")
private String containerName;
@Override
protected Object doExecute() throws Exception {
String oldName = System.getProperty("karaf.name");
if (containerName == null) {
containerName = oldName;
}
if (!containerName.equals(oldName)) {
if (permissionToRenameContainer()) {
if (registerContainerIfNotExists(containerName)) {
System.err.print("A container with the name: " + containerName + " is already member of the cluster. You can use the --container-name option to specify a different name.");
return null;
}
System.setProperty("karaf.name", containerName);
System.setProperty("zookeeper.url",zookeeperUrl);
//Rename the container
File file = new File(System.getProperty("karaf.base") + "/etc/system.properties");
org.apache.felix.utils.properties.Properties props = new org.apache.felix.utils.properties.Properties(file);
props.put("karaf.name", containerName);
props.put("zookeeper.url", zookeeperUrl);
props.save();
//Install required bundles
if (!nonManaged) {
installBundles();
}
org.osgi.service.cm.Configuration config = configurationAdmin.getConfiguration("org.fusesource.fabric.zookeeper");
Properties properties = new Properties();
properties.put("zookeeper.url", zookeeperUrl);
config.setBundleLocation(null);
config.update(properties);
//Restart the container
System.setProperty("karaf.restart", "true");
System.setProperty("karaf.restart.clean", "false");
bundleContext.getBundle(0).stop();
return null;
} else {
return null;
}
} else {
if (registerContainerIfNotExists(containerName)) {
System.err.println("A container with the name: " + containerName + " is already member of the cluster. You can use the --container-name option to specify a different name.");
return null;
}
org.osgi.service.cm.Configuration config = configurationAdmin.getConfiguration("org.fusesource.fabric.zookeeper");
Properties properties = new Properties();
properties.put("zookeeper.url", zookeeperUrl);
config.setBundleLocation(null);
config.update(properties);
installBundles();
return null;
}
}
/**
* Checks if there is an existing container using the same name.
*
* @param name
* @return
* @throws InterruptedException
* @throws KeeperException
*/
private boolean registerContainerIfNotExists(String name) throws InterruptedException, KeeperException {
boolean exists = false;
ZKClient zkClient = null;
try {
zkClient = new ZKClient(zookeeperUrl, Timespan.ONE_MINUTE, null);
zkClient.start();
zkClient.waitForStart();
exists = zkClient.exists(ZkPath.CONTAINER.getPath(name)) != null;
if (!exists) {
ZkPath.createContainerPaths(zkClient, containerName, version);
}
} finally {
if (zkClient != null) {
zkClient.destroy();
}
}
return exists;
}
/**
* Asks the users permission to restart the container.
*
* @return
* @throws IOException
*/
private boolean permissionToRenameContainer() throws IOException {
for (; ; ) {
StringBuffer sb = new StringBuffer();
System.err.println("You are about to change the container name. This action will restart the container.");
System.err.println("The local shell will automatically restart, but ssh connections will be terminated.");
System.err.println("The container will automatically join: " + zookeeperUrl + " the cluster after it restarts.");
System.err.print("Do you wish to proceed (yes/no):");
System.err.flush();
for (; ; ) {
int c = session.getKeyboard().read();
if (c < 0) {
return false;
}
System.err.print((char) c);
if (c == '\r' || c == '\n') {
break;
}
sb.append((char) c);
}
String str = sb.toString();
if ("yes".equals(str)) {
return true;
}
if ("no".equals(str)) {
return false;
}
}
}
public void installBundles() throws BundleException {
Bundle bundleFabricJaas = BundleUtils.findOrInstallBundle(bundleContext, "org.fusesource.fabric.fabric-jaas",
"mvn:org.fusesource.fabric/fabric-jaas/" + FabricConstants.FABRIC_VERSION);
Bundle bundleFabricCommands = BundleUtils.findOrInstallBundle(bundleContext, "org.fusesource.fabric.fabric-commands",
"mvn:org.fusesource.fabric/fabric-commands/" + FabricConstants.FABRIC_VERSION);
bundleFabricJaas.start();
bundleFabricCommands.start();
if (!nonManaged) {
Bundle bundleFabricConfigAdmin = BundleUtils.findOrInstallBundle(bundleContext, "org.fusesource.fabric.fabric-configadmin",
"mvn:org.fusesource.fabric/fabric-configadmin/" + FabricConstants.FABRIC_VERSION);
Bundle bundleFabricAgent = BundleUtils.findOrInstallBundle(bundleContext, "org.fusesource.fabric.fabric-agent",
"mvn:org.fusesource.fabric/fabric-agent/" + FabricConstants.FABRIC_VERSION);
bundleFabricConfigAdmin.start();
bundleFabricAgent.start();
}
}
@Override
public Object run() throws Exception {
return doExecute();
}
@Override
public void setConfigurationAdmin(ConfigurationAdmin configurationAdmin) {
this.configurationAdmin = configurationAdmin;
}
@Override
public void setZooKeeper(IZKClient zooKeeper) {
this.zooKeeper = zooKeeper;
}
@Override
public String getVersion() {
return version;
}
@Override
public void setVersion(String version) {
this.version = version;
}
@Override
public String getZookeeperUrl() {
return zookeeperUrl;
}
@Override
public void setZookeeperUrl(String zookeeperUrl) {
this.zookeeperUrl = zookeeperUrl;
}
public BundleContext getBundleContext() {
return bundleContext;
}
public void setBundleContext(BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
}
| Added the a force option to join command.
| fabric/fabric-boot-commands/src/main/java/org/fusesource/fabric/boot/commands/Join.java | Added the a force option to join command. |
|
Java | apache-2.0 | 94b25792e585692a09811f6415cf16ee93a81851 | 0 | siara-cc/csv_parser | /*
* Copyright (C) 2015 Siara Logics (cc)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Arundale R.
*
*/
package cc.siara.csv;
import java.io.IOException;
import java.io.Reader;
/**
* CSV Token Parser
*
* @author Arundale R.
*/
public class CSVParser {
// Parsing states
final byte ST_NOT_STARTED = 0;
final byte ST_DATA_STARTED_WITHOUT_QUOTE = 1;
final byte ST_DATA_STARTED_WITH_QUOTE = 2;
final byte ST_QUOTE_WITHIN_QUOTE = 3;
final byte ST_DATA_ENDED_WITH_QUOTE = 4;
final byte ST_FIELD_ENDED = 5;
// Members and transients
boolean isWithinComment = false;
boolean isEOL = false;
boolean isEOS = false;
byte state = ST_NOT_STARTED;
Counter counter = null;
ExceptionHandler ex = null;
StringBuffer data = new StringBuffer();
StringBuffer backlog = new StringBuffer();
String reinsertedToken = null;
String lastToken = null;
int reinsertedChar = -1;
int lastChar = -1;
int max_value_len = 65535;
private char delimiter = ',';
private char alt_whitespace = '\t';
/**
* Initializes a CSV Parser with internal counter and ExceptionHandler
*/
public CSVParser() {
counter = new Counter();
ex = new ExceptionHandler(counter);
reset();
}
/**
* Initializes a CSV Parser with internal counter and ExceptionHandler
*
* @param max
* Maximum allowable characters in a column
*/
public CSVParser(int max) {
this();
max_value_len = max;
}
/**
* Initializes a CSV Parser with given Counter and ExceptionHandler
*
* @param c
* Given Counter object
* @param e
* Given Exception Handler object
* @param max
* Maximum allowable characters in a column
*/
public CSVParser(Counter c, ExceptionHandler e, int max) {
ex = e;
counter = c;
max_value_len = max;
reset();
}
/**
* Initializes a CSV Parser with given Counter and ExceptionHandler
*
* @param c
* Given Counter object
* @param e
* Given Exception Handler object
*/
public CSVParser(Counter c, ExceptionHandler e) {
ex = e;
counter = c;
reset();
}
/**
* Sets delimiter character used for parsing
*
* @param d Delimiter
*/
public void setDelimiter(char d) {
this.delimiter = d;
this.alt_whitespace = '\t';
if (d == '\t')
this.alt_whitespace = ' ';
}
/**
* Checks whether End of Field reached based on current character
*
* @param c
* Current character
* @param data
* Current field value for removing dummy \r (Carriage Return),
* if any
* @return
*/
private boolean checkEOF(int c, StringBuffer data) {
if (c == this.delimiter) {
state = ST_FIELD_ENDED;
isEOL = false;
} else if (c == '\n') {
state = ST_FIELD_ENDED;
isEOL = true;
int lastPos = data.length() - 1;
if (lastPos > -1 && data.charAt(lastPos) == '\r')
data.setLength(lastPos);
} else
return false;
return true;
}
/**
* Sets states End of Line and End of Stream to indicate end of parsing
*
* @param data
* Return value
* @return Last column data
*/
private String windUp(StringBuffer data) {
isEOS = true;
isEOL = true;
state = ST_NOT_STARTED;
return data.toString();
}
/**
* Resets the instance so that it can be used and re-used.
*/
public void reset() {
state = ST_NOT_STARTED;
isEOS = false;
isEOL = false;
counter.reset_counters();
data = new StringBuffer();
backlog = new StringBuffer();
reinsertedToken = null;
lastToken = null;
reinsertedChar = -1;
lastChar = -1;
}
/**
* Encapsulates reading a character from the stream.
*
* @param r
* Stream being read
* @return Character read from stream
* @throws IOException
*/
public int readChar(Reader r) throws IOException {
int i;
try {
i = r.read();
} catch (IOException e) {
if (ex != null)
ex.set_err(ExceptionHandler.E_IO);
throw e;
}
lastChar = i;
return i;
}
/**
* Processes given character i according to current state. For each state,
* the if statements decide whether to stay in the current state or jump to
* another. Each state has its own set of decision tree.
*
* The backlog variable keeps characters when a series of spaces and tabs
* are found at the beginning of a field. If a quote is found consequently,
* backlog is ignored, otherwise it is appended to data.
*
* @param i
*/
public void processChar(int i) {
char c = (char) (i & 0xFFFF);
if (isWithinComment) {
counter.increment_counters(c);
return;
}
switch (state) {
case ST_NOT_STARTED:
if (c == ' ' || c == alt_whitespace) {
backlog.append(c);
} else if (checkEOF(c, data)) {
} else if (c == '"') {
state = ST_DATA_STARTED_WITH_QUOTE;
backlog.setLength(0);
} else {
state = ST_DATA_STARTED_WITHOUT_QUOTE;
if (backlog.length() > 0) {
if (data.length() < max_value_len)
data.append(backlog);
backlog.setLength(0);
}
if (data.length() < max_value_len)
data.append(c);
}
break;
case ST_DATA_STARTED_WITHOUT_QUOTE:
if (checkEOF(c, data)) {
} else {
if (data.length() < max_value_len)
data.append(c);
}
break;
case ST_DATA_STARTED_WITH_QUOTE:
if (c == '"')
state = ST_QUOTE_WITHIN_QUOTE;
else {
if (data.length() < max_value_len)
data.append(c);
}
break;
case ST_QUOTE_WITHIN_QUOTE:
if (c == '"') {
state = ST_DATA_STARTED_WITH_QUOTE;
if (data.length() < max_value_len)
data.append(c);
} else if (checkEOF(c, data)) {
} else if (c == ' ' || c == alt_whitespace || c == '\r') {
state = ST_DATA_ENDED_WITH_QUOTE;
} else {
state = ST_DATA_STARTED_WITH_QUOTE;
ex.add_warn(ExceptionHandler.W_CHAR_INVALID);
if (data.length() < max_value_len)
data.append(c);
}
break;
case ST_DATA_ENDED_WITH_QUOTE:
if (c == ' ' || c == alt_whitespace) {
} else if (checkEOF(c, data)) {
} else
ex.add_warn(ExceptionHandler.W_CHAR_INVALID);
break;
}
counter.increment_counters(c);
}
/**
* Puts back one field parsed from stream.
*/
public void reinsertLastToken() {
reinsertedToken = lastToken;
}
/**
* Puts back one character read from stream.
*/
public void reInsertLastChar() {
reinsertedChar = lastChar;
counter.decrement_counters((char) lastChar);
}
/**
* Gets next token by parsing characters from the stream.
*
* A comment is processed separately from the main state machine. Whenever
* not within a comment, this method calls processChar to process the
* character using the state machine.
*
* @param r
* @return
* @throws IOException
*/
public String parseNextToken(Reader r) throws IOException {
if (reinsertedToken != null) {
String ret = reinsertedToken;
reinsertedToken = null;
return ret;
}
if (state == ST_FIELD_ENDED) {
isEOL = false;
state = ST_NOT_STARTED;
backlog.setLength(0);
}
int c = reinsertedChar;
if (c == -1)
c = readChar(r);
else
reinsertedChar = -1;
while (state != ST_FIELD_ENDED) {
if (c == -1)
return windUp(data);
if (c == '/' && !isWithinComment
&& state != ST_DATA_STARTED_WITH_QUOTE) {
int c_next = readChar(r);
if (c_next == -1) {
processChar(c);
return windUp(data);
}
if (c_next == '*')
isWithinComment = true;
else {
processChar(c);
processChar(c_next);
}
} else if (c == '*' && isWithinComment
&& state != ST_DATA_STARTED_WITH_QUOTE) {
int c_next = readChar(r);
if (c_next == -1) {
processChar(c);
return windUp(data);
}
if (c_next == '/')
isWithinComment = false;
else {
processChar(c);
processChar(c_next);
}
} else
processChar(c);
if (state != ST_FIELD_ENDED)
c = readChar(r);
}
String ret = data.toString();
data.setLength(0);
lastToken = ret;
return ret;
}
/**
* Reports end of line.
*
* @return true if End of line reached, false otherwise.
*/
public boolean isEOL() {
return isEOL;
}
/**
* Reports end of stream.
*
* @return true if End of stream reached, false otherwise.
*/
public boolean isEOS() {
return isEOS;
}
/**
* Getter for the Counter object
*
* @return Counter object
*/
public Counter getCounter() {
return counter;
}
}
| src/cc/siara/csv/CSVParser.java | /*
* Copyright (C) 2015 Siara Logics (cc)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Arundale R.
*
*/
package cc.siara.csv;
import java.io.IOException;
import java.io.Reader;
/**
* CSV Token Parser
*
* @author Arundale R.
*/
public class CSVParser {
// Parsing states
final byte ST_NOT_STARTED = 0;
final byte ST_DATA_STARTED_WITHOUT_QUOTE = 1;
final byte ST_DATA_STARTED_WITH_QUOTE = 2;
final byte ST_QUOTE_WITHIN_QUOTE = 3;
final byte ST_DATA_ENDED_WITH_QUOTE = 4;
final byte ST_FIELD_ENDED = 5;
// Members and transients
boolean isWithinComment = false;
boolean isEOL = false;
boolean isEOS = false;
byte state = ST_NOT_STARTED;
Counter counter = null;
ExceptionHandler ex = null;
StringBuffer data = new StringBuffer();
StringBuffer backlog = new StringBuffer();
String reinsertedToken = null;
String lastToken = null;
int reinsertedChar = -1;
int lastChar = -1;
int max_value_len = 65535;
/**
* Initializes a CSV Parser with internal counter and ExceptionHandler
*/
public CSVParser() {
counter = new Counter();
ex = new ExceptionHandler(counter);
reset();
}
/**
* Initializes a CSV Parser with internal counter and ExceptionHandler
*
* @param max
* Maximum allowable characters in a column
*/
public CSVParser(int max) {
this();
max_value_len = max;
}
/**
* Initializes a CSV Parser with given Counter and ExceptionHandler
*
* @param c
* Given Counter object
* @param e
* Given Exception Handler object
* @param max
* Maximum allowable characters in a column
*/
public CSVParser(Counter c, ExceptionHandler e, int max) {
ex = e;
counter = c;
max_value_len = max;
reset();
}
/**
* Initializes a CSV Parser with given Counter and ExceptionHandler
*
* @param c
* Given Counter object
* @param e
* Given Exception Handler object
*/
public CSVParser(Counter c, ExceptionHandler e) {
ex = e;
counter = c;
reset();
}
/**
* Checks whether End of Field reached based on current character
*
* @param c
* Current character
* @param data
* Current field value for removing dummy \r (Carriage Return),
* if any
* @return
*/
private boolean checkEOF(int c, StringBuffer data) {
if (c == ',') {
state = ST_FIELD_ENDED;
isEOL = false;
} else if (c == '\n') {
state = ST_FIELD_ENDED;
isEOL = true;
int lastPos = data.length() - 1;
if (lastPos > -1 && data.charAt(lastPos) == '\r')
data.setLength(lastPos);
} else
return false;
return true;
}
/**
* Sets states End of Line and End of Stream to indicate end of parsing
*
* @param data
* Return value
* @return Last column data
*/
private String windUp(StringBuffer data) {
isEOS = true;
isEOL = true;
state = ST_NOT_STARTED;
return data.toString();
}
/**
* Resets the instance so that it can be used and re-used.
*/
public void reset() {
state = ST_NOT_STARTED;
isEOS = false;
isEOL = false;
counter.reset_counters();
data = new StringBuffer();
backlog = new StringBuffer();
reinsertedToken = null;
lastToken = null;
reinsertedChar = -1;
lastChar = -1;
}
/**
* Encapsulates reading a character from the stream.
*
* @param r
* Stream being read
* @return Character read from stream
* @throws IOException
*/
public int readChar(Reader r) throws IOException {
int i;
try {
i = r.read();
} catch (IOException e) {
if (ex != null)
ex.set_err(ExceptionHandler.E_IO);
throw e;
}
lastChar = i;
return i;
}
/**
* Processes given character i according to current state. For each state,
* the if statements decide whether to stay in the current state or jump to
* another. Each state has its own set of decision tree.
*
* The backlog variable keeps characters when a series of spaces and tabs
* are found at the beginning of a field. If a quote is found consequently,
* backlog is ignored, otherwise it is appended to data.
*
* @param i
*/
public void processChar(int i) {
char c = (char) (i & 0xFFFF);
if (isWithinComment) {
counter.increment_counters(c);
return;
}
switch (state) {
case ST_NOT_STARTED:
if (c == ' ' || c == '\t') {
backlog.append(c);
} else if (checkEOF(c, data)) {
} else if (c == '"') {
state = ST_DATA_STARTED_WITH_QUOTE;
backlog.setLength(0);
} else {
state = ST_DATA_STARTED_WITHOUT_QUOTE;
if (backlog.length() > 0) {
if (data.length() < max_value_len)
data.append(backlog);
backlog.setLength(0);
}
if (data.length() < max_value_len)
data.append(c);
}
break;
case ST_DATA_STARTED_WITHOUT_QUOTE:
if (checkEOF(c, data)) {
} else {
if (data.length() < max_value_len)
data.append(c);
}
break;
case ST_DATA_STARTED_WITH_QUOTE:
if (c == '"')
state = ST_QUOTE_WITHIN_QUOTE;
else {
if (data.length() < max_value_len)
data.append(c);
}
break;
case ST_QUOTE_WITHIN_QUOTE:
if (c == '"') {
state = ST_DATA_STARTED_WITH_QUOTE;
if (data.length() < max_value_len)
data.append(c);
} else if (checkEOF(c, data)) {
} else if (c == ' ' || c == '\t' || c == '\r') {
state = ST_DATA_ENDED_WITH_QUOTE;
} else {
state = ST_DATA_STARTED_WITH_QUOTE;
ex.add_warn(ExceptionHandler.W_CHAR_INVALID);
if (data.length() < max_value_len)
data.append(c);
}
break;
case ST_DATA_ENDED_WITH_QUOTE:
if (c == ' ' || c == '\t') {
} else if (checkEOF(c, data)) {
} else
ex.add_warn(ExceptionHandler.W_CHAR_INVALID);
break;
}
counter.increment_counters(c);
}
/**
* Puts back one field parsed from stream.
*/
public void reinsertLastToken() {
reinsertedToken = lastToken;
}
/**
* Puts back one character read from stream.
*/
public void reInsertLastChar() {
reinsertedChar = lastChar;
counter.decrement_counters((char) lastChar);
}
/**
* Gets next token by parsing characters from the stream.
*
* A comment is processed separately from the main state machine. Whenever
* not within a comment, this method calls processChar to process the
* character using the state machine.
*
* @param r
* @return
* @throws IOException
*/
public String parseNextToken(Reader r) throws IOException {
if (reinsertedToken != null) {
String ret = reinsertedToken;
reinsertedToken = null;
return ret;
}
if (state == ST_FIELD_ENDED) {
isEOL = false;
state = ST_NOT_STARTED;
backlog.setLength(0);
}
int c = reinsertedChar;
if (c == -1)
c = readChar(r);
else
reinsertedChar = -1;
while (state != ST_FIELD_ENDED) {
if (c == -1)
return windUp(data);
if (c == '/' && !isWithinComment
&& state != ST_DATA_STARTED_WITH_QUOTE) {
int c_next = readChar(r);
if (c_next == -1) {
processChar(c);
return windUp(data);
}
if (c_next == '*')
isWithinComment = true;
else {
processChar(c);
processChar(c_next);
}
} else if (c == '*' && isWithinComment
&& state != ST_DATA_STARTED_WITH_QUOTE) {
int c_next = readChar(r);
if (c_next == -1) {
processChar(c);
return windUp(data);
}
if (c_next == '/')
isWithinComment = false;
else {
processChar(c);
processChar(c_next);
}
} else
processChar(c);
if (state != ST_FIELD_ENDED)
c = readChar(r);
}
String ret = data.toString();
data.setLength(0);
lastToken = ret;
return ret;
}
/**
* Reports end of line.
*
* @return true if End of line reached, false otherwise.
*/
public boolean isEOL() {
return isEOL;
}
/**
* Reports end of stream.
*
* @return true if End of stream reached, false otherwise.
*/
public boolean isEOS() {
return isEOS;
}
/**
* Getter for the Counter object
*
* @return Counter object
*/
public Counter getCounter() {
return counter;
}
}
| Add setDelimiter option | src/cc/siara/csv/CSVParser.java | Add setDelimiter option |
|
Java | bsd-2-clause | c16051d7f152b73ea898a3e487873c6ff0dceb97 | 0 | abelbriggs1/runelite,runelite/runelite,devinfrench/runelite,Noremac201/runelite,KronosDesign/runelite,l2-/runelite,Noremac201/runelite,Sethtroll/runelite,KronosDesign/runelite,runelite/runelite,abelbriggs1/runelite,devinfrench/runelite,abelbriggs1/runelite,l2-/runelite,Sethtroll/runelite,runelite/runelite | /*
* Copyright (c) 2018, Lotto <https://github.com/devLotto>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.entityhider;
import net.runelite.client.config.Config;
import net.runelite.client.config.ConfigGroup;
import net.runelite.client.config.ConfigItem;
@ConfigGroup(
keyName = "entityhider",
name = "Entity Hider",
description = "Hides various entities such as players and NPCs"
)
public interface EntityHiderConfig extends Config
{
@ConfigItem(
position = 1,
keyName = "hidePlayers",
name = "Hide Players",
description = "Configures whether or not players are hidden"
)
default boolean hidePlayers()
{
return true;
}
@ConfigItem(
position = 2,
keyName = "hidePlayers2D",
name = "Hide Players 2D",
description = "Configures whether or not players 2D elements are hidden"
)
default boolean hidePlayers2D()
{
return true;
}
@ConfigItem(
position = 3,
keyName = "hideFriends",
name = "Hide Friends",
description = "Configures whether or not friends are hidden"
)
default boolean hideFriends()
{
return false;
}
@ConfigItem(
position = 4,
keyName = "hideClanMates",
name = "Hide Clan Mates",
description = "Configures whether or not clan mates are hidden"
)
default boolean hideClanMates()
{
return false;
}
@ConfigItem(
position = 5,
keyName = "hideLocalPlayer",
name = "Hide Local Player",
description = "Configures whether or not the local player is hidden"
)
default boolean hideLocalPlayer()
{
return false;
}
@ConfigItem(
position = 6,
keyName = "hideLocalPlayer2D",
name = "Hide Local Player 2D",
description = "Configures whether or not the local player's 2D elements are hidden"
)
default boolean hideLocalPlayer2D()
{
return false;
}
@ConfigItem(
position = 7,
keyName = "hideNPCs",
name = "Hide NPCs",
description = "Configures whether or not NPCs are hidden"
)
default boolean hideNPCs()
{
return false;
}
@ConfigItem(
position = 8,
keyName = "hideNPCs2D",
name = "Hide NPCs 2D",
description = "Configures whether or not NPCs 2D elements are hidden"
)
default boolean hideNPCs2D()
{
return false;
}
@ConfigItem(
position = 9,
keyName = "hideAttackers",
name = "Hide Attackers",
description = "Configures whether or not NPCs/players attacking you are hidden"
)
default boolean hideAttackers()
{
return false;
}
@ConfigItem(
position = 10,
keyName = "hideProjectiles",
name = "Hide Projectiles",
description = "Configures whether or not projectiles are hidden"
)
default boolean hideProjectiles()
{
return false;
}
}
| runelite-client/src/main/java/net/runelite/client/plugins/entityhider/EntityHiderConfig.java | /*
* Copyright (c) 2018, Lotto <https://github.com/devLotto>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.entityhider;
import net.runelite.client.config.Config;
import net.runelite.client.config.ConfigGroup;
import net.runelite.client.config.ConfigItem;
@ConfigGroup(
keyName = "entityhider",
name = "Entity Hider",
description = "Hides various entities such as players and NPCs"
)
public interface EntityHiderConfig extends Config
{
@ConfigItem(
position = 1,
keyName = "hidePlayers",
name = "Hide Players",
description = "Configures whether or not players are hidden"
)
default boolean hidePlayers()
{
return true;
}
@ConfigItem(
position = 2,
keyName = "hidePlayers2D",
name = "Hide Players 2D",
description = "Configures whether or not players 2D elements are hidden"
)
default boolean hidePlayers2D()
{
return true;
}
@ConfigItem(
position = 3,
keyName = "hideFriends",
name = "Hide Friends",
description = "Configures whether or not friends are hidden"
)
default boolean hideFriends()
{
return false;
}
@ConfigItem(
position = 4,
keyName = "hideClanMates",
name = "Hide Clan Mates",
description = "Configures whether or not clan mates are hidden"
)
default boolean hideClanMates()
{
return false;
}
@ConfigItem(
position = 5,
keyName = "hideLocalPlayer",
name = "Hide Local Player",
description = "Configures whether or not the local player is hidden"
)
default boolean hideLocalPlayer()
{
return false;
}
@ConfigItem(
position = 6,
keyName = "hideLocalPlayer2D",
name = "Hide Local Player 2D",
description = "Configures whether or not the local player's 2D elements are hidden"
)
default boolean hideLocalPlayer2D()
{
return false;
}
@ConfigItem(
position = 7,
keyName = "hideNPCs",
name = "Hide NPCs",
description = "Configures whether or not NPCs are hidden"
)
default boolean hideNPCs()
{
return true;
}
@ConfigItem(
position = 8,
keyName = "hideNPCs2D",
name = "Hide NPCs 2D",
description = "Configures whether or not NPCs 2D elements are hidden"
)
default boolean hideNPCs2D()
{
return true;
}
@ConfigItem(
position = 9,
keyName = "hideAttackers",
name = "Hide Attackers",
description = "Configures whether or not NPCs/players attacking you are hidden"
)
default boolean hideAttackers()
{
return false;
}
@ConfigItem(
position = 10,
keyName = "hideProjectiles",
name = "Hide Projectiles",
description = "Configures whether or not projectiles are hidden"
)
default boolean hideProjectiles()
{
return false;
}
}
| entityhider: don't hide npcs by default
| runelite-client/src/main/java/net/runelite/client/plugins/entityhider/EntityHiderConfig.java | entityhider: don't hide npcs by default |
|
Java | bsd-2-clause | 78f9de1c7042088ef56fbf2ba6a6da30417b1891 | 0 | Konstantin8105/GenericSort | import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import static org.junit.Assert.assertEquals;
public class ResearchTest {
private static Random random = new Random();
int sizeTest = 10_000;
// TODO create good research
// TODO add file in sorted array
private static Sort[] getSortClasses() {
return new Sort[]{
new MergeSort()
,
new CountingSort()
,
new SelectionSort()
,
new BinarySort()
};
}
private List<Integer> getRandomList(int amountElements, boolean isManyUnique) {
List<Integer> output = new ArrayList<>();
int factorUnique = amountElements;
if (isManyUnique) {
factorUnique *= 10.d;
} else {
factorUnique *= 0.01d;
}
if (factorUnique < 1) {
factorUnique = 1;
}
for (int i = 0; i < amountElements; i++) {
output.add(random.nextInt(factorUnique));
}
return output;
}
private <T> double getTimeOfSort(List<T> input, Sort sortClass) {
List<Long> timePeriod = new ArrayList<>();
int amountTest = 5;
for (int i = 0; i < amountTest; i++) {
long start = (new Date()).getTime();
sortClass.sort(input);
long end = (new Date()).getTime();
timePeriod.add(end - start);
}
double averageTime = 0;
for (Long time : timePeriod) {
averageTime += time;
}
averageTime /= timePeriod.size();
return averageTime;
}
@org.junit.Test
public void testCorrectResult() throws Exception {
System.out.println("\n#Test. Checking of correct result:");
System.out.println("Amount elements = " + sizeTest + " items");
List<Integer> array = getRandomList(sizeTest, true);
for (Sort sortClass : getSortClasses()) {
System.out.print(String.format("> %20s", sortClass.getClass().toString()));
List<Integer> result = sortClass.sort(array);
assertEquals(array.size(), result.size());
System.out.print(" --> OK\n");
}
}
@org.junit.Test
public void testTimeNotUniqueItems() throws Exception {
System.out.println("\n#Test with many same items:");
System.out.println("Amount elements = " + sizeTest + " items");
List<Integer> array = getRandomList(sizeTest, false);
for (Sort sortClass : getSortClasses()) {
System.out.print(String.format("> %20s", sortClass.getClass().toString()));
double time = getTimeOfSort(array, sortClass);
System.out.print(String.format(" --> %4.1f ms\n", time));
}
}
@org.junit.Test
public void testTimeUniqueItems() throws Exception {
System.out.println("\n#Test with many unique items:");
System.out.println("Amount elements = " + sizeTest + " items");
List<Integer> array = getRandomList(sizeTest, true);
for (Sort sortClass : getSortClasses()) {
System.out.print(String.format("> %20s", sortClass.getClass().toString()));
double time = getTimeOfSort(array, sortClass);
System.out.print(String.format(" --> %4.1f ms\n", time));
}
}
@org.junit.Test
public void testResearchUniqueWithDifferentSize() throws Exception {
System.out.println("\n#Research of sorting:");
int minExponent = 4;
int maxExponent = 6;
System.out.println("Amount elements = "
+ Math.pow(10, minExponent)
+ " ... "
+ Math.pow(10, maxExponent)
+ " items");
List<List<Integer>> matrix = new ArrayList<>();
for (int i = minExponent; i <= maxExponent; i++) {
int amountItems = (int)Math.pow(10d,i);
matrix.add(getRandomList(amountItems, true));
}
System.out.println("Result of research");
for (Sort sortClass : getSortClasses()) {
if(sortClass instanceof SelectionSort ||
sortClass instanceof BinarySort){
continue;
}
System.out.println(String.format("%20s", sortClass.getClass().toString()));
System.out.print(String.format("%10s","Amount:"));
for (int i = minExponent; i <= maxExponent; i++) {
System.out.print(String.format(" 10^%d |", i));
}
System.out.println();
System.out.print(String.format("%10s","Time(ms):"));
for (int i = 0; i <= maxExponent - minExponent; i++) {
double time = getTimeOfSort(matrix.get(i), sortClass);
System.out.print(String.format("%7.1f |", time));
System.out.flush();
}
System.out.println("\n");
}
}
}
| sort/src/test/ResearchTest.java | import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import static org.junit.Assert.assertEquals;
public class ResearchTest {
private static Random random = new Random();
int sizeTest = 10_000;
// TODO create good research
// TODO add file in sorted array
private static Sort[] getSortClasses() {
return new Sort[]{
new MergeSort()
,
new CountingSort()
,
new SelectionSort()
,
new BinarySort()
};
}
private List<Integer> getRandomList(int amountElements, boolean isManyUnique) {
List<Integer> output = new ArrayList<>();
int factorUnique = amountElements;
if (isManyUnique) {
factorUnique *= 10.d;
} else {
factorUnique *= 0.01d;
}
if (factorUnique < 1) {
factorUnique = 1;
}
for (int i = 0; i < amountElements; i++) {
output.add(random.nextInt(factorUnique));
}
return output;
}
private <T> double getTimeOfSort(List<T> input, Sort sortClass) {
List<Long> timePeriod = new ArrayList<>();
int amountTest = 5;
for (int i = 0; i < amountTest; i++) {
long start = (new Date()).getTime();
sortClass.sort(input);
long end = (new Date()).getTime();
timePeriod.add(end - start);
}
double averageTime = 0;
for (Long time : timePeriod) {
averageTime += time;
}
averageTime /= timePeriod.size();
return averageTime;
}
@org.junit.Test
public void testCorrectResult() throws Exception {
System.out.println("\n#Test. Checking of correct result:");
System.out.println("Amount elements = " + sizeTest + " items");
List<Integer> array = getRandomList(sizeTest, true);
for (Sort sortClass : getSortClasses()) {
System.out.print(String.format("> %20s", sortClass.getClass().toString()));
List<Integer> result = sortClass.sort(array);
assertEquals(array.size(), result.size());
System.out.print(" --> OK\n");
}
}
@org.junit.Test
public void testTimeNotUniqueItems() throws Exception {
System.out.println("\n#Test with many same items:");
System.out.println("Amount elements = " + sizeTest + " items");
List<Integer> array = getRandomList(sizeTest, false);
for (Sort sortClass : getSortClasses()) {
System.out.print(String.format("> %20s", sortClass.getClass().toString()));
double time = getTimeOfSort(array, sortClass);
System.out.print(String.format(" --> %4.1f ms\n", time));
}
}
@org.junit.Test
public void testTimeUniqueItems() throws Exception {
System.out.println("\n#Test with many unique items:");
System.out.println("Amount elements = " + sizeTest + " items");
List<Integer> array = getRandomList(sizeTest, true);
for (Sort sortClass : getSortClasses()) {
System.out.print(String.format("> %20s", sortClass.getClass().toString()));
double time = getTimeOfSort(array, sortClass);
System.out.print(String.format(" --> %4.1f ms\n", time));
}
}
@org.junit.Test
public void testResearchUniqueWithDifferentSize() throws Exception {
System.out.println("\n#Research of sorting:");
int minExponent = 4;
int maxExponent = 6;
System.out.println("Amount elements = "
+ Math.pow(10, minExponent)
+ " ... "
+ Math.pow(10, maxExponent)
+ " items");
List<List<Integer>> matrix = new ArrayList<>();
for (int i = minExponent; i <= maxExponent; i++) {
int amountItems = (int)Math.pow(10d,i);
matrix.add(getRandomList(amountItems, true));
}
System.out.println("Result of research");
for (Sort sortClass : getSortClasses()) {
if(sortClass instanceof SelectionSort){
continue;
}
System.out.println(String.format("%20s", sortClass.getClass().toString()));
System.out.print(String.format("%10s","Amount:"));
for (int i = minExponent; i <= maxExponent; i++) {
System.out.print(String.format(" 10^%d |", i));
}
System.out.println();
System.out.print(String.format("%10s","Time(ms):"));
for (int i = 0; i <= maxExponent - minExponent; i++) {
double time = getTimeOfSort(matrix.get(i), sortClass);
System.out.print(String.format("%7.1f |", time));
System.out.flush();
}
System.out.println("\n");
}
}
}
| BinarySort finallize
| sort/src/test/ResearchTest.java | BinarySort finallize |
|
Java | mit | 99f641b716ab7618ddb5c85ce3a35dab666ffecb | 0 | cryptomator/siv-mode,cryptomator/siv-mode | package org.cryptomator.siv;
/*******************************************************************************
* Copyright (c) 2015 Sebastian Stenzel
* This file is licensed under the terms of the MIT license.
* See the LICENSE.txt file for more info.
*
* Contributors:
* Sebastian Stenzel - initial API and implementation
******************************************************************************/
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.Mac;
import org.bouncycastle.crypto.macs.CMac;
import org.bouncycastle.crypto.paddings.ISO7816d4Padding;
import org.bouncycastle.crypto.params.KeyParameter;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import java.nio.ByteBuffer;
import java.security.Provider;
import java.util.Arrays;
/**
* Implements the RFC 5297 SIV mode.
*/
public final class SivMode {
private static final byte[] BYTES_ZERO = new byte[16];
private static final byte DOUBLING_CONST = (byte) 0x87;
private final ThreadLocal<BlockCipher> threadLocalCipher;
/**
* Creates an AES-SIV instance using JCE's cipher implementation, which should normally be the best choice.<br>
* <p>
* For embedded systems, you might want to consider using {@link #SivMode(BlockCipherFactory)} with BouncyCastle's {@code AESLightEngine} instead.
*
* @see #SivMode(BlockCipherFactory)
*/
public SivMode() {
this((Provider) null);
}
/**
* Creates an AES-SIV instance using a custom JCE's security provider<br>
* <p>
* For embedded systems, you might want to consider using {@link #SivMode(BlockCipherFactory)} with BouncyCastle's {@code AESLightEngine} instead.
*
* @param jceSecurityProvider to use to create the internal {@link javax.crypto.Cipher} instance
* @see #SivMode(BlockCipherFactory)
*/
public SivMode(final Provider jceSecurityProvider) {
this(new BlockCipherFactory() {
@Override
public BlockCipher create() {
return new JceAesBlockCipher(jceSecurityProvider);
}
});
}
/**
* Creates an instance using a specific Blockcipher.get(). If you want to use AES, just use the default constructor.
*
* @param cipherFactory A factory method creating a Blockcipher.get(). Must use a block size of 128 bits (16 bytes).
*/
public SivMode(final BlockCipherFactory cipherFactory) {
// Try using cipherFactory to check that the block size is valid.
// We assume here that the block size will not vary across calls to .create().
if (cipherFactory.create().getBlockSize() != 16) {
throw new IllegalArgumentException("cipherFactory must create BlockCipher objects with a 16-byte block size");
}
this.threadLocalCipher = new ThreadLocal<BlockCipher>() {
@Override
protected BlockCipher initialValue() {
return cipherFactory.create();
}
};
}
/**
* Creates {@link BlockCipher}s.
*/
public interface BlockCipherFactory {
BlockCipher create();
}
/**
* Convenience method, if you are using the javax.crypto API. This is just a wrapper for {@link #encrypt(byte[], byte[], byte[], byte[]...)}.
*
* @param ctrKey SIV mode requires two separate keys. You can use one long key, which is splitted in half. See https://tools.ietf.org/html/rfc5297#section-2.2
* @param macKey SIV mode requires two separate keys. You can use one long key, which is splitted in half. See https://tools.ietf.org/html/rfc5297#section-2.2
* @param plaintext Your plaintext, which shall be encrypted.
* @param associatedData Optional associated data, which gets authenticated but not encrypted.
* @return IV + Ciphertext as a concatenated byte array.
* @throws IllegalArgumentException if keys are invalid or {@link SecretKey#getEncoded()} is not supported.
*/
public byte[] encrypt(SecretKey ctrKey, SecretKey macKey, byte[] plaintext, byte[]... associatedData) {
final byte[] ctrKeyBytes = ctrKey.getEncoded();
final byte[] macKeyBytes = macKey.getEncoded();
if (ctrKeyBytes == null || macKeyBytes == null) {
throw new IllegalArgumentException("Can't get bytes of given key.");
}
try {
return encrypt(ctrKeyBytes, macKeyBytes, plaintext, associatedData);
} finally {
Arrays.fill(ctrKeyBytes, (byte) 0);
Arrays.fill(macKeyBytes, (byte) 0);
}
}
/**
* Encrypts plaintext using SIV mode. A block cipher defined by the constructor is being used.<br>
*
* @param ctrKey SIV mode requires two separate keys. You can use one long key, which is splitted in half. See https://tools.ietf.org/html/rfc5297#section-2.2
* @param macKey SIV mode requires two separate keys. You can use one long key, which is splitted in half. See https://tools.ietf.org/html/rfc5297#section-2.2
* @param plaintext Your plaintext, which shall be encrypted.
* @param associatedData Optional associated data, which gets authenticated but not encrypted.
* @return IV + Ciphertext as a concatenated byte array.
* @throws IllegalArgumentException if the either of the two keys is of invalid length for the used {@link BlockCipher}.
*/
public byte[] encrypt(byte[] ctrKey, byte[] macKey, byte[] plaintext, byte[]... associatedData) {
// Check if plaintext length will cause overflows
if (plaintext.length > (Integer.MAX_VALUE - 16)) {
throw new IllegalArgumentException("Plaintext is too long");
}
assert plaintext.length + 15 < Integer.MAX_VALUE;
final int numBlocks = (plaintext.length + 15) / 16;
final byte[] iv = s2v(macKey, plaintext, associatedData);
final byte[] keystream = generateKeyStream(ctrKey, iv, numBlocks);
final byte[] ciphertext = xor(plaintext, keystream);
// concat IV + ciphertext:
final byte[] result = new byte[iv.length + ciphertext.length];
System.arraycopy(iv, 0, result, 0, iv.length);
System.arraycopy(ciphertext, 0, result, iv.length, ciphertext.length);
return result;
}
/**
* Convenience method, if you are using the javax.crypto API. This is just a wrapper for {@link #decrypt(byte[], byte[], byte[], byte[]...)}.
*
* @param ctrKey SIV mode requires two separate keys. You can use one long key, which is splitted in half. See https://tools.ietf.org/html/rfc5297#section-2.2
* @param macKey SIV mode requires two separate keys. You can use one long key, which is splitted in half. See https://tools.ietf.org/html/rfc5297#section-2.2
* @param ciphertext Your cipehrtext, which shall be decrypted.
* @param associatedData Optional associated data, which needs to be authenticated during decryption.
* @return Plaintext byte array.
* @throws IllegalArgumentException If keys are invalid or {@link SecretKey#getEncoded()} is not supported.
* @throws UnauthenticCiphertextException If the authentication failed, e.g. because ciphertext and/or associatedData are corrupted.
* @throws IllegalBlockSizeException If the provided ciphertext is of invalid length.
*/
public byte[] decrypt(SecretKey ctrKey, SecretKey macKey, byte[] ciphertext, byte[]... associatedData) throws UnauthenticCiphertextException, IllegalBlockSizeException {
final byte[] ctrKeyBytes = ctrKey.getEncoded();
final byte[] macKeyBytes = macKey.getEncoded();
if (ctrKeyBytes == null || macKeyBytes == null) {
throw new IllegalArgumentException("Can't get bytes of given key.");
}
try {
return decrypt(ctrKeyBytes, macKeyBytes, ciphertext, associatedData);
} finally {
Arrays.fill(ctrKeyBytes, (byte) 0);
Arrays.fill(macKeyBytes, (byte) 0);
}
}
/**
* Decrypts ciphertext using SIV mode. A block cipher defined by the constructor is being used.<br>
*
* @param ctrKey SIV mode requires two separate keys. You can use one long key, which is splitted in half. See https://tools.ietf.org/html/rfc5297#section-2.2
* @param macKey SIV mode requires two separate keys. You can use one long key, which is splitted in half. See https://tools.ietf.org/html/rfc5297#section-2.2
* @param ciphertext Your ciphertext, which shall be encrypted.
* @param associatedData Optional associated data, which needs to be authenticated during decryption.
* @return Plaintext byte array.
* @throws IllegalArgumentException If the either of the two keys is of invalid length for the used {@link BlockCipher}.
* @throws UnauthenticCiphertextException If the authentication failed, e.g. because ciphertext and/or associatedData are corrupted.
* @throws IllegalBlockSizeException If the provided ciphertext is of invalid length.
*/
public byte[] decrypt(byte[] ctrKey, byte[] macKey, byte[] ciphertext, byte[]... associatedData) throws UnauthenticCiphertextException, IllegalBlockSizeException {
if (ciphertext.length < 16) {
throw new IllegalBlockSizeException("Input length must be greater than or equal 16.");
}
final byte[] iv = Arrays.copyOf(ciphertext, 16);
final byte[] actualCiphertext = Arrays.copyOfRange(ciphertext, 16, ciphertext.length);
assert actualCiphertext.length == ciphertext.length - 16;
assert actualCiphertext.length + 15 < Integer.MAX_VALUE;
final int numBlocks = (actualCiphertext.length + 15) / 16;
final byte[] keystream = generateKeyStream(ctrKey, iv, numBlocks);
final byte[] plaintext = xor(actualCiphertext, keystream);
final byte[] control = s2v(macKey, plaintext, associatedData);
// time-constant comparison (taken from MessageDigest.isEqual in JDK8)
assert iv.length == control.length;
int diff = 0;
for (int i = 0; i < iv.length; i++) {
diff |= iv[i] ^ control[i];
}
if (diff == 0) {
return plaintext;
} else {
throw new UnauthenticCiphertextException("authentication in SIV decryption failed");
}
}
byte[] generateKeyStream(byte[] ctrKey, byte[] iv, int numBlocks) {
final byte[] keystream = new byte[numBlocks * 16];
// clear out the 31st and 63rd (rightmost) bit:
final byte[] ctr = Arrays.copyOf(iv, 16);
ctr[8] = (byte) (ctr[8] & 0x7F);
ctr[12] = (byte) (ctr[12] & 0x7F);
final ByteBuffer ctrBuf = ByteBuffer.wrap(ctr);
final long initialCtrVal = ctrBuf.getLong(8);
final BlockCipher cipher = threadLocalCipher.get();
cipher.init(true, new KeyParameter(ctrKey));
for (int i = 0; i < numBlocks; i++) {
ctrBuf.putLong(8, initialCtrVal + i);
cipher.processBlock(ctr, 0, keystream, i * 16);
cipher.reset();
}
return keystream;
}
// Visible for testing, throws IllegalArgumentException if key is not accepted by CMac#init(CipherParameters)
byte[] s2v(byte[] macKey, byte[] plaintext, byte[]... associatedData) {
// Maximum permitted AD length is the block size in bits - 2
if (associatedData.length > 126) {
// SIV mode cannot be used safely with this many AD fields
throw new IllegalArgumentException("too many Associated Data fields");
}
final CipherParameters params = new KeyParameter(macKey);
final CMac mac = new CMac(threadLocalCipher.get());
mac.init(params);
// RFC 5297 defines a n == 0 case here. Where n is the length of the input vector:
// S1 = associatedData1, S2 = associatedData2, ... Sn = plaintext
// Since this method is invoked only by encrypt/decrypt, we always have a plaintext.
// Thus n > 0
byte[] d = mac(mac, BYTES_ZERO);
for (byte[] s : associatedData) {
d = xor(dbl(d), mac(mac, s));
}
final byte[] t;
if (plaintext.length >= 16) {
t = xorend(plaintext, d);
} else {
t = xor(dbl(d), pad(plaintext));
}
return mac(mac, t);
}
private static byte[] mac(Mac mac, byte[] in) {
byte[] result = new byte[mac.getMacSize()];
mac.update(in, 0, in.length);
mac.doFinal(result, 0);
return result;
}
// First bit 1, following bits 0.
private static byte[] pad(byte[] in) {
final byte[] result = Arrays.copyOf(in, 16);
new ISO7816d4Padding().addPadding(result, in.length);
return result;
}
// Code taken from {@link org.bouncycastle.crypto.macs.CMac}
static int shiftLeft(byte[] block, byte[] output) {
int i = block.length;
int bit = 0;
while (--i >= 0) {
int b = block[i] & 0xff;
output[i] = (byte) ((b << 1) | bit);
bit = (b >>> 7) & 1;
}
return bit;
}
// Code taken from {@link org.bouncycastle.crypto.macs.CMac}
static byte[] dbl(byte[] in) {
byte[] ret = new byte[in.length];
int carry = shiftLeft(in, ret);
int xor = 0xff & DOUBLING_CONST;
/*
* NOTE: This construction is an attempt at a constant-time implementation.
*/
int mask = (-carry) & 0xff;
ret[in.length - 1] ^= xor & mask;
return ret;
}
static byte[] xor(byte[] in1, byte[] in2) {
assert in1.length <= in2.length : "Length of first input must be <= length of second input.";
final byte[] result = new byte[in1.length];
for (int i = 0; i < result.length; i++) {
result[i] = (byte) (in1[i] ^ in2[i]);
}
return result;
}
static byte[] xorend(byte[] in1, byte[] in2) {
assert in1.length >= in2.length : "Length of first input must be >= length of second input.";
final byte[] result = Arrays.copyOf(in1, in1.length);
final int diff = in1.length - in2.length;
for (int i = 0; i < in2.length; i++) {
result[i + diff] = (byte) (result[i + diff] ^ in2[i]);
}
return result;
}
}
| src/main/java/org/cryptomator/siv/SivMode.java | package org.cryptomator.siv;
/*******************************************************************************
* Copyright (c) 2015 Sebastian Stenzel
* This file is licensed under the terms of the MIT license.
* See the LICENSE.txt file for more info.
*
* Contributors:
* Sebastian Stenzel - initial API and implementation
******************************************************************************/
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.Mac;
import org.bouncycastle.crypto.macs.CMac;
import org.bouncycastle.crypto.paddings.ISO7816d4Padding;
import org.bouncycastle.crypto.params.KeyParameter;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import java.nio.ByteBuffer;
import java.security.Provider;
import java.util.Arrays;
/**
* Implements the RFC 5297 SIV mode.
*/
public final class SivMode {
private static final byte[] BYTES_ZERO = new byte[16];
private static final byte DOUBLING_CONST = (byte) 0x87;
private final ThreadLocal<BlockCipher> threadLocalCipher;
/**
* Creates an AES-SIV instance using JCE's cipher implementation, which should normally be the best choice.<br>
* <p>
* For embedded systems, you might want to consider using {@link #SivMode(BlockCipherFactory)} with BouncyCastle's {@code AESLightEngine} instead.
*
* @see #SivMode(BlockCipherFactory)
*/
public SivMode() {
this((Provider) null);
}
/**
* Creates an AES-SIV instance using a custom JCE's security provider<br>
* <p>
* For embedded systems, you might want to consider using {@link #SivMode(BlockCipherFactory)} with BouncyCastle's {@code AESLightEngine} instead.
*
* @param jceSecurityProvider to use to create the internal {@link javax.crypto.Cipher} instance
* @see #SivMode(BlockCipherFactory)
*/
public SivMode(final Provider jceSecurityProvider) {
this(new BlockCipherFactory() {
@Override
public BlockCipher create() {
return new JceAesBlockCipher(jceSecurityProvider);
}
});
}
/**
* Creates an instance using a specific Blockcipher.get(). If you want to use AES, just use the default constructor.
*
* @param cipherFactory A factory method creating a Blockcipher.get(). Must use a block size of 128 bits (16 bytes).
*/
public SivMode(final BlockCipherFactory cipherFactory) {
// Try using cipherFactory to check that the block size is valid.
// We assume here that the block size will not vary across calls to .create().
if (cipherFactory.create().getBlockSize() != 16) {
throw new IllegalArgumentException("cipherFactory must create BlockCipher objects with a 16-byte block size");
}
this.threadLocalCipher = new ThreadLocal<BlockCipher>() {
@Override
protected BlockCipher initialValue() {
return cipherFactory.create();
}
};
}
/**
* Creates {@link BlockCipher}s.
*/
public interface BlockCipherFactory {
BlockCipher create();
}
/**
* Convenience method, if you are using the javax.crypto API. This is just a wrapper for {@link #encrypt(byte[], byte[], byte[], byte[]...)}.
*
* @param ctrKey SIV mode requires two separate keys. You can use one long key, which is splitted in half. See https://tools.ietf.org/html/rfc5297#section-2.2
* @param macKey SIV mode requires two separate keys. You can use one long key, which is splitted in half. See https://tools.ietf.org/html/rfc5297#section-2.2
* @param plaintext Your plaintext, which shall be encrypted.
* @param associatedData Optional associated data, which gets authenticated but not encrypted.
* @return IV + Ciphertext as a concatenated byte array.
* @throws IllegalArgumentException if keys are invalid or {@link SecretKey#getEncoded()} is not supported.
*/
public byte[] encrypt(SecretKey ctrKey, SecretKey macKey, byte[] plaintext, byte[]... associatedData) {
final byte[] ctrKeyBytes = ctrKey.getEncoded();
final byte[] macKeyBytes = macKey.getEncoded();
if (ctrKeyBytes == null || macKeyBytes == null) {
throw new IllegalArgumentException("Can't get bytes of given key.");
}
try {
return encrypt(ctrKeyBytes, macKeyBytes, plaintext, associatedData);
} finally {
Arrays.fill(ctrKeyBytes, (byte) 0);
Arrays.fill(macKeyBytes, (byte) 0);
}
}
/**
* Encrypts plaintext using SIV mode. A block cipher defined by the constructor is being used.<br>
*
* @param ctrKey SIV mode requires two separate keys. You can use one long key, which is splitted in half. See https://tools.ietf.org/html/rfc5297#section-2.2
* @param macKey SIV mode requires two separate keys. You can use one long key, which is splitted in half. See https://tools.ietf.org/html/rfc5297#section-2.2
* @param plaintext Your plaintext, which shall be encrypted.
* @param associatedData Optional associated data, which gets authenticated but not encrypted.
* @return IV + Ciphertext as a concatenated byte array.
* @throws IllegalArgumentException if the either of the two keys is of invalid length for the used {@link BlockCipher}.
*/
public byte[] encrypt(byte[] ctrKey, byte[] macKey, byte[] plaintext, byte[]... associatedData) {
// Check if plaintext length will cause overflows
if (plaintext.length > (Integer.MAX_VALUE - 16)) {
throw new IllegalArgumentException("Plaintext is too long");
}
assert plaintext.length + 15 < Integer.MAX_VALUE;
final int numBlocks = (plaintext.length + 15) / 16;
final byte[] iv = s2v(macKey, plaintext, associatedData);
final byte[] keystream = generateKeyStream(ctrKey, iv, numBlocks);
final byte[] ciphertext = xor(plaintext, keystream);
// concat IV + ciphertext:
final byte[] result = new byte[iv.length + ciphertext.length];
System.arraycopy(iv, 0, result, 0, iv.length);
System.arraycopy(ciphertext, 0, result, iv.length, ciphertext.length);
return result;
}
/**
* Convenience method, if you are using the javax.crypto API. This is just a wrapper for {@link #decrypt(byte[], byte[], byte[], byte[]...)}.
*
* @param ctrKey SIV mode requires two separate keys. You can use one long key, which is splitted in half. See https://tools.ietf.org/html/rfc5297#section-2.2
* @param macKey SIV mode requires two separate keys. You can use one long key, which is splitted in half. See https://tools.ietf.org/html/rfc5297#section-2.2
* @param ciphertext Your cipehrtext, which shall be decrypted.
* @param associatedData Optional associated data, which needs to be authenticated during decryption.
* @return Plaintext byte array.
* @throws IllegalArgumentException If keys are invalid or {@link SecretKey#getEncoded()} is not supported.
* @throws UnauthenticCiphertextException If the authentication failed, e.g. because ciphertext and/or associatedData are corrupted.
* @throws IllegalBlockSizeException If the provided ciphertext is of invalid length.
*/
public byte[] decrypt(SecretKey ctrKey, SecretKey macKey, byte[] ciphertext, byte[]... associatedData) throws UnauthenticCiphertextException, IllegalBlockSizeException {
final byte[] ctrKeyBytes = ctrKey.getEncoded();
final byte[] macKeyBytes = macKey.getEncoded();
if (ctrKeyBytes == null || macKeyBytes == null) {
throw new IllegalArgumentException("Can't get bytes of given key.");
}
try {
return decrypt(ctrKeyBytes, macKeyBytes, ciphertext, associatedData);
} finally {
Arrays.fill(ctrKeyBytes, (byte) 0);
Arrays.fill(macKeyBytes, (byte) 0);
}
}
/**
* Decrypts ciphertext using SIV mode. A block cipher defined by the constructor is being used.<br>
*
* @param ctrKey SIV mode requires two separate keys. You can use one long key, which is splitted in half. See https://tools.ietf.org/html/rfc5297#section-2.2
* @param macKey SIV mode requires two separate keys. You can use one long key, which is splitted in half. See https://tools.ietf.org/html/rfc5297#section-2.2
* @param ciphertext Your ciphertext, which shall be encrypted.
* @param associatedData Optional associated data, which needs to be authenticated during decryption.
* @return Plaintext byte array.
* @throws IllegalArgumentException If the either of the two keys is of invalid length for the used {@link BlockCipher}.
* @throws UnauthenticCiphertextException If the authentication failed, e.g. because ciphertext and/or associatedData are corrupted.
* @throws IllegalBlockSizeException If the provided ciphertext is of invalid length.
*/
public byte[] decrypt(byte[] ctrKey, byte[] macKey, byte[] ciphertext, byte[]... associatedData) throws UnauthenticCiphertextException, IllegalBlockSizeException {
if (ciphertext.length < 16) {
throw new IllegalBlockSizeException("Input length must be greater than or equal 16.");
}
final byte[] iv = Arrays.copyOf(ciphertext, 16);
final byte[] actualCiphertext = Arrays.copyOfRange(ciphertext, 16, ciphertext.length);
assert actualCiphertext.length == ciphertext.length - 16;
assert actualCiphertext.length + 15 < Integer.MAX_VALUE;
final int numBlocks = (actualCiphertext.length + 15) / 16;
final byte[] keystream = generateKeyStream(ctrKey, iv, numBlocks);
final byte[] plaintext = xor(actualCiphertext, keystream);
final byte[] control = s2v(macKey, plaintext, associatedData);
// time-constant comparison (taken from MessageDigest.isEqual in JDK8)
assert iv.length == control.length;
int diff = 0;
for (int i = 0; i < iv.length; i++) {
diff |= iv[i] ^ control[i];
}
if (diff == 0) {
return plaintext;
} else {
throw new UnauthenticCiphertextException("authentication in SIV decryption failed");
}
}
byte[] generateKeyStream(byte[] ctrKey, byte[] iv, int numBlocks) {
final byte[] keystream = new byte[numBlocks * 16];
// clear out the 31st and 63rd (rightmost) bit:
final byte[] ctr = Arrays.copyOf(iv, 16);
ctr[8] = (byte) (ctr[8] & 0x7F);
ctr[12] = (byte) (ctr[12] & 0x7F);
final ByteBuffer ctrBuf = ByteBuffer.wrap(ctr);
final long initialCtrVal = ctrBuf.getLong(8);
final BlockCipher cipher = threadLocalCipher.get();
cipher.init(true, new KeyParameter(ctrKey));
for (int i = 0; i < numBlocks; i++) {
ctrBuf.putLong(8, initialCtrVal + i);
cipher.processBlock(ctr, 0, keystream, i * 16);
cipher.reset();
}
return keystream;
}
// Visible for testing, throws IllegalArgumentException if key is not accepted by CMac#init(CipherParameters)
byte[] s2v(byte[] macKey, byte[] plaintext, byte[]... associatedData) {
// Maximum permitted AD length is the block size in bits - 2
if (associatedData.length > 126) {
// SIV mode cannot be used safely with this many AD fields
throw new IllegalArgumentException("too many Associated Data fields");
}
final CipherParameters params = new KeyParameter(macKey);
final CMac mac = new CMac(threadLocalCipher.get());
mac.init(params);
byte[] d = mac(mac, BYTES_ZERO);
for (byte[] s : associatedData) {
d = xor(dbl(d), mac(mac, s));
}
final byte[] t;
if (plaintext.length >= 16) {
t = xorend(plaintext, d);
} else {
t = xor(dbl(d), pad(plaintext));
}
return mac(mac, t);
}
private static byte[] mac(Mac mac, byte[] in) {
byte[] result = new byte[mac.getMacSize()];
mac.update(in, 0, in.length);
mac.doFinal(result, 0);
return result;
}
// First bit 1, following bits 0.
private static byte[] pad(byte[] in) {
final byte[] result = Arrays.copyOf(in, 16);
new ISO7816d4Padding().addPadding(result, in.length);
return result;
}
// Code taken from {@link org.bouncycastle.crypto.macs.CMac}
static int shiftLeft(byte[] block, byte[] output) {
int i = block.length;
int bit = 0;
while (--i >= 0) {
int b = block[i] & 0xff;
output[i] = (byte) ((b << 1) | bit);
bit = (b >>> 7) & 1;
}
return bit;
}
// Code taken from {@link org.bouncycastle.crypto.macs.CMac}
static byte[] dbl(byte[] in) {
byte[] ret = new byte[in.length];
int carry = shiftLeft(in, ret);
int xor = 0xff & DOUBLING_CONST;
/*
* NOTE: This construction is an attempt at a constant-time implementation.
*/
int mask = (-carry) & 0xff;
ret[in.length - 1] ^= xor & mask;
return ret;
}
static byte[] xor(byte[] in1, byte[] in2) {
assert in1.length <= in2.length : "Length of first input must be <= length of second input.";
final byte[] result = new byte[in1.length];
for (int i = 0; i < result.length; i++) {
result[i] = (byte) (in1[i] ^ in2[i]);
}
return result;
}
static byte[] xorend(byte[] in1, byte[] in2) {
assert in1.length >= in2.length : "Length of first input must be >= length of second input.";
final byte[] result = Arrays.copyOf(in1, in1.length);
final int diff = in1.length - in2.length;
for (int i = 0; i < in2.length; i++) {
result[i + diff] = (byte) (result[i + diff] ^ in2[i]);
}
return result;
}
}
| Clarified missing branch
if n = 0 then
return V = AES-CMAC(K, <one>)
fi
Fixes #14
| src/main/java/org/cryptomator/siv/SivMode.java | Clarified missing branch |
|
Java | mit | 31333956e901b5a5c1a446f431b2138d6a5d01bc | 0 | nicorsm/S3-16-simone,nicorsm/S3-16-simone,simoneapp/S3-16-simone,simoneapp/S3-16-simone | package app.simone.DistributedSimon.Activities;
import android.graphics.PorterDuff;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;
import app.simone.R;
public class ColorSetUpActivity extends AppCompatActivity {
private String playerID = "";
private String playerOwnColor = "";
private String sequenceIndex = "";
private DatabaseReference databaseReference;
private final String CHILD_PLAYERS = "users";
private final String NODE_REF_ROOT = "matchesTry";
private final String CHILD_PLAYERSSEQUENCE = "PlayersSequence";
private final String CHILD_CPUSEQUENCE = "CPUSequence";
private final String CHILD_MATCHID = "MATCHID";
private final String CHILD_INDEX = "index";
private Button buttonColor;
private int blinkCount = 0;
private static android.os.Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_set_up);
databaseReference = FirebaseDatabase.getInstance().getReference(NODE_REF_ROOT);
buttonColor = (Button) findViewById(R.id.beautifulButton);
setColor();
}
public void sendColor(View view) throws ExecutionException, InterruptedException {
databaseReference.child(CHILD_MATCHID).child(CHILD_PLAYERSSEQUENCE).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long count = dataSnapshot.getChildrenCount();
dataSnapshot.getRef().child(String.valueOf(count + 1)).setValue(playerOwnColor);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void onResume() {
super.onResume();
blink();
}
private void setColor() {
Log.d("PROVA", "executing query");
databaseReference.child(CHILD_MATCHID).child(CHILD_PLAYERS).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot singleDataSnapshot : dataSnapshot.getChildren()) {
HashMap<String, String> player_info = (HashMap<String, String>) singleDataSnapshot.getValue();
Log.d("PROVA", player_info.toString());
playerID = singleDataSnapshot.getKey();
Log.d("PLAYERID", playerID);
if (!Boolean.parseBoolean(player_info.get("taken"))) {
playerOwnColor = player_info.get("color");
render();
databaseReference.child(CHILD_MATCHID).child(CHILD_PLAYERS).child(playerID).child("taken").setValue("true");
buttonColor.setText(playerID + " " + playerOwnColor);
Log.d("CHILDSNAPSHOT", "changing value");
break;
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void render() {
if (playerOwnColor.equals("YELLOW")) {
buttonColor.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.myYellow), PorterDuff.Mode.MULTIPLY);
}
if (playerOwnColor.equals("GREEN")) {
buttonColor.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.myGreen), PorterDuff.Mode.MULTIPLY);
}
if (playerOwnColor.equals("RED")) {
buttonColor.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.myRed), PorterDuff.Mode.MULTIPLY);
}
if (playerOwnColor.equals("BLUE")) {
buttonColor.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.myBlue), PorterDuff.Mode.MULTIPLY);
}
}
private void blink() {
final DatabaseReference cpuSequenceRef = databaseReference.child(CHILD_MATCHID).child(CHILD_CPUSEQUENCE).getRef();
databaseReference.child(CHILD_MATCHID).child(CHILD_INDEX).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("PROVAINDEX_BLINK", dataSnapshot.getValue(String.class));
final String cpuSequenceIndex = dataSnapshot.getValue(String.class);
cpuSequenceRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String childrenCount = String.valueOf(dataSnapshot.getChildrenCount());
int newIndex = 0;
for (DataSnapshot child : dataSnapshot.getChildren()) {
String colorSequence = child.getValue(String.class);
String index = child.getKey();
Log.d("CHILDLOOP", colorSequence + " " + index);
if (playerOwnColor.equals(colorSequence) && cpuSequenceIndex.equals(index)) {
++blinkCount;
Log.d("BLINKING", String.valueOf(blinkCount));
if (index.equals(childrenCount)) {
buttonColor.setText(playerOwnColor + " " + blinkCount + " your turn!");
} else {
newIndex = Integer.parseInt(index) + 1;
buttonColor.setText(playerOwnColor + " " + blinkCount);
databaseReference.child(CHILD_MATCHID).child(CHILD_INDEX).setValue(String.valueOf(newIndex));
}
} else {
buttonColor.setText(playerOwnColor + " " + blinkCount);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
| app/src/main/java/app/simone/DistributedSimon/Activities/ColorSetUpActivity.java | package app.simone.DistributedSimon.Activities;
import android.graphics.PorterDuff;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Transaction;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import app.simone.R;
public class ColorSetUpActivity extends AppCompatActivity {
private String playerID = "";
private String playerOwnColor = "";
private DatabaseReference databaseReference;
private final String CHILD_PLAYERS = "users";
private final String NODE_REF_ROOT = "matchesTry";
private final String CHILD_PLAYERSSEQUENCE = "PlayersSequence";
private final String CHILD_CPUSEQUENCE = "CPUSequence";
private final String CHILD_MATCHID = "MATCHID";
private Button buttonColor;
private int blinkCount = 0;
private static android.os.Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_set_up);
databaseReference = FirebaseDatabase.getInstance().getReference(NODE_REF_ROOT);
buttonColor = (Button) findViewById(R.id.beautifulButton);
handler = new android.os.Handler() {
@Override
public void handleMessage(final Message msg) {
Log.d("HANDLER", "handling stuff");
if (msg.arg2 == 0) {
buttonColor.setAlpha(0.4f);
}
if (msg.arg2 == 1) {
buttonColor.setAlpha(1);
}
}
};
setColor();
}
public void sendColor(View view) throws ExecutionException, InterruptedException {
databaseReference.child(CHILD_MATCHID).child(CHILD_PLAYERSSEQUENCE).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long count = dataSnapshot.getChildrenCount();
dataSnapshot.getRef().child(String.valueOf(count + 1)).setValue(playerOwnColor);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void onResume() {
super.onResume();
databaseReference.child(CHILD_MATCHID).child(CHILD_CPUSEQUENCE).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("I'm here in cpu", "ciao");
for (DataSnapshot child : dataSnapshot.getChildren()) {
Log.d("CHILDLOOP", child.getValue().toString() + " " + child.getKey());
//get playerOwnColor and blink
String colorSequence = child.getValue().toString();
String index = child.getKey();
long childrenCOunt = dataSnapshot.getChildrenCount();
if (playerOwnColor.equals(colorSequence)) {
if (Long.parseLong(index) == childrenCOunt) {
buttonColor.setText(playerOwnColor + " " + blinkCount + " your turn!");
} else {
buttonColor.setText(playerOwnColor + " " + blinkCount);
// buttonColor.setAlpha(0.4f);
//check if this is last playerOwnColor of sequence
++blinkCount;
Log.d("BLINKCOUNT", String.valueOf(blinkCount));
}
} else {
Message m = new Message();
m.arg2 = 1;
buttonColor.setText(playerOwnColor + " " + blinkCount);
handler.sendMessageDelayed(m, 1000);
// buttonColor.setAlpha(1);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void setColor() {
Log.d("PROVA", "executing query");
databaseReference.child(CHILD_MATCHID).child(CHILD_PLAYERS).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot singleDataSnapshot : dataSnapshot.getChildren()) {
HashMap<String, String> player_info = (HashMap<String, String>) singleDataSnapshot.getValue();
Log.d("PROVA", player_info.toString());
playerID = singleDataSnapshot.getKey();
Log.d("PLAYERID", playerID);
if (!Boolean.parseBoolean(player_info.get("taken"))) {
playerOwnColor = player_info.get("color");
render();
databaseReference.child(CHILD_MATCHID).child(CHILD_PLAYERS).child(playerID).child("taken").setValue("true");
buttonColor.setText(playerID + " " + playerOwnColor);
Log.d("CHILDSNAPSHOT", "changing value");
break;
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void render() {
if (playerOwnColor.equals("YELLOW")) {
buttonColor.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.myYellow), PorterDuff.Mode.MULTIPLY);
}
if (playerOwnColor.equals("GREEN")) {
buttonColor.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.myGreen), PorterDuff.Mode.MULTIPLY);
}
if (playerOwnColor.equals("RED")) {
buttonColor.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.myRed), PorterDuff.Mode.MULTIPLY);
}
if (playerOwnColor.equals("BLUE")) {
buttonColor.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.myBlue), PorterDuff.Mode.MULTIPLY);
}
}
}
| logic reworked
| app/src/main/java/app/simone/DistributedSimon/Activities/ColorSetUpActivity.java | logic reworked |
|
Java | mit | 8c25a9e0219318e873983afbbc9ce9ac18afb927 | 0 | Michionlion/squadron4 | package engine.render;
import assets.models.RawModel;
import assets.textures.Texture2D;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
public class Loader {
private List<Integer> vaos = new ArrayList<>();
private List<Integer> vbos = new ArrayList<>();
private HashMap<String, Integer> textures = new HashMap<>();
public RawModel loadToVAO(float[] positions, float[] textureCoords, int[] indices, boolean is2D) {
int posSize = 3;
if(is2D) posSize = 2;
int vaoID = createVAO();
bindIndicesBuffer(indices);
storeDataInAttributeList(0, posSize, positions);
storeDataInAttributeList(1, 2, textureCoords);
unbindVAO();
return new RawModel(vaoID, indices.length);
}
public Texture2D getTexture(String fileName) {
return new Texture2D(getTextureID(fileName));
}
public int getTextureID(String fileName) {
if(textures.containsKey(fileName)) return textures.get(fileName);
else return loadTexture(fileName);
}
private int loadTexture(String fileName) {
Texture tex = null;
try {
tex = TextureLoader.getTexture("PNG", new FileInputStream("res/"+fileName+".png"));
} catch (IOException ex) {
Logger.getLogger(Loader.class.getName()).log(Level.SEVERE, null, ex);
}
if(tex == null) {
System.err.println("unable to load texture: " + fileName);
return -1;
}
int textureID = tex.getTextureID();
textures.put(fileName, textureID);
return textureID;
}
private int createVAO() {
int vaoID = GL30.glGenVertexArrays();
vaos.add(vaoID);
GL30.glBindVertexArray(vaoID);
return vaoID;
}
private void storeDataInAttributeList(int attNum, int dataSize, float[] data) {
int vboID = GL15.glGenBuffers();
vbos.add(vboID);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboID);
FloatBuffer buffer = storeDataInFloatBuffer(data);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
GL20.glVertexAttribPointer(attNum, dataSize, GL11.GL_FLOAT, false, 0, 0);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
}
private void unbindVAO() {
GL30.glBindVertexArray(0);
}
private void bindIndicesBuffer(int[] indices) {
int vboID = GL15.glGenBuffers();
vbos.add(vboID);
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vboID);
IntBuffer buffer = storeDataInIntBuffer(indices);
GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
}
private IntBuffer storeDataInIntBuffer(int[] data) {
IntBuffer buffer = BufferUtils.createIntBuffer(data.length);
buffer.put(data);
buffer.flip();
return buffer;
}
private FloatBuffer storeDataInFloatBuffer(float[] data) {
FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length);
buffer.put(data);
buffer.flip();
return buffer;
}
public void cleanUp() {
for(int vao : vaos) {
GL30.glDeleteVertexArrays(vao);
}
for(int vbo : vbos) {
GL15.glDeleteBuffers(vbo);
}
for(int tex : textures) {
GL11.glDeleteTextures(tex);
}
}
}
| src/engine/render/Loader.java | package engine.render;
import assets.models.RawModel;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
public class Loader {
private List<Integer> vaos = new ArrayList<>();
private List<Integer> vbos = new ArrayList<>();
private List<Integer> textures = new ArrayList<>();
public RawModel loadToVAO(float[] positions, float[] textureCoords, int[] indices) {
int vaoID = createVAO();
bindIndicesBuffer(indices);
storeDataInAttributeList(0, 3, positions);
storeDataInAttributeList(1, 2, textureCoords);
unbindVAO();
return new RawModel(vaoID, indices.length);
}
public int loadTexture(String fileName) {
Texture tex = null;
try {
tex = TextureLoader.getTexture("PNG", new FileInputStream("res/"+fileName+".png"));
} catch (IOException ex) {
Logger.getLogger(Loader.class.getName()).log(Level.SEVERE, null, ex);
}
if(tex == null) {
System.err.println("unable to load texture: " + fileName);
return -1;
}
int textureID = tex.getTextureID();
textures.add(textureID);
return textureID;
}
private int createVAO() {
int vaoID = GL30.glGenVertexArrays();
vaos.add(vaoID);
GL30.glBindVertexArray(vaoID);
return vaoID;
}
private void storeDataInAttributeList(int attNum, int dataSize, float[] data) {
int vboID = GL15.glGenBuffers();
vbos.add(vboID);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboID);
FloatBuffer buffer = storeDataInFloatBuffer(data);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
GL20.glVertexAttribPointer(attNum, dataSize, GL11.GL_FLOAT, false, 0, 0);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
}
private void unbindVAO() {
GL30.glBindVertexArray(0);
}
private void bindIndicesBuffer(int[] indices) {
int vboID = GL15.glGenBuffers();
vbos.add(vboID);
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vboID);
IntBuffer buffer = storeDataInIntBuffer(indices);
GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW);
}
private IntBuffer storeDataInIntBuffer(int[] data) {
IntBuffer buffer = BufferUtils.createIntBuffer(data.length);
buffer.put(data);
buffer.flip();
return buffer;
}
private FloatBuffer storeDataInFloatBuffer(float[] data) {
FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length);
buffer.put(data);
buffer.flip();
return buffer;
}
public void cleanUp() {
for(int vao : vaos) {
GL30.glDeleteVertexArrays(vao);
}
for(int vbo : vbos) {
GL15.glDeleteBuffers(vbo);
}
for(int tex : textures) {
GL11.glDeleteTextures(tex);
}
}
}
| restructuring for sprite engine | src/engine/render/Loader.java | restructuring for sprite engine |
|
Java | mit | c4022f799cb9bd779273fd401084a79646028e6e | 0 | fatpigsarefat/Quests | package com.leonardobishop.quests;
import com.google.common.io.ByteStreams;
import com.leonardobishop.quests.blocktype.SimilarBlocks;
import com.leonardobishop.quests.bstats.Metrics;
import com.leonardobishop.quests.commands.CommandQuests;
import com.leonardobishop.quests.events.EventInventory;
import com.leonardobishop.quests.events.EventPlayerJoin;
import com.leonardobishop.quests.events.EventPlayerLeave;
import com.leonardobishop.quests.obj.misc.QItemStack;
import com.leonardobishop.quests.player.QPlayer;
import com.leonardobishop.quests.player.QPlayerManager;
import com.leonardobishop.quests.player.questprogressfile.QuestProgress;
import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile;
import com.leonardobishop.quests.player.questprogressfile.TaskProgress;
import com.leonardobishop.quests.quests.Category;
import com.leonardobishop.quests.quests.Quest;
import com.leonardobishop.quests.quests.QuestManager;
import com.leonardobishop.quests.quests.Task;
import com.leonardobishop.quests.quests.tasktypes.TaskTypeManager;
import com.leonardobishop.quests.quests.tasktypes.types.*;
import com.leonardobishop.quests.title.Title;
import com.leonardobishop.quests.title.Title_Bukkit;
import com.leonardobishop.quests.title.Title_BukkitNoTimings;
import com.leonardobishop.quests.title.Title_Other;
import com.leonardobishop.quests.updater.Updater;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
public class Quests extends JavaPlugin {
private static Quests instance;
private static QuestManager questManager;
private static QPlayerManager qPlayerManager;
private static TaskTypeManager taskTypeManager;
private static Updater updater;
private static Title title;
private boolean brokenConfig = false;
public static Quests getInstance() {
return instance;
}
public static QuestManager getQuestManager() {
return questManager;
}
public static QPlayerManager getPlayerManager() {
return qPlayerManager;
}
public static TaskTypeManager getTaskTypeManager() {
return taskTypeManager;
}
public boolean isBrokenConfig() {
return brokenConfig;
}
public static Title getTitle() {
return title;
}
public static Updater getUpdater() {
return updater;
}
public static String convertToFormat(long m) {
long hours = m / 60;
long minutesLeft = m - hours * 60;
String formattedTime = "";
if (hours < 10)
formattedTime = formattedTime + "0";
formattedTime = formattedTime + hours + "h";
formattedTime = formattedTime + " ";
if (minutesLeft < 10)
formattedTime = formattedTime + "0";
formattedTime = formattedTime + minutesLeft + "m";
return formattedTime;
}
public Quests() {
}
public Quests(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) {
super(loader, description, dataFolder, file);
}
public void prepareForTest() {
instance = this;
taskTypeManager = new TaskTypeManager();
questManager = new QuestManager();
qPlayerManager = new QPlayerManager();
updater = new Updater(this);
}
@Override
public void onEnable() {
instance = this;
taskTypeManager = new TaskTypeManager();
questManager = new QuestManager();
qPlayerManager = new QPlayerManager();
dataGenerator();
setupTitle();
taskTypeManager.registerTaskType(new MiningTaskType());
taskTypeManager.registerTaskType(new MiningCertainTaskType());
taskTypeManager.registerTaskType(new BuildingTaskType());
taskTypeManager.registerTaskType(new BuildingCertainTaskType());
taskTypeManager.registerTaskType(new MobkillingTaskType());
taskTypeManager.registerTaskType(new MobkillingCertainTaskType());
taskTypeManager.registerTaskType(new PlayerkillingTaskType());
taskTypeManager.registerTaskType(new FishingTaskType());
taskTypeManager.registerTaskType(new InventoryTaskType());
taskTypeManager.registerTaskType(new WalkingTaskType());
taskTypeManager.registerTaskType(new TamingTaskType());
taskTypeManager.registerTaskType(new MilkingTaskType());
taskTypeManager.registerTaskType(new ShearingTaskType());
taskTypeManager.registerTaskType(new PositionTaskType());
taskTypeManager.registerTaskType(new PlaytimeTaskType());
taskTypeManager.registerTaskType(new BrewingTaskType());
// TODO: FIX
// taskTypeManager.registerTaskType(new BrewingCertainTaskType());
if (Bukkit.getPluginManager().isPluginEnabled("ASkyBlock")) {
taskTypeManager.registerTaskType(new ASkyBlockLevelType());
}
if (Bukkit.getPluginManager().isPluginEnabled("uSkyBlock")) {
taskTypeManager.registerTaskType(new uSkyBlockLevelType());
}
if (Bukkit.getPluginManager().isPluginEnabled("Citizens")) {
taskTypeManager.registerTaskType(new CitizensDeliverTaskType());
taskTypeManager.registerTaskType(new CitizensInteractTaskType());
}
Bukkit.getPluginCommand("quests").setExecutor(new CommandQuests());
Bukkit.getPluginManager().registerEvents(new EventPlayerJoin(), this);
Bukkit.getPluginManager().registerEvents(new EventInventory(), this);
Bukkit.getPluginManager().registerEvents(new EventPlayerLeave(), this);
Metrics metrics = new Metrics(this);
this.getLogger().log(Level.INFO, "Metrics started. This can be disabled at /plugins/bStats/config.yml.");
SimilarBlocks.addBlocks();
new BukkitRunnable() {
@Override
public void run() {
reloadQuests();
for (Player player : Bukkit.getOnlinePlayers()) {
qPlayerManager.loadPlayer(player.getUniqueId());
}
}
}.runTask(this);
new BukkitRunnable() {
@Override
public void run() {
for (QPlayer qPlayer : qPlayerManager.getQPlayers()) {
if (qPlayer.isOnlyDataLoaded()) {
continue;
}
qPlayer.getQuestProgressFile().saveToDisk();
}
}
}.runTaskTimerAsynchronously(this, 12000L, 12000L);
new BukkitRunnable() {
@Override
public void run() {
for (QPlayer qPlayer : qPlayerManager.getQPlayers()) {
if (qPlayer.isOnlyDataLoaded()) {
continue;
}
QuestProgressFile questProgressFile = qPlayer.getQuestProgressFile();
for (Map.Entry<String, Quest> entry : Quests.getQuestManager().getQuests().entrySet()) {
Quest quest = entry.getValue();
QuestProgress questProgress = questProgressFile.getQuestProgress(quest);
if (questProgress != null && questProgress.isStarted()) {
boolean complete = true;
for (TaskProgress taskProgress : questProgress.getTaskProgress()) {
if (!taskProgress.isCompleted()) {
complete = false;
break;
}
}
if (complete) {
questProgressFile.completeQuest(quest);
}
}
}
}
}
}.runTaskTimer(this, 20L, 20L);
new BukkitRunnable() {
@Override
public void run() {
updater = new Updater(Quests.this);
updater.check();
}
}.runTaskAsynchronously(this);
}
@Override
public void onDisable() {
for (QPlayer qPlayer : qPlayerManager.getQPlayers()) {
if (qPlayer.isOnlyDataLoaded()) {
continue;
}
qPlayer.getQuestProgressFile().saveToDisk();
}
}
public void reloadQuests() {
questManager.getQuests().clear();
questManager.getCategories().clear();
taskTypeManager.resetTaskTypes();
// test file integrity
try {
YamlConfiguration config = new YamlConfiguration();
config.load(new File(String.valueOf(Quests.this.getDataFolder() + File.separator + "config.yml")));
} catch (Exception ex) {
Quests.this.getLogger().log(Level.SEVERE, "You have a YAML error in your Quests config. If this is your first time using Quests, please remove the Quests folder and RESTART (not reload!) the server and try again.");
brokenConfig = true;
}
for (String id : getConfig().getConfigurationSection("categories").getKeys(false)) {
ItemStack displayItem = getItemStack("categories." + id + ".display");
Category category = new Category(id, displayItem);
questManager.registerCategory(category);
}
for (String id : getConfig().getConfigurationSection("quests").getKeys(false)) {
String root = "quests." + id;
QItemStack displayItem = getQItemStack(root + ".display");
List<String> rewards = getConfig().getStringList(root + ".rewards");
List<String> requirements = getConfig().getStringList(root + ".options.requires");
List<String> rewardString = getConfig().getStringList(root + ".rewardstring");
boolean repeatable = getConfig().getBoolean(root + ".options.repeatable", false);
boolean cooldown = getConfig().getBoolean(root + ".options.cooldown.enabled", false);
int cooldownTime = getConfig().getInt(root + ".options.cooldown.time", 10);
String category = getConfig().getString(root + ".options.category");
if (rewardString == null) {
rewardString = new ArrayList<>();
}
if (requirements == null) {
requirements = new ArrayList<>();
}
if (rewards == null) {
rewards = new ArrayList<>();
}
if (category == null) {
category = "";
}
Quest quest;
if (category.equals("")) {
quest = new Quest(id, displayItem, rewards, requirements, repeatable, cooldown, cooldownTime, rewardString);
} else {
quest = new Quest(id, displayItem, rewards, requirements, repeatable, cooldown, cooldownTime, rewardString, category);
Category c = questManager.getCategoryById(category);
if (c != null) {
c.registerQuestId(id);
}
}
for (String taskId : getConfig().getConfigurationSection(root + ".tasks").getKeys(false)) {
String taskRoot = root + ".tasks." + taskId;
String taskType = getConfig().getString(taskRoot + ".type");
Task task = new Task(taskId, taskType);
for (String key : getConfig().getConfigurationSection(taskRoot).getKeys(false)) {
task.addConfigValue(key, getConfig().get(taskRoot + "." + key));
}
quest.registerTask(task);
}
this.getLogger().log(Level.INFO, "Registering quest " + quest.getId() + " with " + quest.getTasks().size() + " tasks.");
questManager.registerQuest(quest);
taskTypeManager.registerQuestTasksWithTaskTypes(quest);
}
}
private QItemStack getQItemStack(String path) {
String cName = this.getConfig().getString(path + ".name", path + ".name");
String cType = this.getConfig().getString(path + ".type", path + ".type");
List<String> cLoreNormal = this.getConfig().getStringList(path + ".lore-normal");
List<String> cLoreStarted = this.getConfig().getStringList(path + ".lore-started");
String name;
Material type = null;
int data = 0;
List<String> loreNormal = new ArrayList<>();
if (cLoreNormal != null) {
for (String s : cLoreNormal) {
loreNormal.add(ChatColor.translateAlternateColorCodes('&', s));
}
}
List<String> loreStarted = new ArrayList<>();
if (cLoreStarted != null) {
for (String s : cLoreStarted) {
loreStarted.add(ChatColor.translateAlternateColorCodes('&', s));
}
}
name = ChatColor.translateAlternateColorCodes('&', cName);
if (StringUtils.isNumeric(cType)) {
type = Material.getMaterial(Integer.parseInt(cType));
} else if (Material.getMaterial(cType) != null) {
type = Material.getMaterial(cType);
} else if (cType.contains(":")) {
String[] parts = cType.split(":");
if (parts.length > 1) {
if (StringUtils.isNumeric(parts[0])) {
type = Material.getMaterial(Integer.parseInt(parts[0]));
} else if (Material.getMaterial(parts[0]) != null) {
type = Material.getMaterial(parts[0]);
}
if (StringUtils.isNumeric(parts[1])) {
data = Integer.parseInt(parts[1]);
}
}
}
if (type == null) {
type = Material.STONE;
}
QItemStack is = new QItemStack(name, loreNormal, loreStarted, type, data);
return is;
}
public ItemStack getItemStack(String path) {
String cName = this.getConfig().getString(path + ".name", path + ".name");
String cType = this.getConfig().getString(path + ".type", path + ".type");
List<String> cLore = this.getConfig().getStringList(path + ".lore");
String name;
Material type = null;
int data = 0;
List<String> lore = new ArrayList<>();
if (cLore != null) {
for (String s : cLore) {
lore.add(ChatColor.translateAlternateColorCodes('&', s));
}
}
name = ChatColor.translateAlternateColorCodes('&', cName);
if (StringUtils.isNumeric(cType)) {
type = Material.getMaterial(Integer.parseInt(cType));
} else if (Material.getMaterial(cType) != null) {
type = Material.getMaterial(cType);
} else if (cType.contains(":")) {
String[] parts = cType.split(":");
if (parts.length > 1) {
if (StringUtils.isNumeric(parts[0])) {
type = Material.getMaterial(Integer.parseInt(parts[0]));
} else if (Material.getMaterial(parts[0]) != null) {
type = Material.getMaterial(parts[0]);
}
if (StringUtils.isNumeric(parts[1])) {
data = Integer.parseInt(parts[1]);
}
}
}
if (type == null) {
type = Material.STONE;
}
ItemStack is = new ItemStack(type, 1, (short) data);
ItemMeta ism = is.getItemMeta();
ism.setLore(lore);
ism.setDisplayName(name);
is.setItemMeta(ism);
return is;
}
private boolean setupTitle() {
String version;
try {
version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
} catch (ArrayIndexOutOfBoundsException e) {
return false;
}
boolean success = false;
getLogger().info("Your server is running version " + version + ".");
if (version.equals("v1_8_R3")) {
title = new Title_BukkitNoTimings();
success = true;
} else if (version.equals("v1_8_R2")) {
title = new Title_BukkitNoTimings();
success = true;
} else if (version.equals("v1_8_R1")) {
title = new Title_BukkitNoTimings();
success = true;
} else if (version.equals("v1_9_R2")) {
title = new Title_BukkitNoTimings();
success = true;
} else if (version.equals("v1_9_R1")) {
title = new Title_BukkitNoTimings();
success = true;
} else if (version.equals("v1_10_R1")) {
title = new Title_BukkitNoTimings();
success = true;
} else if (version.equals("v1_11_R1")) {
title = new Title_Bukkit();
success = true;
} else if (version.equals("v1_12_R1")) {
title = new Title_Bukkit();
success = true;
} else if (version.equals("v1_13_R1")) {
title = new Title_Bukkit();
success = true;
} else {
title = new Title_Other();
}
if (title instanceof Title_Bukkit) {
getLogger().info("Titles have been enabled.");
} else if (title instanceof Title_BukkitNoTimings) {
getLogger().info("Titles have been enabled, although they have limited timings.");
} else {
getLogger().info("Titles are not supported for this version.");
}
return success;
}
private void dataGenerator() {
File directory = new File(String.valueOf(this.getDataFolder()));
if (!directory.exists() && !directory.isDirectory()) {
directory.mkdir();
}
File config = new File(this.getDataFolder() + File.separator + "config.yml");
if (!config.exists()) {
try {
config.createNewFile();
try (InputStream in = Quests.class.getClassLoader().getResourceAsStream("config.yml")) {
OutputStream out = new FileOutputStream(config);
ByteStreams.copy(in, out);
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
| src/main/java/com/leonardobishop/quests/Quests.java | package com.leonardobishop.quests;
import com.google.common.io.ByteStreams;
import com.leonardobishop.quests.blocktype.SimilarBlocks;
import com.leonardobishop.quests.bstats.Metrics;
import com.leonardobishop.quests.commands.CommandQuests;
import com.leonardobishop.quests.events.EventInventory;
import com.leonardobishop.quests.events.EventPlayerJoin;
import com.leonardobishop.quests.events.EventPlayerLeave;
import com.leonardobishop.quests.obj.misc.QItemStack;
import com.leonardobishop.quests.player.QPlayer;
import com.leonardobishop.quests.player.QPlayerManager;
import com.leonardobishop.quests.player.questprogressfile.QuestProgress;
import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile;
import com.leonardobishop.quests.player.questprogressfile.TaskProgress;
import com.leonardobishop.quests.quests.Category;
import com.leonardobishop.quests.quests.Quest;
import com.leonardobishop.quests.quests.QuestManager;
import com.leonardobishop.quests.quests.Task;
import com.leonardobishop.quests.quests.tasktypes.TaskTypeManager;
import com.leonardobishop.quests.quests.tasktypes.types.*;
import com.leonardobishop.quests.title.Title;
import com.leonardobishop.quests.title.Title_Bukkit;
import com.leonardobishop.quests.title.Title_BukkitNoTimings;
import com.leonardobishop.quests.title.Title_Other;
import com.leonardobishop.quests.updater.Updater;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
public class Quests extends JavaPlugin {
private static Quests instance;
private static QuestManager questManager;
private static QPlayerManager qPlayerManager;
private static TaskTypeManager taskTypeManager;
private static Updater updater;
private static Title title;
private boolean brokenConfig = false;
public static Quests getInstance() {
return instance;
}
public static QuestManager getQuestManager() {
return questManager;
}
public static QPlayerManager getPlayerManager() {
return qPlayerManager;
}
public static TaskTypeManager getTaskTypeManager() {
return taskTypeManager;
}
public boolean isBrokenConfig() {
return brokenConfig;
}
public static Title getTitle() {
return title;
}
public static Updater getUpdater() {
return updater;
}
public static String convertToFormat(long m) {
long hours = m / 60;
long minutesLeft = m - hours * 60;
String formattedTime = "";
if (hours < 10)
formattedTime = formattedTime + "0";
formattedTime = formattedTime + hours + "h";
formattedTime = formattedTime + " ";
if (minutesLeft < 10)
formattedTime = formattedTime + "0";
formattedTime = formattedTime + minutesLeft + "m";
return formattedTime;
}
public Quests() {
}
public Quests(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) {
super(loader, description, dataFolder, file);
}
public void prepareForTest() {
instance = this;
taskTypeManager = new TaskTypeManager();
questManager = new QuestManager();
qPlayerManager = new QPlayerManager();
updater = new Updater(this);
}
@Override
public void onEnable() {
instance = this;
taskTypeManager = new TaskTypeManager();
questManager = new QuestManager();
qPlayerManager = new QPlayerManager();
dataGenerator();
setupTitle();
taskTypeManager.registerTaskType(new MiningTaskType());
taskTypeManager.registerTaskType(new MiningCertainTaskType());
taskTypeManager.registerTaskType(new BuildingTaskType());
taskTypeManager.registerTaskType(new BuildingCertainTaskType());
taskTypeManager.registerTaskType(new MobkillingTaskType());
taskTypeManager.registerTaskType(new MobkillingCertainTaskType());
taskTypeManager.registerTaskType(new PlayerkillingTaskType());
taskTypeManager.registerTaskType(new FishingTaskType());
taskTypeManager.registerTaskType(new InventoryTaskType());
taskTypeManager.registerTaskType(new WalkingTaskType());
taskTypeManager.registerTaskType(new TamingTaskType());
taskTypeManager.registerTaskType(new MilkingTaskType());
taskTypeManager.registerTaskType(new ShearingTaskType());
taskTypeManager.registerTaskType(new PositionTaskType());
taskTypeManager.registerTaskType(new PlaytimeTaskType());
taskTypeManager.registerTaskType(new BrewingTaskType());
// TODO: FIX
// taskTypeManager.registerTaskType(new BrewingCertainTaskType());
if (Bukkit.getPluginManager().isPluginEnabled("ASkyBlock")) {
taskTypeManager.registerTaskType(new ASkyBlockLevelType());
}
if (Bukkit.getPluginManager().isPluginEnabled("uSkyBlock")) {
taskTypeManager.registerTaskType(new uSkyBlockLevelType());
}
if (Bukkit.getPluginManager().isPluginEnabled("Citizens")) {
taskTypeManager.registerTaskType(new CitizensDeliverTaskType());
taskTypeManager.registerTaskType(new CitizensInteractTaskType());
}
Bukkit.getPluginCommand("quests").setExecutor(new CommandQuests());
Bukkit.getPluginManager().registerEvents(new EventPlayerJoin(), this);
Bukkit.getPluginManager().registerEvents(new EventInventory(), this);
Bukkit.getPluginManager().registerEvents(new EventPlayerLeave(), this);
Metrics metrics = new Metrics(this);
this.getLogger().log(Level.INFO, "Metrics started. This can be disabled at /plugins/bStats/config.yml.");
SimilarBlocks.addBlocks();
new BukkitRunnable() {
@Override
public void run() {
reloadQuests();
for (Player player : Bukkit.getOnlinePlayers()) {
qPlayerManager.loadPlayer(player.getUniqueId());
}
}
}.runTask(this);
new BukkitRunnable() {
@Override
public void run() {
for (QPlayer qPlayer : qPlayerManager.getQPlayers()) {
if (qPlayer.isOnlyDataLoaded()) {
continue;
}
qPlayer.getQuestProgressFile().saveToDisk();
}
}
}.runTaskTimerAsynchronously(this, 12000L, 12000L);
new BukkitRunnable() {
@Override
public void run() {
for (QPlayer qPlayer : qPlayerManager.getQPlayers()) {
if (qPlayer.isOnlyDataLoaded()) {
continue;
}
QuestProgressFile questProgressFile = qPlayer.getQuestProgressFile();
for (Map.Entry<String, Quest> entry : Quests.getQuestManager().getQuests().entrySet()) {
Quest quest = entry.getValue();
QuestProgress questProgress = questProgressFile.getQuestProgress(quest);
if (questProgress != null && questProgress.isStarted()) {
boolean complete = true;
for (TaskProgress taskProgress : questProgress.getTaskProgress()) {
if (!taskProgress.isCompleted()) {
complete = false;
break;
}
}
if (complete) {
questProgressFile.completeQuest(quest);
}
}
}
}
}
}.runTaskTimerAsynchronously(this, 20L, 20L);
new BukkitRunnable() {
@Override
public void run() {
updater = new Updater(Quests.this);
updater.check();
}
}.runTaskAsynchronously(this);
}
@Override
public void onDisable() {
for (QPlayer qPlayer : qPlayerManager.getQPlayers()) {
if (qPlayer.isOnlyDataLoaded()) {
continue;
}
qPlayer.getQuestProgressFile().saveToDisk();
}
}
public void reloadQuests() {
questManager.getQuests().clear();
questManager.getCategories().clear();
taskTypeManager.resetTaskTypes();
// test file integrity
try {
YamlConfiguration config = new YamlConfiguration();
config.load(new File(String.valueOf(Quests.this.getDataFolder() + File.separator + "config.yml")));
} catch (Exception ex) {
Quests.this.getLogger().log(Level.SEVERE, "You have a YAML error in your Quests config. If this is your first time using Quests, please remove the Quests folder and RESTART (not reload!) the server and try again.");
brokenConfig = true;
}
for (String id : getConfig().getConfigurationSection("categories").getKeys(false)) {
ItemStack displayItem = getItemStack("categories." + id + ".display");
Category category = new Category(id, displayItem);
questManager.registerCategory(category);
}
for (String id : getConfig().getConfigurationSection("quests").getKeys(false)) {
String root = "quests." + id;
QItemStack displayItem = getQItemStack(root + ".display");
List<String> rewards = getConfig().getStringList(root + ".rewards");
List<String> requirements = getConfig().getStringList(root + ".options.requires");
List<String> rewardString = getConfig().getStringList(root + ".rewardstring");
boolean repeatable = getConfig().getBoolean(root + ".options.repeatable", false);
boolean cooldown = getConfig().getBoolean(root + ".options.cooldown.enabled", false);
int cooldownTime = getConfig().getInt(root + ".options.cooldown.time", 10);
String category = getConfig().getString(root + ".options.category");
if (rewardString == null) {
rewardString = new ArrayList<>();
}
if (requirements == null) {
requirements = new ArrayList<>();
}
if (rewards == null) {
rewards = new ArrayList<>();
}
if (category == null) {
category = "";
}
Quest quest;
if (category.equals("")) {
quest = new Quest(id, displayItem, rewards, requirements, repeatable, cooldown, cooldownTime, rewardString);
} else {
quest = new Quest(id, displayItem, rewards, requirements, repeatable, cooldown, cooldownTime, rewardString, category);
Category c = questManager.getCategoryById(category);
if (c != null) {
c.registerQuestId(id);
}
}
for (String taskId : getConfig().getConfigurationSection(root + ".tasks").getKeys(false)) {
String taskRoot = root + ".tasks." + taskId;
String taskType = getConfig().getString(taskRoot + ".type");
Task task = new Task(taskId, taskType);
for (String key : getConfig().getConfigurationSection(taskRoot).getKeys(false)) {
task.addConfigValue(key, getConfig().get(taskRoot + "." + key));
}
quest.registerTask(task);
}
this.getLogger().log(Level.INFO, "Registering quest " + quest.getId() + " with " + quest.getTasks().size() + " tasks.");
questManager.registerQuest(quest);
taskTypeManager.registerQuestTasksWithTaskTypes(quest);
}
}
private QItemStack getQItemStack(String path) {
String cName = this.getConfig().getString(path + ".name", path + ".name");
String cType = this.getConfig().getString(path + ".type", path + ".type");
List<String> cLoreNormal = this.getConfig().getStringList(path + ".lore-normal");
List<String> cLoreStarted = this.getConfig().getStringList(path + ".lore-started");
String name;
Material type = null;
int data = 0;
List<String> loreNormal = new ArrayList<>();
if (cLoreNormal != null) {
for (String s : cLoreNormal) {
loreNormal.add(ChatColor.translateAlternateColorCodes('&', s));
}
}
List<String> loreStarted = new ArrayList<>();
if (cLoreStarted != null) {
for (String s : cLoreStarted) {
loreStarted.add(ChatColor.translateAlternateColorCodes('&', s));
}
}
name = ChatColor.translateAlternateColorCodes('&', cName);
if (StringUtils.isNumeric(cType)) {
type = Material.getMaterial(Integer.parseInt(cType));
} else if (Material.getMaterial(cType) != null) {
type = Material.getMaterial(cType);
} else if (cType.contains(":")) {
String[] parts = cType.split(":");
if (parts.length > 1) {
if (StringUtils.isNumeric(parts[0])) {
type = Material.getMaterial(Integer.parseInt(parts[0]));
} else if (Material.getMaterial(parts[0]) != null) {
type = Material.getMaterial(parts[0]);
}
if (StringUtils.isNumeric(parts[1])) {
data = Integer.parseInt(parts[1]);
}
}
}
if (type == null) {
type = Material.STONE;
}
QItemStack is = new QItemStack(name, loreNormal, loreStarted, type, data);
return is;
}
public ItemStack getItemStack(String path) {
String cName = this.getConfig().getString(path + ".name", path + ".name");
String cType = this.getConfig().getString(path + ".type", path + ".type");
List<String> cLore = this.getConfig().getStringList(path + ".lore");
String name;
Material type = null;
int data = 0;
List<String> lore = new ArrayList<>();
if (cLore != null) {
for (String s : cLore) {
lore.add(ChatColor.translateAlternateColorCodes('&', s));
}
}
name = ChatColor.translateAlternateColorCodes('&', cName);
if (StringUtils.isNumeric(cType)) {
type = Material.getMaterial(Integer.parseInt(cType));
} else if (Material.getMaterial(cType) != null) {
type = Material.getMaterial(cType);
} else if (cType.contains(":")) {
String[] parts = cType.split(":");
if (parts.length > 1) {
if (StringUtils.isNumeric(parts[0])) {
type = Material.getMaterial(Integer.parseInt(parts[0]));
} else if (Material.getMaterial(parts[0]) != null) {
type = Material.getMaterial(parts[0]);
}
if (StringUtils.isNumeric(parts[1])) {
data = Integer.parseInt(parts[1]);
}
}
}
if (type == null) {
type = Material.STONE;
}
ItemStack is = new ItemStack(type, 1, (short) data);
ItemMeta ism = is.getItemMeta();
ism.setLore(lore);
ism.setDisplayName(name);
is.setItemMeta(ism);
return is;
}
private boolean setupTitle() {
String version;
try {
version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
} catch (ArrayIndexOutOfBoundsException e) {
return false;
}
boolean success = false;
getLogger().info("Your server is running version " + version + ".");
if (version.equals("v1_8_R3")) {
title = new Title_BukkitNoTimings();
success = true;
} else if (version.equals("v1_8_R2")) {
title = new Title_BukkitNoTimings();
success = true;
} else if (version.equals("v1_8_R1")) {
title = new Title_BukkitNoTimings();
success = true;
} else if (version.equals("v1_9_R2")) {
title = new Title_BukkitNoTimings();
success = true;
} else if (version.equals("v1_9_R1")) {
title = new Title_BukkitNoTimings();
success = true;
} else if (version.equals("v1_10_R1")) {
title = new Title_BukkitNoTimings();
success = true;
} else if (version.equals("v1_11_R1")) {
title = new Title_Bukkit();
success = true;
} else if (version.equals("v1_12_R1")) {
title = new Title_Bukkit();
success = true;
} else if (version.equals("v1_13_R1")) {
title = new Title_Bukkit();
success = true;
} else {
title = new Title_Other();
}
if (title instanceof Title_Bukkit) {
getLogger().info("Titles have been enabled.");
} else if (title instanceof Title_BukkitNoTimings) {
getLogger().info("Titles have been enabled, although they have limited timings.");
} else {
getLogger().info("Titles are not supported for this version.");
}
return success;
}
private void dataGenerator() {
File directory = new File(String.valueOf(this.getDataFolder()));
if (!directory.exists() && !directory.isDirectory()) {
directory.mkdir();
}
File config = new File(this.getDataFolder() + File.separator + "config.yml");
if (!config.exists()) {
try {
config.createNewFile();
try (InputStream in = Quests.class.getClassLoader().getResourceAsStream("config.yml")) {
OutputStream out = new FileOutputStream(config);
ByteStreams.copy(in, out);
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
| Synchronisation
- The quest complete watcher now runs on the main thread because
I'm a fucking idiot
| src/main/java/com/leonardobishop/quests/Quests.java | Synchronisation |
|
Java | epl-1.0 | 8138c4470373cb1e8e5bb6c417ccad75a718e4dc | 0 | rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,Charling-Huang/birt | /*
*************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*
*************************************************************************
*/
package org.eclipse.birt.data.engine.impl;
import java.util.ArrayList;
import java.util.Collection;
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 java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.core.script.ScriptContext;
import org.eclipse.birt.data.engine.api.DataEngineContext;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IBaseQueryDefinition;
import org.eclipse.birt.data.engine.api.IBaseQueryResults;
import org.eclipse.birt.data.engine.api.IBaseTransform;
import org.eclipse.birt.data.engine.api.IBinding;
import org.eclipse.birt.data.engine.api.IConditionalExpression;
import org.eclipse.birt.data.engine.api.IExpressionCollection;
import org.eclipse.birt.data.engine.api.IGroupDefinition;
import org.eclipse.birt.data.engine.api.IScriptExpression;
import org.eclipse.birt.data.engine.api.ISubqueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.Binding;
import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import org.eclipse.birt.data.engine.api.querydefn.SubqueryDefinition;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.expression.CompiledExpression;
import org.eclipse.birt.data.engine.expression.ExpressionCompiler;
import org.eclipse.birt.data.engine.i18n.ResourceConstants;
import org.eclipse.birt.data.engine.impl.aggregation.AggregateRegistry;
import org.eclipse.birt.data.engine.impl.aggregation.AggregateTable;
import org.eclipse.birt.data.engine.odi.IResultIterator;
import org.mozilla.javascript.Scriptable;
/**
* Two main functions for PreparedDataSourceQuery or PreparedSubQuery:
* 1: prepare group, subquery and expressions
* 2: query preparation and sub query execution
*/
final class PreparedQuery
{
private IBaseQueryDefinition baseQueryDefn;
private DataEngineContext dataEngineContext;
private DataEngineSession session;
// private Scriptable sharedScope;
private ExpressionCompiler expressionCompiler;
private IPreparedQueryService queryService;
private AggregateTable aggrTable;
private Map appContext;
// Map of Subquery name (String) to PreparedSubquery
private HashMap subQueryMap;
private HashMap subQueryDefnMap;
private static Logger logger = Logger.getLogger( DataEngineImpl.class.getName( ) );
private ExprManager exprManager;
/**
* @param deContext
* @param scope
* @param queryDefn
* @param queryService
* @param appContext
* @throws DataException
*/
PreparedQuery( DataEngineSession session, DataEngineContext deContext,
IBaseQueryDefinition queryDefn, IPreparedQueryService queryService,
Map appContext ) throws DataException
{
logger.logp( Level.FINE,
PreparedQuery.class.getName( ),
"PreparedQuery",
"PreparedQuery starts up." );
assert queryDefn != null;
this.expressionCompiler = new ExpressionCompiler( );
this.expressionCompiler.setDataSetMode( false );
this.dataEngineContext = deContext;
this.session = session;
if ( queryDefn instanceof SubqueryDefinition )
{
this.baseQueryDefn = SubqueryDefinitionCopyUtil.createSubqueryDefinition( ( (SubqueryDefinition) queryDefn ).getName( ),
(ISubqueryDefinition) queryDefn );
}
else
{
this.baseQueryDefn = queryDefn;
}
this.queryService = queryService;
this.appContext = appContext;
this.exprManager = new ExprManager( baseQueryDefn, session.getEngineContext( ).getScriptContext( ).getContext( ) );
this.subQueryMap = new HashMap( );
this.subQueryDefnMap = new HashMap( );
this.aggrTable = new AggregateTable( this.session.getTempDir( ), this.session.getSharedScope( ),
baseQueryDefn.getGroups( ) );
logger.fine( "Start to prepare a PreparedQuery." );
prepare( );
logger.fine( "Finished preparing the PreparedQuery." );
}
/**
* @throws DataException
*/
private void prepare( ) throws DataException
{
// TODO - validation of static queryDefn
// Prepare all groups; note that the report query iteself
// is treated as a group (with group level 0 ), If there are group
// definitions that of invalid or duplicate group name, then throw
// exceptions.
if ( this.baseQueryDefn.getBindings( ) != null
&& this.baseQueryDefn.getBindings( ).size( ) > 0 )
{
this.expressionCompiler.setDataSetMode( false );
}
List groups = baseQueryDefn.getGroups( );
Set groupNameSet = new HashSet( );
IGroupDefinition group;
for ( int i = 0; i < groups.size( ); i++ )
{
group = (IGroupDefinition) groups.get( i );
if ( group.getName( ) == null
|| group.getName( ).trim( ).length( ) == 0 )
continue;
for ( int j = 0; j < groups.size( ); j++ )
{
if ( group.getName( )
.equals( ( (IGroupDefinition) groups.get( j ) ).getName( ) == null
? ""
: ( (IGroupDefinition) groups.get( j ) ).getName( ) )
&& j != i )
throw new DataException( ResourceConstants.DUPLICATE_GROUP_NAME );
}
groupNameSet.add( group.getName( ) );
}
// The latest column binding (AggregateOn introduced)
Map map = baseQueryDefn.getBindings( );
if ( map != null )
{
Iterator it = map.keySet( ).iterator( );
while ( it.hasNext( ) )
{
Object key = it.next( );
IBinding binding = (IBinding) map.get( key );
String groupName = null;
if ( binding.getExpression( ) != null )
groupName = binding.getExpression( ).getGroupName( );
if ( groupName == null )
{
if ( binding.getAggregatOns( ).size( ) == 0 )
continue;
groupName = binding.getAggregatOns( ).get( 0 ).toString( );
}
if ( ( !groupName.equals( IBaseExpression.GROUP_OVERALL ) )
&& !groupNameSet.contains( groupName ) )
{
throw new DataException( ResourceConstants.GROUP_NOT_EXIST,
new Object[]{
groupName, key
} );
}
}
}
mappingParentColumnBinding( );
for ( int i = 0; i <= groups.size( ); i++ )
{
prepareGroup( baseQueryDefn,
i,
dataEngineContext.getScriptContext( ) );
}
}
/**
* @throws DataException
*
*/
private void mappingParentColumnBinding( ) throws DataException
{
IBaseQueryDefinition queryDef = baseQueryDefn;
while( queryDef instanceof ISubqueryDefinition )
{
queryDef = queryDef.getParentQuery();
Map parentBindings = queryDef.getBindings( );
addParentBindings(parentBindings);
}
}
/**
*
* @param parentBindings
* @throws DataException
*/
private void addParentBindings( Map parentBindings ) throws DataException {
Iterator it = parentBindings.keySet( ).iterator( );
while ( it.hasNext( ) )
{
Object o = it.next( );
IBaseExpression expr = ((IBinding)parentBindings.get( o )).getExpression( );
if ( expr instanceof IScriptExpression )
{
if (!ExpressionUtil.hasAggregation( ( (IScriptExpression) expr ).getText( ) ))
{
if ( baseQueryDefn.getBindings( )
.get( o ) == null )
{
IBinding binding = new Binding( o.toString( ) );
binding.setDataType( expr.getDataType( ) );
binding.setExpression( copyScriptExpr( expr ) );
baseQueryDefn.addBinding( binding );
}
}
}
}
}
/**
* Colon a script expression, however do not populate the "AggregateOn" field. All the column binding that inherit
* from parent query by sub query should have no "AggregateOn" field, for they could not be aggregations. However,
* if an aggregateOn field is set to an expression without aggregation, we should also make it inheritable by sub query
* for the expression actually involves no aggregations.
*
* @param expr
* @return
*/
private ScriptExpression copyScriptExpr( IBaseExpression expr )
{
ScriptExpression se = new ScriptExpression( ( (IScriptExpression) expr ).getText( ),
( (IScriptExpression) expr ).getDataType( ) );
return se;
}
/**
* @param trans
* @param groupLevel
* @param cx
* @throws DataException
*/
private void prepareGroup( IBaseQueryDefinition baseQuery, int groupLevel,
ScriptContext cx ) throws DataException
{
IBaseTransform trans = baseQuery;
String groupName = IBaseExpression.GROUP_OVERALL;
// Group 0
if ( groupLevel != 0 )
{
IGroupDefinition igd = (IGroupDefinition) ( (IBaseQueryDefinition) trans ).getGroups( )
.get( groupLevel - 1 );
trans = igd;
groupName = igd.getName();
}
Collection exprCol = new ArrayList( );
Map resultSetExpressions = new HashMap();
//The latest column binding (AggregateOn introduced)
Map map = baseQuery.getBindings( );
if (map != null)
{
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
IBinding icbe = ((IBinding)map.get(key));
if ( icbe.getExpression( ) != null && icbe.getExpression( )
.getGroupName( )
.equals( groupName ) && groupLevel!= 0 )
{
exprCol.add( icbe.getExpression( ) );
resultSetExpressions.put(key, icbe);
}else if ( groupLevel == 0 && icbe.getAggregatOns( ).size( ) == 0 )
{
exprCol.add( icbe.getExpression( ) );
resultSetExpressions.put(key, icbe);
}else if ( groupLevel!= 0 && icbe.getAggregatOns( ).contains( groupName ))
{
exprCol.add( icbe.getExpression( ) );
resultSetExpressions.put(key, icbe);
}
}
}
prepareExpressions(exprCol, groupLevel, false, true, cx);
String key = null;
if( trans instanceof IGroupDefinition )
{
IGroupDefinition gd = (IGroupDefinition)trans;
key = gd.getKeyColumn( ) != null ? gd.getKeyColumn( ):gd.getKeyExpression( );
}
this.exprManager.addBindingExpr( key, resultSetExpressions, groupLevel );
// Prepare subqueries appearing in this group
Collection subQueries = trans.getSubqueries( );
Iterator subIt = subQueries.iterator( );
while ( subIt.hasNext( ) )
{
ISubqueryDefinition subquery = (ISubqueryDefinition) subIt.next( );
PreparedSubquery pq = new PreparedSubquery( this.session, this.dataEngineContext,
subquery,
queryService,
groupLevel );
subQueryMap.put( subquery.getName(), pq);
subQueryDefnMap.put( subquery.getName( ), new Object[]{
subquery, new Integer( groupLevel )
} );
}
}
/**
* Prepares all expressions in the given collection
*
* @param expressions
* @param groupLevel
* @param afterGroup
* @param cx
* @throws DataException
*/
private void prepareExpressions( Collection expressions, int groupLevel,
boolean afterGroup, boolean isDetailedRow, ScriptContext cx ) throws DataException
{
if ( expressions == null )
return;
AggregateRegistry reg = this.aggrTable.getAggrRegistry( groupLevel,
-1,
isDetailedRow,
cx );
Iterator it = expressions.iterator();
while ( it.hasNext() )
{
prepareExpression((IBaseExpression) it.next(), groupLevel, cx, reg);
}
}
/**
* Prepares one expression
*
* @param expr
* @param groupLevel
* @param cx
* @param reg
*/
private void prepareExpression( IBaseExpression expr, int groupLevel,
ScriptContext cx, AggregateRegistry reg )
{
ExpressionCompiler compiler = this.expressionCompiler;
if ( expr instanceof IScriptExpression )
{
String exprText = ((IScriptExpression) expr).getText();
CompiledExpression handle = compiler.compile( exprText, reg, cx.getContext( ));
expr.setHandle( handle );
}
else if ( expr instanceof IConditionalExpression )
{
// 3 sub expressions of the conditional expression should be prepared
// individually
IConditionalExpression ce = (IConditionalExpression) expr;
ce = transformConditionalExpression( ce );
prepareExpression( ce.getExpression(), groupLevel, cx, reg );
if ( ce.getOperand1() != null )
prepareExpression( ce.getOperand1(), groupLevel, cx, reg );
if ( ce.getOperand2() != null )
prepareExpression( ce.getOperand2(), groupLevel, cx, reg );
// No separate preparation is required for the conditional expression
// Set itself as the compiled handle
expr.setHandle( ce );
}
else if ( expr instanceof IExpressionCollection )
{
IExpressionCollection ce = (IExpressionCollection) expr;
Object[] exprs = ce.getExpressions( ).toArray( );
for ( int i = 0; i < exprs.length; i++ )
{
prepareExpression( (IBaseExpression)exprs[i],
groupLevel,
cx,
reg );
}
}
}
/**
* When a TopN/TopPercent/BottomN/BottomPercent ConditionalExpression is
* set, transform it to
* Total.TopN/Total.TopPercent/Total.BottomN/Total.BottomPercent
* aggregations with "isTrue" operator.
*
* @param ce
* @return
*/
private IConditionalExpression transformConditionalExpression(
IConditionalExpression ce )
{
String prefix = null;
switch ( ce.getOperator( ) )
{
case IConditionalExpression.OP_TOP_N :
prefix = "Total.isTopN";
break;
case IConditionalExpression.OP_TOP_PERCENT :
prefix = "Total.isTopNPercent";
break;
case IConditionalExpression.OP_BOTTOM_N :
prefix = "Total.isBottomN";
break;
case IConditionalExpression.OP_BOTTOM_PERCENT :
prefix = "Total.isBottomNPercent";
break;
}
if( prefix != null )
{
ce = new ConditionalExpression( prefix +
"(" + ce.getExpression( ).getText( ) + "," +
( (IScriptExpression) ce.getOperand1( ) ).getText( ) + ")",
IConditionalExpression.OP_TRUE );
}
return ce;
}
/**
* Return the QueryResults. But the execution of query would be deferred
*
* @param outerResults
* If query is nested within another query, this is the outer
* query's query result handle.
* @param scope
* The ElementState object for the report item using the query;
* this acts as the JS scope for evaluating script expressions.
* @param executor
* @parem dataSourceQuery
*/
QueryResults doPrepare( IBaseQueryResults outerResults,
Scriptable scope, QueryExecutor executor,
PreparedDataSourceQuery dataSourceQuery ) throws DataException
{
if ( this.baseQueryDefn == null )
{
// we are closed
DataException e = new DataException(ResourceConstants.PREPARED_QUERY_CLOSED);
logger.logp( Level.WARNING,
PreparedQuery.class.getName( ),
"doPrepare",
"PreparedQuery instance is closed.",
e );
throw e;
}
// pass the prepared query's pass thru context to its executor
executor.setAppContext( this.appContext );
//here prepare the execution. After the preparation the result metadata is available by
//calling getResultClass, and the query is ready for execution.
logger.finer( "Start to prepare the execution." );
executor.prepareExecution( outerResults, scope );
logger.finer( "Finish preparing the execution." );
QueryResults result = new QueryResults( new ServiceForQueryResults( this.session,
executor.getQueryScope( ),
executor.getNestedLevel( ) + 1,
dataSourceQuery,
queryService,
executor,
this.baseQueryDefn,
this.exprManager ) );
if( this.baseQueryDefn.cacheQueryResults() )
{
result.setID( this.session.getQueryResultIDUtil().nextID( ) );
}
return result;
}
/**
* @param subQueryName
* @return
*/
ISubqueryDefinition getSubQueryDefn( String subQueryName )
{
return (ISubqueryDefinition) ( (Object[]) subQueryDefnMap.get( subQueryName ) )[0];
}
/**
* @param subQueryName
* @return
*/
int getSubQueryLevel( String subQueryName )
{
return ( (Integer) ( (Object[]) subQueryDefnMap.get( subQueryName ) )[1] ).intValue( );
}
/**
* Executes a subquery
*
* @param iterator
* @param subQueryName
* @param subScope
* @return
* @throws DataException
*/
QueryResults execSubquery( IResultIterator iterator, IQueryExecutor executor, String subQueryName,
Scriptable subScope ) throws DataException
{
assert subQueryName != null;
PreparedSubquery subquery = (PreparedSubquery) subQueryMap.get( subQueryName );
if ( subquery == null )
{
DataException e = new DataException( ResourceConstants.SUBQUERY_NOT_FOUND,
subQueryName );
logger.logp( Level.FINE,
PreparedQuery.class.getName( ),
"execSubquery",
"Subquery name not found",
e );
throw e;
}
return subquery.execute( iterator, executor, subScope );
}
/**
* Closes the prepared query. This instance can no longer be executed after
* it is closed
*
* TODO: expose this method in the IPreparedQuery interface
*/
void close( )
{
this.baseQueryDefn = null;
this.aggrTable = null;
this.subQueryMap = null;
logger.logp( Level.FINER,
PreparedQuery.class.getName( ),
"close",
"Prepared query closed" );
// TODO: close all open QueryResults obtained from this PreparedQuery
}
/**
* @return sharedScope
*/
Scriptable getSharedScope( )
{
return this.session.getSharedScope( );
}
/**
* @return baseQueryDefinition
*/
IBaseQueryDefinition getBaseQueryDefn( )
{
return baseQueryDefn;
}
/**
* @return aggregateTable
*/
AggregateTable getAggrTable( )
{
return aggrTable;
}
} | data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/PreparedQuery.java | /*
*************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*
*************************************************************************
*/
package org.eclipse.birt.data.engine.impl;
import java.util.ArrayList;
import java.util.Collection;
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 java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.core.script.ScriptContext;
import org.eclipse.birt.data.engine.api.DataEngineContext;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IBaseQueryDefinition;
import org.eclipse.birt.data.engine.api.IBaseQueryResults;
import org.eclipse.birt.data.engine.api.IBaseTransform;
import org.eclipse.birt.data.engine.api.IBinding;
import org.eclipse.birt.data.engine.api.IConditionalExpression;
import org.eclipse.birt.data.engine.api.IExpressionCollection;
import org.eclipse.birt.data.engine.api.IGroupDefinition;
import org.eclipse.birt.data.engine.api.IScriptExpression;
import org.eclipse.birt.data.engine.api.ISubqueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.Binding;
import org.eclipse.birt.data.engine.api.querydefn.ConditionalExpression;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import org.eclipse.birt.data.engine.api.querydefn.SubqueryDefinition;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.expression.CompiledExpression;
import org.eclipse.birt.data.engine.expression.ExpressionCompiler;
import org.eclipse.birt.data.engine.i18n.ResourceConstants;
import org.eclipse.birt.data.engine.impl.aggregation.AggregateRegistry;
import org.eclipse.birt.data.engine.impl.aggregation.AggregateTable;
import org.eclipse.birt.data.engine.odi.IResultIterator;
import org.mozilla.javascript.Scriptable;
/**
* Two main functions for PreparedDataSourceQuery or PreparedSubQuery:
* 1: prepare group, subquery and expressions
* 2: query preparation and sub query execution
*/
final class PreparedQuery
{
private IBaseQueryDefinition baseQueryDefn;
private DataEngineContext dataEngineContext;
private DataEngineSession session;
// private Scriptable sharedScope;
private ExpressionCompiler expressionCompiler;
private IPreparedQueryService queryService;
private AggregateTable aggrTable;
private Map appContext;
// Map of Subquery name (String) to PreparedSubquery
private HashMap subQueryMap;
private HashMap subQueryDefnMap;
private static Logger logger = Logger.getLogger( DataEngineImpl.class.getName( ) );
private ExprManager exprManager;
/**
* @param deContext
* @param scope
* @param queryDefn
* @param queryService
* @param appContext
* @throws DataException
*/
PreparedQuery( DataEngineSession session, DataEngineContext deContext,
IBaseQueryDefinition queryDefn, IPreparedQueryService queryService,
Map appContext ) throws DataException
{
logger.logp( Level.FINE,
PreparedQuery.class.getName( ),
"PreparedQuery",
"PreparedQuery starts up." );
assert queryDefn != null;
this.expressionCompiler = new ExpressionCompiler( );
this.expressionCompiler.setDataSetMode( false );
this.dataEngineContext = deContext;
this.session = session;
if ( queryDefn instanceof SubqueryDefinition )
{
this.baseQueryDefn = SubqueryDefinitionCopyUtil.createSubqueryDefinition( ( (SubqueryDefinition) queryDefn ).getName( ),
(ISubqueryDefinition) queryDefn );
}
else
{
this.baseQueryDefn = queryDefn;
}
this.queryService = queryService;
this.appContext = appContext;
this.exprManager = new ExprManager( baseQueryDefn, session.getEngineContext( ).getScriptContext( ).getContext( ) );
this.subQueryMap = new HashMap( );
this.subQueryDefnMap = new HashMap( );
this.aggrTable = new AggregateTable( this.session.getTempDir( ), this.session.getSharedScope( ),
baseQueryDefn.getGroups( ) );
logger.fine( "Start to prepare a PreparedQuery." );
prepare( );
logger.fine( "Finished preparing the PreparedQuery." );
}
/**
* @throws DataException
*/
private void prepare( ) throws DataException
{
// TODO - validation of static queryDefn
// Prepare all groups; note that the report query iteself
// is treated as a group (with group level 0 ), If there are group
// definitions that of invalid or duplicate group name, then throw
// exceptions.
if ( this.baseQueryDefn.getBindings( ) != null
&& this.baseQueryDefn.getBindings( ).size( ) > 0 )
{
this.expressionCompiler.setDataSetMode( false );
}
List groups = baseQueryDefn.getGroups( );
Set groupNameSet = new HashSet( );
IGroupDefinition group;
for ( int i = 0; i < groups.size( ); i++ )
{
group = (IGroupDefinition) groups.get( i );
if ( group.getName( ) == null
|| group.getName( ).trim( ).length( ) == 0 )
continue;
for ( int j = 0; j < groups.size( ); j++ )
{
if ( group.getName( )
.equals( ( (IGroupDefinition) groups.get( j ) ).getName( ) == null
? ""
: ( (IGroupDefinition) groups.get( j ) ).getName( ) )
&& j != i )
throw new DataException( ResourceConstants.DUPLICATE_GROUP_NAME );
}
groupNameSet.add( group.getName( ) );
}
// The latest column binding (AggregateOn introduced)
Map map = baseQueryDefn.getBindings( );
if ( map != null )
{
Iterator it = map.keySet( ).iterator( );
while ( it.hasNext( ) )
{
Object key = it.next( );
IBinding binding = (IBinding) map.get( key );
String groupName = null;
if ( binding.getExpression( ) != null )
groupName = binding.getExpression( ).getGroupName( );
if ( groupName == null )
{
if ( binding.getAggregatOns( ).size( ) == 0 )
continue;
groupName = binding.getAggregatOns( ).get( 0 ).toString( );
}
if ( ( !groupName.equals( IBaseExpression.GROUP_OVERALL ) )
&& !groupNameSet.contains( groupName ) )
{
throw new DataException( ResourceConstants.GROUP_NOT_EXIST,
new Object[]{
groupName, key
} );
}
}
}
mappingParentColumnBinding( );
for ( int i = 0; i <= groups.size( ); i++ )
{
prepareGroup( baseQueryDefn,
i,
dataEngineContext.getScriptContext( ) );
}
}
/**
* @throws DataException
*
*/
private void mappingParentColumnBinding( ) throws DataException
{
IBaseQueryDefinition queryDef = baseQueryDefn;
while( queryDef instanceof ISubqueryDefinition )
{
queryDef = queryDef.getParentQuery();
Map parentBindings = queryDef.getBindings( );
addParentBindings(parentBindings);
}
}
/**
*
* @param parentBindings
* @throws DataException
*/
private void addParentBindings( Map parentBindings ) throws DataException {
Iterator it = parentBindings.keySet( ).iterator( );
while ( it.hasNext( ) )
{
Object o = it.next( );
IBaseExpression expr = ((IBinding)parentBindings.get( o )).getExpression( );
if ( expr instanceof IScriptExpression )
{
if (!ExpressionUtil.hasAggregation( ( (IScriptExpression) expr ).getText( ) ))
{
if ( baseQueryDefn.getBindings( )
.get( o ) == null )
{
IBinding binding = new Binding( o.toString( ) );
binding.setDataType( expr.getDataType( ) );
binding.setExpression( copyScriptExpr( expr ) );
baseQueryDefn.addBinding( binding );
}
}
}
}
}
/**
* Colon a script expression, however do not populate the "AggregateOn" field. All the column binding that inherit
* from parent query by sub query should have no "AggregateOn" field, for they could not be aggregations. However,
* if an aggregateOn field is set to an expression without aggregation, we should also make it inheritable by sub query
* for the expression actually involves no aggregations.
*
* @param expr
* @return
*/
private ScriptExpression copyScriptExpr( IBaseExpression expr )
{
ScriptExpression se = new ScriptExpression( ( (IScriptExpression) expr ).getText( ),
( (IScriptExpression) expr ).getDataType( ) );
return se;
}
/**
* @param trans
* @param groupLevel
* @param cx
* @throws DataException
*/
private void prepareGroup( IBaseQueryDefinition baseQuery, int groupLevel,
ScriptContext cx ) throws DataException
{
IBaseTransform trans = baseQuery;
String groupName = IBaseExpression.GROUP_OVERALL;
// Group 0
if ( groupLevel != 0 )
{
IGroupDefinition igd = (IGroupDefinition) ( (IBaseQueryDefinition) trans ).getGroups( )
.get( groupLevel - 1 );
trans = igd;
groupName = igd.getName();
}
Collection exprCol = new ArrayList( );
Map resultSetExpressions = new HashMap();
//The latest column binding (AggregateOn introduced)
Map map = baseQuery.getBindings( );
if (map != null)
{
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
IBinding icbe = ((IBinding)map.get(key));
if ( icbe.getExpression( ) != null && icbe.getExpression( )
.getGroupName( )
.equals( groupName ) && groupLevel!= 0 )
{
exprCol.add( icbe.getExpression( ) );
resultSetExpressions.put(key, icbe);
}else if ( groupLevel == 0 && icbe.getAggregatOns( ).size( ) == 0 )
{
exprCol.add( icbe.getExpression( ) );
resultSetExpressions.put(key, icbe);
}else if ( groupLevel!= 0 && icbe.getAggregatOns( ).contains( groupName ))
{
exprCol.add( icbe.getExpression( ) );
resultSetExpressions.put(key, icbe);
}
}
}
prepareExpressions(exprCol, groupLevel, false, true, cx);
String key = null;
if( trans instanceof IGroupDefinition )
{
IGroupDefinition gd = (IGroupDefinition)trans;
key = gd.getKeyColumn( ) != null ? gd.getKeyColumn( ):gd.getKeyExpression( );
}
this.exprManager.addBindingExpr( key, resultSetExpressions, groupLevel );
// Prepare subqueries appearing in this group
Collection subQueries = trans.getSubqueries( );
Iterator subIt = subQueries.iterator( );
while ( subIt.hasNext( ) )
{
ISubqueryDefinition subquery = (ISubqueryDefinition) subIt.next( );
PreparedSubquery pq = new PreparedSubquery( this.session, this.dataEngineContext,
subquery,
queryService,
groupLevel );
subQueryMap.put( subquery.getName(), pq);
subQueryDefnMap.put( subquery.getName( ), new Object[]{
subquery, new Integer( groupLevel )
} );
}
}
/**
* Prepares all expressions in the given collection
*
* @param expressions
* @param groupLevel
* @param afterGroup
* @param cx
* @throws DataException
*/
private void prepareExpressions( Collection expressions, int groupLevel,
boolean afterGroup, boolean isDetailedRow, ScriptContext cx ) throws DataException
{
if ( expressions == null )
return;
AggregateRegistry reg = this.aggrTable.getAggrRegistry( groupLevel,
-1,
isDetailedRow,
cx );
Iterator it = expressions.iterator();
while ( it.hasNext() )
{
prepareExpression((IBaseExpression) it.next(), groupLevel, cx, reg);
}
}
/**
* Prepares one expression
*
* @param expr
* @param groupLevel
* @param cx
* @param reg
*/
private void prepareExpression( IBaseExpression expr, int groupLevel,
ScriptContext cx, AggregateRegistry reg )
{
ExpressionCompiler compiler = this.expressionCompiler;
if ( expr instanceof IScriptExpression )
{
String exprText = ((IScriptExpression) expr).getText();
CompiledExpression handle = compiler.compile( exprText, reg, cx.getContext( ));
expr.setHandle( handle );
}
else if ( expr instanceof IConditionalExpression )
{
// 3 sub expressions of the conditional expression should be prepared
// individually
IConditionalExpression ce = (IConditionalExpression) expr;
ce = transformConditionalExpression( ce );
prepareExpression( ce.getExpression(), groupLevel, cx, reg );
if ( ce.getOperand1() != null )
prepareExpression( ce.getOperand1(), groupLevel, cx, reg );
if ( ce.getOperand2() != null )
prepareExpression( ce.getOperand2(), groupLevel, cx, reg );
// No separate preparation is required for the conditional expression
// Set itself as the compiled handle
expr.setHandle( ce );
}
else if ( expr instanceof IExpressionCollection )
{
IExpressionCollection ce = (IExpressionCollection) expr;
Object[] exprs = ce.getExpressions( ).toArray( );
for ( int i = 0; i < exprs.length; i++ )
{
prepareExpression( (IBaseExpression)exprs[i],
groupLevel,
cx,
reg );
}
}
else
{
// Should never get here
assert false;
}
}
/**
* When a TopN/TopPercent/BottomN/BottomPercent ConditionalExpression is
* set, transform it to
* Total.TopN/Total.TopPercent/Total.BottomN/Total.BottomPercent
* aggregations with "isTrue" operator.
*
* @param ce
* @return
*/
private IConditionalExpression transformConditionalExpression(
IConditionalExpression ce )
{
String prefix = null;
switch ( ce.getOperator( ) )
{
case IConditionalExpression.OP_TOP_N :
prefix = "Total.isTopN";
break;
case IConditionalExpression.OP_TOP_PERCENT :
prefix = "Total.isTopNPercent";
break;
case IConditionalExpression.OP_BOTTOM_N :
prefix = "Total.isBottomN";
break;
case IConditionalExpression.OP_BOTTOM_PERCENT :
prefix = "Total.isBottomNPercent";
break;
}
if( prefix != null )
{
ce = new ConditionalExpression( prefix +
"(" + ce.getExpression( ).getText( ) + "," +
( (IScriptExpression) ce.getOperand1( ) ).getText( ) + ")",
IConditionalExpression.OP_TRUE );
}
return ce;
}
/**
* Return the QueryResults. But the execution of query would be deferred
*
* @param outerResults
* If query is nested within another query, this is the outer
* query's query result handle.
* @param scope
* The ElementState object for the report item using the query;
* this acts as the JS scope for evaluating script expressions.
* @param executor
* @parem dataSourceQuery
*/
QueryResults doPrepare( IBaseQueryResults outerResults,
Scriptable scope, QueryExecutor executor,
PreparedDataSourceQuery dataSourceQuery ) throws DataException
{
if ( this.baseQueryDefn == null )
{
// we are closed
DataException e = new DataException(ResourceConstants.PREPARED_QUERY_CLOSED);
logger.logp( Level.WARNING,
PreparedQuery.class.getName( ),
"doPrepare",
"PreparedQuery instance is closed.",
e );
throw e;
}
// pass the prepared query's pass thru context to its executor
executor.setAppContext( this.appContext );
//here prepare the execution. After the preparation the result metadata is available by
//calling getResultClass, and the query is ready for execution.
logger.finer( "Start to prepare the execution." );
executor.prepareExecution( outerResults, scope );
logger.finer( "Finish preparing the execution." );
QueryResults result = new QueryResults( new ServiceForQueryResults( this.session,
executor.getQueryScope( ),
executor.getNestedLevel( ) + 1,
dataSourceQuery,
queryService,
executor,
this.baseQueryDefn,
this.exprManager ) );
if( this.baseQueryDefn.cacheQueryResults() )
{
result.setID( this.session.getQueryResultIDUtil().nextID( ) );
}
return result;
}
/**
* @param subQueryName
* @return
*/
ISubqueryDefinition getSubQueryDefn( String subQueryName )
{
return (ISubqueryDefinition) ( (Object[]) subQueryDefnMap.get( subQueryName ) )[0];
}
/**
* @param subQueryName
* @return
*/
int getSubQueryLevel( String subQueryName )
{
return ( (Integer) ( (Object[]) subQueryDefnMap.get( subQueryName ) )[1] ).intValue( );
}
/**
* Executes a subquery
*
* @param iterator
* @param subQueryName
* @param subScope
* @return
* @throws DataException
*/
QueryResults execSubquery( IResultIterator iterator, IQueryExecutor executor, String subQueryName,
Scriptable subScope ) throws DataException
{
assert subQueryName != null;
PreparedSubquery subquery = (PreparedSubquery) subQueryMap.get( subQueryName );
if ( subquery == null )
{
DataException e = new DataException( ResourceConstants.SUBQUERY_NOT_FOUND,
subQueryName );
logger.logp( Level.FINE,
PreparedQuery.class.getName( ),
"execSubquery",
"Subquery name not found",
e );
throw e;
}
return subquery.execute( iterator, executor, subScope );
}
/**
* Closes the prepared query. This instance can no longer be executed after
* it is closed
*
* TODO: expose this method in the IPreparedQuery interface
*/
void close( )
{
this.baseQueryDefn = null;
this.aggrTable = null;
this.subQueryMap = null;
logger.logp( Level.FINER,
PreparedQuery.class.getName( ),
"close",
"Prepared query closed" );
// TODO: close all open QueryResults obtained from this PreparedQuery
}
/**
* @return sharedScope
*/
Scriptable getSharedScope( )
{
return this.session.getSharedScope( );
}
/**
* @return baseQueryDefinition
*/
IBaseQueryDefinition getBaseQueryDefn( )
{
return baseQueryDefn;
}
/**
* @return aggregateTable
*/
AggregateTable getAggrTable( )
{
return aggrTable;
}
} | Fix the bugzilla bug 258636 : AssertionError when displaying simple Table-Report containing Aggregation Item deployed on BEA Weblogic 10.0
| data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/PreparedQuery.java | Fix the bugzilla bug 258636 : AssertionError when displaying simple Table-Report containing Aggregation Item deployed on BEA Weblogic 10.0 |
|
Java | epl-1.0 | 96c3a9161e3cff40bda22f3d7b2a07c8dc1f43b4 | 0 | tmdgitb/pengenalan_pola_shih,tmdgitb/pengenalan_pola_sigit_hendy_ilham,tmdgitb/pengenalan_pola_shih,tmdgitb/pengenalan_pola_sigit_hendy_ilham | package id.ac.itb.sigit.pengenalanpola;
import org.opencv.core.Mat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sigit on 03/10/2015.
*/
public class ChainCodeWhiteConverter {
private static final Logger log = LoggerFactory.getLogger(HistogramApp.class);
private boolean flag[][];
private int toleransiWhite = 230, toleransi = 150;
private boolean searchObject = true, searchSubObject = false;
private int minHor = 0, maxHor = 0, minVer = 0, maxVer = 0;
private Mat imgMat;
public List<ChainCode> chainCodes;
/**
* @param data MUST BE GRAYSCALE
*/
public ChainCodeWhiteConverter(Mat data) {
this(data, "");
}
/**
* @param data MUST BE GRAYSCALE
* @param msg
*/
public ChainCodeWhiteConverter(Mat data, String msg) {
imgMat = data;
chainCodes = new ArrayList<>();
}
public List<ChainCode> getChainCode() {
byte[] imagByte = new byte[1];
flag = new boolean[imgMat.rows()][imgMat.cols()];
int objectIdx = 0;
for (int y = 0; y < imgMat.rows(); y++) {
Mat scanline = imgMat.row(y);
for (int x = 0; x < imgMat.cols(); x++) {
scanline.get(0, x, imagByte);
int grayScale = grayScale(imagByte);
if (grayScale > toleransiWhite && searchObject && !flag[y][x]) {
minVer = y;
maxVer = y;
minHor = x;
maxHor = x;
String chaincode = prosesChaincode(y, x, 3, imgMat, 1);
ChainCode chainCode = new ChainCode();
String kodeBelok = getKodeBelok(chaincode);
chainCode.setChainCode(chaincode);
chainCode.setKodeBelok(kodeBelok);
chainCode.setX(x);
chainCode.setY(y);
if (chaincode.length() > 20) {
log.info("Chaincode object #{} at ({}, {}): {}", objectIdx, x, y, chaincode);
objectIdx++;
List<ChainCode> subChainCodes = subObject(imgMat);
if (subChainCodes.size() > 0) {
chainCode.getSubChainCode().addAll(subChainCodes);
}
chainCodes.add(chainCode);
}
searchObject = false;
}
if (grayScale > toleransiWhite && flag[y][x]) {
scanline.get(0, x + 1, imagByte);
int grayScale1 = grayScale(imagByte);
if (grayScale1 < toleransiWhite) {
searchObject = true;
} else {
searchObject = false;
}
}
}
}
return chainCodes;
}
private List<ChainCode> subObject(Mat imgMat) {
List<ChainCode> subChainCodes = new ArrayList<>();
byte[] imagByte = new byte[1];
for (int y = minVer; y <= maxVer; y++) {
Mat scanline = imgMat.row(y);
for (int x = minHor; x <= maxHor; x++) {
scanline.get(0, x, imagByte);
int grayScale = grayScale(imagByte);
scanline.get(0, x + 1, imagByte);
int nextGrayScale = grayScale(imagByte);
if (grayScale > toleransiWhite && flag[y][x]) {
if (nextGrayScale > toleransiWhite) {
searchSubObject = true;
} else {
searchSubObject = false;
}
}
if (grayScale < toleransi && searchSubObject && !flag[y][x]) {
scanline.get(0, x + 1, imagByte);
String chaincode2 = prosesChaincode(y, x, 3, imgMat, 0);
ChainCode subChainCode = new ChainCode();
subChainCode.setChainCode(chaincode2);
subChainCodes.add(subChainCode);
//charDef.getSubChainCode().add(chaincode2);
log.info("Chaincode subobject : {}", chaincode2);
searchSubObject = false;
}
if (grayScale < toleransi && flag[y][x]) {
if (nextGrayScale > toleransi) {
searchSubObject = true;
} else {
searchSubObject = false;
}
}
}
}
return subChainCodes;
}
private String prosesChaincode(int row, int col, int arah, Mat imgMat, int mode) {
if (flag[row][col]) {
return "";
}
flag[row][col] = true;
//kondisi perjalanan arah 1
if (arah == 1) {
//
//cek arah 7 (samping kiri)
//
String arah7 = objectarah7(row, col, imgMat, mode);
if (arah7 != "") {
return arah7;
}
//
//cek arah 8
//
String arah8 = objectarah8(row, col, imgMat, mode);
if (arah8 != "") {
return arah8;
}
//
//cek arah 1 (depan)
//
String arah1 = objectarah1(row, col, imgMat, mode);
if (arah1 != "") {
return arah1;
}
//
//cek arah 2
//
String arah2 = objectarah2(row, col, imgMat, mode);
if (arah2 != "") {
return arah2;
}
//
//cek arah 3
//
String arah3 = objectarah3(row, col, imgMat, mode);
if (arah3 != "") {
return arah3;
}
}
//kondisi perjalanan arah 2
else if (arah == 2) {
//
//cek arah 8 (samping kiri)
//
String arah8 = objectarah8(row, col, imgMat, mode);
if (arah8 != "") {
return arah8;
}
//
//cek arah 1 (depan)
//
String arah1 = objectarah1(row, col, imgMat, mode);
if (arah1 != "") {
return arah1;
}
//
//cek arah 2
//
String arah2 = objectarah2(row, col, imgMat, mode);
if (arah2 != "") {
return arah2;
}
//
//cek arah 3
//
String arah3 = objectarah3(row, col, imgMat, mode);
if (arah3 != "") {
return arah3;
}
//
//cek arah 4
//
String arah4 = objectarah4(row, col, imgMat, mode);
if (arah4 != "") {
return arah4;
}
} else if (arah == 3) {
//
//cek arah 1 (depan)
//
String arah1 = objectarah1(row, col, imgMat, mode);
if (arah1 != "") {
return arah1;
}
//
//cek arah 2
//
String arah2 = objectarah2(row, col, imgMat, mode);
if (arah2 != "") {
return arah2;
}
//
//cek arah 3
//
String arah3 = objectarah3(row, col, imgMat, mode);
if (arah3 != "") {
return arah3;
}
//
//cek arah 4
//
String arah4 = objectarah4(row, col, imgMat, mode);
if (arah4 != "") {
return arah4;
}
//
//cek arah 5
//
String arah5 = objectarah5(row, col, imgMat, mode);
if (arah5 != "") {
return arah5;
}
} else if (arah == 4) {
//
//cek arah 2
//
String arah2 = objectarah2(row, col, imgMat, mode);
if (arah2 != "") {
return arah2;
}
//
//cek arah 3
//
String arah3 = objectarah3(row, col, imgMat, mode);
if (arah3 != "") {
return arah3;
}
//
//cek arah 4
//
String arah4 = objectarah4(row, col, imgMat, mode);
if (arah4 != "") {
return arah4;
}
//
//cek arah 5
//
String arah5 = objectarah5(row, col, imgMat, mode);
if (arah5 != "") {
return arah5;
}
//
//cek arah 6
//
String arah6 = objectarah6(row, col, imgMat, mode);
if (arah6 != "") {
return arah6;
}
//
//cek arah 7
//
String arah7 = objectarah7(row, col, imgMat, mode);
if (arah7 != "") {
return arah7;
}
} else if (arah == 5) {
//
//cek arah 3
//
String arah3 = objectarah3(row, col, imgMat, mode);
if (arah3 != "") {
return arah3;
}
//
//cek arah 4
//
String arah4 = objectarah4(row, col, imgMat, mode);
if (arah4 != "") {
return arah4;
}
//
//cek arah 5
//
String arah5 = objectarah5(row, col, imgMat, mode);
if (arah5 != "") {
return arah5;
}
//
//cek arah 6
//
String arah6 = objectarah6(row, col, imgMat, mode);
if (arah6 != "") {
return arah6;
}
//
//cek arah 7
//
String arah7 = objectarah7(row, col, imgMat, mode);
if (arah7 != "") {
return arah7;
}
} else if (arah == 6) {
//
//cek arah 4
//
String arah4 = objectarah4(row, col, imgMat, mode);
if (arah4 != "") {
return arah4;
}
//
//cek arah 5
//
String arah5 = objectarah5(row, col, imgMat, mode);
if (arah5 != "") {
return arah5;
}
//
//cek arah 6
//
String arah6 = objectarah6(row, col, imgMat, mode);
if (arah6 != "") {
return arah6;
}
//
//cek arah 7
//
String arah7 = objectarah7(row, col, imgMat, mode);
if (arah7 != "") {
return arah7;
}
//
//cek arah 8
//
String arah8 = objectarah8(row, col, imgMat, mode);
if (arah8 != "") {
return arah8;
}
//
//cek arah 1 (depan)
//
String arah1 = objectarah1(row, col, imgMat, mode);
if (arah1 != "") {
return arah1;
}
} else if (arah == 7) {
//
//cek arah 5
//
String arah5 = objectarah5(row, col, imgMat, mode);
if (arah5 != "") {
return arah5;
}
//
//cek arah 6
//
String arah6 = objectarah6(row, col, imgMat, mode);
if (arah6 != "") {
return arah6;
}
//
//cek arah 7
//
String arah7 = objectarah7(row, col, imgMat, mode);
if (arah7 != "") {
return arah7;
}
//
//cek arah 8
//
String arah8 = objectarah8(row, col, imgMat, mode);
if (arah8 != "") {
return arah8;
}
//
//cek arah 1 (depan)
//
String arah1 = objectarah1(row, col, imgMat, mode);
if (arah1 != "") {
return arah1;
}
//
//cek arah 2
//
String arah2 = objectarah2(row, col, imgMat, mode);
if (arah2 != "") {
return arah2;
}
} else //if(arah==8)
{
//
//cek arah 6
//
String arah6 = objectarah6(row, col, imgMat, mode);
if (arah6 != "") {
return arah6;
}
//
//cek arah 7
//
String arah7 = objectarah7(row, col, imgMat, mode);
if (arah7 != "") {
return arah7;
}
//
//cek arah 8
//
String arah8 = objectarah8(row, col, imgMat, mode);
if (arah8 != "") {
return arah8;
}
//
//cek arah 1 (depan)
//
String arah1 = objectarah1(row, col, imgMat, mode);
if (arah1 != "") {
return arah1;
}
//
//cek arah 2
//
String arah2 = objectarah2(row, col, imgMat, mode);
if (arah2 != "") {
return arah2;
}
}
return "";
}
private int grayScale(byte[] imagByte) {
return Byte.toUnsignedInt(imagByte[0]);
}
private String objectarah1(int row, int col, Mat imgMat, int mode) {
int temprow, tempcol;
byte[] imagByte = new byte[1];
temprow = row - 1;
tempcol = col;
imgMat.get(temprow, tempcol, imagByte);
int gray1 = grayScale(imagByte);
if (mode == 1) {
if (gray1 > toleransiWhite) {
areaObject(row, col);
return "1" + prosesChaincode(temprow, tempcol, 1, imgMat, mode);
}
} else {
if (gray1 < toleransi) {
return "1" + prosesChaincode(temprow, tempcol, 1, imgMat, mode);
}
}
return "";
}
private String objectarah2(int row, int col, Mat imgMat, int mode) {
int temprow, tempcol;
byte[] imagByte = new byte[1];
temprow = row - 1;
tempcol = col + 1;
imgMat.get(temprow, tempcol, imagByte);
int gray2 = grayScale(imagByte);
if (mode == 1) {
if (gray2 > toleransiWhite) {
areaObject(row, col);
return "2" + prosesChaincode(temprow, tempcol, 2, imgMat, mode);
}
} else {
if (gray2 < toleransi) {
return "2" + prosesChaincode(temprow, tempcol, 2, imgMat, mode);
}
}
return "";
}
private String objectarah3(int row, int col, Mat imgMat, int mode) {
int temprow, tempcol;
byte[] imagByte = new byte[1];
temprow = row;
tempcol = col + 1;
imgMat.get(temprow, tempcol, imagByte);
int gray3 = grayScale(imagByte);
if (mode == 1) {
if (gray3 > toleransiWhite) {
areaObject(row, col);
return "3" + prosesChaincode(temprow, tempcol, 3, imgMat, mode);
}
} else {
if (gray3 < toleransi) {
return "3" + prosesChaincode(temprow, tempcol, 3, imgMat, mode);
}
}
return "";
}
private String objectarah4(int row, int col, Mat imgMat, int mode) {
int temprow, tempcol;
byte[] imagByte = new byte[1];
temprow = row + 1;
tempcol = col + 1;
imgMat.get(temprow, tempcol, imagByte);
int gray4 = grayScale(imagByte);
if (mode == 1) {
if (gray4 > toleransiWhite) {
areaObject(row, col);
return "4" + prosesChaincode(temprow, tempcol, 4, imgMat, mode);
}
} else {
if (gray4 < toleransi) {
return "4" + prosesChaincode(temprow, tempcol, 4, imgMat, mode);
}
}
return "";
}
private String objectarah5(int row, int col, Mat imgMat, int mode) {
int temprow, tempcol;
byte[] imagByte = new byte[1];
temprow = row + 1;
tempcol = col;
imgMat.get(temprow, tempcol, imagByte);
int gray5 = grayScale(imagByte);
if (mode == 1) {
if (gray5 > toleransiWhite) {
areaObject(row, col);
return "5" + prosesChaincode(temprow, tempcol, 5, imgMat, mode);
}
} else {
if (gray5 < toleransi) {
return "5" + prosesChaincode(temprow, tempcol, 5, imgMat, mode);
}
}
return "";
}
private String objectarah6(int row, int col, Mat imgMat, int mode) {
int temprow, tempcol;
byte[] imagByte = new byte[1];
temprow = row + 1;
tempcol = col - 1;
imgMat.get(temprow, tempcol, imagByte);
int gray6 = grayScale(imagByte);
if (mode == 1) {
if (gray6 > toleransiWhite) {
areaObject(row, col);
return "6" + prosesChaincode(temprow, tempcol, 6, imgMat, mode);
}
} else {
if (gray6 < toleransi) {
return "6" + prosesChaincode(temprow, tempcol, 6, imgMat, mode);
}
}
return "";
}
private String objectarah7(int row, int col, Mat imgMat, int mode) {
int temprow, tempcol;
byte[] imagByte = new byte[1];
temprow = row;
tempcol = col - 1;
imgMat.get(temprow, tempcol, imagByte);
int gray7 = grayScale(imagByte);
if (mode == 1) {
if (gray7 > toleransiWhite) {
areaObject(row, col);
return "7" + prosesChaincode(temprow, tempcol, 7, imgMat, mode);
}
} else {
if (gray7 < toleransi) {
return "7" + prosesChaincode(temprow, tempcol, 7, imgMat, mode);
}
}
return "";
}
private String objectarah8(int row, int col, Mat imgMat, int mode) {
int temprow, tempcol;
byte[] imagByte = new byte[1];
temprow = row - 1;
tempcol = col - 1;
imgMat.get(temprow, tempcol, imagByte);
int gray8 = grayScale(imagByte);
if (mode == 1) {
if (gray8 > toleransiWhite) {
areaObject(row, col);
return "8" + prosesChaincode(temprow, tempcol, 8, imgMat, mode);
}
} else {
if (gray8 < toleransi) {
return "8" + prosesChaincode(temprow, tempcol, 8, imgMat, mode);
}
}
return "";
}
private void areaObject(int row, int col) {
if (minHor > col) {
minHor = col;
} else if (maxHor < col) {
maxHor = col;
}
if (minVer > row) {
minVer = row;
} else if (maxVer < row) {
maxVer = row;
}
}
private String getKodeBelok(String chainCode) {
String kodeBelok = "";
String temp = String.valueOf(chainCode.charAt(0));
char[] tempChar = new char[2];
tempChar[0] = chainCode.charAt(0);
tempChar[1] = chainCode.charAt(0);
kodeBelok += chainCode.charAt(0);
boolean rep = false;
for (int i = 0; i < chainCode.length() - 1; i++) {
if (i == 105) {
char f = chainCode.charAt(i);
}
char ff = chainCode.charAt(i);
if (tempChar[0] != chainCode.charAt(i)) {
if (tempChar[1] != chainCode.charAt(i)) {
tempChar[0] = tempChar[1];
tempChar[1] = chainCode.charAt(i);
kodeBelok += chainCode.charAt(i);
} else {
tempChar[0] = tempChar[1];
tempChar[1] = chainCode.charAt(i);
}
} else {
if (tempChar[1] == chainCode.charAt(i + 1) && tempChar[0] != tempChar[1]) {
i++;
} else if (tempChar[1] == chainCode.charAt(i + 1)) {
} else {
tempChar[0] = tempChar[1];
tempChar[1] = chainCode.charAt(i + 1);
kodeBelok += chainCode.charAt(i + 1);
i++;
}
}
}
return kodeBelok;
}
}
| src/main/java/id/ac/itb/sigit/pengenalanpola/ChainCodeWhiteConverter.java | package id.ac.itb.sigit.pengenalanpola;
import org.opencv.core.Mat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sigit on 03/10/2015.
*/
public class ChainCodeWhiteConverter {
private static final Logger log = LoggerFactory.getLogger(HistogramApp.class);
private boolean flag[][];
private int toleransiWhite = 230, toleransi = 150;
private boolean searchObject = true, searchSubObject = false;
private int minHor = 0, maxHor = 0, minVer = 0, maxVer = 0;
private Mat imgMat;
public List<ChainCode> chainCodes;
/**
* @param data MUST BE GRAYSCALE
*/
public ChainCodeWhiteConverter(Mat data) {
this(data, "");
}
/**
* @param data MUST BE GRAYSCALE
* @param msg
*/
public ChainCodeWhiteConverter(Mat data, String msg) {
imgMat = data;
chainCodes = new ArrayList<>();
}
public List<ChainCode> getChainCode() {
byte[] imagByte = new byte[1];
flag = new boolean[imgMat.rows()][imgMat.cols()];
int objectIdx = 0;
for (int y = 0; y < imgMat.rows(); y++) {
Mat scanline = imgMat.row(y);
for (int x = 0; x < imgMat.cols(); x++) {
scanline.get(0, x, imagByte);
int grayScale = grayScale(imagByte);
if (grayScale > toleransiWhite && searchObject && !flag[y][x]) {
minVer = y;
maxVer = y;
minHor = x;
maxHor = x;
String chaincode = prosesChaincode(y, x, 3, imgMat, 1);
ChainCode chainCode = new ChainCode();
String kodeBelok = getKodeBelok(chaincode);
chainCode.setChainCode(chaincode);
chainCode.setKodeBelok(kodeBelok);
chainCode.setX(x);
chainCode.setY(y);
if (chaincode.length() > 20) {
log.info("Chaincode object #{} at ({}, {}): {}", objectIdx, x, y, chaincode);
objectIdx++;
List<ChainCode> subChainCodes = subObject(imgMat);
if (subChainCodes.size() > 0) {
chainCode.getSubChainCode().addAll(subChainCodes);
}
chainCodes.add(chainCode);
}
searchObject = false;
}
if (grayScale > toleransiWhite && flag[y][x]) {
scanline.get(0, x + 1, imagByte);
int grayScale1 = grayScale(imagByte);
if (grayScale1 < toleransiWhite) {
searchObject = true;
} else {
searchObject = false;
}
}
}
}
return chainCodes;
}
private List<ChainCode> subObject(Mat imgMat) {
List<ChainCode> subChainCodes = new ArrayList<>();
byte[] imagByte = new byte[1];
for (int y = minVer; y <= maxVer; y++) {
Mat scanline = imgMat.row(y);
for (int x = minHor; x <= maxHor; x++) {
scanline.get(0, x, imagByte);
int grayScale = grayScale(imagByte);
scanline.get(0, x + 1, imagByte);
int nextGrayScale = grayScale(imagByte);
if (grayScale > toleransiWhite && flag[y][x]) {
if (nextGrayScale > toleransiWhite) {
searchSubObject = true;
} else {
searchSubObject = false;
}
}
if (grayScale < toleransi && searchSubObject && !flag[y][x]) {
scanline.get(0, x + 1, imagByte);
String chaincode2 = prosesChaincode(y, x, 3, imgMat, 0);
ChainCode subChainCode = new ChainCode();
subChainCode.setChainCode(chaincode2);
subChainCodes.add(subChainCode);
//charDef.getSubChainCode().add(chaincode2);
log.info("Chaincode subobject : {}", chaincode2);
searchSubObject = false;
}
if (grayScale < toleransi && flag[y][x]) {
if (nextGrayScale > toleransi) {
searchSubObject = true;
} else {
searchSubObject = false;
}
}
}
}
return subChainCodes;
}
private String prosesChaincode(int row, int col, int arah, Mat imgMat, int mode) {
if (flag[row][col]) {
return "";
}
flag[row][col] = true;
//kondisi perjalanan arah 1
if (arah == 1) {
//
//cek arah 7 (samping kiri)
//
String arah7 = objectarah7(row, col, imgMat, mode);
if (arah7 != "") {
return arah7;
}
//
//cek arah 8
//
String arah8 = objectarah8(row, col, imgMat, mode);
if (arah8 != "") {
return arah8;
}
//
//cek arah 1 (depan)
//
String arah1 = objectarah1(row, col, imgMat, mode);
if (arah1 != "") {
return arah1;
}
//
//cek arah 2
//
String arah2 = objectarah2(row, col, imgMat, mode);
if (arah2 != "") {
return arah2;
}
//
//cek arah 3
//
String arah3 = objectarah3(row, col, imgMat, mode);
if (arah3 != "") {
return arah3;
}
}
//kondisi perjalanan arah 2
else if (arah == 2) {
//
//cek arah 8 (samping kiri)
//
String arah8 = objectarah8(row, col, imgMat, mode);
if (arah8 != "") {
return arah8;
}
//
//cek arah 1 (depan)
//
String arah1 = objectarah1(row, col, imgMat, mode);
if (arah1 != "") {
return arah1;
}
//
//cek arah 2
//
String arah2 = objectarah2(row, col, imgMat, mode);
if (arah2 != "") {
return arah2;
}
//
//cek arah 3
//
String arah3 = objectarah3(row, col, imgMat, mode);
if (arah3 != "") {
return arah3;
}
//
//cek arah 4
//
String arah4 = objectarah4(row, col, imgMat, mode);
if (arah4 != "") {
return arah4;
}
} else if (arah == 3) {
//
//cek arah 1 (depan)
//
String arah1 = objectarah1(row, col, imgMat, mode);
if (arah1 != "") {
return arah1;
}
//
//cek arah 2
//
String arah2 = objectarah2(row, col, imgMat, mode);
if (arah2 != "") {
return arah2;
}
//
//cek arah 3
//
String arah3 = objectarah3(row, col, imgMat, mode);
if (arah3 != "") {
return arah3;
}
//
//cek arah 4
//
String arah4 = objectarah4(row, col, imgMat, mode);
if (arah4 != "") {
return arah4;
}
//
//cek arah 5
//
String arah5 = objectarah5(row, col, imgMat, mode);
if (arah5 != "") {
return arah5;
}
} else if (arah == 4) {
//
//cek arah 2
//
String arah2 = objectarah2(row, col, imgMat, mode);
if (arah2 != "") {
return arah2;
}
//
//cek arah 3
//
String arah3 = objectarah3(row, col, imgMat, mode);
if (arah3 != "") {
return arah3;
}
//
//cek arah 4
//
String arah4 = objectarah4(row, col, imgMat, mode);
if (arah4 != "") {
return arah4;
}
//
//cek arah 5
//
String arah5 = objectarah5(row, col, imgMat, mode);
if (arah5 != "") {
return arah5;
}
//
//cek arah 6
//
String arah6 = objectarah6(row, col, imgMat, mode);
if (arah6 != "") {
return arah6;
}
//
//cek arah 7
//
String arah7 = objectarah7(row, col, imgMat, mode);
if (arah7 != "") {
return arah7;
}
} else if (arah == 5) {
//
//cek arah 3
//
String arah3 = objectarah3(row, col, imgMat, mode);
if (arah3 != "") {
return arah3;
}
//
//cek arah 4
//
String arah4 = objectarah4(row, col, imgMat, mode);
if (arah4 != "") {
return arah4;
}
//
//cek arah 5
//
String arah5 = objectarah5(row, col, imgMat, mode);
if (arah5 != "") {
return arah5;
}
//
//cek arah 6
//
String arah6 = objectarah6(row, col, imgMat, mode);
if (arah6 != "") {
return arah6;
}
//
//cek arah 7
//
String arah7 = objectarah7(row, col, imgMat, mode);
if (arah7 != "") {
return arah7;
}
} else if (arah == 6) {
//
//cek arah 4
//
String arah4 = objectarah4(row, col, imgMat, mode);
if (arah4 != "") {
return arah4;
}
//
//cek arah 5
//
String arah5 = objectarah5(row, col, imgMat, mode);
if (arah5 != "") {
return arah5;
}
//
//cek arah 6
//
String arah6 = objectarah6(row, col, imgMat, mode);
if (arah6 != "") {
return arah6;
}
//
//cek arah 7
//
String arah7 = objectarah7(row, col, imgMat, mode);
if (arah7 != "") {
return arah7;
}
//
//cek arah 8
//
String arah8 = objectarah8(row, col, imgMat, mode);
if (arah8 != "") {
return arah8;
}
//
//cek arah 1 (depan)
//
String arah1 = objectarah1(row, col, imgMat, mode);
if (arah1 != "") {
return arah1;
}
} else if (arah == 7) {
//
//cek arah 5
//
String arah5 = objectarah5(row, col, imgMat, mode);
if (arah5 != "") {
return arah5;
}
//
//cek arah 6
//
String arah6 = objectarah6(row, col, imgMat, mode);
if (arah6 != "") {
return arah6;
}
//
//cek arah 7
//
String arah7 = objectarah7(row, col, imgMat, mode);
if (arah7 != "") {
return arah7;
}
//
//cek arah 8
//
String arah8 = objectarah8(row, col, imgMat, mode);
if (arah8 != "") {
return arah8;
}
//
//cek arah 1 (depan)
//
String arah1 = objectarah1(row, col, imgMat, mode);
if (arah1 != "") {
return arah1;
}
//
//cek arah 2
//
String arah2 = objectarah2(row, col, imgMat, mode);
if (arah2 != "") {
return arah2;
}
} else //if(arah==8)
{
//
//cek arah 6
//
String arah6 = objectarah6(row, col, imgMat, mode);
if (arah6 != "") {
return arah6;
}
//
//cek arah 7
//
String arah7 = objectarah7(row, col, imgMat, mode);
if (arah7 != "") {
return arah7;
}
//
//cek arah 8
//
String arah8 = objectarah8(row, col, imgMat, mode);
if (arah8 != "") {
return arah8;
}
//
//cek arah 1 (depan)
//
String arah1 = objectarah1(row, col, imgMat, mode);
if (arah1 != "") {
return arah1;
}
//
//cek arah 2
//
String arah2 = objectarah2(row, col, imgMat, mode);
if (arah2 != "") {
return arah2;
}
}
return "";
}
private int grayScale(byte[] imagByte) {
return Byte.toUnsignedInt(imagByte[0]);
}
private String objectarah1(int row, int col, Mat imgMat, int mode) {
int temprow, tempcol;
byte[] imagByte = new byte[1];
temprow = row - 1;
tempcol = col;
imgMat.get(temprow, tempcol, imagByte);
int gray1 = grayScale(imagByte);
if (mode == 1) {
if (gray1 > toleransiWhite) {
areaObject(row, col);
return "1" + prosesChaincode(temprow, tempcol, 1, imgMat, mode);
}
} else {
if (gray1 < toleransi) {
return "1" + prosesChaincode(temprow, tempcol, 1, imgMat, mode);
}
}
return "";
}
private String objectarah2(int row, int col, Mat imgMat, int mode) {
int temprow, tempcol;
byte[] imagByte = new byte[1];
temprow = row - 1;
tempcol = col + 1;
imgMat.get(temprow, tempcol, imagByte);
int gray2 = grayScale(imagByte);
if (mode == 1) {
if (gray2 > toleransiWhite) {
areaObject(row, col);
return "2" + prosesChaincode(temprow, tempcol, 2, imgMat, mode);
}
} else {
if (gray2 < toleransi) {
return "2" + prosesChaincode(temprow, tempcol, 2, imgMat, mode);
}
}
return "";
}
private String objectarah3(int row, int col, Mat imgMat, int mode) {
int temprow, tempcol;
byte[] imagByte = new byte[1];
temprow = row;
tempcol = col + 1;
imgMat.get(temprow, tempcol, imagByte);
int gray3 = grayScale(imagByte);
if (mode == 1) {
if (gray3 > toleransiWhite) {
areaObject(row, col);
return "3" + prosesChaincode(temprow, tempcol, 3, imgMat, mode);
}
} else {
if (gray3 < toleransi) {
return "3" + prosesChaincode(temprow, tempcol, 3, imgMat, mode);
}
}
return "";
}
private String objectarah4(int row, int col, Mat imgMat, int mode) {
int temprow, tempcol;
byte[] imagByte = new byte[1];
temprow = row + 1;
tempcol = col + 1;
imgMat.get(temprow, tempcol, imagByte);
int gray4 = grayScale(imagByte);
if (mode == 1) {
if (gray4 > toleransiWhite) {
areaObject(row, col);
return "4" + prosesChaincode(temprow, tempcol, 4, imgMat, mode);
}
} else {
if (gray4 < toleransi) {
return "4" + prosesChaincode(temprow, tempcol, 4, imgMat, mode);
}
}
return "";
}
private String objectarah5(int row, int col, Mat imgMat, int mode) {
int temprow, tempcol;
byte[] imagByte = new byte[1];
temprow = row + 1;
tempcol = col;
imgMat.get(temprow, tempcol, imagByte);
int gray5 = grayScale(imagByte);
if (mode == 1) {
if (gray5 > toleransiWhite) {
areaObject(row, col);
return "5" + prosesChaincode(temprow, tempcol, 5, imgMat, mode);
}
} else {
if (gray5 < toleransi) {
return "5" + prosesChaincode(temprow, tempcol, 5, imgMat, mode);
}
}
return "";
}
private String objectarah6(int row, int col, Mat imgMat, int mode) {
int temprow, tempcol;
byte[] imagByte = new byte[1];
temprow = row + 1;
tempcol = col - 1;
imgMat.get(temprow, tempcol, imagByte);
int gray6 = grayScale(imagByte);
if (mode == 1) {
if (gray6 > toleransiWhite) {
areaObject(row, col);
return "6" + prosesChaincode(temprow, tempcol, 6, imgMat, mode);
}
} else {
if (gray6 < toleransi) {
return "6" + prosesChaincode(temprow, tempcol, 6, imgMat, mode);
}
}
return "";
}
private String objectarah7(int row, int col, Mat imgMat, int mode) {
int temprow, tempcol;
byte[] imagByte = new byte[1];
temprow = row;
tempcol = col - 1;
imgMat.get(temprow, tempcol, imagByte);
int gray7 = grayScale(imagByte);
if (mode == 1) {
if (gray7 > toleransiWhite) {
areaObject(row, col);
return "7" + prosesChaincode(temprow, tempcol, 7, imgMat, mode);
}
} else {
if (gray7 < toleransi) {
return "7" + prosesChaincode(temprow, tempcol, 7, imgMat, mode);
}
}
return "";
}
private String objectarah8(int row, int col, Mat imgMat, int mode) {
int temprow, tempcol;
byte[] imagByte = new byte[1];
temprow = row - 1;
tempcol = col - 1;
imgMat.get(temprow, tempcol, imagByte);
int gray8 = grayScale(imagByte);
if (mode == 1) {
if (gray8 > toleransiWhite) {
areaObject(row, col);
return "8" + prosesChaincode(temprow, tempcol, 8, imgMat, mode);
}
} else {
if (gray8 < toleransi) {
return "8" + prosesChaincode(temprow, tempcol, 8, imgMat, mode);
}
}
return "";
}
private void areaObject(int row, int col) {
if (minHor > col) {
minHor = col;
} else if (maxHor < col) {
maxHor = col;
}
if (minVer > row) {
minVer = row;
} else if (maxVer < row) {
maxVer = row;
}
}
private String getKodeBelok(String chainCode) {
String kodeBelok = "";
String Temp = String.valueOf(chainCode.charAt(0));
char[] tempChar = new char[2];
tempChar[0] = chainCode.charAt(0);
tempChar[1] = chainCode.charAt(0);
kodeBelok += chainCode.charAt(0);
boolean rep = false;
for (int i = 0; i < chainCode.length() - 1; i++) {
if (i == 105) {
char f = chainCode.charAt(i);
}
char ff = chainCode.charAt(i);
if (tempChar[0] != chainCode.charAt(i)) {
if (tempChar[1] != chainCode.charAt(i)) {
tempChar[0] = tempChar[1];
tempChar[1] = chainCode.charAt(i);
kodeBelok += chainCode.charAt(i);
} else {
tempChar[0] = tempChar[1];
tempChar[1] = chainCode.charAt(i);
}
} else {
if (tempChar[1] == chainCode.charAt(i + 1) && tempChar[0] != tempChar[1]) {
i++;
} else if (tempChar[1] == chainCode.charAt(i + 1)) {
} else {
tempChar[0] = tempChar[1];
tempChar[1] = chainCode.charAt(i + 1);
kodeBelok += chainCode.charAt(i + 1);
i++;
}
}
}
return kodeBelok;
}
}
| with resampling and confidence value
| src/main/java/id/ac/itb/sigit/pengenalanpola/ChainCodeWhiteConverter.java | with resampling and confidence value |
|
Java | epl-1.0 | 6dd82de9af69e5308bf219b92e73950528408a7b | 0 | sebastiangoetz/slr-toolkit,sebastiangoetz/slr-toolkit,sebastiangoetz/slr-toolkit,sebastiangoetz/slr-toolkit | package de.tudresden.slr.model.bibtex.ui.presentation;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.common.command.BasicCommandStack;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider;
import org.eclipse.emf.edit.ui.view.ExtendedPropertySheetPage;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.resource.FontDescriptor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.ide.IGotoMarker;
import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.PropertySheet;
import org.eclipse.ui.views.properties.PropertySheetPage;
import de.tudresden.slr.Utils;
import de.tudresden.slr.model.bibtex.Document;
import de.tudresden.slr.model.bibtex.ui.presentation.serialization.DocumentStorageEditorInput;
import de.tudresden.slr.model.modelregistry.ModelRegistryPlugin;
/**
* An example showing how to create a multi-page editor. This example has 3
* pages:
* <ul>
* <li>page 0 contains a nested text editor.
* <li>page 1 allows you to change the font used in page 2
* <li>page 2 shows the words in page 0 in sorted order
* </ul>
*/
public class BibtexEditor extends MultiPageEditorPart implements
ISelectionProvider {
public static final String ID = "de.tudresden.slr.model.bibtex.presentation.BibtexEditor";
// TODO: prettify
protected Composite parent = null;
protected Document document;
protected AdapterFactoryContentProvider contentProvider;
protected AdapterFactoryEditingDomain editingDomain;
protected int pdfIndex = -1;
protected int webindex = -1;
// protected Composite webcomposite;
protected Browser browser;
protected int propertyindex = -1;
protected PropertySheetPage property;
private ISelection selection;
private Set<ISelectionChangedListener> selectionListeners = new HashSet<>();
private static List<PropertySheetPage> propertySheetPages = new ArrayList<>();
protected Collection<Resource> changedResources = new ArrayList<Resource>();
protected Collection<Resource> removedResources = new ArrayList<Resource>();
protected Collection<Resource> savedResources = new ArrayList<Resource>();
/**
* This listens for when the outline becomes active <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
private IPartListener partListener = new IPartListener() {
@Override
public void partActivated(IWorkbenchPart part) {
if (part instanceof PropertySheet) {
if (propertySheetPages.contains(((PropertySheet) part)
.getCurrentPage())) {
getActionBarContributor()
.setActiveEditor(BibtexEditor.this);
setSelection(getSelection());
// handleActivate();
}
} else if (part == BibtexEditor.this) {
// handleActivate();
}
}
@Override
public void partBroughtToTop(IWorkbenchPart p) {
// Ignore.
}
@Override
public void partClosed(IWorkbenchPart p) {
// Ignore.
}
@Override
public void partDeactivated(IWorkbenchPart p) {
// Ignore.
}
@Override
public void partOpened(IWorkbenchPart p) {
}
};
public BibtexEditor() {
super();
initializeEditingDomain();
}
/**
* This sets up the editing domain for the model editor. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
protected void initializeEditingDomain() {
ModelRegistryPlugin.getModelRegistry().getEditingDomain()
.ifPresent((domain) -> editingDomain = domain);
contentProvider = new AdapterFactoryContentProvider(
editingDomain.getAdapterFactory());
}
@Override
protected void pageChange(int newPageIndex) {
if (newPageIndex == webindex && browser != null) {
String url = "";
if (document.getUrl() != null) {
url = document.getUrl();
} else if (document.getDoi() != null) {
url = "http://doi.org/" + document.getDoi();
} else {
return;
}
browser.setUrl(url);
// call url only once
browser = null;
} else if (newPageIndex == propertyindex) {
property.setPropertySourceProvider(contentProvider);
property.selectionChanged(BibtexEditor.this, getSelection());
} else if (newPageIndex == pdfIndex) {
openPdf();
this.setActivePage(0);
return;
}
super.pageChange(newPageIndex);
}
/**
* open the file document which is refered to in the bibtex entry. The path
* has to start from the root of the project where the bibtex entry is
* included.
*/
private void openPdf() {
IFile res = Utils.getIFilefromDocument(document);
if (res == null || res.getProject() == null) {
MessageDialog.openInformation(this.getSite().getShell(), "Bibtex"
+ document.getKey(), "Root or Resource not found");
return;
}
IFile file = res.getProject().getFile(document.getFile());
if (file.exists()) {
IFileStore fileStore = EFS.getLocalFileSystem().getStore(
file.getLocation());
IWorkbenchPage page = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
try {
IDE.openEditorOnFileStore(page, fileStore);
} catch (PartInitException e) {
e.printStackTrace();
}
} else {
MessageDialog.openInformation(this.getSite().getShell(), "Bibtex"
+ document.getKey(), "Document not found");
}
}
private void createPageLabel(Composite composite, GridData gridData) {
Label label = new Label(composite, SWT.CENTER);
label.setText(document.getTitle());
FontDescriptor boldDescriptor = FontDescriptor.createFrom(
label.getFont()).setStyle(SWT.BOLD);
Font boldFont = boldDescriptor.createFont(label.getDisplay());
label.setFont(boldFont);
label.setLayoutData(gridData);
}
private void createAuthorsLabel(Composite composite, GridData gridData) {
Label label = new Label(composite, SWT.CENTER);
label.setText(String.join(" and ", document.getAuthors()));
label.setLayoutData(gridData);
}
private void createDateLabel(Composite composite, GridData gridData) {
Label label = new Label(composite, SWT.CENTER);
StringBuilder labelText = new StringBuilder();
if (document.getMonth() != null) {
labelText.append(document.getMonth()).append(" ");
}
if (document.getYear() != null) {
labelText.append(document.getYear());
}
if (labelText.length() > 0) {
labelText.insert(0, "published in ");
}
label.setText(labelText.toString());
// TODO: dispose font
FontDescriptor italicDescriptor = FontDescriptor.createFrom(
label.getFont()).setStyle(SWT.ITALIC);
// TODO: use just one font object
Font italicFont = italicDescriptor.createFont(label.getDisplay());
label.setFont(italicFont);
label.setLayoutData(gridData);
}
private void createAbstractText(Composite composite) {
GridData gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.grabExcessHorizontalSpace = true;
gridData.verticalAlignment = GridData.FILL;
gridData.grabExcessVerticalSpace = true;
StyledText text = new StyledText(composite, SWT.V_SCROLL
| SWT.READ_ONLY | SWT.WRAP);
text.setEditable(false);
text.setLayoutData(gridData);
if (document.getAbstract() != null) {
text.setText(document.getAbstract());
}
}
/**
* Creates page 0 of the multi-page editor, which contains a text editor.
*/
protected void createAbstractPage() {
Composite localParent = getContainer();
if (localParent == null) {
localParent = parent;
}
Composite composite = new Composite(localParent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
layout.makeColumnsEqualWidth = true;
composite.setLayout(layout);
GridData gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.grabExcessHorizontalSpace = true;
createPageLabel(composite, gridData);
createAuthorsLabel(composite, gridData);
createDateLabel(composite, gridData);
createAbstractText(composite);
int index = addPage(composite);
setPageText(index, "Abstract");
}
/**
* Creates page 1 of the multi-page editor, which allows you to change the
* font used in page 2.
*/
protected void createPropertyPage() {
property = new PropertySheetPage();
Composite localParent = getContainer();
if (localParent == null) {
localParent = parent;
}
property.createControl(localParent);
property.setPropertySourceProvider(contentProvider);
propertyindex = addPage(property.getControl());
setPageText(propertyindex, "Properties");
}
/**
* Creates a browser for downloading the document which the bibtex entry
* refers to. This only works if there is an URL or DOI in the bibtex entry.
*/
protected void createWebpage() {
if (document.getUrl() == null && document.getDoi() == null) {
return;
}
Composite localParent = getContainer();
if (localParent == null) {
localParent = parent;
}
Composite webcomposite = new Composite(localParent, SWT.NONE);
FillLayout layout = new FillLayout();
webcomposite.setLayout(layout);
browser = new Browser(webcomposite, SWT.NONE);
browser.setLayout(layout);
webindex = addPage(webcomposite);
setPageText(webindex, "Webpage");
}
/**
* Creates an anchor for opening the research paper. This only works if the
* paper is referred in the bibtex entry and the named file exists.
*/
protected void createPdfPage() {
if (document.getFile() != null && !document.getFile().isEmpty()) {
IFile res = Utils.getIFilefromDocument(document);
if (res == null) {
return;
}
IFile projFile = res.getProject().getFile(document.getFile());
if (projFile.exists()) {
Composite localParent = getContainer();
if (localParent == null) {
localParent = parent;
}
Composite composite = new Composite(localParent, SWT.NONE);
// FillLayout layout = new FillLayout();
// composite.setLayout(layout);
// StyledText text = new StyledText(composite, SWT.H_SCROLL |
// SWT.V_SCROLL);
// text.setEditable(false);
pdfIndex = addPage(composite);
setPageText(pdfIndex, "PDF");
}
}
}
@Override
protected void createPages() {
getSite().setSelectionProvider(this);
if (parent == null) {
parent = getContainer();
}
createAbstractPage();
createPropertyPage();
createWebpage();
createPdfPage();
}
@Override
public void doSave(IProgressMonitor progressMonitor) {
// Save only resources that have actually changed.
//
final Map<Object, Object> saveOptions = new HashMap<Object, Object>();
saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED,
Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
saveOptions.put(Resource.OPTION_LINE_DELIMITER,
Resource.OPTION_LINE_DELIMITER_UNSPECIFIED);
// Do the work within an operation because this is a long running
// activity that modifies the workbench.
//
WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
// This is the method that gets invoked when the operation runs.
//
@Override
public void execute(IProgressMonitor monitor) {
// Save the resources to the file system.
//
boolean first = true;
for (Resource resource : editingDomain.getResourceSet()
.getResources()) {
if ((first || !resource.getContents().isEmpty() || isPersisted(resource))
&& !editingDomain.isReadOnly(resource)) {
try {
long timeStamp = resource.getTimeStamp();
resource.save(saveOptions);
if (resource.getTimeStamp() != timeStamp) {
savedResources.add(resource);
}
} catch (Exception exception) {
}
first = false;
}
}
}
};
try {
// This runs the options, and shows progress.
//
new ProgressMonitorDialog(getSite().getShell()).run(true, false,
operation);
// Refresh the necessary state.
//
((BasicCommandStack) editingDomain.getCommandStack()).saveIsDone();
firePropertyChange(IEditorPart.PROP_DIRTY);
} catch (Exception exception) {
// Something went wrong that shouldn't.
//
}
}
protected boolean isPersisted(Resource resource) {
boolean result = false;
try {
InputStream stream = editingDomain.getResourceSet()
.getURIConverter().createInputStream(resource.getURI());
if (stream != null) {
result = true;
stream.close();
}
} catch (IOException e) {
// Ignore
}
return result;
}
@Override
public void doSaveAs() {
// TODO: save entry as new bib file
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
/**
* The <code>MultiPageEditorExample</code> implementation of this method
* checks that the input is an instance of <code>IFileEditorInput</code>.
*/
@Override
public void init(IEditorSite site, IEditorInput editorInput)
throws PartInitException {
if (!(editorInput instanceof DocumentStorageEditorInput)) {
PartInitException pie = new PartInitException(
"Invalid Input: Must be DocumentStorageEditorInput");
System.out.println(editorInput);
pie.printStackTrace();
throw pie;
}
super.init(site, editorInput);
setPartName(editorInput.getName());
site.getPage().addPartListener(partListener);
extractDocument(editorInput);
getActionBarContributor().setActiveEditor(BibtexEditor.this);
setSelection(getSelection());
// TODO: notify propertysheetpage
/*
* //getActionBarContributor().setActiveEditor(this); if
* (propertySheetPages.isEmpty()){ getPropertySheetPage(); } for
* (PropertySheetPage p : propertySheetPages){
* p.setPropertySourceProvider(new
* AdapterFactoryContentProvider(adapterFactory)); p.refresh(); }
*/
// setInputWithNotify(editorInput);
ModelRegistryPlugin.getModelRegistry().setActiveDocument(document);
}
protected void extractDocument(IEditorInput editorInput) {
try {
this.document = ((DocumentStorageEditorInput) editorInput)
.getStorage().getDocument();
this.selection = new StructuredSelection(this.document);
ModelRegistryPlugin.getModelRegistry().setActiveDocument(document);
} catch (CoreException e) {
e.printStackTrace();
}
}
@Override
public ISelection getSelection() {
return selection;
}
@Override
public void setSelection(ISelection selection) {
this.selection = selection;
final SelectionChangedEvent event = new SelectionChangedEvent(this,
selection);
selectionListeners
.forEach(listener -> listener.selectionChanged(event));
// getSite().getSelectionProvider().setSelection(selection);
// setStatusLineManager(selection);
}
/**
* This is how the framework determines which interfaces we implement. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@SuppressWarnings("rawtypes")
@Override
public Object getAdapter(Class key) {
/*
* if (key.equals(IContentOutlinePage.class)) { return showOutlineView()
* ? getContentOutlinePage() : null; } else
*/if (key.equals(IPropertySheetPage.class)) {
return getPropertySheetPage();
} else if (key.equals(IGotoMarker.class)) {
return this;
} else {
return super.getAdapter(key);
}
}
/**
* This accesses a cached version of the property sheet. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
public IPropertySheetPage getPropertySheetPage() {
PropertySheetPage propertySheetPage = new ExtendedPropertySheetPage(
editingDomain) {
@Override
public void setSelectionToViewer(List<?> selection) {
// BibtexEditor.this.setSelectionToViewer(selection);
BibtexEditor.this.setFocus();
}
@Override
public void setActionBars(IActionBars actionBars) {
super.setActionBars(actionBars);
// getActionBarContributor().shareGlobalActions(this,
// actionBars);
}
};
propertySheetPage.setPropertySourceProvider(contentProvider);
propertySheetPages.add(propertySheetPage);
propertySheetPage.handleEntrySelection(getSelection());
propertySheetPage.setRootEntry(null);
return propertySheetPage;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public IEditorActionBarContributor getActionBarContributor() {
return getEditorSite().getActionBarContributor();
}
@Override
public void addSelectionChangedListener(ISelectionChangedListener listener) {
selectionListeners.add(listener);
}
@Override
public void removeSelectionChangedListener(
ISelectionChangedListener listener) {
selectionListeners.remove(listener);
}
protected IResourceChangeListener resourceChangeListener = new IResourceChangeListener() {
@Override
public void resourceChanged(IResourceChangeEvent event) {
IResourceDelta delta = event.getDelta();
try {
class ResourceDeltaVisitor implements IResourceDeltaVisitor {
protected ResourceSet resourceSet = editingDomain
.getResourceSet();
protected Collection<Resource> changedResources = new ArrayList<Resource>();
protected Collection<Resource> removedResources = new ArrayList<Resource>();
@Override
public boolean visit(IResourceDelta delta) {
if (delta.getResource().getType() == IResource.FILE) {
if (delta.getKind() == IResourceDelta.REMOVED
|| delta.getKind() == IResourceDelta.CHANGED
&& delta.getFlags() != IResourceDelta.MARKERS) {
Resource resource = resourceSet
.getResource(URI
.createPlatformResourceURI(
delta.getFullPath()
.toString(),
true), false);
if (resource != null) {
if (delta.getKind() == IResourceDelta.REMOVED) {
removedResources.add(resource);
} else if (!savedResources.remove(resource)) {
changedResources.add(resource);
}
}
}
return false;
}
return true;
}
public Collection<Resource> getChangedResources() {
return changedResources;
}
public Collection<Resource> getRemovedResources() {
return removedResources;
}
}
final ResourceDeltaVisitor visitor = new ResourceDeltaVisitor();
delta.accept(visitor);
if (!visitor.getRemovedResources().isEmpty()) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
removedResources.addAll(visitor
.getRemovedResources());
if (!isDirty()) {
getSite().getPage().closeEditor(
BibtexEditor.this, false);
}
}
});
}
if (!visitor.getChangedResources().isEmpty()) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
changedResources.addAll(visitor
.getChangedResources());
if (getSite().getPage().getActiveEditor() == BibtexEditor.this) {
handleActivate();
}
}
});
}
} catch (CoreException exception) {
exception.printStackTrace();
}
}
};
protected void handleActivate() {
// Recompute the read only state.
//
if (editingDomain.getResourceToReadOnlyMap() != null) {
editingDomain.getResourceToReadOnlyMap().clear();
// Refresh any actions that may become enabled or disabled.
//
setSelection(getSelection());
}
if (!removedResources.isEmpty()) {
removedResources.clear();
changedResources.clear();
savedResources.clear();
} else if (!changedResources.isEmpty()) {
changedResources.removeAll(savedResources);
handleChangedResources();
changedResources.clear();
savedResources.clear();
}
}
/**
* Handles what to do with changed resources on activation. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void handleChangedResources() {
if (!changedResources.isEmpty()) {
if (isDirty()) {
changedResources.addAll(editingDomain.getResourceSet()
.getResources());
}
editingDomain.getCommandStack().flush();
for (Resource resource : changedResources) {
if (resource.isLoaded()) {
resource.unload();
try {
resource.load(Collections.EMPTY_MAP);
} catch (IOException exception) {
}
}
}
}
}
@Override
public boolean isDirty() {
return ((BasicCommandStack) editingDomain.getCommandStack())
.isSaveNeeded();
}
} | plugins/de.tudresden.slr.model.bibtex.ui/src/de/tudresden/slr/model/bibtex/ui/presentation/BibtexEditor.java | package de.tudresden.slr.model.bibtex.ui.presentation;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.common.command.BasicCommandStack;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider;
import org.eclipse.emf.edit.ui.view.ExtendedPropertySheetPage;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.resource.FontDescriptor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.ide.IGotoMarker;
import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.PropertySheet;
import org.eclipse.ui.views.properties.PropertySheetPage;
import de.tudresden.slr.Utils;
import de.tudresden.slr.model.bibtex.Document;
import de.tudresden.slr.model.bibtex.ui.presentation.serialization.DocumentStorageEditorInput;
import de.tudresden.slr.model.modelregistry.ModelRegistryPlugin;
/**
* An example showing how to create a multi-page editor. This example has 3
* pages:
* <ul>
* <li>page 0 contains a nested text editor.
* <li>page 1 allows you to change the font used in page 2
* <li>page 2 shows the words in page 0 in sorted order
* </ul>
*/
public class BibtexEditor extends MultiPageEditorPart implements
ISelectionProvider {
public static final String ID = "de.tudresden.slr.model.bibtex.presentation.BibtexEditor";
// TODO: prettify
protected Composite parent = null;
protected Document document;
protected AdapterFactory adapterFactory;
protected AdapterFactoryEditingDomain editingDomain;
protected int pdfIndex = -1;
protected int webindex = -1;
protected Composite webcomposite;
protected Browser browser;
protected int propertyindex = -1;
protected PropertySheetPage property;
private ISelection selection;
private Set<ISelectionChangedListener> selectionListeners = new HashSet<>();
private static List<PropertySheetPage> propertySheetPages = new ArrayList<>();
protected Collection<Resource> changedResources = new ArrayList<Resource>();
protected Collection<Resource> removedResources = new ArrayList<Resource>();
protected Collection<Resource> savedResources = new ArrayList<Resource>();
/**
* This listens for when the outline becomes active <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
private IPartListener partListener = new IPartListener() {
@Override
public void partActivated(IWorkbenchPart part) {
if (part instanceof PropertySheet) {
if (propertySheetPages.contains(((PropertySheet) part)
.getCurrentPage())) {
getActionBarContributor()
.setActiveEditor(BibtexEditor.this);
setSelection(getSelection());
// handleActivate();
}
} else if (part == BibtexEditor.this) {
// handleActivate();
}
}
@Override
public void partBroughtToTop(IWorkbenchPart p) {
// Ignore.
}
@Override
public void partClosed(IWorkbenchPart p) {
// Ignore.
}
@Override
public void partDeactivated(IWorkbenchPart p) {
// Ignore.
}
@Override
public void partOpened(IWorkbenchPart p) {
}
};
public BibtexEditor() {
super();
initializeEditingDomain();
}
/**
* This sets up the editing domain for the model editor. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
protected void initializeEditingDomain() {
ModelRegistryPlugin.getModelRegistry().getEditingDomain()
.ifPresent((domain) -> editingDomain = domain);
adapterFactory = editingDomain.getAdapterFactory();
}
@Override
protected void pageChange(int newPageIndex) {
if (newPageIndex == webindex && webcomposite != null) {
String url = "";
if (document.getUrl() != null) {
url = document.getUrl();
} else if (document.getDoi() != null) {
url = "http://doi.org/" + document.getDoi();
} else {
return;
}
boolean effort = browser.setUrl(url);
// call url only once
webcomposite = null;
} else if (newPageIndex == propertyindex) {
property.setPropertySourceProvider(new AdapterFactoryContentProvider(
adapterFactory));
property.selectionChanged(BibtexEditor.this, getSelection());
} else if (newPageIndex == pdfIndex) {
openPdf();
this.setActivePage(0);
return;
}
super.pageChange(newPageIndex);
}
/**
* open the file document which is refered to in the bibtex entry. The path
* has to start from the root of the project where the bibtex entry is
* included.
*/
private void openPdf() {
IFile res = Utils.getIFilefromDocument(document);
if (res == null || res.getProject() == null) {
MessageDialog.openInformation(this.getSite().getShell(), "Bibtex"
+ document.getKey(), "Root or Resource not found");
return;
}
IFile file = res.getProject().getFile(document.getFile());
if (file.exists()) {
IFileStore fileStore = EFS.getLocalFileSystem().getStore(
file.getLocation());
IWorkbenchPage page = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
try {
IDE.openEditorOnFileStore(page, fileStore);
} catch (PartInitException e) {
e.printStackTrace();
}
} else {
MessageDialog.openInformation(this.getSite().getShell(), "Bibtex"
+ document.getKey(), "Document not found");
}
}
private void createPageLabel(Composite composite, GridData gridData) {
Label label = new Label(composite, SWT.CENTER);
label.setText(document.getTitle());
FontDescriptor boldDescriptor = FontDescriptor.createFrom(
label.getFont()).setStyle(SWT.BOLD);
Font boldFont = boldDescriptor.createFont(label.getDisplay());
label.setFont(boldFont);
label.setLayoutData(gridData);
}
private void createAuthorsLabel(Composite composite, GridData gridData) {
Label label = new Label(composite, SWT.CENTER);
label.setText(String.join(" and ", document.getAuthors()));
label.setLayoutData(gridData);
}
private void createDateLabel(Composite composite, GridData gridData) {
Label label = new Label(composite, SWT.CENTER);
StringBuilder labelText = new StringBuilder();
if (document.getMonth() != null) {
labelText.append(document.getMonth()).append(" ");
}
if (document.getYear() != null) {
labelText.append(document.getYear());
}
if (labelText.length() > 0) {
labelText.insert(0, "published in ");
}
label.setText(labelText.toString());
// TODO: dispose font
FontDescriptor italicDescriptor = FontDescriptor.createFrom(
label.getFont()).setStyle(SWT.ITALIC);
// TODO: use just one font object
Font italicFont = italicDescriptor.createFont(label.getDisplay());
label.setFont(italicFont);
label.setLayoutData(gridData);
}
private void createAbstractText(Composite composite) {
GridData gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.grabExcessHorizontalSpace = true;
gridData.verticalAlignment = GridData.FILL;
gridData.grabExcessVerticalSpace = true;
StyledText text = new StyledText(composite, SWT.V_SCROLL
| SWT.READ_ONLY | SWT.WRAP);
text.setEditable(false);
text.setLayoutData(gridData);
if (document.getAbstract() != null) {
text.setText(document.getAbstract());
}
}
/**
* Creates page 0 of the multi-page editor, which contains a text editor.
*/
protected void createAbstractPage() {
Composite localParent = getContainer();
if (localParent == null) {
localParent = parent;
}
Composite composite = new Composite(localParent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
layout.makeColumnsEqualWidth = true;
composite.setLayout(layout);
GridData gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.grabExcessHorizontalSpace = true;
createPageLabel(composite, gridData);
createAuthorsLabel(composite, gridData);
createDateLabel(composite, gridData);
createAbstractText(composite);
int index = addPage(composite);
setPageText(index, "Abstract");
}
/**
* Creates page 1 of the multi-page editor, which allows you to change the
* font used in page 2.
*/
protected void createPropertyPage() {
property = new PropertySheetPage();
Composite localParent = getContainer();
if (localParent == null) {
localParent = parent;
}
property.createControl(localParent);
property.setPropertySourceProvider(new AdapterFactoryContentProvider(
adapterFactory));
propertyindex = addPage(property.getControl());
setPageText(propertyindex, "Properties");
}
/**
* Creates a browser for downloading the document which the bibtex entry
* refers to. This only works if there is an URL or DOI in the bibtex entry.
*/
protected void createWebpage() {
if (document.getUrl() == null && document.getDoi() == null) {
return;
}
Composite localParent = getContainer();
if (localParent == null) {
localParent = parent;
}
webcomposite = new Composite(localParent, SWT.NONE);
FillLayout layout = new FillLayout();
webcomposite.setLayout(layout);
browser = new Browser(webcomposite, SWT.NONE);
browser.setLayout(layout);
webindex = addPage(webcomposite);
setPageText(webindex, "Webpage");
}
/**
* Creates an anchor for opening the research paper. This only works if the
* paper is refered in the bibtex entry and the named file exists.
*/
protected void createPdfPage() {
if (document.getFile() != null && !document.getFile().isEmpty()) {
IFile res = Utils.getIFilefromDocument(document);
if (res == null) {
return;
}
IFile projFile = res.getProject().getFile(document.getFile());
if (projFile.exists()) {
Composite localParent = getContainer();
if (localParent == null) {
localParent = parent;
}
Composite composite = new Composite(localParent, SWT.NONE);
// FillLayout layout = new FillLayout();
// composite.setLayout(layout);
// StyledText text = new StyledText(composite, SWT.H_SCROLL |
// SWT.V_SCROLL);
// text.setEditable(false);
pdfIndex = addPage(composite);
setPageText(pdfIndex, "PDF");
}
}
}
@Override
protected void createPages() {
getSite().setSelectionProvider(this);
if (parent == null) {
parent = getContainer();
}
createAbstractPage();
createPropertyPage();
createWebpage();
createPdfPage();
}
@Override
public void doSave(IProgressMonitor progressMonitor) {
// Save only resources that have actually changed.
//
final Map<Object, Object> saveOptions = new HashMap<Object, Object>();
saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED,
Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
saveOptions.put(Resource.OPTION_LINE_DELIMITER,
Resource.OPTION_LINE_DELIMITER_UNSPECIFIED);
// Do the work within an operation because this is a long running
// activity that modifies the workbench.
//
WorkspaceModifyOperation operation = new WorkspaceModifyOperation() {
// This is the method that gets invoked when the operation runs.
//
@Override
public void execute(IProgressMonitor monitor) {
// Save the resources to the file system.
//
boolean first = true;
for (Resource resource : editingDomain.getResourceSet()
.getResources()) {
if ((first || !resource.getContents().isEmpty() || isPersisted(resource))
&& !editingDomain.isReadOnly(resource)) {
try {
long timeStamp = resource.getTimeStamp();
resource.save(saveOptions);
if (resource.getTimeStamp() != timeStamp) {
savedResources.add(resource);
}
} catch (Exception exception) {
}
first = false;
}
}
}
};
try {
// This runs the options, and shows progress.
//
new ProgressMonitorDialog(getSite().getShell()).run(true, false,
operation);
// Refresh the necessary state.
//
((BasicCommandStack) editingDomain.getCommandStack()).saveIsDone();
firePropertyChange(IEditorPart.PROP_DIRTY);
} catch (Exception exception) {
// Something went wrong that shouldn't.
//
}
}
protected boolean isPersisted(Resource resource) {
boolean result = false;
try {
InputStream stream = editingDomain.getResourceSet()
.getURIConverter().createInputStream(resource.getURI());
if (stream != null) {
result = true;
stream.close();
}
} catch (IOException e) {
// Ignore
}
return result;
}
@Override
public void doSaveAs() {
// TODO: save entry as new bib file
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
/**
* The <code>MultiPageEditorExample</code> implementation of this method
* checks that the input is an instance of <code>IFileEditorInput</code>.
*/
@Override
public void init(IEditorSite site, IEditorInput editorInput)
throws PartInitException {
if (!(editorInput instanceof DocumentStorageEditorInput)) {
PartInitException pie = new PartInitException(
"Invalid Input: Must be DocumentStorageEditorInput");
System.out.println(editorInput);
pie.printStackTrace();
throw pie;
}
super.init(site, editorInput);
setPartName(editorInput.getName());
site.getPage().addPartListener(partListener);
extractDocument(editorInput);
getActionBarContributor().setActiveEditor(BibtexEditor.this);
setSelection(getSelection());
// TODO: notify propertysheetpage
/*
* //getActionBarContributor().setActiveEditor(this); if
* (propertySheetPages.isEmpty()){ getPropertySheetPage(); } for
* (PropertySheetPage p : propertySheetPages){
* p.setPropertySourceProvider(new
* AdapterFactoryContentProvider(adapterFactory)); p.refresh(); }
*/
// setInputWithNotify(editorInput);
ModelRegistryPlugin.getModelRegistry().setActiveDocument(document);
}
protected void extractDocument(IEditorInput editorInput) {
try {
this.document = ((DocumentStorageEditorInput) editorInput)
.getStorage().getDocument();
this.selection = new StructuredSelection(this.document);
ModelRegistryPlugin.getModelRegistry().setActiveDocument(document);
} catch (CoreException e) {
e.printStackTrace();
}
}
@Override
public ISelection getSelection() {
return selection;
}
@Override
public void setSelection(ISelection selection) {
this.selection = selection;
final SelectionChangedEvent event = new SelectionChangedEvent(this,
selection);
selectionListeners
.forEach(listener -> listener.selectionChanged(event));
// getSite().getSelectionProvider().setSelection(selection);
// setStatusLineManager(selection);
}
/**
* This is how the framework determines which interfaces we implement. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@SuppressWarnings("rawtypes")
@Override
public Object getAdapter(Class key) {
/*
* if (key.equals(IContentOutlinePage.class)) { return showOutlineView()
* ? getContentOutlinePage() : null; } else
*/if (key.equals(IPropertySheetPage.class)) {
return getPropertySheetPage();
} else if (key.equals(IGotoMarker.class)) {
return this;
} else {
return super.getAdapter(key);
}
}
/**
* This accesses a cached version of the property sheet. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
public IPropertySheetPage getPropertySheetPage() {
PropertySheetPage propertySheetPage = new ExtendedPropertySheetPage(
editingDomain) {
@Override
public void setSelectionToViewer(List<?> selection) {
// BibtexEditor.this.setSelectionToViewer(selection);
BibtexEditor.this.setFocus();
}
@Override
public void setActionBars(IActionBars actionBars) {
super.setActionBars(actionBars);
// getActionBarContributor().shareGlobalActions(this,
// actionBars);
}
};
propertySheetPage
.setPropertySourceProvider(new AdapterFactoryContentProvider(
adapterFactory));
propertySheetPages.add(propertySheetPage);
propertySheetPage.handleEntrySelection(getSelection());
propertySheetPage.setRootEntry(null);
return propertySheetPage;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public IEditorActionBarContributor getActionBarContributor() {
return getEditorSite().getActionBarContributor();
}
@Override
public void addSelectionChangedListener(ISelectionChangedListener listener) {
selectionListeners.add(listener);
}
@Override
public void removeSelectionChangedListener(
ISelectionChangedListener listener) {
selectionListeners.remove(listener);
}
protected IResourceChangeListener resourceChangeListener = new IResourceChangeListener() {
@Override
public void resourceChanged(IResourceChangeEvent event) {
IResourceDelta delta = event.getDelta();
try {
class ResourceDeltaVisitor implements IResourceDeltaVisitor {
protected ResourceSet resourceSet = editingDomain
.getResourceSet();
protected Collection<Resource> changedResources = new ArrayList<Resource>();
protected Collection<Resource> removedResources = new ArrayList<Resource>();
@Override
public boolean visit(IResourceDelta delta) {
if (delta.getResource().getType() == IResource.FILE) {
if (delta.getKind() == IResourceDelta.REMOVED
|| delta.getKind() == IResourceDelta.CHANGED
&& delta.getFlags() != IResourceDelta.MARKERS) {
Resource resource = resourceSet
.getResource(URI
.createPlatformResourceURI(
delta.getFullPath()
.toString(),
true), false);
if (resource != null) {
if (delta.getKind() == IResourceDelta.REMOVED) {
removedResources.add(resource);
} else if (!savedResources.remove(resource)) {
changedResources.add(resource);
}
}
}
return false;
}
return true;
}
public Collection<Resource> getChangedResources() {
return changedResources;
}
public Collection<Resource> getRemovedResources() {
return removedResources;
}
}
final ResourceDeltaVisitor visitor = new ResourceDeltaVisitor();
delta.accept(visitor);
if (!visitor.getRemovedResources().isEmpty()) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
removedResources.addAll(visitor
.getRemovedResources());
if (!isDirty()) {
getSite().getPage().closeEditor(
BibtexEditor.this, false);
}
}
});
}
if (!visitor.getChangedResources().isEmpty()) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
changedResources.addAll(visitor
.getChangedResources());
if (getSite().getPage().getActiveEditor() == BibtexEditor.this) {
handleActivate();
}
}
});
}
} catch (CoreException exception) {
exception.printStackTrace();
}
}
};
protected void handleActivate() {
// Recompute the read only state.
//
if (editingDomain.getResourceToReadOnlyMap() != null) {
editingDomain.getResourceToReadOnlyMap().clear();
// Refresh any actions that may become enabled or disabled.
//
setSelection(getSelection());
}
if (!removedResources.isEmpty()) {
removedResources.clear();
changedResources.clear();
savedResources.clear();
} else if (!changedResources.isEmpty()) {
changedResources.removeAll(savedResources);
handleChangedResources();
changedResources.clear();
savedResources.clear();
}
}
/**
* Handles what to do with changed resources on activation. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void handleChangedResources() {
if (!changedResources.isEmpty()) {
if (isDirty()) {
changedResources.addAll(editingDomain.getResourceSet()
.getResources());
}
editingDomain.getCommandStack().flush();
for (Resource resource : changedResources) {
if (resource.isLoaded()) {
resource.unload();
try {
resource.load(Collections.EMPTY_MAP);
} catch (IOException exception) {
}
}
}
}
}
@Override
public boolean isDirty() {
return ((BasicCommandStack) editingDomain.getCommandStack())
.isSaveNeeded();
}
} | clean up | plugins/de.tudresden.slr.model.bibtex.ui/src/de/tudresden/slr/model/bibtex/ui/presentation/BibtexEditor.java | clean up |
|
Java | mpl-2.0 | 105e24b9246e3fbfb4e4a2088ed6ee222106dade | 0 | Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV | package org.helioviewer.jhv.plugins.eveplugin.view.chart;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.RoundRectangle2D;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.JComponent;
import javax.swing.event.MouseInputListener;
import org.helioviewer.jhv.base.interval.Interval;
import org.helioviewer.jhv.base.time.TimeUtils;
import org.helioviewer.jhv.gui.UIGlobals;
import org.helioviewer.jhv.layers.Layers;
import org.helioviewer.jhv.layers.LayersListener;
import org.helioviewer.jhv.plugins.eveplugin.DrawConstants;
import org.helioviewer.jhv.plugins.eveplugin.EVEState;
import org.helioviewer.jhv.plugins.eveplugin.draw.DrawController;
import org.helioviewer.jhv.plugins.eveplugin.draw.TimingListener;
import org.helioviewer.jhv.viewmodel.view.View;
// Class will not be serialized so we suppress the warnings
@SuppressWarnings("serial")
public class ChartDrawIntervalPane extends JComponent implements TimingListener, MouseInputListener, LayersListener {
private Interval movieInterval;
private boolean mouseOverInterval = true;
// private boolean mouseOverLeftGraspPoint = false;
// private boolean mouseOverRightGraspPoint = false;
private Point mousePressed = null;
private int leftIntervalBorderPosition = -10;
private int rightIntervalBorderPosition = -10;
private final DrawController drawController;
private final EVEState eveState;
public ChartDrawIntervalPane() {
initVisualComponents();
addMouseListener(this);
addMouseMotionListener(this);
Layers.addLayersListener(this);
drawController = DrawController.getSingletonInstance();
drawController.addTimingListener(this);
eveState = EVEState.getSingletonInstance();
}
private void initVisualComponents() {
setPreferredSize(new Dimension(getPreferredSize().width, DrawConstants.INTERVAL_SELECTION_HEIGHT));
setSize(getPreferredSize());
}
@Override
protected void paintComponent(Graphics g1) {
super.paintComponent(g1);
Graphics2D g = (Graphics2D) g1;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setFont(DrawConstants.font);
drawBackground(g);
Interval availableInterval = DrawController.getSingletonInstance().getAvailableInterval();
Interval selectedInterval = DrawController.getSingletonInstance().getSelectedInterval();
if (availableInterval != null && selectedInterval != null) {
computeIntervalBorderPositions(availableInterval, selectedInterval);
drawIntervalBackground(g);
drawInterval(g);
drawMovieInterval(g, availableInterval);
drawLabels(g, availableInterval, selectedInterval);
drawBorders(g);
drawIntervalGraspPoints(g);
drawIntervalHBar(g);
}
}
private void drawIntervalBackground(Graphics2D g) {
g.setColor(DrawConstants.SELECTED_INTERVAL_BACKGROUND_COLOR);
g.fillRect(leftIntervalBorderPosition - 1, 0, rightIntervalBorderPosition - leftIntervalBorderPosition, getHeight() - 3);
}
private void computeIntervalBorderPositions(Interval availableInterval, Interval selectedInterval) {
final double diffMin = (availableInterval.end - availableInterval.start) / 60000.0;
long start = selectedInterval.start - availableInterval.start;
start = Math.round(start / 60000.0);
long end = selectedInterval.end - availableInterval.start;
end = Math.round(end / 60000.0);
final int availableIntervalSpace = getWidth() - (DrawConstants.GRAPH_LEFT_SPACE + DrawConstants.GRAPH_RIGHT_SPACE + DrawConstants.RANGE_SELECTION_WIDTH) - 1;
leftIntervalBorderPosition = (int) ((start / diffMin) * availableIntervalSpace) + DrawConstants.GRAPH_LEFT_SPACE;
rightIntervalBorderPosition = (int) ((end / diffMin) * availableIntervalSpace) + DrawConstants.GRAPH_LEFT_SPACE;
}
private void drawBackground(Graphics2D g) {
final int availableIntervalSpace = getWidth() - (DrawConstants.GRAPH_LEFT_SPACE + DrawConstants.GRAPH_RIGHT_SPACE + DrawConstants.RANGE_SELECTION_WIDTH) - 1;
g.setColor(DrawConstants.AVAILABLE_INTERVAL_BACKGROUND_COLOR);
g.fillRect(DrawConstants.GRAPH_LEFT_SPACE, 2, availableIntervalSpace, getHeight() - 3);
}
private void drawInterval(Graphics2D g) {
// final int availableIntervalSpace = getWidth() -
// (DrawConstants.GRAPH_LEFT_SPACE + DrawConstants.GRAPH_RIGHT_SPACE +
// DrawConstants.RANGE_SELECTION_WIDTH) - 1;
g.setColor(Color.black);
g.fillRect(leftIntervalBorderPosition, getHeight() - 2, rightIntervalBorderPosition - leftIntervalBorderPosition, 2);
g.setColor(DrawConstants.BORDER_COLOR);
g.fillRect(leftIntervalBorderPosition, 0, rightIntervalBorderPosition - leftIntervalBorderPosition, 1);
}
private void drawMovieInterval(Graphics2D g, Interval availableInterval) {
if (availableInterval == null || movieInterval == null) {
return;
}
if (movieInterval.end < availableInterval.start || movieInterval.start > availableInterval.end) {
return;
}
final int availableIntervalWidth = getWidth() - (DrawConstants.GRAPH_LEFT_SPACE + DrawConstants.GRAPH_RIGHT_SPACE + DrawConstants.RANGE_SELECTION_WIDTH) - 1;
final double ratioX = availableIntervalWidth / (double) (availableInterval.end - availableInterval.start);
int min = DrawConstants.GRAPH_LEFT_SPACE;
if (availableInterval.containsPointInclusive(movieInterval.start)) {
min += (int) ((movieInterval.start - availableInterval.start) * ratioX);
}
int max = DrawConstants.GRAPH_LEFT_SPACE + availableIntervalWidth;
if (availableInterval.containsPointInclusive(movieInterval.end)) {
max = DrawConstants.GRAPH_LEFT_SPACE + (int) ((movieInterval.end - availableInterval.start) * ratioX);
}
int offset = 7;
g.setColor(DrawConstants.MOVIE_INTERVAL_COLOR);
g.drawLine(min, offset, max, offset);
g.drawLine(min, offset + 2, max, offset + 2);
g.drawLine(min, offset + 9, max, offset + 9);
g.drawLine(min, offset + 11, max, offset + 11);
for (int x = min; x <= max; ++x) {
final int mod4 = (x - min) % 4;
final int mod12 = (x - min) % 12;
if (mod4 == 0) {
final int width = 1;
if (mod12 == 0) {
g.fillRect(x, offset + 1, width, 10);
} else {
g.fillRect(x, offset + 1, width, 2);
g.fillRect(x, offset + 9, width, 2);
}
}
}
}
private void drawBorders(Graphics2D g) {
g.setColor(DrawConstants.BORDER_COLOR);
}
private void drawIntervalGraspPoints(Graphics2D g) {
g.setColor(Color.BLACK);
g.fill(new RoundRectangle2D.Double(leftIntervalBorderPosition - 1, 0, 2, getHeight(), 5, 5));
g.fill(new RoundRectangle2D.Double(rightIntervalBorderPosition - 1, 0, 2, getHeight(), 5, 5));
}
private void drawIntervalHBar(Graphics2D g) {
g.setColor(Color.BLACK);
g.fill(new RoundRectangle2D.Double(DrawConstants.GRAPH_LEFT_SPACE, 0, leftIntervalBorderPosition - DrawConstants.GRAPH_LEFT_SPACE, 2, 5, 5));
g.fill(new RoundRectangle2D.Double(rightIntervalBorderPosition, 0, getWidth() - rightIntervalBorderPosition - DrawConstants.GRAPH_RIGHT_SPACE, 2, 5, 5));
}
private void drawLabels(Graphics2D g, Interval availableInterval, Interval selectedInterval) {
if (availableInterval.start > availableInterval.end) {
return;
}
final int tickTextWidth = (int) g.getFontMetrics().getStringBounds(DrawConstants.FULL_DATE_TIME_FORMAT.format(new Date()), g).getWidth();
final int availableIntervalWidth = getWidth() - (DrawConstants.GRAPH_LEFT_SPACE + DrawConstants.GRAPH_RIGHT_SPACE + DrawConstants.RANGE_SELECTION_WIDTH) - 1;
final int maxTicks = Math.max(2, (availableIntervalWidth - tickTextWidth * 2) / tickTextWidth);
final double ratioX = availableIntervalWidth / (double) (availableInterval.end - availableInterval.start);
if (availableInterval.containsPointInclusive(availableInterval.start + TimeUtils.DAY_IN_MILLIS * 366 * 3)) {
drawLabelsYear(g, availableInterval, selectedInterval, maxTicks, availableIntervalWidth, ratioX);
return;
}
if (availableInterval.containsPointInclusive(availableInterval.start + TimeUtils.DAY_IN_MILLIS * 31 * 3)) {
drawLabelsMonth(g, availableInterval, selectedInterval, maxTicks, availableIntervalWidth, ratioX);
return;
}
if (availableInterval.containsPointInclusive(availableInterval.start + TimeUtils.DAY_IN_MILLIS * 3)) {
drawLabelsDay(g, availableInterval, selectedInterval, maxTicks, availableIntervalWidth, ratioX);
return;
}
drawLabelsTime(g, availableInterval, selectedInterval, maxTicks, availableIntervalWidth, ratioX);
}
private void drawLabelsTime(Graphics2D g, Interval availableInterval, Interval selectedInterval, final int maxTicks, final int availableIntervalWidth, final double ratioX) {
final long timeDiff = availableInterval.end - availableInterval.start;
final double ratioTime = timeDiff / (double) maxTicks;
int day = -1;
GregorianCalendar tickGreg = new GregorianCalendar();
String tickText;
for (int i = 0; i < maxTicks; ++i) {
final Date tickValue = new Date(availableInterval.start + (long) (i * ratioTime));
tickGreg.setTime(tickValue);
int currentday = tickGreg.get(GregorianCalendar.DAY_OF_MONTH);
if (day != currentday) {
tickText = DrawConstants.FULL_DATE_TIME_FORMAT_NO_SEC.format(tickValue);
day = currentday;
} else {
tickText = DrawConstants.HOUR_TIME_FORMAT_NO_SEC.format(tickValue);
}
drawLabel(g, availableInterval, selectedInterval, tickText, availableIntervalWidth, tickValue.getTime(), ratioX);
}
}
private void drawLabelsDay(Graphics2D g, Interval availableInterval, Interval selectedInterval, final int maxTicks, final int availableIntervalWidth, final double ratioX) {
final Calendar calendar = new GregorianCalendar();
calendar.clear();
calendar.setTime(new Date(availableInterval.start));
int startYear = calendar.get(Calendar.YEAR);
int startMonth = calendar.get(Calendar.MONTH);
int startDay = calendar.get(Calendar.DAY_OF_MONTH);
calendar.clear();
calendar.set(startYear, startMonth, startDay);
if (!availableInterval.containsPointInclusive(calendar.getTime().getTime())) {
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
startYear = calendar.get(Calendar.YEAR);
startMonth = calendar.get(Calendar.MONTH);
startDay = calendar.get(Calendar.DAY_OF_MONTH);
final long diffMillis = availableInterval.end - calendar.getTimeInMillis();
final int numberOfDays = (int) Math.round(diffMillis / (1000. * 60. * 60. * 24.));
final int tickCount = Math.min(numberOfDays, maxTicks);
final double ratioDays = Math.ceil((double) numberOfDays / (double) tickCount);
for (int i = 0; i < maxTicks; ++i) {
calendar.clear();
calendar.set(startYear, startMonth, startDay);
calendar.add(Calendar.DAY_OF_MONTH, (int) (i * ratioDays));
final String tickText = DrawConstants.DAY_MONTH_YEAR_TIME_FORMAT.format(calendar.getTime());
drawLabel(g, availableInterval, selectedInterval, tickText, availableIntervalWidth, calendar.getTime().getTime(), ratioX);
}
}
private void drawLabelsMonth(Graphics2D g, Interval availableInterval, Interval selectedInterval, final int maxTicks, final int availableIntervalWidth, final double ratioX) {
final Calendar calendar = new GregorianCalendar();
calendar.clear();
calendar.setTime(new Date(availableInterval.start));
int startYear = calendar.get(Calendar.YEAR);
int startMonth = calendar.get(Calendar.MONTH);
calendar.clear();
calendar.set(startYear, startMonth, 1);
if (!availableInterval.containsPointInclusive(calendar.getTime().getTime())) {
calendar.add(Calendar.MONTH, 1);
}
startYear = calendar.get(Calendar.YEAR);
startMonth = calendar.get(Calendar.MONTH);
calendar.clear();
calendar.setTime(new Date(availableInterval.end));
final int endYear = calendar.get(Calendar.YEAR);
final int endMonth = calendar.get(Calendar.MONTH);
final int yearDifference = endYear - startYear;
final int monthDifference = endMonth - startMonth;
final int numberOfMonths = monthDifference > 0 ? yearDifference * 12 + monthDifference + 1 : yearDifference * 12 - monthDifference + 1;
final int tickCount = Math.min(numberOfMonths, maxTicks);
final double ratioMonth = Math.ceil((double) numberOfMonths / (double) tickCount);
for (int i = 0; i < maxTicks; ++i) {
calendar.clear();
calendar.set(startYear, startMonth, 1);
calendar.add(Calendar.MONTH, (int) (i * ratioMonth));
final String tickText = DrawConstants.MONTH_YEAR_TIME_FORMAT.format(calendar.getTime());
drawLabel(g, availableInterval, selectedInterval, tickText, availableIntervalWidth, calendar.getTime().getTime(), ratioX);
}
}
private void drawLabelsYear(Graphics2D g, Interval availableInterval, Interval selectedInterval, final int maxTicks, final int availableIntervalWidth, final double ratioX) {
final Calendar calendar = new GregorianCalendar();
calendar.clear();
calendar.setTime(new Date(availableInterval.start));
int startYear = calendar.get(Calendar.YEAR);
calendar.clear();
calendar.set(startYear, 0, 1);
if (!availableInterval.containsPointInclusive(calendar.getTime().getTime())) {
startYear++;
}
calendar.clear();
calendar.setTime(new Date(availableInterval.end));
int endYear = calendar.get(Calendar.YEAR);
final int hticks = Math.min(Math.max(endYear - startYear + 1, 2), maxTicks);
final int yearDifference = (endYear - startYear) / (hticks - 1);
for (int i = 0; i < hticks; ++i) {
calendar.clear();
calendar.set(startYear + i * yearDifference, 0, 1);
final String tickText = DrawConstants.YEAR_ONLY_TIME_FORMAT.format(calendar.getTime());
drawLabel(g, availableInterval, selectedInterval, tickText, availableIntervalWidth, calendar.getTime().getTime(), ratioX);
}
}
private void drawLabel(Graphics2D g, Interval availableInterval, Interval selectedInterval, final String tickText, final int availableIntervalWidth, final long date, final double ratioX) {
final int textWidth = (int) g.getFontMetrics().getStringBounds(tickText, g).getWidth();
final int x = DrawConstants.GRAPH_LEFT_SPACE + (int) ((date - availableInterval.start) * ratioX);
if (selectedInterval.containsPointInclusive(date)) {
g.setColor(DrawConstants.AVAILABLE_INTERVAL_BACKGROUND_COLOR);
} else {
g.setColor(DrawConstants.SELECTED_INTERVAL_BACKGROUND_COLOR);
}
g.drawLine(x, 2, x, getHeight() - 1);
g.setColor(DrawConstants.LABEL_TEXT_COLOR);
if (x + textWidth > DrawConstants.GRAPH_LEFT_SPACE + availableIntervalWidth) {
if ((x - 2) < DrawConstants.GRAPH_LEFT_SPACE + availableIntervalWidth) {
g.drawString(tickText, x - 2 - textWidth, getHeight() - 5);
}
} else {
g.drawString(tickText, x + 2, getHeight() - 5);
}
}
private void moveSelectedInterval(final Point newMousePosition, boolean forced) {
if (mousePressed != null) {
final int diffPixel = mousePressed.x > newMousePosition.x ? mousePressed.x - newMousePosition.x : newMousePosition.x - mousePressed.x;
final double intervalWidthPixel = (1. * rightIntervalBorderPosition - leftIntervalBorderPosition);
if (mousePressed.x > newMousePosition.x) {
drawController.moveTime(-diffPixel / intervalWidthPixel);
} else {
drawController.moveTime(diffPixel / intervalWidthPixel);
}
mousePressed = newMousePosition;
}
}
// Zoom Controller Listener
@Override
public void availableIntervalChanged() {
}
@Override
public void selectedIntervalChanged(boolean keepFullValueRange) {
repaint();
}
// Mouse Listener
@Override
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
if (p.x >= DrawConstants.GRAPH_LEFT_SPACE && p.x <= getWidth() - DrawConstants.GRAPH_RIGHT_SPACE) {
mousePressed = new Point(leftIntervalBorderPosition + (rightIntervalBorderPosition - leftIntervalBorderPosition) / 2, 0);
moveSelectedInterval(p, true);
mousePressed = null;
}
} else if ((e.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) {
jumpSelectedInterval(p);
}
}
private void jumpSelectedInterval(Point point) {
final double intervalWidthPixel = (1. * rightIntervalBorderPosition - leftIntervalBorderPosition);
double middle = leftIntervalBorderPosition + 0.5 * intervalWidthPixel;
double distance = point.getX() - middle;
drawController.moveTime(distance);
}
@Override
public void mouseEntered(MouseEvent e) {
Point p = e.getPoint();
if (p.x >= DrawConstants.GRAPH_LEFT_SPACE && p.x <= getWidth() - DrawConstants.GRAPH_RIGHT_SPACE) {
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
} else {
setCursor(Cursor.getDefaultCursor());
}
repaint();
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
mousePressed = e.getPoint();
if (mouseOverInterval) {
setCursor(UIGlobals.closedHandCursor);
}
}
@Override
public void mouseReleased(MouseEvent e) {
Point p = e.getPoint();
eveState.setMouseTimeIntervalDragging(false);
if (mouseOverInterval) {
moveSelectedInterval(p, true);
setCursor(UIGlobals.openHandCursor);
}
mousePressed = null;
repaint();
}
// Mouse Motion Listener
@Override
public void mouseDragged(MouseEvent e) {
eveState.setMouseTimeIntervalDragging(true);
if (mouseOverInterval) {
moveSelectedInterval(e.getPoint(), false);
}
}
@Override
public void mouseMoved(MouseEvent e) {
Point p = e.getPoint();
mouseOverInterval = false;
// is mouse cursor above selected interval?
if (p.x >= leftIntervalBorderPosition && p.x <= rightIntervalBorderPosition) {
mouseOverInterval = true;
setCursor(UIGlobals.openHandCursor);
}
// reset cursor if it does not point to the interval area
if (!mouseOverInterval) {
if (p.x >= DrawConstants.GRAPH_LEFT_SPACE && p.x <= getWidth() - DrawConstants.GRAPH_RIGHT_SPACE) {
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
} else {
setCursor(Cursor.getDefaultCursor());
}
}
}
// Layers Listener
@Override
public void layerAdded(View view) {
}
@Override
public void activeLayerChanged(View view) {
if (view != null) {
movieInterval = new Interval(view.getFirstTime().milli, view.getLastTime().milli);
repaint();
}
}
}
| src/plugins/jhv-eveplugin/src/org/helioviewer/jhv/plugins/eveplugin/view/chart/ChartDrawIntervalPane.java | package org.helioviewer.jhv.plugins.eveplugin.view.chart;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.RoundRectangle2D;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.JComponent;
import javax.swing.event.MouseInputListener;
import org.helioviewer.jhv.base.interval.Interval;
import org.helioviewer.jhv.base.time.TimeUtils;
import org.helioviewer.jhv.gui.UIGlobals;
import org.helioviewer.jhv.layers.Layers;
import org.helioviewer.jhv.layers.LayersListener;
import org.helioviewer.jhv.plugins.eveplugin.DrawConstants;
import org.helioviewer.jhv.plugins.eveplugin.EVEState;
import org.helioviewer.jhv.plugins.eveplugin.draw.DrawController;
import org.helioviewer.jhv.plugins.eveplugin.draw.TimingListener;
import org.helioviewer.jhv.viewmodel.view.View;
// Class will not be serialized so we suppress the warnings
@SuppressWarnings("serial")
public class ChartDrawIntervalPane extends JComponent implements TimingListener, MouseInputListener, LayersListener {
private Interval movieInterval;
private boolean mouseOverInterval = true;
// private boolean mouseOverLeftGraspPoint = false;
// private boolean mouseOverRightGraspPoint = false;
private Point mousePressed = null;
private int leftIntervalBorderPosition = -10;
private int rightIntervalBorderPosition = -10;
private final DrawController drawController;
private final EVEState eveState;
public ChartDrawIntervalPane() {
initVisualComponents();
addMouseListener(this);
addMouseMotionListener(this);
Layers.addLayersListener(this);
drawController = DrawController.getSingletonInstance();
drawController.addTimingListener(this);
eveState = EVEState.getSingletonInstance();
}
private void initVisualComponents() {
setPreferredSize(new Dimension(getPreferredSize().width, DrawConstants.INTERVAL_SELECTION_HEIGHT));
setSize(getPreferredSize());
}
@Override
protected void paintComponent(Graphics g1) {
super.paintComponent(g1);
Graphics2D g = (Graphics2D) g1;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setFont(DrawConstants.font);
drawBackground(g);
Interval availableInterval = DrawController.getSingletonInstance().getAvailableInterval();
Interval selectedInterval = DrawController.getSingletonInstance().getSelectedInterval();
if (availableInterval != null && selectedInterval != null) {
computeIntervalBorderPositions(availableInterval, selectedInterval);
drawIntervalBackground(g);
drawInterval(g);
drawMovieInterval(g, availableInterval);
drawLabels(g, availableInterval, selectedInterval);
drawBorders(g);
drawIntervalGraspPoints(g);
drawIntervalHBar(g);
}
}
private void drawIntervalBackground(Graphics2D g) {
g.setColor(DrawConstants.SELECTED_INTERVAL_BACKGROUND_COLOR);
g.fillRect(leftIntervalBorderPosition - 1, 0, rightIntervalBorderPosition - leftIntervalBorderPosition, getHeight() - 3);
}
private void computeIntervalBorderPositions(Interval availableInterval, Interval selectedInterval) {
final double diffMin = (availableInterval.end - availableInterval.start) / 60000.0;
long start = selectedInterval.start - availableInterval.start;
start = Math.round(start / 60000.0);
long end = selectedInterval.end - availableInterval.start;
end = Math.round(end / 60000.0);
final int availableIntervalSpace = getWidth() - (DrawConstants.GRAPH_LEFT_SPACE + DrawConstants.GRAPH_RIGHT_SPACE + DrawConstants.RANGE_SELECTION_WIDTH) - 1;
leftIntervalBorderPosition = (int) ((start / diffMin) * availableIntervalSpace) + DrawConstants.GRAPH_LEFT_SPACE;
rightIntervalBorderPosition = (int) ((end / diffMin) * availableIntervalSpace) + DrawConstants.GRAPH_LEFT_SPACE;
}
private void drawBackground(Graphics2D g) {
final int availableIntervalSpace = getWidth() - (DrawConstants.GRAPH_LEFT_SPACE + DrawConstants.GRAPH_RIGHT_SPACE + DrawConstants.RANGE_SELECTION_WIDTH) - 1;
g.setColor(DrawConstants.AVAILABLE_INTERVAL_BACKGROUND_COLOR);
g.fillRect(DrawConstants.GRAPH_LEFT_SPACE, 2, availableIntervalSpace, getHeight() - 3);
}
private void drawInterval(Graphics2D g) {
// final int availableIntervalSpace = getWidth() -
// (DrawConstants.GRAPH_LEFT_SPACE + DrawConstants.GRAPH_RIGHT_SPACE +
// DrawConstants.RANGE_SELECTION_WIDTH) - 1;
g.setColor(Color.black);
g.fillRect(leftIntervalBorderPosition, getHeight() - 2, rightIntervalBorderPosition - leftIntervalBorderPosition, 2);
g.setColor(DrawConstants.BORDER_COLOR);
g.fillRect(leftIntervalBorderPosition, 0, rightIntervalBorderPosition - leftIntervalBorderPosition, 1);
}
private void drawMovieInterval(Graphics2D g, Interval availableInterval) {
if (availableInterval == null || movieInterval == null) {
return;
}
if (movieInterval.end < availableInterval.start || movieInterval.start > availableInterval.end) {
return;
}
final int availableIntervalWidth = getWidth() - (DrawConstants.GRAPH_LEFT_SPACE + DrawConstants.GRAPH_RIGHT_SPACE + DrawConstants.RANGE_SELECTION_WIDTH) - 1;
final double ratioX = availableIntervalWidth / (double) (availableInterval.end - availableInterval.start);
int min = DrawConstants.GRAPH_LEFT_SPACE;
if (availableInterval.containsPointInclusive(movieInterval.start)) {
min += (int) ((movieInterval.start - availableInterval.start) * ratioX);
}
int max = DrawConstants.GRAPH_LEFT_SPACE + availableIntervalWidth;
if (availableInterval.containsPointInclusive(movieInterval.end)) {
max = DrawConstants.GRAPH_LEFT_SPACE + (int) ((movieInterval.end - availableInterval.start) * ratioX);
}
int offset = 7;
g.setColor(DrawConstants.MOVIE_INTERVAL_COLOR);
g.drawLine(min, offset, max, offset);
g.drawLine(min, offset + 2, max, offset + 2);
g.drawLine(min, offset + 9, max, offset + 9);
g.drawLine(min, offset + 11, max, offset + 11);
for (int x = min; x <= max; ++x) {
final int mod4 = (x - min) % 4;
final int mod12 = (x - min) % 12;
if (mod4 == 0) {
final int width = 1;
if (mod12 == 0) {
g.fillRect(x, offset + 1, width, 10);
} else {
g.fillRect(x, offset + 1, width, 2);
g.fillRect(x, offset + 9, width, 2);
}
}
}
}
private void drawBorders(Graphics2D g) {
g.setColor(DrawConstants.BORDER_COLOR);
}
private void drawIntervalGraspPoints(Graphics2D g) {
g.setColor(Color.BLACK);
g.fill(new RoundRectangle2D.Double(leftIntervalBorderPosition - 1, 0, 2, getHeight(), 5, 5));
g.fill(new RoundRectangle2D.Double(rightIntervalBorderPosition - 1, 0, 2, getHeight(), 5, 5));
}
private void drawIntervalHBar(Graphics2D g) {
g.setColor(Color.BLACK);
g.fill(new RoundRectangle2D.Double(DrawConstants.GRAPH_LEFT_SPACE, 0, leftIntervalBorderPosition - DrawConstants.GRAPH_LEFT_SPACE, 2, 5, 5));
g.fill(new RoundRectangle2D.Double(rightIntervalBorderPosition, 0, getWidth() - rightIntervalBorderPosition - DrawConstants.GRAPH_RIGHT_SPACE, 2, 5, 5));
}
private void drawLabels(Graphics2D g, Interval availableInterval, Interval selectedInterval) {
if (availableInterval.start > availableInterval.end) {
return;
}
final int tickTextWidth = (int) g.getFontMetrics().getStringBounds(DrawConstants.FULL_DATE_TIME_FORMAT.format(new Date()), g).getWidth();
final int availableIntervalWidth = getWidth() - (DrawConstants.GRAPH_LEFT_SPACE + DrawConstants.GRAPH_RIGHT_SPACE + DrawConstants.RANGE_SELECTION_WIDTH) - 1;
final int maxTicks = Math.max(2, (availableIntervalWidth - tickTextWidth * 2) / tickTextWidth);
final double ratioX = availableIntervalWidth / (double) (availableInterval.end - availableInterval.start);
if (availableInterval.containsPointInclusive(availableInterval.start + TimeUtils.DAY_IN_MILLIS * 366 * 3)) {
drawLabelsYear(g, availableInterval, selectedInterval, maxTicks, availableIntervalWidth, ratioX);
return;
}
if (availableInterval.containsPointInclusive(availableInterval.start + TimeUtils.DAY_IN_MILLIS * 31 * 3)) {
drawLabelsMonth(g, availableInterval, selectedInterval, maxTicks, availableIntervalWidth, ratioX);
return;
}
if (availableInterval.containsPointInclusive(availableInterval.start + TimeUtils.DAY_IN_MILLIS * 3)) {
drawLabelsDay(g, availableInterval, selectedInterval, maxTicks, availableIntervalWidth, ratioX);
return;
}
drawLabelsTime(g, availableInterval, selectedInterval, maxTicks, availableIntervalWidth, ratioX);
}
private void drawLabelsTime(Graphics2D g, Interval availableInterval, Interval selectedInterval, final int maxTicks, final int availableIntervalWidth, final double ratioX) {
final long timeDiff = availableInterval.end - availableInterval.start;
final double ratioTime = timeDiff / (double) maxTicks;
int day = -1;
GregorianCalendar tickGreg = new GregorianCalendar();
String tickText;
for (int i = 0; i < maxTicks; ++i) {
final Date tickValue = new Date(availableInterval.start + (long) (i * ratioTime));
tickGreg.setTime(tickValue);
int currentday = tickGreg.get(GregorianCalendar.DAY_OF_MONTH);
if (day != currentday) {
tickText = DrawConstants.FULL_DATE_TIME_FORMAT_NO_SEC.format(tickValue);
day = currentday;
} else {
tickText = DrawConstants.HOUR_TIME_FORMAT_NO_SEC.format(tickValue);
}
drawLabel(g, availableInterval, selectedInterval, tickText, availableIntervalWidth, tickValue.getTime(), ratioX);
}
}
private void drawLabelsDay(Graphics2D g, Interval availableInterval, Interval selectedInterval, final int maxTicks, final int availableIntervalWidth, final double ratioX) {
final Calendar calendar = new GregorianCalendar();
calendar.clear();
calendar.setTime(new Date(availableInterval.start));
int startYear = calendar.get(Calendar.YEAR);
int startMonth = calendar.get(Calendar.MONTH);
int startDay = calendar.get(Calendar.DAY_OF_MONTH);
calendar.clear();
calendar.set(startYear, startMonth, startDay);
if (!availableInterval.containsPointInclusive(calendar.getTime().getTime())) {
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
startYear = calendar.get(Calendar.YEAR);
startMonth = calendar.get(Calendar.MONTH);
startDay = calendar.get(Calendar.DAY_OF_MONTH);
final long diffMillis = availableInterval.end - calendar.getTimeInMillis();
final int numberOfDays = (int) Math.round(diffMillis / (1000. * 60. * 60. * 24.));
final int tickCount = Math.min(numberOfDays, maxTicks);
final double ratioDays = Math.ceil((double) numberOfDays / (double) tickCount);
for (int i = 0; i < maxTicks; ++i) {
calendar.clear();
calendar.set(startYear, startMonth, startDay);
calendar.add(Calendar.DAY_OF_MONTH, (int) (i * ratioDays));
final String tickText = DrawConstants.DAY_MONTH_YEAR_TIME_FORMAT.format(calendar.getTime());
drawLabel(g, availableInterval, selectedInterval, tickText, availableIntervalWidth, calendar.getTime().getTime(), ratioX);
}
}
private void drawLabelsMonth(Graphics2D g, Interval availableInterval, Interval selectedInterval, final int maxTicks, final int availableIntervalWidth, final double ratioX) {
final Calendar calendar = new GregorianCalendar();
calendar.clear();
calendar.setTime(new Date(availableInterval.start));
int startYear = calendar.get(Calendar.YEAR);
int startMonth = calendar.get(Calendar.MONTH);
calendar.clear();
calendar.set(startYear, startMonth, 1);
if (!availableInterval.containsPointInclusive(calendar.getTime().getTime())) {
calendar.add(Calendar.MONTH, 1);
}
startYear = calendar.get(Calendar.YEAR);
startMonth = calendar.get(Calendar.MONTH);
calendar.clear();
calendar.setTime(new Date(availableInterval.end));
final int endYear = calendar.get(Calendar.YEAR);
final int endMonth = calendar.get(Calendar.MONTH);
final int yearDifference = endYear - startYear;
final int monthDifference = endMonth - startMonth;
final int numberOfMonths = monthDifference > 0 ? yearDifference * 12 + monthDifference + 1 : yearDifference * 12 - monthDifference + 1;
final int tickCount = Math.min(numberOfMonths, maxTicks);
final double ratioMonth = Math.ceil((double) numberOfMonths / (double) tickCount);
for (int i = 0; i < maxTicks; ++i) {
calendar.clear();
calendar.set(startYear, startMonth, 1);
calendar.add(Calendar.MONTH, (int) (i * ratioMonth));
final String tickText = DrawConstants.MONTH_YEAR_TIME_FORMAT.format(calendar.getTime());
drawLabel(g, availableInterval, selectedInterval, tickText, availableIntervalWidth, calendar.getTime().getTime(), ratioX);
}
}
private void drawLabelsYear(Graphics2D g, Interval availableInterval, Interval selectedInterval, final int maxTicks, final int availableIntervalWidth, final double ratioX) {
final Calendar calendar = new GregorianCalendar();
calendar.clear();
calendar.setTime(new Date(availableInterval.start));
int startYear = calendar.get(Calendar.YEAR);
calendar.clear();
calendar.set(startYear, 0, 1);
if (!availableInterval.containsPointInclusive(calendar.getTime().getTime())) {
startYear++;
}
calendar.clear();
calendar.setTime(new Date(availableInterval.end));
int endYear = calendar.get(Calendar.YEAR);
final int hticks = Math.min(Math.max(endYear - startYear + 1, 2), maxTicks);
final int yearDifference = (endYear - startYear) / (hticks - 1);
for (int i = 0; i < hticks; ++i) {
calendar.clear();
calendar.set(startYear + i * yearDifference, 0, 1);
final String tickText = DrawConstants.YEAR_ONLY_TIME_FORMAT.format(calendar.getTime());
drawLabel(g, availableInterval, selectedInterval, tickText, availableIntervalWidth, calendar.getTime().getTime(), ratioX);
}
}
private void drawLabel(Graphics2D g, Interval availableInterval, Interval selectedInterval, final String tickText, final int availableIntervalWidth, final long date, final double ratioX) {
final int textWidth = (int) g.getFontMetrics().getStringBounds(tickText, g).getWidth();
final int x = DrawConstants.GRAPH_LEFT_SPACE + (int) ((date - availableInterval.start) * ratioX);
if (selectedInterval.containsPointInclusive(date)) {
g.setColor(DrawConstants.AVAILABLE_INTERVAL_BACKGROUND_COLOR);
} else {
g.setColor(DrawConstants.SELECTED_INTERVAL_BACKGROUND_COLOR);
}
g.drawLine(x, 2, x, getHeight() - 1);
g.setColor(DrawConstants.LABEL_TEXT_COLOR);
if (x + textWidth > DrawConstants.GRAPH_LEFT_SPACE + availableIntervalWidth) {
if ((x - 2) < DrawConstants.GRAPH_LEFT_SPACE + availableIntervalWidth) {
g.drawString(tickText, x - 2 - textWidth, getHeight() - 5);
}
} else {
g.drawString(tickText, x + 2, getHeight() - 5);
}
}
private void moveSelectedInterval(final Point newMousePosition, boolean forced) {
if (mousePressed != null) {
final int diffPixel = mousePressed.x > newMousePosition.x ? mousePressed.x - newMousePosition.x : newMousePosition.x - mousePressed.x;
final double availableIntervalSpace = getWidth() - (DrawConstants.GRAPH_LEFT_SPACE + DrawConstants.GRAPH_RIGHT_SPACE + DrawConstants.RANGE_SELECTION_WIDTH) - 1.0;
final double movedUnits = diffPixel / availableIntervalSpace;
final double intervalWidthPixel = (1. * leftIntervalBorderPosition / rightIntervalBorderPosition);
if (mousePressed.x > newMousePosition.x) {
drawController.moveTime(-movedUnits / intervalWidthPixel);
} else {
drawController.moveTime(-movedUnits / intervalWidthPixel);
}
mousePressed = newMousePosition;
}
}
// Zoom Controller Listener
@Override
public void availableIntervalChanged() {
}
@Override
public void selectedIntervalChanged(boolean keepFullValueRange) {
repaint();
}
// Mouse Listener
@Override
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
if (p.x >= DrawConstants.GRAPH_LEFT_SPACE && p.x <= getWidth() - DrawConstants.GRAPH_RIGHT_SPACE) {
mousePressed = new Point(leftIntervalBorderPosition + (rightIntervalBorderPosition - leftIntervalBorderPosition) / 2, 0);
moveSelectedInterval(p, true);
mousePressed = null;
}
} else if ((e.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) {
jumpSelectedInterval(p);
}
}
private void jumpSelectedInterval(Point point) {
final double availableIntervalSpace = getWidth() - (DrawConstants.GRAPH_LEFT_SPACE + DrawConstants.GRAPH_RIGHT_SPACE + DrawConstants.RANGE_SELECTION_WIDTH) - 1.0;
final double position = (point.getX() - DrawConstants.GRAPH_LEFT_SPACE) / availableIntervalSpace;
double middlePosition = drawController.getScaledSelectedMinTime() + drawController.getScaledSelectedMaxTime() - drawController.getScaledSelectedMinTime();
double start;
double end;
if (position <= middlePosition) {
// jump to left
start = drawController.getScaledSelectedMinTime() - (drawController.getScaledSelectedMaxTime() - drawController.getScaledSelectedMinTime());
end = drawController.getScaledSelectedMaxTime() - (drawController.getScaledSelectedMaxTime() - drawController.getScaledSelectedMinTime());
if (start < drawController.getScaledMinTime()) {
end += (drawController.getScaledMinTime() - start);
start = drawController.getScaledMinTime();
}
} else {
// jump to right
start = drawController.getScaledSelectedMinTime() + (drawController.getScaledSelectedMaxTime() - drawController.getScaledSelectedMinTime());
end = drawController.getScaledSelectedMaxTime() + (drawController.getScaledSelectedMaxTime() - drawController.getScaledSelectedMinTime());
if (end > drawController.getScaledMaxTime()) {
start -= (end - drawController.getScaledMaxTime());
end = drawController.getScaledMaxTime();
}
}
if (drawController.minMaxTimeIntervalContainsTime(start)) {
drawController.setScaledSelectedTime(start, end, true);
}
}
@Override
public void mouseEntered(MouseEvent e) {
Point p = e.getPoint();
if (p.x >= DrawConstants.GRAPH_LEFT_SPACE && p.x <= getWidth() - DrawConstants.GRAPH_RIGHT_SPACE) {
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
} else {
setCursor(Cursor.getDefaultCursor());
}
repaint();
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
mousePressed = e.getPoint();
if (mouseOverInterval) {
setCursor(UIGlobals.closedHandCursor);
}
}
@Override
public void mouseReleased(MouseEvent e) {
Point p = e.getPoint();
eveState.setMouseTimeIntervalDragging(false);
if (mouseOverInterval) {
moveSelectedInterval(p, true);
setCursor(UIGlobals.openHandCursor);
}
mousePressed = null;
repaint();
}
// Mouse Motion Listener
@Override
public void mouseDragged(MouseEvent e) {
eveState.setMouseTimeIntervalDragging(true);
if (mouseOverInterval) {
moveSelectedInterval(e.getPoint(), false);
}
}
@Override
public void mouseMoved(MouseEvent e) {
Point p = e.getPoint();
mouseOverInterval = false;
// is mouse cursor above selected interval?
if (p.x >= leftIntervalBorderPosition && p.x <= rightIntervalBorderPosition) {
mouseOverInterval = true;
setCursor(UIGlobals.openHandCursor);
}
// reset cursor if it does not point to the interval area
if (!mouseOverInterval) {
if (p.x >= DrawConstants.GRAPH_LEFT_SPACE && p.x <= getWidth() - DrawConstants.GRAPH_RIGHT_SPACE) {
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
} else {
setCursor(Cursor.getDefaultCursor());
}
}
}
// Layers Listener
@Override
public void layerAdded(View view) {
}
@Override
public void activeLayerChanged(View view) {
if (view != null) {
movieInterval = new Interval(view.getFirstTime().milli, view.getLastTime().milli);
repaint();
}
}
}
| let the jump and move selected interval use the move time from draw controller
git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@7016 b4e469a2-07ce-4b26-9273-4d7d95a670c7
| src/plugins/jhv-eveplugin/src/org/helioviewer/jhv/plugins/eveplugin/view/chart/ChartDrawIntervalPane.java | let the jump and move selected interval use the move time from draw controller |
|
Java | agpl-3.0 | 16e6d42967de2a7b6a610b846a23c28ba97c838f | 0 | imCodePartnerAB/imcms,imCodePartnerAB/imcms,imCodePartnerAB/imcms | package com.imcode.imcms.domain.service.api;
import com.imcode.imcms.domain.dto.MenuDTO;
import com.imcode.imcms.domain.dto.MenuItemDTO;
import com.imcode.imcms.domain.exception.SortNotSupportedException;
import com.imcode.imcms.domain.service.AbstractVersionedContentService;
import com.imcode.imcms.domain.service.CommonContentService;
import com.imcode.imcms.domain.service.DocumentMenuService;
import com.imcode.imcms.domain.service.IdDeleterMenuService;
import com.imcode.imcms.domain.service.LanguageService;
import com.imcode.imcms.domain.service.VersionService;
import com.imcode.imcms.model.CommonContent;
import com.imcode.imcms.model.Language;
import com.imcode.imcms.persistence.entity.Menu;
import com.imcode.imcms.persistence.entity.MenuItem;
import com.imcode.imcms.persistence.entity.Version;
import com.imcode.imcms.persistence.repository.MenuRepository;
import com.imcode.imcms.sorted.TypeSort;
import imcode.server.Imcms;
import imcode.server.user.UserDomainObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import static com.imcode.imcms.persistence.entity.Meta.DisabledLanguageShowMode.SHOW_IN_DEFAULT_LANGUAGE;
@Service
@Transactional
public class DefaultMenuService extends AbstractVersionedContentService<Menu, MenuRepository>
implements IdDeleterMenuService {
private static final String DATA_META_ID_ATTRIBUTE = "data-meta-id";
private static final String DATA_INDEX_ATTRIBUTE = "data-index";
private static final String DATA_TREEKEY_ATTRIBUTE = "data-treekey";
private static final String DATA_LEVEL_ATTRIBUTE = "data-level";
private static final String DATA_SUBLEVELS_ATTRIBUTE = "data-sublvls";
private static final String CLASS_ATTRIBUTE = "class";
private final VersionService versionService;
private final DocumentMenuService documentMenuService;
private final Function<List<MenuItemDTO>, Set<MenuItem>> menuItemDtoListToMenuItemList;
private final BiFunction<Menu, Language, MenuDTO> menuSaver;
private final UnaryOperator<MenuItem> toMenuItemsWithoutId;
private final LanguageService languageService;
private final BiFunction<MenuItem, Language, MenuItemDTO> menuItemToDTO;
private final BiFunction<MenuItem, Language, MenuItemDTO> menuItemToMenuItemDtoWithLang;
private final CommonContentService commonContentService;
private final Function<MenuItemDTO, MenuItem> menuItemDtoToMenuItem;
DefaultMenuService(MenuRepository menuRepository,
VersionService versionService,
DocumentMenuService documentMenuService,
BiFunction<MenuItem, Language, MenuItemDTO> menuItemToDTO,
Function<List<MenuItemDTO>, Set<MenuItem>> menuItemDtoListToMenuItemList,
LanguageService languageService,
BiFunction<Menu, Language, MenuDTO> menuToMenuDTO,
UnaryOperator<MenuItem> toMenuItemsWithoutId,
BiFunction<MenuItem, Language, MenuItemDTO> menuItemToMenuItemDtoWithLang,
CommonContentService commonContentService,
Function<MenuItemDTO, MenuItem> menuItemDtoToMenuItem) {
super(menuRepository);
this.versionService = versionService;
this.documentMenuService = documentMenuService;
this.menuItemToMenuItemDtoWithLang = menuItemToMenuItemDtoWithLang;
this.menuItemDtoListToMenuItemList = menuItemDtoListToMenuItemList;
this.menuItemToDTO = menuItemToDTO;
this.languageService = languageService;
this.toMenuItemsWithoutId = toMenuItemsWithoutId;
this.commonContentService = commonContentService;
this.menuItemDtoToMenuItem = menuItemDtoToMenuItem;
this.menuSaver = (menu, language) -> menuToMenuDTO.apply(menuRepository.save(menu), language);
}
@Override
public List<MenuItemDTO> getMenuItems(int docId, int menuIndex, String language, boolean nested, String typeSort) {
List<MenuItemDTO> menuItemsOf = getMenuItemsOf(menuIndex, docId, MenuItemsStatus.ALL, language, false);
if (typeSort == null) {
if (nested) {
typeSort = String.valueOf(TypeSort.TREE_SORT);
} else {
typeSort = String.valueOf(TypeSort.MANUAL);
}
}
setHasNewerVersionsInItems(menuItemsOf);
if (!nested || !typeSort.equals(String.valueOf(TypeSort.TREE_SORT))) {
convertItemsToFlatList(menuItemsOf);
}
if (!nested && typeSort.equals(String.valueOf(TypeSort.TREE_SORT))) {
throw new SortNotSupportedException("Current sorting don't support in menuIndex: " + menuIndex);
}
return getSortingMenuItemsByTypeSort(typeSort, menuItemsOf);
}
@Override
public List<MenuItemDTO> getSortedMenuItems(MenuDTO menuDTO) {
if (!menuDTO.isNested() && menuDTO.getTypeSort().equals(String.valueOf(TypeSort.TREE_SORT))) {
throw new SortNotSupportedException("Current sorting don't support in flat menu!");
}
if (!menuDTO.isNested() || !menuDTO.getTypeSort().equals(String.valueOf(TypeSort.TREE_SORT))) {
convertItemsToFlatList(menuDTO.getMenuItems());
}
final Language userLanguage = languageService.findByCode(Imcms.getUser().getLanguage());
//double map because from client to fetch itemsDTO which have only doc id and no more info..
final List<MenuItemDTO> menuItemsDTO = menuDTO.getMenuItems().stream()
.map(menuItemDtoToMenuItem)
.map(menuItem -> menuItemToDTO.apply(menuItem, userLanguage))
.collect(Collectors.toList());
setHasNewerVersionsInItems(menuItemsDTO);
return getSortingMenuItemsByTypeSort(menuDTO.getTypeSort(), menuItemsDTO);
}
private void convertItemsToFlatList(List<MenuItemDTO> menuItems) {
final List<MenuItemDTO> childrenMenuItems = new ArrayList<>();
for (MenuItemDTO menuItemDTO : menuItems) {
childrenMenuItems.addAll(getAllNestedMenuItems(menuItemDTO));
}
menuItems.addAll(childrenMenuItems);
}
private List<MenuItemDTO> getSortingMenuItemsByTypeSort(String typeSort, List<MenuItemDTO> menuItems) {
switch (TypeSort.valueOf(typeSort)) {
case TREE_SORT:
return menuItems;
case MANUAL:
return getAndSetUpEmptyChildrenMenuItems(menuItems);
case ALPHABETICAL_ASC:
return getAndSetUpEmptyChildrenMenuItems(menuItems).stream()
.sorted(Comparator.comparing(MenuItemDTO::getTitle,
Comparator.nullsLast(String::compareToIgnoreCase)))
.collect(Collectors.toList());
case ALPHABETICAL_DESC:
return getAndSetUpEmptyChildrenMenuItems(menuItems).stream()
.sorted(Comparator.comparing(MenuItemDTO::getTitle,
Comparator.nullsLast(String::compareToIgnoreCase)).reversed())
.collect(Collectors.toList());
case PUBLISHED_DATE_ASC:
return getAndSetUpEmptyChildrenMenuItems(menuItems).stream()
.sorted(Comparator.comparing(MenuItemDTO::getPublishedDate,
Comparator.nullsLast(Comparator.reverseOrder())))
.collect(Collectors.toList());
case PUBLISHED_DATE_DESC:
return getAndSetUpEmptyChildrenMenuItems(menuItems).stream()
.sorted(Comparator.comparing(MenuItemDTO::getPublishedDate,
Comparator.nullsLast(Comparator.naturalOrder())))
.collect(Collectors.toList());
case MODIFIED_DATE_ASC:
return getAndSetUpEmptyChildrenMenuItems(menuItems).stream()
.sorted(Comparator.comparing(MenuItemDTO::getModifiedDate,
Comparator.nullsLast(Comparator.reverseOrder())))
.collect(Collectors.toList());
case MODIFIED_DATE_DESC:
return getAndSetUpEmptyChildrenMenuItems(menuItems).stream()
.sorted(Comparator.comparing(MenuItemDTO::getModifiedDate,
Comparator.nullsLast(Comparator.naturalOrder())))
.collect(Collectors.toList());
default:
return Collections.EMPTY_LIST;//never come true...
}
}
@Override
public List<MenuItemDTO> getVisibleMenuItems(int docId, int menuIndex, String language, boolean nested) {
List<MenuItemDTO> menuItemsOf = getMenuItemsOf(menuIndex, docId, MenuItemsStatus.ALL, language, true);
if (!nested) {
convertItemsToFlatList(menuItemsOf);
}
setHasNewerVersionsInItems(menuItemsOf);
return !nested ? getAndSetUpEmptyChildrenMenuItems(menuItemsOf) : menuItemsOf;
}
@Override
public List<MenuItemDTO> getPublicMenuItems(int docId, int menuIndex, String language, boolean nested) {
List<MenuItemDTO> menuItemsOf = getMenuItemsOf(menuIndex, docId, MenuItemsStatus.PUBLIC, language, true);
if (!nested) {
convertItemsToFlatList(menuItemsOf);
}
setHasNewerVersionsInItems(menuItemsOf);
return !nested ? getAndSetUpEmptyChildrenMenuItems(menuItemsOf) : menuItemsOf;
}
@Override
public String getVisibleMenuAsHtml(int docId, int menuIndex, String language,
boolean nested, String attributes, String treeKey, String wrap) {
List<MenuItemDTO> menuItemsOf = getMenuItemsOf(menuIndex, docId, MenuItemsStatus.ALL, language, true);
if (!nested) {
convertItemsToFlatList(menuItemsOf);
}
setHasNewerVersionsInItems(menuItemsOf);
return convertToMenuHtml(docId, menuIndex, menuItemsOf, nested, attributes, treeKey, wrap);
}
private String convertToMenuHtml(int docId, int menuIndex, List<MenuItemDTO> menuItemDTOS, boolean nested,
String attributes, String treeKey, String wrap) {
List<MenuItemDTO> menuItems;
String ulTag = "<ul>";
String ulTagClose = "</ul>";
String ulData = "<ul data-menu-index=\"%d\" data-doc-id=\"%d\">";
StringBuilder buildContentMenu = new StringBuilder();
buildContentMenu.append(ulData);
if (nested) {
menuItems = menuItemDTOS;
} else {
menuItems = menuItemDTOS.stream()
.flatMap(MenuItemDTO::flattened)
.collect(Collectors.toList());
}
String[] wrapElements = wrap.split(",");
for (MenuItemDTO menuItemDTO : menuItems) {
if (attributes.contains("data")) {
String contentItemElement = String.format(
"<li %s=\"%d\" %s=\"%d\" %s=\"%s\" %s=\"%d\" %s=\"%s\">%s</li>",
DATA_META_ID_ATTRIBUTE, menuItemDTO.getDocumentId(),
DATA_INDEX_ATTRIBUTE, 1,
DATA_TREEKEY_ATTRIBUTE, treeKey,
DATA_LEVEL_ATTRIBUTE, 1,
DATA_SUBLEVELS_ATTRIBUTE, !menuItemDTO.getChildren().isEmpty(),
menuItemDTO.getTitle()).concat("\n");
buildContentMenu.append(contentItemElement);
if (!menuItemDTO.getChildren().isEmpty()) {
buildChildsContentMenuItem(buildContentMenu, menuItemDTO.getChildren(), treeKey, 0);
}
}
}
buildContentMenu.append(ulTagClose);
return String.format(buildContentMenu.toString(), menuIndex, docId);
}
private String buildChildsContentMenuItem(StringBuilder content, List<MenuItemDTO> childrenItems, String treeKey, int count) {
String ulTagClose = "</ul>";
StringBuilder contentBuilder = new StringBuilder();
int index = 0;
int countCall = count;
for (MenuItemDTO itemDTO : childrenItems) {
if (!itemDTO.getChildren().isEmpty()) {
content.append(String.format(
"<ul><li %s=\"%d\" %s=\"%d\" %s=\"%s\" %s=\"%d\" %s=\"%s\">%s",
DATA_META_ID_ATTRIBUTE, itemDTO.getDocumentId(),
DATA_INDEX_ATTRIBUTE, index,
DATA_TREEKEY_ATTRIBUTE, treeKey,
DATA_LEVEL_ATTRIBUTE, 1,
DATA_SUBLEVELS_ATTRIBUTE, !itemDTO.getChildren().isEmpty(),
itemDTO.getDocumentId()).concat("\n<ul>"));
buildChildsContentMenuItem(content, itemDTO.getChildren(), "20", count++);
} else {
contentBuilder.append(singleBuildContentItem(itemDTO));
}
}
contentBuilder.append(ulTagClose);
content.append(contentBuilder);
return content.toString();
}
private String singleBuildContentItem(MenuItemDTO itemDTO) {
StringBuilder stringBuilder = new StringBuilder();
int index = 0;
stringBuilder.append(String.format(
"<li %s=\"%d\" %s=\"%d\" %s=\"%s\" %s=\"%d\" %s=\"%s\">%s</li>",
DATA_META_ID_ATTRIBUTE, itemDTO.getDocumentId(),
DATA_INDEX_ATTRIBUTE, index,
DATA_TREEKEY_ATTRIBUTE, "k",
DATA_LEVEL_ATTRIBUTE, 1,
DATA_SUBLEVELS_ATTRIBUTE, !itemDTO.getChildren().isEmpty(),
itemDTO.getDocumentId()).concat("\n"));
return stringBuilder.toString();
}
@Override
public String getPublicMenuAsHtml(int docId, int menuIndex, String language,
boolean nested, String attributes, String treeKey, String wrap) {
return null;
}
@Override
public String getVisibleMenuAsHtml(int docId, int menuIndex) {
return null;
}
@Override
public String getPublicMenuAsHtml(int docId, int menuIndex) {
return null;
}
@Override
public MenuDTO saveFrom(MenuDTO menuDTO) {
final Integer docId = menuDTO.getDocId();
final Menu menu = Optional.ofNullable(getMenu(menuDTO.getMenuIndex(), docId))
.orElseGet(() -> createMenu(menuDTO));
menu.setNested(menuDTO.isNested());
menu.setTypeSort(menuDTO.getTypeSort());
menu.setMenuItems(menuItemDtoListToMenuItemList.apply(menuDTO.getMenuItems()));
final MenuDTO savedMenu = menuSaver.apply(menu, languageService.findByCode(Imcms.getUser().getLanguage()));
super.updateWorkingVersion(docId);
return savedMenu;
}
@Override
@Transactional
public void deleteByVersion(Version version) {
repository.deleteByVersion(version);
}
@Override
@Transactional
public void deleteByDocId(Integer docIdToDelete) {
repository.deleteByDocId(docIdToDelete);
}
@Override
public Menu removeId(Menu jpa, Version newVersion) {
final Menu menu = new Menu();
menu.setId(null);
menu.setNo(jpa.getNo());
menu.setVersion(newVersion);
menu.setNested(jpa.isNested());
menu.setTypeSort(jpa.getTypeSort());
final Set<MenuItem> newMenuItems = jpa.getMenuItems()
.stream()
.map(toMenuItemsWithoutId)
.collect(Collectors.toCollection(LinkedHashSet::new));
menu.setMenuItems(newMenuItems);
return menu;
}
private Menu getMenu(int menuNo, int docId) {
final Version workingVersion = versionService.getDocumentWorkingVersion(docId);
return repository.findByNoAndVersionAndFetchMenuItemsEagerly(menuNo, workingVersion);
}
private Menu createMenu(MenuDTO menuDTO) {
final Version workingVersion = versionService.getDocumentWorkingVersion(menuDTO.getDocId());
return createMenu(menuDTO, workingVersion);
}
private Menu createMenu(MenuDTO menuDTO, Version version) {
final Menu menu = new Menu();
menu.setNo(menuDTO.getMenuIndex());
menu.setVersion(version);
return menu;
}
@Override
public List<Menu> getAll() {
return repository.findAll();
}
private List<MenuItemDTO> getMenuItemsOf(
int menuIndex, int docId, MenuItemsStatus status, String langCode, boolean isVisible
) {
final Function<Integer, Version> versionReceiver = MenuItemsStatus.ALL.equals(status)
? versionService::getDocumentWorkingVersion
: versionService::getLatestVersion;
final Version version = versionService.getVersion(docId, versionReceiver);
final Language language = languageService.findByCode(langCode);
final Menu menu = repository.findByNoAndVersionAndFetchMenuItemsEagerly(menuIndex, version);
final UserDomainObject user = Imcms.getUser();
final Function<MenuItem, MenuItemDTO> menuItemFunction = isVisible
? menuItem -> menuItemToMenuItemDtoWithLang.apply(menuItem, language)
: menuItem -> menuItemToDTO.apply(menuItem, language);
return Optional.ofNullable(menu)
.map(Menu::getMenuItems)
.orElseGet(LinkedHashSet::new)
.stream()
.map(menuItemFunction)
.filter(Objects::nonNull)
.filter(menuItemDTO -> (status == MenuItemsStatus.ALL || isPublicMenuItem(menuItemDTO)))
.filter(menuItemDTO -> documentMenuService.hasUserAccessToDoc(menuItemDTO.getDocumentId(), user))
.filter(isMenuItemAccessibleForLang(language, versionReceiver))
.peek(menuItemDTO -> {
if (status == MenuItemsStatus.ALL) return;
final List<MenuItemDTO> children = menuItemDTO.getChildren()
.stream()
.filter(this::isPublicMenuItem)
.collect(Collectors.toList());
menuItemDTO.setChildren(children);
})
.collect(Collectors.toList());
}
private Predicate<MenuItemDTO> isMenuItemAccessibleForLang(Language language, Function<Integer, Version> versionReceiver) {
return menuItemDTO -> {
final int versionNo = versionService.getVersion(menuItemDTO.getDocumentId(), versionReceiver).getNo();
final List<CommonContent> menuItemDocContent = commonContentService.getOrCreateCommonContents(menuItemDTO.getDocumentId(), versionNo);
final List<Language> enabledLanguages = menuItemDocContent.stream()
.filter(item -> item.getLanguage().isEnabled())
.map(CommonContent::getLanguage)
.collect(Collectors.toList());
final boolean isLanguageEnabled = enabledLanguages.contains(language);
final boolean isCurrentLangDefault = language.getCode().equals(Imcms.getServices().getLanguageMapper().getDefaultLanguage());
final boolean isAllowedToShowWithDefaultLanguage = documentMenuService.getDisabledLanguageShowMode(menuItemDTO.getDocumentId()).equals(SHOW_IN_DEFAULT_LANGUAGE);
return isLanguageEnabled || (!isCurrentLangDefault && isAllowedToShowWithDefaultLanguage);
};
}
private boolean isPublicMenuItem(MenuItemDTO menuItemDTO) {
return documentMenuService.isPublicMenuItem(menuItemDTO.getDocumentId());
}
private List<MenuItemDTO> getAllNestedMenuItems(MenuItemDTO menuItemDTO) {
List<MenuItemDTO> nestedMenuItems = new ArrayList<>();
for (MenuItemDTO menuItem : menuItemDTO.getChildren()) {
if (!menuItem.getChildren().isEmpty()) {
nestedMenuItems.add(menuItem);
nestedMenuItems.addAll(getAllNestedMenuItems(menuItem));
} else {
nestedMenuItems.add(menuItem);
}
}
return nestedMenuItems;
}
private List<MenuItemDTO> getAndSetUpEmptyChildrenMenuItems(List<MenuItemDTO> menuItemDTOs) {
return menuItemDTOs.stream()
.peek(menuItem -> {
if (!menuItem.getChildren().isEmpty()) {
menuItem.setChildren(Collections.emptyList());
}
})
.collect(Collectors.toList());
}
// TODO: 27.11.19 maybe need add new column hasNewerVersion jpa in future?
private void setHasNewerVersionsInItems(List<MenuItemDTO> items) {
items.stream()
.flatMap(MenuItemDTO::flattened)
.peek(docItem ->
docItem.setHasNewerVersion(versionService.hasNewerVersion(docItem.getDocumentId()))
);
}
}
| src/main/java/com/imcode/imcms/domain/service/api/DefaultMenuService.java | package com.imcode.imcms.domain.service.api;
import com.imcode.imcms.domain.dto.MenuDTO;
import com.imcode.imcms.domain.dto.MenuItemDTO;
import com.imcode.imcms.domain.exception.SortNotSupportedException;
import com.imcode.imcms.domain.service.AbstractVersionedContentService;
import com.imcode.imcms.domain.service.CommonContentService;
import com.imcode.imcms.domain.service.DocumentMenuService;
import com.imcode.imcms.domain.service.IdDeleterMenuService;
import com.imcode.imcms.domain.service.LanguageService;
import com.imcode.imcms.domain.service.VersionService;
import com.imcode.imcms.model.CommonContent;
import com.imcode.imcms.model.Language;
import com.imcode.imcms.persistence.entity.Menu;
import com.imcode.imcms.persistence.entity.MenuItem;
import com.imcode.imcms.persistence.entity.Version;
import com.imcode.imcms.persistence.repository.MenuRepository;
import com.imcode.imcms.sorted.TypeSort;
import imcode.server.Imcms;
import imcode.server.user.UserDomainObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import static com.imcode.imcms.persistence.entity.Meta.DisabledLanguageShowMode.SHOW_IN_DEFAULT_LANGUAGE;
@Service
@Transactional
public class DefaultMenuService extends AbstractVersionedContentService<Menu, MenuRepository>
implements IdDeleterMenuService {
private final VersionService versionService;
private final DocumentMenuService documentMenuService;
private final Function<List<MenuItemDTO>, Set<MenuItem>> menuItemDtoListToMenuItemList;
private final BiFunction<Menu, Language, MenuDTO> menuSaver;
private final UnaryOperator<MenuItem> toMenuItemsWithoutId;
private final LanguageService languageService;
private final BiFunction<MenuItem, Language, MenuItemDTO> menuItemToDTO;
private final BiFunction<MenuItem, Language, MenuItemDTO> menuItemToMenuItemDtoWithLang;
private final CommonContentService commonContentService;
private final Function<MenuItemDTO, MenuItem> menuItemDtoToMenuItem;
DefaultMenuService(MenuRepository menuRepository,
VersionService versionService,
DocumentMenuService documentMenuService,
BiFunction<MenuItem, Language, MenuItemDTO> menuItemToDTO,
Function<List<MenuItemDTO>, Set<MenuItem>> menuItemDtoListToMenuItemList,
LanguageService languageService,
BiFunction<Menu, Language, MenuDTO> menuToMenuDTO,
UnaryOperator<MenuItem> toMenuItemsWithoutId,
BiFunction<MenuItem, Language, MenuItemDTO> menuItemToMenuItemDtoWithLang,
CommonContentService commonContentService,
Function<MenuItemDTO, MenuItem> menuItemDtoToMenuItem) {
super(menuRepository);
this.versionService = versionService;
this.documentMenuService = documentMenuService;
this.menuItemToMenuItemDtoWithLang = menuItemToMenuItemDtoWithLang;
this.menuItemDtoListToMenuItemList = menuItemDtoListToMenuItemList;
this.menuItemToDTO = menuItemToDTO;
this.languageService = languageService;
this.toMenuItemsWithoutId = toMenuItemsWithoutId;
this.commonContentService = commonContentService;
this.menuItemDtoToMenuItem = menuItemDtoToMenuItem;
this.menuSaver = (menu, language) -> menuToMenuDTO.apply(menuRepository.save(menu), language);
}
@Override
public List<MenuItemDTO> getMenuItems(int docId, int menuIndex, String language, boolean nested, String typeSort) {
List<MenuItemDTO> menuItemsOf = getMenuItemsOf(menuIndex, docId, MenuItemsStatus.ALL, language, false);
if (typeSort == null) {
if (nested) {
typeSort = String.valueOf(TypeSort.TREE_SORT);
} else {
typeSort = String.valueOf(TypeSort.MANUAL);
}
}
setHasNewerVersionsInItems(menuItemsOf);
if (!nested || !typeSort.equals(String.valueOf(TypeSort.TREE_SORT))) {
convertItemsToFlatList(menuItemsOf);
}
if (!nested && typeSort.equals(String.valueOf(TypeSort.TREE_SORT))) {
throw new SortNotSupportedException("Current sorting don't support in menuIndex: " + menuIndex);
}
return getSortingMenuItemsByTypeSort(typeSort, menuItemsOf);
}
@Override
public List<MenuItemDTO> getSortedMenuItems(MenuDTO menuDTO) {
if (!menuDTO.isNested() && menuDTO.getTypeSort().equals(String.valueOf(TypeSort.TREE_SORT))) {
throw new SortNotSupportedException("Current sorting don't support in flat menu!");
}
if (!menuDTO.isNested() || !menuDTO.getTypeSort().equals(String.valueOf(TypeSort.TREE_SORT))) {
convertItemsToFlatList(menuDTO.getMenuItems());
}
final Language userLanguage = languageService.findByCode(Imcms.getUser().getLanguage());
//double map because from client to fetch itemsDTO which have only doc id and no more info..
final List<MenuItemDTO> menuItemsDTO = menuDTO.getMenuItems().stream()
.map(menuItemDtoToMenuItem)
.map(menuItem -> menuItemToDTO.apply(menuItem, userLanguage))
.collect(Collectors.toList());
setHasNewerVersionsInItems(menuItemsDTO);
return getSortingMenuItemsByTypeSort(menuDTO.getTypeSort(), menuItemsDTO);
}
private void convertItemsToFlatList(List<MenuItemDTO> menuItems) {
final List<MenuItemDTO> childrenMenuItems = new ArrayList<>();
for (MenuItemDTO menuItemDTO : menuItems) {
childrenMenuItems.addAll(getAllNestedMenuItems(menuItemDTO));
}
menuItems.addAll(childrenMenuItems);
}
private List<MenuItemDTO> getSortingMenuItemsByTypeSort(String typeSort, List<MenuItemDTO> menuItems) {
switch (TypeSort.valueOf(typeSort)) {
case TREE_SORT:
return menuItems;
case MANUAL:
return getAndSetUpEmptyChildrenMenuItems(menuItems);
case ALPHABETICAL_ASC:
return getAndSetUpEmptyChildrenMenuItems(menuItems).stream()
.sorted(Comparator.comparing(MenuItemDTO::getTitle,
Comparator.nullsLast(String::compareToIgnoreCase)))
.collect(Collectors.toList());
case ALPHABETICAL_DESC:
return getAndSetUpEmptyChildrenMenuItems(menuItems).stream()
.sorted(Comparator.comparing(MenuItemDTO::getTitle,
Comparator.nullsLast(String::compareToIgnoreCase)).reversed())
.collect(Collectors.toList());
case PUBLISHED_DATE_ASC:
return getAndSetUpEmptyChildrenMenuItems(menuItems).stream()
.sorted(Comparator.comparing(MenuItemDTO::getPublishedDate,
Comparator.nullsLast(Comparator.reverseOrder())))
.collect(Collectors.toList());
case PUBLISHED_DATE_DESC:
return getAndSetUpEmptyChildrenMenuItems(menuItems).stream()
.sorted(Comparator.comparing(MenuItemDTO::getPublishedDate,
Comparator.nullsLast(Comparator.naturalOrder())))
.collect(Collectors.toList());
case MODIFIED_DATE_ASC:
return getAndSetUpEmptyChildrenMenuItems(menuItems).stream()
.sorted(Comparator.comparing(MenuItemDTO::getModifiedDate,
Comparator.nullsLast(Comparator.reverseOrder())))
.collect(Collectors.toList());
case MODIFIED_DATE_DESC:
return getAndSetUpEmptyChildrenMenuItems(menuItems).stream()
.sorted(Comparator.comparing(MenuItemDTO::getModifiedDate,
Comparator.nullsLast(Comparator.naturalOrder())))
.collect(Collectors.toList());
default:
return Collections.EMPTY_LIST;//never come true...
}
}
@Override
public List<MenuItemDTO> getVisibleMenuItems(int docId, int menuIndex, String language, boolean nested) {
List<MenuItemDTO> menuItemsOf = getMenuItemsOf(menuIndex, docId, MenuItemsStatus.ALL, language, true);
if (!nested) {
convertItemsToFlatList(menuItemsOf);
}
setHasNewerVersionsInItems(menuItemsOf);
return !nested ? getAndSetUpEmptyChildrenMenuItems(menuItemsOf) : menuItemsOf;
}
@Override
public List<MenuItemDTO> getPublicMenuItems(int docId, int menuIndex, String language, boolean nested) {
List<MenuItemDTO> menuItemsOf = getMenuItemsOf(menuIndex, docId, MenuItemsStatus.PUBLIC, language, true);
if (!nested) {
convertItemsToFlatList(menuItemsOf);
}
setHasNewerVersionsInItems(menuItemsOf);
return !nested ? getAndSetUpEmptyChildrenMenuItems(menuItemsOf) : menuItemsOf;
}
@Override
public MenuDTO saveFrom(MenuDTO menuDTO) {
final Integer docId = menuDTO.getDocId();
final Menu menu = Optional.ofNullable(getMenu(menuDTO.getMenuIndex(), docId))
.orElseGet(() -> createMenu(menuDTO));
menu.setNested(menuDTO.isNested());
menu.setTypeSort(menuDTO.getTypeSort());
menu.setMenuItems(menuItemDtoListToMenuItemList.apply(menuDTO.getMenuItems()));
final MenuDTO savedMenu = menuSaver.apply(menu, languageService.findByCode(Imcms.getUser().getLanguage()));
super.updateWorkingVersion(docId);
return savedMenu;
}
@Override
@Transactional
public void deleteByVersion(Version version) {
repository.deleteByVersion(version);
}
@Override
@Transactional
public void deleteByDocId(Integer docIdToDelete) {
repository.deleteByDocId(docIdToDelete);
}
@Override
public Menu removeId(Menu jpa, Version newVersion) {
final Menu menu = new Menu();
menu.setId(null);
menu.setNo(jpa.getNo());
menu.setVersion(newVersion);
menu.setNested(jpa.isNested());
menu.setTypeSort(jpa.getTypeSort());
final Set<MenuItem> newMenuItems = jpa.getMenuItems()
.stream()
.map(toMenuItemsWithoutId)
.collect(Collectors.toCollection(LinkedHashSet::new));
menu.setMenuItems(newMenuItems);
return menu;
}
private Menu getMenu(int menuNo, int docId) {
final Version workingVersion = versionService.getDocumentWorkingVersion(docId);
return repository.findByNoAndVersionAndFetchMenuItemsEagerly(menuNo, workingVersion);
}
private Menu createMenu(MenuDTO menuDTO) {
final Version workingVersion = versionService.getDocumentWorkingVersion(menuDTO.getDocId());
return createMenu(menuDTO, workingVersion);
}
private Menu createMenu(MenuDTO menuDTO, Version version) {
final Menu menu = new Menu();
menu.setNo(menuDTO.getMenuIndex());
menu.setVersion(version);
return menu;
}
@Override
public List<Menu> getAll() {
return repository.findAll();
}
private List<MenuItemDTO> getMenuItemsOf(
int menuIndex, int docId, MenuItemsStatus status, String langCode, boolean isVisible
) {
final Function<Integer, Version> versionReceiver = MenuItemsStatus.ALL.equals(status)
? versionService::getDocumentWorkingVersion
: versionService::getLatestVersion;
final Version version = versionService.getVersion(docId, versionReceiver);
final Language language = languageService.findByCode(langCode);
final Menu menu = repository.findByNoAndVersionAndFetchMenuItemsEagerly(menuIndex, version);
final UserDomainObject user = Imcms.getUser();
final Function<MenuItem, MenuItemDTO> menuItemFunction = isVisible
? menuItem -> menuItemToMenuItemDtoWithLang.apply(menuItem, language)
: menuItem -> menuItemToDTO.apply(menuItem, language);
return Optional.ofNullable(menu)
.map(Menu::getMenuItems)
.orElseGet(LinkedHashSet::new)
.stream()
.map(menuItemFunction)
.filter(Objects::nonNull)
.filter(menuItemDTO -> (status == MenuItemsStatus.ALL || isPublicMenuItem(menuItemDTO)))
.filter(menuItemDTO -> documentMenuService.hasUserAccessToDoc(menuItemDTO.getDocumentId(), user))
.filter(isMenuItemAccessibleForLang(language, versionReceiver))
.peek(menuItemDTO -> {
if (status == MenuItemsStatus.ALL) return;
final List<MenuItemDTO> children = menuItemDTO.getChildren()
.stream()
.filter(this::isPublicMenuItem)
.collect(Collectors.toList());
menuItemDTO.setChildren(children);
})
.collect(Collectors.toList());
}
private Predicate<MenuItemDTO> isMenuItemAccessibleForLang(Language language, Function<Integer, Version> versionReceiver) {
return menuItemDTO -> {
final int versionNo = versionService.getVersion(menuItemDTO.getDocumentId(), versionReceiver).getNo();
final List<CommonContent> menuItemDocContent = commonContentService.getOrCreateCommonContents(menuItemDTO.getDocumentId(), versionNo);
final List<Language> enabledLanguages = menuItemDocContent.stream()
.filter(item -> item.getLanguage().isEnabled())
.map(CommonContent::getLanguage)
.collect(Collectors.toList());
final boolean isLanguageEnabled = enabledLanguages.contains(language);
final boolean isCurrentLangDefault = language.getCode().equals(Imcms.getServices().getLanguageMapper().getDefaultLanguage());
final boolean isAllowedToShowWithDefaultLanguage = documentMenuService.getDisabledLanguageShowMode(menuItemDTO.getDocumentId()).equals(SHOW_IN_DEFAULT_LANGUAGE);
return isLanguageEnabled || (!isCurrentLangDefault && isAllowedToShowWithDefaultLanguage);
};
}
private boolean isPublicMenuItem(MenuItemDTO menuItemDTO) {
return documentMenuService.isPublicMenuItem(menuItemDTO.getDocumentId());
}
private List<MenuItemDTO> getAllNestedMenuItems(MenuItemDTO menuItemDTO) {
List<MenuItemDTO> nestedMenuItems = new ArrayList<>();
for (MenuItemDTO menuItem : menuItemDTO.getChildren()) {
if (!menuItem.getChildren().isEmpty()) {
nestedMenuItems.add(menuItem);
nestedMenuItems.addAll(getAllNestedMenuItems(menuItem));
} else {
nestedMenuItems.add(menuItem);
}
}
return nestedMenuItems;
}
private List<MenuItemDTO> getAndSetUpEmptyChildrenMenuItems(List<MenuItemDTO> menuItemDTOs) {
return menuItemDTOs.stream()
.peek(menuItem -> {
if (!menuItem.getChildren().isEmpty()) {
menuItem.setChildren(Collections.emptyList());
}
})
.collect(Collectors.toList());
}
// TODO: 27.11.19 maybe need add new column hasNewerVersion jpa in future?
private void setHasNewerVersionsInItems(List<MenuItemDTO> items) {
items.stream()
.flatMap(MenuItemDTO::flattened)
.peek(docItem ->
docItem.setHasNewerVersion(versionService.hasNewerVersion(docItem.getDocumentId()))
);
}
}
| Issue IMCMS-501: Menu - Generated output asHtml()
- Add basic api methods;
- Add api implementation generate visible menu html code;
| src/main/java/com/imcode/imcms/domain/service/api/DefaultMenuService.java | Issue IMCMS-501: Menu - Generated output asHtml() - Add basic api methods; - Add api implementation generate visible menu html code; |
|
Java | agpl-3.0 | 0a034ff1586a06bf5363a209e53ef52960a92fa7 | 0 | OPEN-ENT-NG/vie-scolaire,OPEN-ENT-NG/vie-scolaire,OPEN-ENT-NG/vie-scolaire,OPEN-ENT-NG/vie-scolaire,OPEN-ENT-NG/vie-scolaire,OPEN-ENT-NG/vie-scolaire | /*
* Copyright (c) Région Hauts-de-France, Département 77, CGI, 2016.
*
* This file is part of OPEN ENT NG. OPEN ENT NG is a versatile ENT Project based on the JVM and ENT Core Project.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation (version 3 of the License).
* For the sake of explanation, any module that communicate over native
* Web protocols, such as HTTP, with OPEN ENT NG is outside the scope of this
* license and could be license under its own terms. This is merely considered
* normal use of OPEN ENT NG, and does not fall under the heading of "covered work".
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
package fr.openent.viescolaire.service.impl;
import fr.openent.Viescolaire;
import fr.openent.viescolaire.service.UserService;
import fr.wseduc.webutils.Either;
import io.vertx.core.Handler;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.entcore.common.neo4j.Neo4j;
import org.entcore.common.neo4j.Neo4jResult;
import org.entcore.common.sql.Sql;
import org.entcore.common.sql.SqlResult;
import org.entcore.common.sql.SqlStatementsBuilder;
import org.entcore.common.user.UserInfos;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import static fr.wseduc.webutils.Utils.handlerToAsyncHandler;
/**
* Created by ledunoiss on 08/11/2016.
*/
public class DefaultUserService implements UserService {
private EventBus eb;
private final Neo4j neo4j = Neo4j.getInstance();
public DefaultUserService(EventBus eb) {
this.eb = eb;
}
@Override
public void getUserId(UserInfos user, Handler<Either<String, JsonObject>> handler) {
StringBuilder query = new StringBuilder()
.append("SELECT id FROM " + Viescolaire.VSCO_SCHEMA);
switch (user.getType()) {
case "Teacher":
case "Personnel": {
query.append(".personnel");
}
break;
case "Relative": {
query.append(".parent");
}
break;
case "Student": {
query.append(".eleve");
}
break;
}
query.append(" WHERE fk4j_user_id = ?;");
Sql.getInstance().prepared(query.toString(), new fr.wseduc.webutils.collections.JsonArray().add(user.getUserId()),
SqlResult.validUniqueResultHandler(handler));
}
@Override
public void getStructures(UserInfos user, Handler<Either<String, JsonArray>> handler) {
List<String> structures = user.getStructures();
StringBuilder query = new StringBuilder()
.append("SELECT * FROM " + Viescolaire.VSCO_SCHEMA + ".structure " +
"WHERE structure.fk4j_structure_id IN " + Sql.listPrepared(structures.toArray()));
JsonArray params = new fr.wseduc.webutils.collections.JsonArray();
for (int i = 0; i < structures.size(); i++) {
params.add(structures.get(i));
}
Sql.getInstance().prepared(query.toString(), params, SqlResult.validResultHandler(handler));
}
@Override
public void getClasses(UserInfos user, Handler<Either<String, JsonArray>> handler) {
List<String> classes = user.getClasses();
JsonArray params = new fr.wseduc.webutils.collections.JsonArray();
StringBuilder query = new StringBuilder()
.append("SELECT * FROM " + Viescolaire.VSCO_SCHEMA + ".classe " +
"WHERE classe.fk4j_classe_id IN " + Sql.listPrepared(classes.toArray()));
for (int i = 0; i < classes.size(); i++) {
params.add(classes.get(i));
}
Sql.getInstance().prepared(query.toString(), params, SqlResult.validResultHandler(handler));
}
@Override
public void getMatiere(UserInfos user, Handler<Either<String, JsonArray>> handler) {
StringBuilder query = new StringBuilder();
JsonArray params = new fr.wseduc.webutils.collections.JsonArray();
switch (user.getType()) {
case "Teacher" : {
query.append("SELECT matiere.* " +
"FROM " + Viescolaire.VSCO_SCHEMA + ".matiere " +
"INNER JOIN " + Viescolaire.VSCO_SCHEMA + ".personnel ON (personnel.id = matiere.id_professeur)" +
"WHERE personnel.fk4j_user_id = ?");
params.add(user.getUserId());
}
break;
case "Eleve" : {
List<String> classes = user.getClasses();
query.append("SELECT matiere.* " +
"FROM " + Viescolaire.VSCO_SCHEMA + ".matiere INNER JOIN " + Viescolaire.VSCO_SCHEMA + ".personnel ON (matiere.id_professeur = personnel.id) " +
"INNER JOIN " + Viescolaire.VSCO_SCHEMA + ".rel_personnel_classe ON (personnel.id = rel_personnel_classe.id_personnel) " +
"INNER JOIN " + Viescolaire.VSCO_SCHEMA + ".classe ON (rel_personnel_classe.id_classe = classe.id) " +
"WHERE classe.externalid IN " + Sql.listPrepared(classes.toArray()));
for (int i = 0; i < classes.size(); i++) {
params.add(classes.get(i));
}
}
break;
default : {
handler.handle(new Either.Right<String, JsonArray>(new fr.wseduc.webutils.collections.JsonArray()));
}
}
Sql.getInstance().prepared(query.toString(), params, SqlResult.validResultHandler(handler));
}
@Override
public void getMoyenne(String idEleve, Long[] idDevoirs, final Handler<Either<String, JsonObject>> handler) {
JsonObject action = new JsonObject()
.put("action", "note.getNotesParElevesParDevoirs")
.put("idEleves", new fr.wseduc.webutils.collections.JsonArray().add(idEleve))
.put("idDevoirs", new fr.wseduc.webutils.collections.JsonArray(Arrays.asList(idDevoirs)));
eb.send(Viescolaire.COMPETENCES_BUS_ADDRESS, action, handlerToAsyncHandler(new Handler<Message<JsonObject>>() {
@Override
public void handle(Message<JsonObject> message) {
if ("ok".equals(message.body().getString("status"))) {
JsonArray notes = new fr.wseduc.webutils.collections.JsonArray();
JsonArray listNotes = message.body().getJsonArray("results");
for (int i = 0; i < listNotes.size(); i++) {
JsonObject note = listNotes.getJsonObject(i);
JsonObject noteDevoir = new JsonObject()
.put("valeur", Double.valueOf(note.getString("valeur")))
.put("diviseur", Double.valueOf(note.getString("diviseur")))
.put("ramenerSur", note.getBoolean("ramener_sur"))
.put("coefficient", Double.valueOf(note.getString("coefficient")));
notes.add(noteDevoir);
}
Either<String, JsonObject> result = null;
if (notes.size() > 0) {
JsonObject action = new JsonObject()
.put("action", "note.calculMoyenne")
.put("listeNoteDevoirs", notes)
.put("statistiques", false)
.put("diviseurM", 20);
eb.send(Viescolaire.COMPETENCES_BUS_ADDRESS, action, handlerToAsyncHandler(new Handler<Message<JsonObject>>() {
@Override
public void handle(Message<JsonObject> message) {
Either<String, JsonObject> result = null;
if ("ok".equals(message.body().getString("status"))) {
result = new Either.Right<String, JsonObject>(message.body().getJsonObject("result"));
handler.handle(result);
} else {
result = new Either.Left<>(message.body().getString("message"));
handler.handle(result);
}
}
}));
} else {
result = new Either.Right<>(new JsonObject());
}
handler.handle(result);
} else {
handler.handle(new Either.Left<String, JsonObject>(message.body().getString("message")));
}
}
}));
}
@Override
public void createPersonnesSupp(JsonArray users, Handler<Either<String, JsonObject>> handler) {
SqlStatementsBuilder statements = new SqlStatementsBuilder();
for (Object u : users) {
if (!(u instanceof JsonObject) || !validProfile((JsonObject) u)) {
continue;
}
final JsonObject user = (JsonObject) u;
// Insert user in the right table
String uQuery =
"INSERT INTO " + Viescolaire.VSCO_SCHEMA + ".personnes_supp(id_user, display_name, user_type, " +
"first_name, last_name, delete_date, birth_date) " +
"VALUES (?, ?, ?, ?, ?, to_timestamp(? /1000), ? );";
JsonArray uParams = new fr.wseduc.webutils.collections.JsonArray()
.add(user.getString("id"))
.add(user.getString("displayName"))
.add(user.getString("type"))
.add(user.getString("firstName"))
.add(user.getString("lastName"))
.add(user.getString("deleteDate"))
.add(user.getString("birthDate"));
statements.prepared(uQuery, uParams);
if (user.containsKey("classIds") && user.getJsonArray("classIds").size() > 0) {
formatGroups(user.getJsonArray("classIds"), user.getString("id"), statements,
Viescolaire.CLASSE_TYPE);
}
if (user.containsKey("groupIds") && user.getJsonArray("groupIds").size() > 0) {
formatGroups(user.getJsonArray("groupIds"), user.getString("id"), statements,
Viescolaire.GROUPE_TYPE);
}
if (user.containsKey("structureIds") && user.getJsonArray("structureIds").size() > 0) {
formatStructure(user.getJsonArray("structureIds"), user.getString("id"), statements);
}
}
Sql.getInstance().transaction(statements.build(), SqlResult.validUniqueResultHandler(handler));
}
/**
* Inject creation request in SqlStatementBuilder for every class in ids
* @param ids class ids list
* @param userId user id
* @param statements Sql statement builder
* @param type Group type
*/
private static void formatGroups (JsonArray ids, String userId, SqlStatementsBuilder statements, Integer type) {
for (int i = 0; i < ids.size(); i++) {
String query =
"INSERT INTO " + Viescolaire.VSCO_SCHEMA + ".rel_groupes_personne_supp(id_groupe, id_user, type_groupe) " +
"VALUES (?, ?, ?);";
JsonArray params = new fr.wseduc.webutils.collections.JsonArray()
.add(ids.getString(i))
.add(userId)
.add(type);
statements.prepared(query, params);
}
}
/**
* Return if the user is a valid profile user
* @param user user object
* @return true | false if the profile is a valid profile
*/
private static boolean validProfile (JsonObject user) {
return "Teacher".equals(user.getString("type")) || "Student".equals(user.getString("type"));
}
/**
* Inject creation request in SqlStatementBuilder for every stucture in ids
* @param ids structure ids list
* @param userId user id
* @param statements Sql statement builder
*/
private static void formatStructure (JsonArray ids, String userId, SqlStatementsBuilder statements) {
for (int i = 0; i < ids.size(); i++) {
String query =
"INSERT INTO " + Viescolaire.VSCO_SCHEMA + ".rel_structures_personne_supp(id_structure, id_user) " +
"VALUES (?, ?);";
JsonArray params = new fr.wseduc.webutils.collections.JsonArray()
.add(ids.getString(i))
.add(userId);
statements.prepared(query, params);
}
}
/**
* Recupere les établissements inactifs de l'utilisateur connecté
* @param userInfos : utilisateur connecté
* @param handler handler comportant le resultat
*/
@Override
public void getActivesIDsStructures(UserInfos userInfos, String module,
Handler<Either<String, JsonArray>> handler) {
StringBuilder query =new StringBuilder();
JsonArray params = new fr.wseduc.webutils.collections.JsonArray();
query.append("SELECT id_etablissement ")
.append("FROM "+ module +".etablissements_actifs ")
.append("WHERE id_etablissement IN " + Sql.listPrepared(userInfos.getStructures().toArray()))
.append(" AND actif = TRUE");
for(String idStructure : userInfos.getStructures()){
params.add(idStructure);
}
Sql.getInstance().prepared(query.toString(), params, SqlResult.validResultHandler(handler));
}
/**
* Recupere les établissements inactifs de l'utilisateur connecté
* @param handler handler comportant le resultat
*/
@Override
public void getActivesIDsStructures( String module,
Handler<Either<String, JsonArray>> handler) {
StringBuilder query =new StringBuilder();
JsonArray params = new fr.wseduc.webutils.collections.JsonArray();
query.append("SELECT id_etablissement ")
.append("FROM "+ module +".etablissements_actifs ")
.append("WHERE actif = TRUE");
Sql.getInstance().prepared(query.toString(), params, SqlResult.validResultHandler(handler));
}
/**
* Active un établissement
* @param id : établissement
* @param handler handler comportant le resultat
*/
@Override
public void createActiveStructure (String id, String module, UserInfos user,
Handler<Either<String, JsonArray>> handler) {
SqlStatementsBuilder s = new SqlStatementsBuilder();
JsonObject data = new JsonObject();
String userQuery = "SELECT " + module + ".merge_users(?,?)";
s.prepared(userQuery, (new fr.wseduc.webutils.collections.JsonArray()).add(user.getUserId()).add(user.getUsername()));
data.put("id_etablissement", id);
data.put("actif", true);
s.insert(module + ".etablissements_actifs ", data, "id_etablissement");
Sql.getInstance().transaction(s.build(), SqlResult.validResultHandler(handler));
}
/**
* Supprime un étbalissement actif
* @param id : utilisateur connecté
* @param handler handler comportant le resultat
*/
@Override
public void deleteActiveStructure(String id, String module, Handler<Either<String, JsonArray>> handler) {
String query = "DELETE FROM " + module + ".etablissements_actifs WHERE id_etablissement = ?";
Sql.getInstance().prepared(query, (new fr.wseduc.webutils.collections.JsonArray()).add(Sql.parseId(id)), SqlResult.validResultHandler(handler));
}
@Override
public void getUAI(String idEtabl, Handler<Either<String,JsonObject>> handler){
StringBuilder query= new StringBuilder();
query.append("MATCH(s:Structure) WHERE s.id={id} RETURN s.UAI as uai");
Neo4j.getInstance().execute(query.toString(), new JsonObject().put("id", idEtabl), Neo4jResult.validUniqueResultHandler(handler));
}
@Override
public void getResponsablesEtabl(List<String> idsResponsable, Handler<Either<String,JsonArray>> handler){
StringBuilder query=new StringBuilder();
query.append("MATCH (u:User) WHERE u.id IN {id} RETURN u.externalId as externalId, u.displayName as displayName");
Neo4j.getInstance().execute(query.toString(), new JsonObject().put("id",new fr.wseduc.webutils.collections.JsonArray(idsResponsable)), Neo4jResult.validResultHandler(handler));
}
@Override
public void getElevesRelatives(List<String> idsClass,Handler<Either<String,JsonArray>> handler){
StringBuilder query = new StringBuilder();
JsonObject param = new JsonObject();
query.append("MATCH (c:Class)<-[:DEPENDS]-(:ProfileGroup)<-[:IN]-(u:User {profiles:['Student']})-[:RELATED]-(r:User{profiles:['Relative']}) WHERE c.id IN {idClass}");
query.append(" RETURN u.id as idNeo4j, u.externalId as externalId,u.attachmentId as attachmentId,u.lastName as lastName,u.level as level,u.firstName as firstName,u.relative as relative,");
query.append("r.externalId as externalIdRelative, r.title as civilite, r.lastName as lastNameRelative, r.firstName as firstNameRelative, r.address as address, r.zipCode as zipCode, r.city as city,");
query.append("c.id as idClass, c.name as nameClass, c.externalId as externalIdClass ORDER BY nameClass, lastName");
param.put("idClass", new fr.wseduc.webutils.collections.JsonArray(idsClass));
Neo4j.getInstance().execute(query.toString(), param, Neo4jResult.validResultHandler(handler));
}
@Override
public void getCodeDomaine(String idClass,Handler<Either<String,JsonArray>> handler){
StringBuilder query = new StringBuilder();
query.append("SELECT id_groupe,id as id_domaine, code_domaine as code_domaine ");
query.append("FROM notes.domaines INNER JOIN notes.rel_groupe_cycle ");
query.append("ON notes.domaines.id_cycle= notes.rel_groupe_cycle.id_cycle ");
query.append("WHERE notes.rel_groupe_cycle.id_groupe = ? AND code_domaine IS NOT NULL");
JsonArray params = new fr.wseduc.webutils.collections.JsonArray();
params.add(idClass);
Sql.getInstance().prepared(query.toString(), params, SqlResult.validResultHandler(handler));
}
@Override
public void getResponsablesDirection(String idStructure, Handler<Either<String, JsonArray>> handler) {
String query = "MATCH (u:User{profiles:['Personnel']})-[ADMINISTRATIVE_ATTACHMENT]->(s:Structure {id:{structureId}}) " +
"WHERE ANY(function IN u.functions WHERE function =~ '(?i).*\\\\$DIR\\\\$.*')" +
" RETURN u.id as id, u.displayName as displayName, u.externalId as externalId";
JsonObject param = new JsonObject();
param.put("structureId",idStructure);
Neo4j.getInstance().execute(query,param,Neo4jResult.validResultHandler(handler));
}
/**
* Retourne la liste des enfants pour un utilisateur donné
* @param idUser Id de l'utilisateur
* @param handler Handler comportant le resultat de la requete
*/
@Override
public void getEnfants(String idUser, Handler<Either<String, JsonArray>> handler) {
StringBuilder query = new StringBuilder();
query.append("MATCH (m:User {id: {id}})<-[:RELATED]-(n:User)")
.append("RETURN n.id as id, n.firstName as firstName, n.lastName as lastName, n.level as level, n.classes as classes, n.birthDate as birthDate ORDER BY lastName");
neo4j.execute(query.toString(), new JsonObject().put("id", idUser), Neo4jResult.validResultHandler(handler));
}
/**
* Retourne la liste des personnels pour une liste d'id donnée
*
* @param idPersonnels ids des personnels
* @param handler Handler comportant le resultat de la requete
*/
public void getPersonnels(List<String> idPersonnels, Handler<Either<String, JsonArray>> handler) {
StringBuilder query = new StringBuilder();
query.append("MATCH (u:User)")
.append("WHERE ANY (x IN u.profiles WHERE x IN ['Teacher', 'Personnel']) AND u.id IN {idPersonnel}")
.append("RETURN u.id as id, u.lastName as lastName, u.firstName as firstName, u.emailAcademy as emailAcademy");
neo4j.execute(query.toString(), new JsonObject().put("idPersonnel", new fr.wseduc.webutils.collections.JsonArray(idPersonnels)), Neo4jResult.validResultHandler(handler));
}
@Override
public void list(String structureId, String classId, String groupId,
JsonArray expectedProfiles, String filterActivated, String nameFilter,
UserInfos userInfos, Handler<Either<String, JsonArray>> results) {
JsonObject params = new JsonObject();
String filter = "";
String filterProfile = "WHERE 1=1 ";
String optionalMatch =
"OPTIONAL MATCH u-[:IN]->(:ProfileGroup)-[:DEPENDS]->(class:Class)-[:BELONGS]->(s) " +
"OPTIONAL MATCH u-[:RELATED]->(parent: User) " +
"OPTIONAL MATCH (child: User)-[:RELATED]->u " +
"OPTIONAL MATCH u-[rf:HAS_FUNCTION]->fg-[:CONTAINS_FUNCTION*0..1]->(f:Function) ";
if (expectedProfiles != null && expectedProfiles.size() > 0) {
filterProfile += "AND p.name IN {expectedProfiles} ";
params.put("expectedProfiles", expectedProfiles);
}
if (classId != null && !classId.trim().isEmpty()) {
filter = "(n:Class {id : {classId}})<-[:DEPENDS]-(g:ProfileGroup)<-[:IN]-";
params.put("classId", classId);
} else if (structureId != null && !structureId.trim().isEmpty()) {
filter = "(n:Structure {id : {structureId}})<-[:DEPENDS]-(g:ProfileGroup)<-[:IN]-";
params.put("structureId", structureId);
} else if (groupId != null && !groupId.trim().isEmpty()) {
filter = "(n:Group {id : {groupId}})<-[:IN]-";
params.put("groupId", groupId);
}
String condition = "";
String functionMatch = "WITH u MATCH (s:Structure)<-[:DEPENDS]-(pg:ProfileGroup)-[:HAS_PROFILE]->(p:Profile), u-[:IN]->pg ";
if(nameFilter != null && !nameFilter.trim().isEmpty()){
condition += "AND u.displayName =~ {regex} ";
params.put("regex", "(?i)^.*?" + Pattern.quote(nameFilter.trim()) + ".*?$");
}
if(filterActivated != null){
if("inactive".equals(filterActivated)){
condition += "AND NOT(u.activationCode IS NULL) ";
} else if("active".equals(filterActivated)){
condition += "AND u.activationCode IS NULL ";
}
}
String query =
"MATCH " + filter + "(u:User) " +
functionMatch + filterProfile + condition + optionalMatch +
"RETURN DISTINCT u.id as id, p.name as type, u.externalId as externalId, " +
"u.activationCode as code, u.login as login, u.firstName as firstName, " +
"u.lastName as lastName, u.displayName as displayName, u.source as source, u.attachmentId as attachmentId, " +
"u.birthDate as birthDate, " +
"extract(function IN u.functions | last(split(function, \"$\"))) as aafFunctions, " +
"collect(distinct {id: s.id, name: s.name}) as structures, " +
"collect(distinct {id: class.id, name: class.name}) as allClasses, " +
"collect(distinct [f.externalId, rf.scope]) as functions, " +
"CASE WHEN parent IS NULL THEN [] ELSE collect(distinct {id: parent.id, firstName: parent.firstName, lastName: parent.lastName}) END as parents, " +
"CASE WHEN child IS NULL THEN [] ELSE collect(distinct {id: child.id, firstName: child.firstName, lastName: child.lastName, attachmentId : child.attachmentId }) END as children, " +
"HEAD(COLLECT(distinct parent.externalId)) as parent1ExternalId, " + // Hack for GEPI export
"HEAD(TAIL(COLLECT(distinct parent.externalId))) as parent2ExternalId " + // Hack for GEPI export
"ORDER BY type DESC, displayName ASC ";
neo4j.execute(query, params, Neo4jResult.validResultHandler(results));
}
} | src/main/java/fr/openent/viescolaire/service/impl/DefaultUserService.java | /*
* Copyright (c) Région Hauts-de-France, Département 77, CGI, 2016.
*
* This file is part of OPEN ENT NG. OPEN ENT NG is a versatile ENT Project based on the JVM and ENT Core Project.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation (version 3 of the License).
* For the sake of explanation, any module that communicate over native
* Web protocols, such as HTTP, with OPEN ENT NG is outside the scope of this
* license and could be license under its own terms. This is merely considered
* normal use of OPEN ENT NG, and does not fall under the heading of "covered work".
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
package fr.openent.viescolaire.service.impl;
import fr.openent.Viescolaire;
import fr.openent.viescolaire.service.UserService;
import fr.wseduc.webutils.Either;
import io.vertx.core.Handler;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.entcore.common.neo4j.Neo4j;
import org.entcore.common.neo4j.Neo4jResult;
import org.entcore.common.sql.Sql;
import org.entcore.common.sql.SqlResult;
import org.entcore.common.sql.SqlStatementsBuilder;
import org.entcore.common.user.UserInfos;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import static fr.wseduc.webutils.Utils.handlerToAsyncHandler;
/**
* Created by ledunoiss on 08/11/2016.
*/
public class DefaultUserService implements UserService {
private EventBus eb;
private final Neo4j neo4j = Neo4j.getInstance();
public DefaultUserService(EventBus eb) {
this.eb = eb;
}
@Override
public void getUserId(UserInfos user, Handler<Either<String, JsonObject>> handler) {
StringBuilder query = new StringBuilder()
.append("SELECT id FROM " + Viescolaire.VSCO_SCHEMA);
switch (user.getType()) {
case "Teacher":
case "Personnel": {
query.append(".personnel");
}
break;
case "Relative": {
query.append(".parent");
}
break;
case "Student": {
query.append(".eleve");
}
break;
}
query.append(" WHERE fk4j_user_id = ?;");
Sql.getInstance().prepared(query.toString(), new fr.wseduc.webutils.collections.JsonArray().add(user.getUserId()),
SqlResult.validUniqueResultHandler(handler));
}
@Override
public void getStructures(UserInfos user, Handler<Either<String, JsonArray>> handler) {
List<String> structures = user.getStructures();
StringBuilder query = new StringBuilder()
.append("SELECT * FROM " + Viescolaire.VSCO_SCHEMA + ".structure " +
"WHERE structure.fk4j_structure_id IN " + Sql.listPrepared(structures.toArray()));
JsonArray params = new fr.wseduc.webutils.collections.JsonArray();
for (int i = 0; i < structures.size(); i++) {
params.add(structures.get(i));
}
Sql.getInstance().prepared(query.toString(), params, SqlResult.validResultHandler(handler));
}
@Override
public void getClasses(UserInfos user, Handler<Either<String, JsonArray>> handler) {
List<String> classes = user.getClasses();
JsonArray params = new fr.wseduc.webutils.collections.JsonArray();
StringBuilder query = new StringBuilder()
.append("SELECT * FROM " + Viescolaire.VSCO_SCHEMA + ".classe " +
"WHERE classe.fk4j_classe_id IN " + Sql.listPrepared(classes.toArray()));
for (int i = 0; i < classes.size(); i++) {
params.add(classes.get(i));
}
Sql.getInstance().prepared(query.toString(), params, SqlResult.validResultHandler(handler));
}
@Override
public void getMatiere(UserInfos user, Handler<Either<String, JsonArray>> handler) {
StringBuilder query = new StringBuilder();
JsonArray params = new fr.wseduc.webutils.collections.JsonArray();
switch (user.getType()) {
case "Teacher" : {
query.append("SELECT matiere.* " +
"FROM " + Viescolaire.VSCO_SCHEMA + ".matiere " +
"INNER JOIN " + Viescolaire.VSCO_SCHEMA + ".personnel ON (personnel.id = matiere.id_professeur)" +
"WHERE personnel.fk4j_user_id = ?");
params.add(user.getUserId());
}
break;
case "Eleve" : {
List<String> classes = user.getClasses();
query.append("SELECT matiere.* " +
"FROM " + Viescolaire.VSCO_SCHEMA + ".matiere INNER JOIN " + Viescolaire.VSCO_SCHEMA + ".personnel ON (matiere.id_professeur = personnel.id) " +
"INNER JOIN " + Viescolaire.VSCO_SCHEMA + ".rel_personnel_classe ON (personnel.id = rel_personnel_classe.id_personnel) " +
"INNER JOIN " + Viescolaire.VSCO_SCHEMA + ".classe ON (rel_personnel_classe.id_classe = classe.id) " +
"WHERE classe.externalid IN " + Sql.listPrepared(classes.toArray()));
for (int i = 0; i < classes.size(); i++) {
params.add(classes.get(i));
}
}
break;
default : {
handler.handle(new Either.Right<String, JsonArray>(new fr.wseduc.webutils.collections.JsonArray()));
}
}
Sql.getInstance().prepared(query.toString(), params, SqlResult.validResultHandler(handler));
}
@Override
public void getMoyenne(String idEleve, Long[] idDevoirs, final Handler<Either<String, JsonObject>> handler) {
JsonObject action = new JsonObject()
.put("action", "note.getNotesParElevesParDevoirs")
.put("idEleves", new fr.wseduc.webutils.collections.JsonArray().add(idEleve))
.put("idDevoirs", new fr.wseduc.webutils.collections.JsonArray(Arrays.asList(idDevoirs)));
eb.send(Viescolaire.COMPETENCES_BUS_ADDRESS, action, handlerToAsyncHandler(new Handler<Message<JsonObject>>() {
@Override
public void handle(Message<JsonObject> message) {
if ("ok".equals(message.body().getString("status"))) {
JsonArray notes = new fr.wseduc.webutils.collections.JsonArray();
JsonArray listNotes = message.body().getJsonArray("results");
for (int i = 0; i < listNotes.size(); i++) {
JsonObject note = listNotes.getJsonObject(i);
JsonObject noteDevoir = new JsonObject()
.put("valeur", Double.valueOf(note.getString("valeur")))
.put("diviseur", Double.valueOf(note.getString("diviseur")))
.put("ramenerSur", note.getBoolean("ramener_sur"))
.put("coefficient", Double.valueOf(note.getString("coefficient")));
notes.add(noteDevoir);
}
Either<String, JsonObject> result = null;
if (notes.size() > 0) {
JsonObject action = new JsonObject()
.put("action", "note.calculMoyenne")
.put("listeNoteDevoirs", notes)
.put("statistiques", false)
.put("diviseurM", 20);
eb.send(Viescolaire.COMPETENCES_BUS_ADDRESS, action, handlerToAsyncHandler(new Handler<Message<JsonObject>>() {
@Override
public void handle(Message<JsonObject> message) {
Either<String, JsonObject> result = null;
if ("ok".equals(message.body().getString("status"))) {
result = new Either.Right<String, JsonObject>(message.body().getJsonObject("result"));
handler.handle(result);
} else {
result = new Either.Left<>(message.body().getString("message"));
handler.handle(result);
}
}
}));
} else {
result = new Either.Right<>(new JsonObject());
}
handler.handle(result);
} else {
handler.handle(new Either.Left<String, JsonObject>(message.body().getString("message")));
}
}
}));
}
@Override
public void createPersonnesSupp(JsonArray users, Handler<Either<String, JsonObject>> handler) {
SqlStatementsBuilder statements = new SqlStatementsBuilder();
for (Object u : users) {
if (!(u instanceof JsonObject) || !validProfile((JsonObject) u)) {
continue;
}
final JsonObject user = (JsonObject) u;
// Insert user in the right table
String uQuery =
"INSERT INTO " + Viescolaire.VSCO_SCHEMA + ".personnes_supp(id_user, display_name, user_type, " +
"first_name, last_name, delete_date, birth_date ) " +
"VALUES (?, ?, ?, ?, ?, to_timestamp(? /1000) );";
JsonArray uParams = new fr.wseduc.webutils.collections.JsonArray()
.add(user.getString("id"))
.add(user.getString("displayName"))
.add(user.getString("type"))
.add(user.getString("firstName"))
.add(user.getString("lastName"))
.add(user.getString("deleteDate"));
statements.prepared(uQuery, uParams);
if (user.containsKey("classIds") && user.getJsonArray("classIds").size() > 0) {
formatGroups(user.getJsonArray("classIds"), user.getString("id"), statements,
Viescolaire.CLASSE_TYPE);
}
if (user.containsKey("groupIds") && user.getJsonArray("groupIds").size() > 0) {
formatGroups(user.getJsonArray("groupIds"), user.getString("id"), statements,
Viescolaire.GROUPE_TYPE);
}
if (user.containsKey("structureIds") && user.getJsonArray("structureIds").size() > 0) {
formatStructure(user.getJsonArray("structureIds"), user.getString("id"), statements);
}
}
Sql.getInstance().transaction(statements.build(), SqlResult.validUniqueResultHandler(handler));
}
/**
* Inject creation request in SqlStatementBuilder for every class in ids
* @param ids class ids list
* @param userId user id
* @param statements Sql statement builder
* @param type Group type
*/
private static void formatGroups (JsonArray ids, String userId, SqlStatementsBuilder statements, Integer type) {
for (int i = 0; i < ids.size(); i++) {
String query =
"INSERT INTO " + Viescolaire.VSCO_SCHEMA + ".rel_groupes_personne_supp(id_groupe, id_user, type_groupe) " +
"VALUES (?, ?, ?);";
JsonArray params = new fr.wseduc.webutils.collections.JsonArray()
.add(ids.getString(i))
.add(userId)
.add(type);
statements.prepared(query, params);
}
}
/**
* Return if the user is a valid profile user
* @param user user object
* @return true | false if the profile is a valid profile
*/
private static boolean validProfile (JsonObject user) {
return "Teacher".equals(user.getString("type")) || "Student".equals(user.getString("type"));
}
/**
* Inject creation request in SqlStatementBuilder for every stucture in ids
* @param ids structure ids list
* @param userId user id
* @param statements Sql statement builder
*/
private static void formatStructure (JsonArray ids, String userId, SqlStatementsBuilder statements) {
for (int i = 0; i < ids.size(); i++) {
String query =
"INSERT INTO " + Viescolaire.VSCO_SCHEMA + ".rel_structures_personne_supp(id_structure, id_user) " +
"VALUES (?, ?);";
JsonArray params = new fr.wseduc.webutils.collections.JsonArray()
.add(ids.getString(i))
.add(userId);
statements.prepared(query, params);
}
}
/**
* Recupere les établissements inactifs de l'utilisateur connecté
* @param userInfos : utilisateur connecté
* @param handler handler comportant le resultat
*/
@Override
public void getActivesIDsStructures(UserInfos userInfos, String module,
Handler<Either<String, JsonArray>> handler) {
StringBuilder query =new StringBuilder();
JsonArray params = new fr.wseduc.webutils.collections.JsonArray();
query.append("SELECT id_etablissement ")
.append("FROM "+ module +".etablissements_actifs ")
.append("WHERE id_etablissement IN " + Sql.listPrepared(userInfos.getStructures().toArray()))
.append(" AND actif = TRUE");
for(String idStructure : userInfos.getStructures()){
params.add(idStructure);
}
Sql.getInstance().prepared(query.toString(), params, SqlResult.validResultHandler(handler));
}
/**
* Recupere les établissements inactifs de l'utilisateur connecté
* @param handler handler comportant le resultat
*/
@Override
public void getActivesIDsStructures( String module,
Handler<Either<String, JsonArray>> handler) {
StringBuilder query =new StringBuilder();
JsonArray params = new fr.wseduc.webutils.collections.JsonArray();
query.append("SELECT id_etablissement ")
.append("FROM "+ module +".etablissements_actifs ")
.append("WHERE actif = TRUE");
Sql.getInstance().prepared(query.toString(), params, SqlResult.validResultHandler(handler));
}
/**
* Active un établissement
* @param id : établissement
* @param handler handler comportant le resultat
*/
@Override
public void createActiveStructure (String id, String module, UserInfos user,
Handler<Either<String, JsonArray>> handler) {
SqlStatementsBuilder s = new SqlStatementsBuilder();
JsonObject data = new JsonObject();
String userQuery = "SELECT " + module + ".merge_users(?,?)";
s.prepared(userQuery, (new fr.wseduc.webutils.collections.JsonArray()).add(user.getUserId()).add(user.getUsername()));
data.put("id_etablissement", id);
data.put("actif", true);
s.insert(module + ".etablissements_actifs ", data, "id_etablissement");
Sql.getInstance().transaction(s.build(), SqlResult.validResultHandler(handler));
}
/**
* Supprime un étbalissement actif
* @param id : utilisateur connecté
* @param handler handler comportant le resultat
*/
@Override
public void deleteActiveStructure(String id, String module, Handler<Either<String, JsonArray>> handler) {
String query = "DELETE FROM " + module + ".etablissements_actifs WHERE id_etablissement = ?";
Sql.getInstance().prepared(query, (new fr.wseduc.webutils.collections.JsonArray()).add(Sql.parseId(id)), SqlResult.validResultHandler(handler));
}
@Override
public void getUAI(String idEtabl, Handler<Either<String,JsonObject>> handler){
StringBuilder query= new StringBuilder();
query.append("MATCH(s:Structure) WHERE s.id={id} RETURN s.UAI as uai");
Neo4j.getInstance().execute(query.toString(), new JsonObject().put("id", idEtabl), Neo4jResult.validUniqueResultHandler(handler));
}
@Override
public void getResponsablesEtabl(List<String> idsResponsable, Handler<Either<String,JsonArray>> handler){
StringBuilder query=new StringBuilder();
query.append("MATCH (u:User) WHERE u.id IN {id} RETURN u.externalId as externalId, u.displayName as displayName");
Neo4j.getInstance().execute(query.toString(), new JsonObject().put("id",new fr.wseduc.webutils.collections.JsonArray(idsResponsable)), Neo4jResult.validResultHandler(handler));
}
@Override
public void getElevesRelatives(List<String> idsClass,Handler<Either<String,JsonArray>> handler){
StringBuilder query = new StringBuilder();
JsonObject param = new JsonObject();
query.append("MATCH (c:Class)<-[:DEPENDS]-(:ProfileGroup)<-[:IN]-(u:User {profiles:['Student']})-[:RELATED]-(r:User{profiles:['Relative']}) WHERE c.id IN {idClass}");
query.append(" RETURN u.id as idNeo4j, u.externalId as externalId,u.attachmentId as attachmentId,u.lastName as lastName,u.level as level,u.firstName as firstName,u.relative as relative,");
query.append("r.externalId as externalIdRelative, r.title as civilite, r.lastName as lastNameRelative, r.firstName as firstNameRelative, r.address as address, r.zipCode as zipCode, r.city as city,");
query.append("c.id as idClass, c.name as nameClass, c.externalId as externalIdClass ORDER BY nameClass, lastName");
param.put("idClass", new fr.wseduc.webutils.collections.JsonArray(idsClass));
Neo4j.getInstance().execute(query.toString(), param, Neo4jResult.validResultHandler(handler));
}
@Override
public void getCodeDomaine(String idClass,Handler<Either<String,JsonArray>> handler){
StringBuilder query = new StringBuilder();
query.append("SELECT id_groupe,id as id_domaine, code_domaine as code_domaine ");
query.append("FROM notes.domaines INNER JOIN notes.rel_groupe_cycle ");
query.append("ON notes.domaines.id_cycle= notes.rel_groupe_cycle.id_cycle ");
query.append("WHERE notes.rel_groupe_cycle.id_groupe = ? AND code_domaine IS NOT NULL");
JsonArray params = new fr.wseduc.webutils.collections.JsonArray();
params.add(idClass);
Sql.getInstance().prepared(query.toString(), params, SqlResult.validResultHandler(handler));
}
@Override
public void getResponsablesDirection(String idStructure, Handler<Either<String, JsonArray>> handler) {
String query = "MATCH (u:User{profiles:['Personnel']})-[ADMINISTRATIVE_ATTACHMENT]->(s:Structure {id:{structureId}}) " +
"WHERE ANY(function IN u.functions WHERE function =~ '(?i).*\\\\$DIR\\\\$.*')" +
" RETURN u.id as id, u.displayName as displayName, u.externalId as externalId";
JsonObject param = new JsonObject();
param.put("structureId",idStructure);
Neo4j.getInstance().execute(query,param,Neo4jResult.validResultHandler(handler));
}
/**
* Retourne la liste des enfants pour un utilisateur donné
* @param idUser Id de l'utilisateur
* @param handler Handler comportant le resultat de la requete
*/
@Override
public void getEnfants(String idUser, Handler<Either<String, JsonArray>> handler) {
StringBuilder query = new StringBuilder();
query.append("MATCH (m:User {id: {id}})<-[:RELATED]-(n:User)")
.append("RETURN n.id as id, n.firstName as firstName, n.lastName as lastName, n.level as level, n.classes as classes, n.birthDate as birthDate ORDER BY lastName");
neo4j.execute(query.toString(), new JsonObject().put("id", idUser), Neo4jResult.validResultHandler(handler));
}
/**
* Retourne la liste des personnels pour une liste d'id donnée
*
* @param idPersonnels ids des personnels
* @param handler Handler comportant le resultat de la requete
*/
public void getPersonnels(List<String> idPersonnels, Handler<Either<String, JsonArray>> handler) {
StringBuilder query = new StringBuilder();
query.append("MATCH (u:User)")
.append("WHERE ANY (x IN u.profiles WHERE x IN ['Teacher', 'Personnel']) AND u.id IN {idPersonnel}")
.append("RETURN u.id as id, u.lastName as lastName, u.firstName as firstName, u.emailAcademy as emailAcademy");
neo4j.execute(query.toString(), new JsonObject().put("idPersonnel", new fr.wseduc.webutils.collections.JsonArray(idPersonnels)), Neo4jResult.validResultHandler(handler));
}
@Override
public void list(String structureId, String classId, String groupId,
JsonArray expectedProfiles, String filterActivated, String nameFilter,
UserInfos userInfos, Handler<Either<String, JsonArray>> results) {
JsonObject params = new JsonObject();
String filter = "";
String filterProfile = "WHERE 1=1 ";
String optionalMatch =
"OPTIONAL MATCH u-[:IN]->(:ProfileGroup)-[:DEPENDS]->(class:Class)-[:BELONGS]->(s) " +
"OPTIONAL MATCH u-[:RELATED]->(parent: User) " +
"OPTIONAL MATCH (child: User)-[:RELATED]->u " +
"OPTIONAL MATCH u-[rf:HAS_FUNCTION]->fg-[:CONTAINS_FUNCTION*0..1]->(f:Function) ";
if (expectedProfiles != null && expectedProfiles.size() > 0) {
filterProfile += "AND p.name IN {expectedProfiles} ";
params.put("expectedProfiles", expectedProfiles);
}
if (classId != null && !classId.trim().isEmpty()) {
filter = "(n:Class {id : {classId}})<-[:DEPENDS]-(g:ProfileGroup)<-[:IN]-";
params.put("classId", classId);
} else if (structureId != null && !structureId.trim().isEmpty()) {
filter = "(n:Structure {id : {structureId}})<-[:DEPENDS]-(g:ProfileGroup)<-[:IN]-";
params.put("structureId", structureId);
} else if (groupId != null && !groupId.trim().isEmpty()) {
filter = "(n:Group {id : {groupId}})<-[:IN]-";
params.put("groupId", groupId);
}
String condition = "";
String functionMatch = "WITH u MATCH (s:Structure)<-[:DEPENDS]-(pg:ProfileGroup)-[:HAS_PROFILE]->(p:Profile), u-[:IN]->pg ";
if(nameFilter != null && !nameFilter.trim().isEmpty()){
condition += "AND u.displayName =~ {regex} ";
params.put("regex", "(?i)^.*?" + Pattern.quote(nameFilter.trim()) + ".*?$");
}
if(filterActivated != null){
if("inactive".equals(filterActivated)){
condition += "AND NOT(u.activationCode IS NULL) ";
} else if("active".equals(filterActivated)){
condition += "AND u.activationCode IS NULL ";
}
}
String query =
"MATCH " + filter + "(u:User) " +
functionMatch + filterProfile + condition + optionalMatch +
"RETURN DISTINCT u.id as id, p.name as type, u.externalId as externalId, " +
"u.activationCode as code, u.login as login, u.firstName as firstName, " +
"u.lastName as lastName, u.displayName as displayName, u.source as source, u.attachmentId as attachmentId, " +
"u.birthDate as birthDate, " +
"extract(function IN u.functions | last(split(function, \"$\"))) as aafFunctions, " +
"collect(distinct {id: s.id, name: s.name}) as structures, " +
"collect(distinct {id: class.id, name: class.name}) as allClasses, " +
"collect(distinct [f.externalId, rf.scope]) as functions, " +
"CASE WHEN parent IS NULL THEN [] ELSE collect(distinct {id: parent.id, firstName: parent.firstName, lastName: parent.lastName}) END as parents, " +
"CASE WHEN child IS NULL THEN [] ELSE collect(distinct {id: child.id, firstName: child.firstName, lastName: child.lastName, attachmentId : child.attachmentId }) END as children, " +
"HEAD(COLLECT(distinct parent.externalId)) as parent1ExternalId, " + // Hack for GEPI export
"HEAD(TAIL(COLLECT(distinct parent.externalId))) as parent2ExternalId " + // Hack for GEPI export
"ORDER BY type DESC, displayName ASC ";
neo4j.execute(query, params, Neo4jResult.validResultHandler(results));
}
} | FIX [MN-303] | [ELEVE SUPPRIME] : BirthDate on deleteUsers.
| src/main/java/fr/openent/viescolaire/service/impl/DefaultUserService.java | FIX [MN-303] | [ELEVE SUPPRIME] : BirthDate on deleteUsers. |
|
Java | agpl-3.0 | fbc412ba4ec7371a696afe6600dead2bb28ff034 | 0 | ShatalovYaroslav/catalog,ow2-proactive/catalog,ow2-proactive/catalog,ShatalovYaroslav/catalog,ow2-proactive/catalog,ShatalovYaroslav/catalog | /*
* ProActive Parallel Suite(TM):
* The Open Source library for parallel and distributed
* Workflows & Scheduling, Orchestration, Cloud Automation
* and Big Data Analysis on Enterprise Grids & Clouds.
*
* Copyright (c) 2007 - 2017 ActiveEon
* Contact: [email protected]
*
* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation: version 3 of
* the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*/
package org.ow2.proactive.catalog.service;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.apache.commons.io.FilenameUtils;
import org.apache.tika.detect.Detector;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.AutoDetectParser;
import org.ow2.proactive.catalog.dto.CatalogObjectDependencyList;
import org.ow2.proactive.catalog.dto.CatalogObjectMetadata;
import org.ow2.proactive.catalog.dto.CatalogRawObject;
import org.ow2.proactive.catalog.dto.DependsOnCatalogObject;
import org.ow2.proactive.catalog.dto.Metadata;
import org.ow2.proactive.catalog.repository.BucketRepository;
import org.ow2.proactive.catalog.repository.CatalogObjectRepository;
import org.ow2.proactive.catalog.repository.CatalogObjectRevisionRepository;
import org.ow2.proactive.catalog.repository.entity.BucketEntity;
import org.ow2.proactive.catalog.repository.entity.CatalogObjectEntity;
import org.ow2.proactive.catalog.repository.entity.CatalogObjectRevisionEntity;
import org.ow2.proactive.catalog.repository.entity.KeyValueLabelMetadataEntity;
import org.ow2.proactive.catalog.service.exception.BucketNotFoundException;
import org.ow2.proactive.catalog.service.exception.CatalogObjectAlreadyExistingException;
import org.ow2.proactive.catalog.service.exception.CatalogObjectNotFoundException;
import org.ow2.proactive.catalog.service.exception.KindOrContentTypeIsNotValidException;
import org.ow2.proactive.catalog.service.exception.RevisionNotFoundException;
import org.ow2.proactive.catalog.service.exception.UnprocessableEntityException;
import org.ow2.proactive.catalog.service.exception.WrongParametersException;
import org.ow2.proactive.catalog.service.model.GenericInfoBucketData;
import org.ow2.proactive.catalog.util.ArchiveManagerHelper;
import org.ow2.proactive.catalog.util.ArchiveManagerHelper.FileNameAndContent;
import org.ow2.proactive.catalog.util.ArchiveManagerHelper.ZipArchiveContent;
import org.ow2.proactive.catalog.util.RevisionCommitMessageBuilder;
import org.ow2.proactive.catalog.util.SeparatorUtility;
import org.ow2.proactive.catalog.util.name.validator.KindAndContentTypeValidator;
import org.ow2.proactive.catalog.util.parser.WorkflowParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.google.common.annotations.VisibleForTesting;
import lombok.extern.log4j.Log4j2;
/**
* @author ActiveEon Team
*/
@Log4j2
@Service
@Transactional
public class CatalogObjectService {
@Autowired
private CatalogObjectRepository catalogObjectRepository;
@Autowired
private CatalogObjectRevisionRepository catalogObjectRevisionRepository;
@Autowired
private BucketRepository bucketRepository;
@Autowired
private ArchiveManagerHelper archiveManager;
@Autowired
private KeyValueLabelMetadataHelper keyValueLabelMetadataHelper;
@Autowired
private GenericInformationAdder genericInformationAdder;
@Autowired
private RevisionCommitMessageBuilder revisionCommitMessageBuilder;
@Autowired
private KindAndContentTypeValidator kindAndContentTypeValidator;
@Autowired
private SeparatorUtility separatorUtility;
@Value("${kind.separator}")
protected String kindSeparator;
private AutoDetectParser mediaTypeFileParser = new AutoDetectParser();
public CatalogObjectMetadata createCatalogObject(String bucketName, String name, String kind, String commitMessage,
String username, String contentType, byte[] rawObject, String extension) {
return this.createCatalogObject(bucketName,
name,
kind,
commitMessage,
username,
contentType,
Collections.emptyList(),
rawObject,
extension);
}
public List<CatalogObjectMetadata> createCatalogObjects(String bucketName, String kind, String commitMessage,
String username, byte[] zipArchive) {
List<FileNameAndContent> filesContainedInArchive = archiveManager.extractZIP(zipArchive);
if (filesContainedInArchive.isEmpty()) {
throw new UnprocessableEntityException("Malformed archive");
}
BucketEntity bucketEntity = findBucketByNameAndCheck(bucketName);
return filesContainedInArchive.stream().map(file -> {
String objectName = file.getName();
CatalogObjectEntity catalogObject = catalogObjectRepository.findOne(new CatalogObjectEntity.CatalogObjectEntityKey(bucketEntity.getId(),
objectName));
if (catalogObject == null) {
String contentTypeOfFile = getFileMimeType(file);
return this.createCatalogObject(bucketName,
objectName,
kind,
commitMessage,
username,
contentTypeOfFile,
Collections.emptyList(),
file.getContent(),
FilenameUtils.getExtension(file.getFileNameWithExtension()));
} else {
return this.createCatalogObjectRevision(bucketName,
objectName,
commitMessage,
username,
file.getContent());
}
}).collect(Collectors.toList());
}
public CatalogObjectMetadata createCatalogObject(String bucketName, String name, String kind, String commitMessage,
String username, String contentType, List<Metadata> metadataList, byte[] rawObject, String extension) {
if (!kindAndContentTypeValidator.isValid(kind)) {
throw new KindOrContentTypeIsNotValidException(kind, "kind");
}
if (!kindAndContentTypeValidator.isValid(contentType)) {
throw new KindOrContentTypeIsNotValidException(contentType, "content type");
}
BucketEntity bucketEntity = findBucketByNameAndCheck(bucketName);
CatalogObjectRevisionEntity catalogObjectEntityCheck = catalogObjectRevisionRepository.findDefaultCatalogObjectByNameInBucket(Collections.singletonList(bucketName),
name);
if (catalogObjectEntityCheck != null) {
throw new CatalogObjectAlreadyExistingException(bucketName, name);
}
CatalogObjectEntity catalogObjectEntity = CatalogObjectEntity.builder()
.bucket(bucketEntity)
.contentType(contentType)
.kind(kind)
.extension(extension)
.id(new CatalogObjectEntity.CatalogObjectEntityKey(bucketEntity.getId(),
name))
.build();
bucketEntity.getCatalogObjects().add(catalogObjectEntity);
CatalogObjectRevisionEntity result = buildCatalogObjectRevisionEntity(commitMessage,
username,
metadataList,
rawObject,
catalogObjectEntity);
return new CatalogObjectMetadata(result);
}
private String getFileMimeType(FileNameAndContent file) {
InputStream is = new BufferedInputStream(new ByteArrayInputStream(file.getContent()));
Detector detector = mediaTypeFileParser.getDetector();
org.apache.tika.metadata.Metadata md = new org.apache.tika.metadata.Metadata();
md.set(org.apache.tika.metadata.Metadata.RESOURCE_NAME_KEY, file.getFileNameWithExtension());
MediaType mediaType = MediaType.OCTET_STREAM;
try {
mediaType = detector.detect(is, md);
} catch (IOException e) {
log.warn("there is a problem of identifying mime type for the file from archive : " + file.getName(), e);
}
return mediaType.toString();
}
public CatalogObjectMetadata updateObjectMetadata(String bucketName, String name, Optional<String> kind,
Optional<String> contentType) {
findBucketByNameAndCheck(bucketName);
CatalogObjectRevisionEntity catalogObjectRevisionEntity = findCatalogObjectByNameAndBucketAndCheck(bucketName,
name);
if (!kind.isPresent() && !contentType.isPresent()) {
throw new WrongParametersException("at least one parameter should be present");
}
if (kind.isPresent() && !kindAndContentTypeValidator.isValid(kind.get())) {
throw new KindOrContentTypeIsNotValidException(kind.get(), "kind");
}
if (contentType.isPresent() && !kindAndContentTypeValidator.isValid(contentType.get())) {
throw new KindOrContentTypeIsNotValidException(contentType.get(), "content type");
}
CatalogObjectEntity catalogObjectEntity = catalogObjectRevisionEntity.getCatalogObject();
kind.ifPresent(catalogObjectEntity::setKind);
contentType.ifPresent(catalogObjectEntity::setContentType);
catalogObjectRepository.save(catalogObjectEntity);
return new CatalogObjectMetadata(catalogObjectEntity);
}
/**
* This methods computes the successor(s) (depends_on) and predecessor(s) (called_by) of a given catalog object
*
* @param bucketName
* @param name
* @param revisionCommitTime
* @return CatalogObjectDependencyList composed of two list of dependencies dependsOn and calledBy
*/
protected CatalogObjectDependencyList processObjectDependencies(String bucketName, String name,
long revisionCommitTime) {
List<String> dependsOnCatalogObjectsList = catalogObjectRevisionRepository.findDependsOnCatalogObjectNamesFromKeyValueMetadata(bucketName,
name,
revisionCommitTime);
List<DependsOnCatalogObject> dependsOnBucketAndObjectNameList = new ArrayList<>();
for (String dependOnCatalogObject : dependsOnCatalogObjectsList) {
String revisionCommitTimeOfDependsOnObject = catalogObjectRevisionRepository.findRevisionOfDependsOnCatalogObjectFromKeyLabelMetadata(bucketName,
name,
revisionCommitTime,
dependOnCatalogObject);
dependsOnBucketAndObjectNameList.add(new DependsOnCatalogObject(dependOnCatalogObject,
isDependsOnObjectExistInCatalog(separatorUtility.getSplitBySeparator(dependOnCatalogObject)
.get(0),
separatorUtility.getSplitBySeparator(dependOnCatalogObject)
.get(1),
revisionCommitTimeOfDependsOnObject)));
}
List<CatalogObjectRevisionEntity> calledByCatalogObjectList = catalogObjectRevisionRepository.findCalledByCatalogObjectsFromKeyValueMetadata(separatorUtility.getConcatWithSeparator(bucketName,
name));
List<String> calledByBucketAndObjectNameList = calledByCatalogObjectList.stream()
.map(revisionEntity -> separatorUtility.getConcatWithSeparator(revisionEntity.getCatalogObject()
.getBucket()
.getBucketName(),
revisionEntity.getCatalogObject()
.getId()
.getName()))
.collect(Collectors.toList());
return new CatalogObjectDependencyList(dependsOnBucketAndObjectNameList, calledByBucketAndObjectNameList);
}
private boolean isDependsOnObjectExistInCatalog(String bucketName, String name,
String revisionCommitTimeOfDependsOnObject) {
CatalogObjectRevisionEntity catalogObjectRevisionEntity;
if (revisionCommitTimeOfDependsOnObject.equals(WorkflowParser.LATEST_VERSION)) {
catalogObjectRevisionEntity = catalogObjectRevisionRepository.findDefaultCatalogObjectByNameInBucket(Collections.singletonList(bucketName),
name);
} else {
catalogObjectRevisionEntity = catalogObjectRevisionRepository.findCatalogObjectRevisionByCommitTime(Collections.singletonList(bucketName),
name,
Long.parseLong(revisionCommitTimeOfDependsOnObject));
}
return catalogObjectRevisionEntity != null;
}
/**
*
* @param bucketName
* @param name
* @param revisionCommitTime
* @return CatalogObjectDependencyList composed of two list of dependencies: dependsOn and calledBy
*/
public CatalogObjectDependencyList getObjectDependencies(String bucketName, String name, long revisionCommitTime) {
// Check that the bucketName/name object exists in the catalog
findCatalogObjectByNameAndBucketAndCheck(bucketName, name);
return processObjectDependencies(bucketName, name, revisionCommitTime);
}
public CatalogObjectDependencyList getObjectDependencies(String bucketName, String name) {
// Check that the bucketName/name object exists in the catalog and retrieve the commit time
CatalogObjectRevisionEntity catalogObject = findCatalogObjectByNameAndBucketAndCheck(bucketName, name);
return processObjectDependencies(bucketName, name, catalogObject.getCommitTime());
}
private BucketEntity findBucketByNameAndCheck(String bucketName) {
BucketEntity bucketEntity = bucketRepository.findOneByBucketName(bucketName);
if (bucketEntity == null) {
throw new BucketNotFoundException(bucketName);
}
return bucketEntity;
}
private CatalogObjectRevisionEntity findCatalogObjectByNameAndBucketAndCheck(String bucketName, String name) {
CatalogObjectRevisionEntity catalogObject = catalogObjectRevisionRepository.findDefaultCatalogObjectByNameInBucket(Collections.singletonList(bucketName),
name);
if (catalogObject == null) {
throw new CatalogObjectNotFoundException(bucketName, name);
}
return catalogObject;
}
private CatalogObjectRevisionEntity buildCatalogObjectRevisionEntity(final String commitMessage,
final String username, final List<org.ow2.proactive.catalog.dto.Metadata> metadataList,
final byte[] rawObject, final CatalogObjectEntity catalogObjectEntity) {
List<KeyValueLabelMetadataEntity> keyValueMetadataEntities = KeyValueLabelMetadataHelper.convertToEntity(metadataList);
if (keyValueMetadataEntities == null) {
throw new NullPointerException("Cannot build catalog object!");
}
List<KeyValueLabelMetadataEntity> keyValues = CollectionUtils.isEmpty(metadataList) ? keyValueLabelMetadataHelper.extractKeyValuesFromRaw(catalogObjectEntity.getKind(),
rawObject)
: keyValueMetadataEntities;
GenericInfoBucketData genericInfoBucketData = createGenericInfoBucketData(catalogObjectEntity.getBucket());
if (genericInfoBucketData == null) {
throw new NullPointerException("Cannot build catalog object!");
}
List<KeyValueLabelMetadataEntity> genericInformationWithBucketDataList = keyValueLabelMetadataHelper.replaceMetadataRelatedGenericInfoAndKeepOthers(keyValues,
genericInfoBucketData);
byte[] workflowWithReplacedGenericInfo = genericInformationAdder.addGenericInformationToRawObjectIfWorkflow(rawObject,
catalogObjectEntity.getKind(),
keyValueLabelMetadataHelper.toMap(keyValueLabelMetadataHelper.getOnlyGenericInformation(genericInformationWithBucketDataList)));
CatalogObjectRevisionEntity catalogObjectRevisionEntity = CatalogObjectRevisionEntity.builder()
.commitMessage(commitMessage)
.username(username)
.commitTime(LocalDateTime.now()
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli())
.keyValueMetadataList(genericInformationWithBucketDataList)
.rawObject(workflowWithReplacedGenericInfo)
.catalogObject(catalogObjectEntity)
.build();
genericInformationWithBucketDataList.forEach(keyValue -> keyValue.setCatalogObjectRevision(catalogObjectRevisionEntity));
catalogObjectEntity.addRevision(catalogObjectRevisionEntity);
return catalogObjectRevisionRepository.save(catalogObjectRevisionEntity);
}
private GenericInfoBucketData createGenericInfoBucketData(BucketEntity bucket) {
if (bucket == null) {
return GenericInfoBucketData.EMPTY;
}
return GenericInfoBucketData.builder().bucketName(bucket.getBucketName()).group(bucket.getOwner()).build();
}
public List<CatalogObjectMetadata> listCatalogObjects(List<String> bucketNames) {
bucketNames.forEach(bucketName -> findBucketByNameAndCheck(bucketName));
List<CatalogObjectRevisionEntity> result = catalogObjectRevisionRepository.findDefaultCatalogObjectsInBucket(bucketNames);
return buildMetadataWithLink(result);
}
private List<CatalogObjectMetadata> buildMetadataWithLink(List<CatalogObjectRevisionEntity> result) {
return result.stream().map(CatalogObjectMetadata::new).collect(Collectors.toList());
}
public List<CatalogObjectMetadata> listCatalogObjectsByKind(List<String> bucketNames, String kind) {
bucketNames.forEach(bucketName -> findBucketByNameAndCheck(bucketName));
List<CatalogObjectRevisionEntity> result = catalogObjectRevisionRepository.findDefaultCatalogObjectsOfKindInBucket(bucketNames,
kind);
return buildMetadataWithLink(result);
}
// find catalog objects by kind and content type
public List<CatalogObjectMetadata> listCatalogObjectsByKindAndContentType(List<String> bucketNames, String kind,
String contentType) {
bucketNames.forEach(bucketName -> findBucketByNameAndCheck(bucketName));
List<CatalogObjectRevisionEntity> result = catalogObjectRevisionRepository.findDefaultCatalogObjectsOfKindAndContentTypeInBucket(bucketNames,
kind,
contentType);
return buildMetadataWithLink(result);
}
// find catalog objects by content type
public List<CatalogObjectMetadata> listCatalogObjectsByContentType(List<String> bucketNames, String contentType) {
bucketNames.forEach(bucketName -> findBucketByNameAndCheck(bucketName));
List<CatalogObjectRevisionEntity> result = catalogObjectRevisionRepository.findDefaultCatalogObjectsOfContentTypeInBucket(bucketNames,
contentType);
return buildMetadataWithLink(result);
}
public ZipArchiveContent getCatalogObjectsAsZipArchive(String bucketName, List<String> catalogObjectsNames) {
List<CatalogObjectRevisionEntity> revisions = getCatalogObjects(bucketName, catalogObjectsNames);
return archiveManager.compressZIP(revisions);
}
public List<CatalogObjectMetadata> listSelectedCatalogObjects(String bucketName, List<String> catalogObjectsNames) {
List<CatalogObjectRevisionEntity> result = getCatalogObjects(bucketName, catalogObjectsNames);
return buildMetadataWithLink(result);
}
private List<CatalogObjectRevisionEntity> getCatalogObjects(String bucketName, List<String> catalogObjectsNames) {
findBucketByNameAndCheck(bucketName);
List<CatalogObjectRevisionEntity> revisions = catalogObjectsNames.stream()
.map(name -> catalogObjectRevisionRepository.findDefaultCatalogObjectByNameInBucket(Collections.singletonList(bucketName),
name))
.collect(Collectors.toList());
return revisions;
}
public CatalogObjectMetadata delete(String bucketName, String name) throws CatalogObjectNotFoundException {
BucketEntity bucketEntity = findBucketByNameAndCheck(bucketName);
CatalogObjectMetadata catalogObjectMetadata = getCatalogObjectMetadata(bucketName, name);
try {
catalogObjectRepository.delete(new CatalogObjectEntity.CatalogObjectEntityKey(bucketEntity.getId(), name));
} catch (EmptyResultDataAccessException emptyResultDataAccessException) {
log.warn("CatalogObject {} does not exist in bucket {}", name, bucketName);
throw new CatalogObjectNotFoundException(bucketName, name);
}
return catalogObjectMetadata;
}
public CatalogObjectMetadata getCatalogObjectMetadata(String bucketName, String name) {
return new CatalogObjectMetadata(findCatalogObjectByNameAndBucketAndCheck(bucketName, name));
}
public CatalogRawObject getCatalogRawObject(String bucketName, String name) {
return new CatalogRawObject(findCatalogObjectByNameAndBucketAndCheck(bucketName, name));
}
/**
* #################### Revision Operations ###################
**/
public CatalogObjectMetadata createCatalogObjectRevision(String bucketName, String name, String commitMessage,
String username, byte[] rawObject) {
return this.createCatalogObjectRevision(bucketName,
name,
commitMessage,
username,
Collections.emptyList(),
rawObject);
}
public CatalogObjectMetadata createCatalogObjectRevision(String bucketName, String name, String commitMessage,
String username, List<Metadata> metadataListParsed, byte[] rawObject) {
BucketEntity bucketEntity = findBucketByNameAndCheck(bucketName);
CatalogObjectEntity catalogObject = catalogObjectRepository.findOne(new CatalogObjectEntity.CatalogObjectEntityKey(bucketEntity.getId(),
name));
if (catalogObject == null) {
throw new CatalogObjectNotFoundException(bucketName, name);
}
CatalogObjectRevisionEntity revisionEntity = buildCatalogObjectRevisionEntity(commitMessage,
username,
metadataListParsed,
rawObject,
catalogObject);
return new CatalogObjectMetadata(revisionEntity);
}
public List<CatalogObjectMetadata> listCatalogObjectRevisions(String bucketName, String name) {
BucketEntity bucketEntity = findBucketByNameAndCheck(bucketName);
findCatalogObjectByNameAndBucketAndCheck(bucketName, name);
CatalogObjectEntity list = catalogObjectRepository.readCatalogObjectRevisionsById(new CatalogObjectEntity.CatalogObjectEntityKey(bucketEntity.getId(),
name));
return list.getRevisions().stream().map(CatalogObjectMetadata::new).collect(Collectors.toList());
}
public CatalogObjectMetadata getCatalogObjectRevision(String bucketName, String name, long commitTime)
throws UnsupportedEncodingException {
CatalogObjectRevisionEntity revisionEntity = getCatalogObjectRevisionEntityByCommitTime(bucketName,
name,
commitTime);
return new CatalogObjectMetadata(revisionEntity);
}
public CatalogRawObject getCatalogObjectRevisionRaw(String bucketName, String name, long commitTime)
throws UnsupportedEncodingException {
CatalogObjectRevisionEntity revisionEntity = getCatalogObjectRevisionEntityByCommitTime(bucketName,
name,
commitTime);
return new CatalogRawObject(revisionEntity);
}
public CatalogObjectMetadata restore(String bucketName, String name, Long commitTime) {
CatalogObjectRevisionEntity catalogObjectRevision = catalogObjectRevisionRepository.findCatalogObjectRevisionByCommitTime(Collections.singletonList(bucketName),
name,
commitTime);
if (catalogObjectRevision == null) {
throw new RevisionNotFoundException(bucketName, name, commitTime);
}
String restoreCommitMessage = revisionCommitMessageBuilder.build(catalogObjectRevision.getCommitMessage(),
commitTime);
CatalogObjectRevisionEntity restoredRevision = buildCatalogObjectRevisionEntity(restoreCommitMessage,
catalogObjectRevision.getUsername(),
keyValueLabelMetadataHelper.convertFromEntity(catalogObjectRevision.getKeyValueMetadataList()),
catalogObjectRevision.getRawObject(),
catalogObjectRevision.getCatalogObject());
return new CatalogObjectMetadata(restoredRevision);
}
/**
* Method returns all ordered stored kinds for all objects in catalog
*
* @return unique set of kinds with root kind
* for example kinds: a/b, a/c, d/f/g
* should return a, a/b, a/c, d, d/f, d/f/g
*/
public TreeSet<String> getKinds() {
Set<String> allStoredKinds = catalogObjectRepository.findAllKinds();
TreeSet<String> resultKinds = new TreeSet<>();
allStoredKinds.forEach(kind -> {
String[] splittedKinds = kind.split(kindSeparator);
StringBuilder rootKinds = new StringBuilder();
for (int i = 0; i < splittedKinds.length - 1; i++) {
rootKinds.append(splittedKinds[i]);
resultKinds.add(rootKinds.toString());
rootKinds.append(kindSeparator);
}
resultKinds.add(kind);
});
return resultKinds;
}
/**
* @return all ordered content types for all objects in catalog
*/
public TreeSet<String> getContentTypes() {
return new TreeSet<>(catalogObjectRepository.findAllContentTypes());
}
@VisibleForTesting
protected CatalogObjectRevisionEntity getCatalogObjectRevisionEntityByCommitTime(String bucketName, String name,
long commitTime) {
CatalogObjectRevisionEntity revisionEntity = catalogObjectRevisionRepository.findCatalogObjectRevisionByCommitTime(Collections.singletonList(bucketName),
name,
commitTime);
if (revisionEntity == null) {
throw new RevisionNotFoundException(bucketName, name, commitTime);
}
return revisionEntity;
}
}
| src/main/java/org/ow2/proactive/catalog/service/CatalogObjectService.java | /*
* ProActive Parallel Suite(TM):
* The Open Source library for parallel and distributed
* Workflows & Scheduling, Orchestration, Cloud Automation
* and Big Data Analysis on Enterprise Grids & Clouds.
*
* Copyright (c) 2007 - 2017 ActiveEon
* Contact: [email protected]
*
* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation: version 3 of
* the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*/
package org.ow2.proactive.catalog.service;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.apache.commons.io.FilenameUtils;
import org.apache.tika.detect.Detector;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.AutoDetectParser;
import org.ow2.proactive.catalog.dto.CatalogObjectDependencyList;
import org.ow2.proactive.catalog.dto.CatalogObjectMetadata;
import org.ow2.proactive.catalog.dto.CatalogRawObject;
import org.ow2.proactive.catalog.dto.DependsOnCatalogObject;
import org.ow2.proactive.catalog.dto.Metadata;
import org.ow2.proactive.catalog.repository.BucketRepository;
import org.ow2.proactive.catalog.repository.CatalogObjectRepository;
import org.ow2.proactive.catalog.repository.CatalogObjectRevisionRepository;
import org.ow2.proactive.catalog.repository.entity.BucketEntity;
import org.ow2.proactive.catalog.repository.entity.CatalogObjectEntity;
import org.ow2.proactive.catalog.repository.entity.CatalogObjectRevisionEntity;
import org.ow2.proactive.catalog.repository.entity.KeyValueLabelMetadataEntity;
import org.ow2.proactive.catalog.service.exception.BucketNotFoundException;
import org.ow2.proactive.catalog.service.exception.CatalogObjectAlreadyExistingException;
import org.ow2.proactive.catalog.service.exception.CatalogObjectNotFoundException;
import org.ow2.proactive.catalog.service.exception.KindOrContentTypeIsNotValidException;
import org.ow2.proactive.catalog.service.exception.RevisionNotFoundException;
import org.ow2.proactive.catalog.service.exception.UnprocessableEntityException;
import org.ow2.proactive.catalog.service.exception.WrongParametersException;
import org.ow2.proactive.catalog.service.model.GenericInfoBucketData;
import org.ow2.proactive.catalog.util.ArchiveManagerHelper;
import org.ow2.proactive.catalog.util.ArchiveManagerHelper.FileNameAndContent;
import org.ow2.proactive.catalog.util.ArchiveManagerHelper.ZipArchiveContent;
import org.ow2.proactive.catalog.util.RevisionCommitMessageBuilder;
import org.ow2.proactive.catalog.util.SeparatorUtility;
import org.ow2.proactive.catalog.util.name.validator.KindAndContentTypeValidator;
import org.ow2.proactive.catalog.util.parser.WorkflowParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.google.common.annotations.VisibleForTesting;
import lombok.extern.log4j.Log4j2;
/**
* @author ActiveEon Team
*/
@Log4j2
@Service
@Transactional
public class CatalogObjectService {
@Autowired
private CatalogObjectRepository catalogObjectRepository;
@Autowired
private CatalogObjectRevisionRepository catalogObjectRevisionRepository;
@Autowired
private BucketRepository bucketRepository;
@Autowired
private ArchiveManagerHelper archiveManager;
@Autowired
private KeyValueLabelMetadataHelper keyValueLabelMetadataHelper;
@Autowired
private GenericInformationAdder genericInformationAdder;
@Autowired
private RevisionCommitMessageBuilder revisionCommitMessageBuilder;
@Autowired
private KindAndContentTypeValidator kindAndContentTypeValidator;
@Autowired
private SeparatorUtility separatorUtility;
@Value("${kind.separator}")
protected String kindSeparator;
private AutoDetectParser mediaTypeFileParser = new AutoDetectParser();
public CatalogObjectMetadata createCatalogObject(String bucketName, String name, String kind, String commitMessage,
String username, String contentType, byte[] rawObject, String extension) {
return this.createCatalogObject(bucketName,
name,
kind,
commitMessage,
username,
contentType,
Collections.emptyList(),
rawObject,
extension);
}
public List<CatalogObjectMetadata> createCatalogObjects(String bucketName, String kind, String commitMessage,
String username, byte[] zipArchive) {
List<FileNameAndContent> filesContainedInArchive = archiveManager.extractZIP(zipArchive);
if (filesContainedInArchive.isEmpty()) {
throw new UnprocessableEntityException("Malformed archive");
}
BucketEntity bucketEntity = findBucketByNameAndCheck(bucketName);
return filesContainedInArchive.stream().map(file -> {
String objectName = file.getName();
CatalogObjectEntity catalogObject = catalogObjectRepository.findOne(new CatalogObjectEntity.CatalogObjectEntityKey(bucketEntity.getId(),
objectName));
if (catalogObject == null) {
String contentTypeOfFile = getFileMimeType(file);
return this.createCatalogObject(bucketName,
objectName,
kind,
commitMessage,
username,
contentTypeOfFile,
Collections.emptyList(),
file.getContent(),
FilenameUtils.getExtension(file.getFileNameWithExtension()));
} else {
return this.createCatalogObjectRevision(bucketName,
objectName,
commitMessage,
username,
file.getContent());
}
}).collect(Collectors.toList());
}
public CatalogObjectMetadata createCatalogObject(String bucketName, String name, String kind, String commitMessage,
String username, String contentType, List<Metadata> metadataList, byte[] rawObject, String extension) {
if (!kindAndContentTypeValidator.isValid(kind)) {
throw new KindOrContentTypeIsNotValidException(kind, "kind");
}
if (!kindAndContentTypeValidator.isValid(contentType)) {
throw new KindOrContentTypeIsNotValidException(contentType, "content type");
}
BucketEntity bucketEntity = findBucketByNameAndCheck(bucketName);
CatalogObjectRevisionEntity catalogObjectEntityCheck = catalogObjectRevisionRepository.findDefaultCatalogObjectByNameInBucket(Collections.singletonList(bucketName),
name);
if (catalogObjectEntityCheck != null) {
throw new CatalogObjectAlreadyExistingException(bucketName, name);
}
CatalogObjectEntity catalogObjectEntity = CatalogObjectEntity.builder()
.bucket(bucketEntity)
.contentType(contentType)
.kind(kind)
.extension(extension)
.id(new CatalogObjectEntity.CatalogObjectEntityKey(bucketEntity.getId(),
name))
.build();
bucketEntity.getCatalogObjects().add(catalogObjectEntity);
CatalogObjectRevisionEntity result = buildCatalogObjectRevisionEntity(commitMessage,
username,
metadataList,
rawObject,
catalogObjectEntity);
return new CatalogObjectMetadata(result);
}
private String getFileMimeType(FileNameAndContent file) {
InputStream is = new BufferedInputStream(new ByteArrayInputStream(file.getContent()));
Detector detector = mediaTypeFileParser.getDetector();
org.apache.tika.metadata.Metadata md = new org.apache.tika.metadata.Metadata();
md.set(org.apache.tika.metadata.Metadata.RESOURCE_NAME_KEY, file.getFileNameWithExtension());
MediaType mediaType = MediaType.OCTET_STREAM;
try {
mediaType = detector.detect(is, md);
} catch (IOException e) {
log.warn("there is a problem of identifying mime type for the file from archive : " + file.getName(), e);
}
return mediaType.toString();
}
public CatalogObjectMetadata updateObjectMetadata(String bucketName, String name, Optional<String> kind,
Optional<String> contentType) {
findBucketByNameAndCheck(bucketName);
CatalogObjectRevisionEntity catalogObjectRevisionEntity = findCatalogObjectByNameAndBucketAndCheck(bucketName,
name);
if (!kind.isPresent() && !contentType.isPresent()) {
throw new WrongParametersException("at least one parameter should be present");
}
if (kind.isPresent() && !kindAndContentTypeValidator.isValid(kind.get())) {
throw new KindOrContentTypeIsNotValidException(kind.get(), "kind");
}
if (contentType.isPresent() && !kindAndContentTypeValidator.isValid(contentType.get())) {
throw new KindOrContentTypeIsNotValidException(contentType.get(), "content type");
}
CatalogObjectEntity catalogObjectEntity = catalogObjectRevisionEntity.getCatalogObject();
kind.ifPresent(catalogObjectEntity::setKind);
contentType.ifPresent(catalogObjectEntity::setContentType);
catalogObjectRepository.save(catalogObjectEntity);
return new CatalogObjectMetadata(catalogObjectEntity);
}
/**
* This methods computes the successor(s) (depends_on) and predecessor(s) (called_by) of a given catalog object
*
* @param bucketName
* @param name
* @param revisionCommitTime
* @return CatalogObjectDependencyList composed of two list of dependencies dependsOn and calledBy
*/
protected CatalogObjectDependencyList processObjectDependencies(String bucketName, String name,
long revisionCommitTime) {
List<String> dependsOnCatalogObjectsList = catalogObjectRevisionRepository.findDependsOnCatalogObjectNamesFromKeyValueMetadata(bucketName,
name,
revisionCommitTime);
List<DependsOnCatalogObject> dependsOnBucketAndObjectNameList = new ArrayList<>();
for (String dependOnCatalogObject : dependsOnCatalogObjectsList) {
String revisionCommitTimeOfDependsOnObject = catalogObjectRevisionRepository.findRevisionOfDependsOnCatalogObjectFromKeyLabelMetadata(bucketName,
name,
revisionCommitTime,
dependOnCatalogObject);
dependsOnBucketAndObjectNameList.add(new DependsOnCatalogObject(dependOnCatalogObject,
isDependsOnObjectExistInCatalog(separatorUtility.getSplitBySeparator(dependOnCatalogObject)
.get(0),
separatorUtility.getSplitBySeparator(dependOnCatalogObject)
.get(1),
revisionCommitTimeOfDependsOnObject)));
}
List<CatalogObjectRevisionEntity> calledByCatalogObjectList = catalogObjectRevisionRepository.findCalledByCatalogObjectsFromKeyValueMetadata(separatorUtility.getConcatWithSeparator(bucketName,
name));
List<String> calledByBucketAndObjectNameList = calledByCatalogObjectList.stream()
.map(revisionEntity -> separatorUtility.getConcatWithSeparator(revisionEntity.getCatalogObject()
.getBucket()
.getBucketName(),
revisionEntity.getCatalogObject()
.getId()
.getName()))
.collect(Collectors.toList());
return new CatalogObjectDependencyList(dependsOnBucketAndObjectNameList, calledByBucketAndObjectNameList);
}
private boolean isDependsOnObjectExistInCatalog(String bucketName, String name,
String revisionCommitTimeOfDependsOnObject) {
CatalogObjectRevisionEntity catalogObjectRevisionEntity;
if (revisionCommitTimeOfDependsOnObject.equals(WorkflowParser.LATEST_VERSION)) {
catalogObjectRevisionEntity = catalogObjectRevisionRepository.findDefaultCatalogObjectByNameInBucket(Collections.singletonList(bucketName),
name);
} else {
catalogObjectRevisionEntity = catalogObjectRevisionRepository.findCatalogObjectRevisionByCommitTime(Collections.singletonList(bucketName),
name,
Long.parseLong(revisionCommitTimeOfDependsOnObject));
}
return catalogObjectRevisionEntity != null;
}
/**
*
* @param bucketName
* @param name
* @param revisionCommitTime
* @return CatalogObjectDependencyList composed of two list of dependencies: dependsOn and calledBy
*/
public CatalogObjectDependencyList getObjectDependencies(String bucketName, String name, long revisionCommitTime) {
// Check that the bucketName/name object exists in the catalog
findCatalogObjectByNameAndBucketAndCheck(bucketName, name);
return processObjectDependencies(bucketName, name, revisionCommitTime);
}
public CatalogObjectDependencyList getObjectDependencies(String bucketName, String name) {
// Check that the bucketName/name object exists in the catalog and retrieve the commit time
CatalogObjectRevisionEntity catalogObject = findCatalogObjectByNameAndBucketAndCheck(bucketName, name);
return processObjectDependencies(bucketName, name, catalogObject.getCommitTime());
}
private BucketEntity findBucketByNameAndCheck(String bucketName) {
BucketEntity bucketEntity = bucketRepository.findOneByBucketName(bucketName);
if (bucketEntity == null) {
throw new BucketNotFoundException(bucketName);
}
return bucketEntity;
}
private CatalogObjectRevisionEntity findCatalogObjectByNameAndBucketAndCheck(String bucketName, String name) {
CatalogObjectRevisionEntity catalogObject = catalogObjectRevisionRepository.findDefaultCatalogObjectByNameInBucket(Collections.singletonList(bucketName),
name);
if (catalogObject == null) {
throw new CatalogObjectNotFoundException(bucketName, name);
}
return catalogObject;
}
private CatalogObjectRevisionEntity buildCatalogObjectRevisionEntity(final String commitMessage,
final String username, final List<org.ow2.proactive.catalog.dto.Metadata> metadataList,
final byte[] rawObject, final CatalogObjectEntity catalogObjectEntity) {
List<KeyValueLabelMetadataEntity> keyValueMetadataEntities = KeyValueLabelMetadataHelper.convertToEntity(metadataList);
List<KeyValueLabelMetadataEntity> keyValues = CollectionUtils.isEmpty(metadataList) ? keyValueLabelMetadataHelper.extractKeyValuesFromRaw(catalogObjectEntity.getKind(),
rawObject)
: keyValueMetadataEntities;
GenericInfoBucketData genericInfoBucketData = createGenericInfoBucketData(catalogObjectEntity.getBucket());
List<KeyValueLabelMetadataEntity> genericInformationWithBucketDataList = keyValueLabelMetadataHelper.replaceMetadataRelatedGenericInfoAndKeepOthers(keyValues,
genericInfoBucketData);
byte[] workflowWithReplacedGenericInfo = genericInformationAdder.addGenericInformationToRawObjectIfWorkflow(rawObject,
catalogObjectEntity.getKind(),
keyValueLabelMetadataHelper.toMap(keyValueLabelMetadataHelper.getOnlyGenericInformation(genericInformationWithBucketDataList)));
CatalogObjectRevisionEntity catalogObjectRevisionEntity = CatalogObjectRevisionEntity.builder()
.commitMessage(commitMessage)
.username(username)
.commitTime(LocalDateTime.now()
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli())
.keyValueMetadataList(genericInformationWithBucketDataList)
.rawObject(workflowWithReplacedGenericInfo)
.catalogObject(catalogObjectEntity)
.build();
genericInformationWithBucketDataList.forEach(keyValue -> keyValue.setCatalogObjectRevision(catalogObjectRevisionEntity));
catalogObjectEntity.addRevision(catalogObjectRevisionEntity);
return catalogObjectRevisionRepository.save(catalogObjectRevisionEntity);
}
private GenericInfoBucketData createGenericInfoBucketData(BucketEntity bucket) {
if (bucket == null) {
return GenericInfoBucketData.EMPTY;
}
return GenericInfoBucketData.builder().bucketName(bucket.getBucketName()).group(bucket.getOwner()).build();
}
public List<CatalogObjectMetadata> listCatalogObjects(List<String> bucketNames) {
bucketNames.forEach(bucketName -> findBucketByNameAndCheck(bucketName));
List<CatalogObjectRevisionEntity> result = catalogObjectRevisionRepository.findDefaultCatalogObjectsInBucket(bucketNames);
return buildMetadataWithLink(result);
}
private List<CatalogObjectMetadata> buildMetadataWithLink(List<CatalogObjectRevisionEntity> result) {
return result.stream().map(CatalogObjectMetadata::new).collect(Collectors.toList());
}
public List<CatalogObjectMetadata> listCatalogObjectsByKind(List<String> bucketNames, String kind) {
bucketNames.forEach(bucketName -> findBucketByNameAndCheck(bucketName));
List<CatalogObjectRevisionEntity> result = catalogObjectRevisionRepository.findDefaultCatalogObjectsOfKindInBucket(bucketNames,
kind);
return buildMetadataWithLink(result);
}
// find catalog objects by kind and content type
public List<CatalogObjectMetadata> listCatalogObjectsByKindAndContentType(List<String> bucketNames, String kind,
String contentType) {
bucketNames.forEach(bucketName -> findBucketByNameAndCheck(bucketName));
List<CatalogObjectRevisionEntity> result = catalogObjectRevisionRepository.findDefaultCatalogObjectsOfKindAndContentTypeInBucket(bucketNames,
kind,
contentType);
return buildMetadataWithLink(result);
}
// find catalog objects by content type
public List<CatalogObjectMetadata> listCatalogObjectsByContentType(List<String> bucketNames, String contentType) {
bucketNames.forEach(bucketName -> findBucketByNameAndCheck(bucketName));
List<CatalogObjectRevisionEntity> result = catalogObjectRevisionRepository.findDefaultCatalogObjectsOfContentTypeInBucket(bucketNames,
contentType);
return buildMetadataWithLink(result);
}
public ZipArchiveContent getCatalogObjectsAsZipArchive(String bucketName, List<String> catalogObjectsNames) {
List<CatalogObjectRevisionEntity> revisions = getCatalogObjects(bucketName, catalogObjectsNames);
return archiveManager.compressZIP(revisions);
}
public List<CatalogObjectMetadata> listSelectedCatalogObjects(String bucketName, List<String> catalogObjectsNames) {
List<CatalogObjectRevisionEntity> result = getCatalogObjects(bucketName, catalogObjectsNames);
return buildMetadataWithLink(result);
}
private List<CatalogObjectRevisionEntity> getCatalogObjects(String bucketName, List<String> catalogObjectsNames) {
findBucketByNameAndCheck(bucketName);
List<CatalogObjectRevisionEntity> revisions = catalogObjectsNames.stream()
.map(name -> catalogObjectRevisionRepository.findDefaultCatalogObjectByNameInBucket(Collections.singletonList(bucketName),
name))
.collect(Collectors.toList());
return revisions;
}
public CatalogObjectMetadata delete(String bucketName, String name) throws CatalogObjectNotFoundException {
BucketEntity bucketEntity = findBucketByNameAndCheck(bucketName);
CatalogObjectMetadata catalogObjectMetadata = getCatalogObjectMetadata(bucketName, name);
try {
catalogObjectRepository.delete(new CatalogObjectEntity.CatalogObjectEntityKey(bucketEntity.getId(), name));
} catch (EmptyResultDataAccessException emptyResultDataAccessException) {
log.warn("CatalogObject {} does not exist in bucket {}", name, bucketName);
throw new CatalogObjectNotFoundException(bucketName, name);
}
return catalogObjectMetadata;
}
public CatalogObjectMetadata getCatalogObjectMetadata(String bucketName, String name) {
return new CatalogObjectMetadata(findCatalogObjectByNameAndBucketAndCheck(bucketName, name));
}
public CatalogRawObject getCatalogRawObject(String bucketName, String name) {
return new CatalogRawObject(findCatalogObjectByNameAndBucketAndCheck(bucketName, name));
}
/**
* #################### Revision Operations ###################
**/
public CatalogObjectMetadata createCatalogObjectRevision(String bucketName, String name, String commitMessage,
String username, byte[] rawObject) {
return this.createCatalogObjectRevision(bucketName,
name,
commitMessage,
username,
Collections.emptyList(),
rawObject);
}
public CatalogObjectMetadata createCatalogObjectRevision(String bucketName, String name, String commitMessage,
String username, List<Metadata> metadataListParsed, byte[] rawObject) {
BucketEntity bucketEntity = findBucketByNameAndCheck(bucketName);
CatalogObjectEntity catalogObject = catalogObjectRepository.findOne(new CatalogObjectEntity.CatalogObjectEntityKey(bucketEntity.getId(),
name));
if (catalogObject == null) {
throw new CatalogObjectNotFoundException(bucketName, name);
}
CatalogObjectRevisionEntity revisionEntity = buildCatalogObjectRevisionEntity(commitMessage,
username,
metadataListParsed,
rawObject,
catalogObject);
return new CatalogObjectMetadata(revisionEntity);
}
public List<CatalogObjectMetadata> listCatalogObjectRevisions(String bucketName, String name) {
BucketEntity bucketEntity = findBucketByNameAndCheck(bucketName);
findCatalogObjectByNameAndBucketAndCheck(bucketName, name);
CatalogObjectEntity list = catalogObjectRepository.readCatalogObjectRevisionsById(new CatalogObjectEntity.CatalogObjectEntityKey(bucketEntity.getId(),
name));
return list.getRevisions().stream().map(CatalogObjectMetadata::new).collect(Collectors.toList());
}
public CatalogObjectMetadata getCatalogObjectRevision(String bucketName, String name, long commitTime)
throws UnsupportedEncodingException {
CatalogObjectRevisionEntity revisionEntity = getCatalogObjectRevisionEntityByCommitTime(bucketName,
name,
commitTime);
return new CatalogObjectMetadata(revisionEntity);
}
public CatalogRawObject getCatalogObjectRevisionRaw(String bucketName, String name, long commitTime)
throws UnsupportedEncodingException {
CatalogObjectRevisionEntity revisionEntity = getCatalogObjectRevisionEntityByCommitTime(bucketName,
name,
commitTime);
return new CatalogRawObject(revisionEntity);
}
public CatalogObjectMetadata restore(String bucketName, String name, Long commitTime) {
CatalogObjectRevisionEntity catalogObjectRevision = catalogObjectRevisionRepository.findCatalogObjectRevisionByCommitTime(Collections.singletonList(bucketName),
name,
commitTime);
if (catalogObjectRevision == null) {
throw new RevisionNotFoundException(bucketName, name, commitTime);
}
String restoreCommitMessage = revisionCommitMessageBuilder.build(catalogObjectRevision.getCommitMessage(),
commitTime);
CatalogObjectRevisionEntity restoredRevision = buildCatalogObjectRevisionEntity(restoreCommitMessage,
catalogObjectRevision.getUsername(),
keyValueLabelMetadataHelper.convertFromEntity(catalogObjectRevision.getKeyValueMetadataList()),
catalogObjectRevision.getRawObject(),
catalogObjectRevision.getCatalogObject());
return new CatalogObjectMetadata(restoredRevision);
}
/**
* Method returns all ordered stored kinds for all objects in catalog
*
* @return unique set of kinds with root kind
* for example kinds: a/b, a/c, d/f/g
* should return a, a/b, a/c, d, d/f, d/f/g
*/
public TreeSet<String> getKinds() {
Set<String> allStoredKinds = catalogObjectRepository.findAllKinds();
TreeSet<String> resultKinds = new TreeSet<>();
allStoredKinds.forEach(kind -> {
String[] splittedKinds = kind.split(kindSeparator);
StringBuilder rootKinds = new StringBuilder();
for (int i = 0; i < splittedKinds.length - 1; i++) {
rootKinds.append(splittedKinds[i]);
resultKinds.add(rootKinds.toString());
rootKinds.append(kindSeparator);
}
resultKinds.add(kind);
});
return resultKinds;
}
/**
* @return all ordered content types for all objects in catalog
*/
public TreeSet<String> getContentTypes() {
return new TreeSet<>(catalogObjectRepository.findAllContentTypes());
}
@VisibleForTesting
protected CatalogObjectRevisionEntity getCatalogObjectRevisionEntityByCommitTime(String bucketName, String name,
long commitTime) {
CatalogObjectRevisionEntity revisionEntity = catalogObjectRevisionRepository.findCatalogObjectRevisionByCommitTime(Collections.singletonList(bucketName),
name,
commitTime);
if (revisionEntity == null) {
throw new RevisionNotFoundException(bucketName, name, commitTime);
}
return revisionEntity;
}
}
| Fix issues detected by descartes from stamp project. (#157)
* Fix issues detected by descartes from stamp project.
* Fix spotlessApply.
| src/main/java/org/ow2/proactive/catalog/service/CatalogObjectService.java | Fix issues detected by descartes from stamp project. (#157) |
|
Java | agpl-3.0 | e0b36464b517383a59a33e20b20bfb94b33fb485 | 0 | Metatavu/kunta-api-server,Metatavu/kunta-api-server,Metatavu/kunta-api-server | package fi.metatavu.kuntaapi.server.integrations.kuntarekry;
import java.io.Serializable;
import java.time.OffsetDateTime;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
@SuppressWarnings ("squid:S3437")
@JsonIgnoreProperties(ignoreUnknown = true)
public class KuntaRekryJob implements Serializable {
private static final long serialVersionUID = -7272380834345432920L;
@JacksonXmlProperty (localName = "jobtitle")
private String jobTitle;
@JacksonXmlProperty (localName = "employmenttype")
private String employmentType;
@JacksonXmlProperty (localName = "jobdescription")
private String jobDescription;
@JacksonXmlProperty (localName = "jobid")
private Long jobId;
@JacksonXmlProperty (localName = "location")
private String location;
@JacksonXmlProperty (localName = "organisation")
private String organisation;
@JacksonXmlProperty (localName = "organisationalunit")
private String organisationalUnit;
@JacksonXmlProperty (localName = "employmentduration")
private String employmentDuration;
@JacksonXmlProperty (localName = "taskarea")
private String taskArea;
@JacksonXmlProperty (localName = "publicationtimestart")
private OffsetDateTime publicationTimeStart;
@JacksonXmlProperty (localName = "publicationtimeend")
private OffsetDateTime publicationTimeEnd;
@JacksonXmlProperty (localName = "url")
private String url;
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getEmploymentType() {
return employmentType;
}
public void setEmploymentType(String employmentType) {
this.employmentType = employmentType;
}
public String getJobDescription() {
return jobDescription;
}
public void setJobDescription(String jobDescription) {
this.jobDescription = jobDescription;
}
@Deprecated
public Long getJobId() {
return jobId;
}
@Deprecated
public void setJobId(Long jobId) {
this.jobId = jobId;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getOrganisation() {
return organisation;
}
public void setOrganisation(String organisation) {
this.organisation = organisation;
}
public String getOrganisationalUnit() {
return organisationalUnit;
}
public void setOrganisationalUnit(String organisationalUnit) {
this.organisationalUnit = organisationalUnit;
}
public String getEmploymentDuration() {
return employmentDuration;
}
public void setEmploymentDuration(String employmentDuration) {
this.employmentDuration = employmentDuration;
}
public String getTaskArea() {
return taskArea;
}
public void setTaskArea(String taskArea) {
this.taskArea = taskArea;
}
public OffsetDateTime getPublicationTimeStart() {
return publicationTimeStart;
}
public void setPublicationTimeStart(OffsetDateTime publicationTimeStart) {
this.publicationTimeStart = publicationTimeStart;
}
public OffsetDateTime getPublicationTimeEnd() {
return publicationTimeEnd;
}
public void setPublicationTimeEnd(OffsetDateTime publicationTimeEnd) {
this.publicationTimeEnd = publicationTimeEnd;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
| src/main/java/fi/metatavu/kuntaapi/server/integrations/kuntarekry/KuntaRekryJob.java | package fi.metatavu.kuntaapi.server.integrations.kuntarekry;
import java.io.Serializable;
import java.time.OffsetDateTime;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
@SuppressWarnings ("squid:S3437")
public class KuntaRekryJob implements Serializable {
private static final long serialVersionUID = -7272380834345432920L;
@JacksonXmlProperty (localName = "jobtitle")
private String jobTitle;
@JacksonXmlProperty (localName = "employmenttype")
private String employmentType;
@JacksonXmlProperty (localName = "jobdescription")
private String jobDescription;
@JacksonXmlProperty (localName = "jobid")
private Long jobId;
@JacksonXmlProperty (localName = "location")
private String location;
@JacksonXmlProperty (localName = "organisation")
private String organisation;
@JacksonXmlProperty (localName = "organisationalunit")
private String organisationalUnit;
@JacksonXmlProperty (localName = "employmentduration")
private String employmentDuration;
@JacksonXmlProperty (localName = "taskarea")
private String taskArea;
@JacksonXmlProperty (localName = "publicationtimestart")
private OffsetDateTime publicationTimeStart;
@JacksonXmlProperty (localName = "publicationtimeend")
private OffsetDateTime publicationTimeEnd;
@JacksonXmlProperty (localName = "url")
private String url;
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getEmploymentType() {
return employmentType;
}
public void setEmploymentType(String employmentType) {
this.employmentType = employmentType;
}
public String getJobDescription() {
return jobDescription;
}
public void setJobDescription(String jobDescription) {
this.jobDescription = jobDescription;
}
@Deprecated
public Long getJobId() {
return jobId;
}
@Deprecated
public void setJobId(Long jobId) {
this.jobId = jobId;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getOrganisation() {
return organisation;
}
public void setOrganisation(String organisation) {
this.organisation = organisation;
}
public String getOrganisationalUnit() {
return organisationalUnit;
}
public void setOrganisationalUnit(String organisationalUnit) {
this.organisationalUnit = organisationalUnit;
}
public String getEmploymentDuration() {
return employmentDuration;
}
public void setEmploymentDuration(String employmentDuration) {
this.employmentDuration = employmentDuration;
}
public String getTaskArea() {
return taskArea;
}
public void setTaskArea(String taskArea) {
this.taskArea = taskArea;
}
public OffsetDateTime getPublicationTimeStart() {
return publicationTimeStart;
}
public void setPublicationTimeStart(OffsetDateTime publicationTimeStart) {
this.publicationTimeStart = publicationTimeStart;
}
public OffsetDateTime getPublicationTimeEnd() {
return publicationTimeEnd;
}
public void setPublicationTimeEnd(OffsetDateTime publicationTimeEnd) {
this.publicationTimeEnd = publicationTimeEnd;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
| Ignored unknown properties from kunta rekry job
| src/main/java/fi/metatavu/kuntaapi/server/integrations/kuntarekry/KuntaRekryJob.java | Ignored unknown properties from kunta rekry job |
|
Java | agpl-3.0 | 5c9b3bdfd150d9bc670569f8deb6901b58b9daa4 | 0 | geomajas/geomajas-project-server,geomajas/geomajas-project-client-gwt2,geomajas/geomajas-project-client-gwt,geomajas/geomajas-project-client-gwt2,geomajas/geomajas-project-server,geomajas/geomajas-project-client-gwt,geomajas/geomajas-project-client-gwt,geomajas/geomajas-project-server | plugin/geomajas-layer-wms/src/main/java/org/geomajas/layer/wms/WmsLayerParameter.java | /*
* This file is part of Geomajas, a component framework for building
* rich Internet applications (RIA) with sophisticated capabilities for the
* display, analysis and management of geographic information.
* It is a building block that allows developers to add maps
* and other geographic data capabilities to their web applications.
*
* Copyright 2008-2010 Geosparc, http://www.geosparc.com, Belgium
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.geomajas.layer.wms;
/**
*
* @author Oliver May <[email protected]>
*
*/
public class WmsLayerParameter {
private String key;
private String value;
public WmsLayerParameter(String key, String value) {
this.key = key;
this.value = value;
}
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setKey(String key) {
this.key = key;
}
public String getKey() {
return key;
}
}
| MAJ-774 WmsLayer extra parameter
| plugin/geomajas-layer-wms/src/main/java/org/geomajas/layer/wms/WmsLayerParameter.java | MAJ-774 WmsLayer extra parameter |
||
Java | apache-2.0 | 0a3e62397b430f200029e598ac55c79414f562d8 | 0 | dlwhitehurst/blackboard,dlwhitehurst/blackboard | /**
* Copyright 2010 David L. Whitehurst
*
* Licensed under the Apache License, Version 2.0
* (the "License"); You may not use this file except
* in compliance with the License. You may obtain a
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*
*/
package org.dlw.ai.blackboard;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dlw.ai.blackboard.knowledge.KnowledgeSources;
import org.dlw.ai.blackboard.knowledge.primitive.KnowledgeSourcesImpl;
import org.dlw.ai.blackboard.util.SystemConstants;
/**
* <p>
* This class manages the collection of
* {@link org.dlw.ai.blackboard.knowledge.KnowledgeSource} type instances. It
* acts as a brain or collection of cummulative knowledge sources. The
* {@link Controller} will get these knowledge sources when the problem solving
* begins. An interesting class, the {@link Brain} acts as the librarian and
* gathers all intelligent resources for our blackboard problem.
* </p>
*
* <p>
* This class is not extendable and therefore not part of the API. Its use is
* specific to the problem domain being solved by
* {@link org.dlw.ai.blackboard.Main}.
* </p>
*
* <blockquote><i>Brain - "(def.) an organ of soft nervous tissue contained in
* the skull of vertebrates, functioning as the coordinating center of sensation
* and intellectual and nervous activity.</i></blockquote>
*
* @author dlwhitehurst
*
*/
public final class Brain {
/**
* Attribute collection and entire problem domain of knowledge sources
*/
private final KnowledgeSourcesImpl knowledgeSources = new KnowledgeSourcesImpl();
/**
* Attribute class logger
*/
private final Log log = LogFactory.getLog(Brain.class);
/**
* Engage the brain by loading and obtaining a fresh set of knowledge
* sources (intelligence)
*
*/
public void engage() {
knowledgeSources.reset();
/**
* Notify
*/
if (log.isInfoEnabled()) {
log.info("Knowledge sources reset and loaded.");
} else {
System.err.println(SystemConstants.INFO_LEVEL_FATAL);
System.exit(0);
}
}
/**
* @return the knowledgeSources
*/
public KnowledgeSources getKnowledgeSources() {
return knowledgeSources;
}
}
| src/main/java/org/dlw/ai/blackboard/Brain.java | /**
* Copyright 2010 David L. Whitehurst
*
* Licensed under the Apache License, Version 2.0
* (the "License"); You may not use this file except
* in compliance with the License. You may obtain a
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*
*/
package org.dlw.ai.blackboard;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dlw.ai.blackboard.knowledge.KnowledgeSources;
import org.dlw.ai.blackboard.knowledge.primitive.KnowledgeSourcesImpl;
import org.dlw.ai.blackboard.util.SystemConstants;
/**
* <p>
* This class manages the collection of
* {@link org.dlw.ai.blackboard.knowledge.KnowledgeSource} type instances. It
* acts as a brain or collection of cummulative knowledge sources. The
* {@link Controller} will get these knowledge sources when the problem solving
* begins. An interesting class, the {@link Brain} acts as the librarian and
* gathers all intelligent resources for our blackboard problem.
* </p>
*
* <p>
* This class is not extendable and therefore not part of the API. Its use is
* specific to the problem domain being solved by
* {@link org.dlw.ai.blackboard.Main}.
* </p>
*
* <blockquote><i>Brain - "(def.) an organ of soft nervous tissue contained in
* the skull of vertebrates, functioning as the coordinating center of sensation
* and intellectual and nervous activity.</i></blockquote>
*
* @author dlwhitehurst
*
*/
public final class Brain {
/**
* Attribute collection and entire problem domain of knowledge sources
*/
private final KnowledgeSourcesImpl knowledgeSources = new KnowledgeSourcesImpl();
/**
* Attribute class logger
*/
private final Log log = LogFactory.getLog(Brain.class);
/**
* Engage the brain by loading and obtaining a fresh set of knowledge
* sources (intelligence)
*
*/
public void engage() {
knowledgeSources.reset();
/**
* Notify
*/
if (log.isInfoEnabled()) {
log.info("Knowledge sources reset and loaded.");
} else {
System.err.println(SystemConstants.INFO_LEVEL_FATAL);
System.exit(0); // die
}
}
/**
* @return the knowledgeSources
*/
public KnowledgeSources getKnowledgeSources() {
return knowledgeSources;
}
}
| v1.0.0 Release Candidate | src/main/java/org/dlw/ai/blackboard/Brain.java | v1.0.0 Release Candidate |
|
Java | apache-2.0 | 7c4cfe76779fbc5455f939503420fa5ddcaf42cb | 0 | condast/AieonF,condast/AieonF | package org.aieonf.orientdb.cache;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Iterator;
import org.aieonf.commons.parser.ParseException;
import org.aieonf.commons.strings.StringUtils;
import org.aieonf.commons.transaction.AbstractTransaction;
import org.aieonf.commons.transaction.ITransaction;
import org.aieonf.concept.IConcept;
import org.aieonf.concept.IDescriptor;
import org.aieonf.concept.body.BodyFactory;
import org.aieonf.concept.core.Descriptor;
import org.aieonf.concept.domain.IDomainAieon;
import org.aieonf.concept.file.ProjectFolderUtils;
import org.aieonf.concept.loader.ILoaderAieon;
import org.aieonf.concept.loader.LoaderAieon;
import org.aieonf.concept.security.LoginData;
import org.aieonf.model.builder.IModelBuilderListener;
import org.aieonf.model.builder.ModelBuilderEvent;
import org.aieonf.model.filter.IModelFilter;
import org.aieonf.model.provider.IModelDatabase;
import org.aieonf.model.provider.IModelProvider;
import org.aieonf.orientdb.service.LoginConsumer;
import com.orientechnologies.orient.core.db.OPartitionedDatabasePool;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.*;
/**
* Handles the Orient Databae
* @See :https://orientdb.com/docs/2.2/documenttx-Database-Tinkerpop.html
* @author Kees
*
* @param <D>
* @param <Descriptor>
*/
public class CacheDatabase<D extends IDomainAieon> implements IModelDatabase<D, IDescriptor> {
public static final String S_BUNDLE_ID = "org.aieonf.orientdb";
public static final String S_IDENTIFIER = "documenttxModel";
private static final String S_LOCAL = "plocal:";
private static final String S_FILE = "file:";
protected static final String S_ROOT = "Root";
protected static final String S_CACHE = "Cache";
protected static final String S_DESCRIPTORS = "Descriptors";
private ODatabaseDocumentTx database;
private String source;
private boolean connected;
private Collection<IModelBuilderListener<IDescriptor>> listeners;
public CacheDatabase() {
listeners = new ArrayList<IModelBuilderListener<IDescriptor>>();
this.connected = false;
}
/**
* Connect to the database
*
* @param loader
*/
@SuppressWarnings("resource")
protected void connect( IDomainAieon domain ){
if( connected )
return;
LoginData login = LoginConsumer.getLoginData();
if(( login == null ) || !login.isLoggedIn() )
return;
String user = login.getLoginName();
String pwd = login.getPassword();
ILoaderAieon loader = new LoaderAieon( domain);
loader.set( IConcept.Attributes.SOURCE, S_BUNDLE_ID);
loader.setIdentifier( S_CACHE );
File file = ProjectFolderUtils.getDefaultUserFile( loader, true);
source = file.toURI().toString();
source = source.replace( S_FILE, S_LOCAL);
ODatabaseDocumentTx doc = new ODatabaseDocumentTx (source);
if(!doc.exists() ) {
database = doc.create();
database.addCluster(S_DESCRIPTORS);
OSecurity sm = database.getMetadata().getSecurity();
sm.createUser( user, pwd, new String[]{"admin"});
}
else {
OPartitionedDatabasePool pool = new OPartitionedDatabasePool(source , user, pwd );
database = pool.acquire();
}
this.connected = true;
}
@Override
public String getIdentifier(){
return S_IDENTIFIER;
}
@Override
public void addListener(IModelBuilderListener<IDescriptor> listener) {
this.listeners.add(listener);
}
@Override
public void removeListener(IModelBuilderListener<IDescriptor> listener) {
this.listeners.remove(listener);
}
protected final void notifyListeners( ModelBuilderEvent<IDescriptor> event ){
for( IModelBuilderListener<IDescriptor> listener: this.listeners )
listener.notifyChange(event);
}
@Override
public void open( IDomainAieon domain){
try{
this.connect(domain);
if(!connected )
return;
}
catch( Exception ex ){
ex.printStackTrace();
}
}
@Override
public boolean isOpen(){
return !this.database.isClosed();
}
@Override
public void sync(){
try{
this.database.commit();
}
catch( Exception ex ){
ex.printStackTrace();
}
finally{
if( this.database != null )
this.database.rollback();
}
}
public ITransaction<IDescriptor,IModelProvider<D, IDescriptor>> createTransaction() {
Transaction transaction = new Transaction( this );
transaction.create();
return transaction;
}
@Override
public void close(){
//database.commit();
if( database != null )
database.close();
}
@Override
public boolean contains(IDescriptor descriptor) {
for (ODocument document : database.browseClass( descriptor.getName())) {
String id = document.field( IDescriptor.Attributes.ID.name().toLowerCase());
if( descriptor.getID().equals( id ))
return true;
}
return false;
}
@SuppressWarnings("unchecked")
public Collection<IDescriptor> query( String query ){
Collection<ODocument> docs = (Collection<ODocument>) this.database.query(new OSQLSynchQuery<ODocument>(query));
Collection<IDescriptor> results = new ArrayList<IDescriptor>();
for( ODocument doc: docs )
results.add( new ODescriptor( doc ));
return results;
}
@Override
public Collection<IDescriptor> get(IDescriptor descriptor) throws ParseException {
Collection<IDescriptor> results = new ArrayList<IDescriptor>();
for (ODocument document : database.browseClass( descriptor.getName())) {
String id = document.field( IDescriptor.Attributes.ID.name().toLowerCase());
if( descriptor.getID().equals( id ))
results.add( descriptor );
}
return results;
}
@Override
public Collection<IDescriptor> search(IModelFilter<IDescriptor, IDescriptor> filter) throws ParseException {
Collection<IDescriptor> results = new ArrayList<IDescriptor>();
for (ODocument document : database.browseCluster( S_DESCRIPTORS )) {
ODescriptor descriptor = new ODescriptor(document);
if( filter.accept( descriptor ))
results.add( descriptor );
}
return results;
}
@Override
public boolean hasFunction(String function) {
return IModelProvider.DefaultModels.DESCRIPTOR.equals( function );
}
@Override
public boolean add(IDescriptor descriptor) {
ODocument odesc= createDocument( descriptor );
odesc.save( /*S_DESCRIPTORS*/ );//Add to cluster descriptors
return true;
}
@Override
public void remove(IDescriptor descriptor) {
ODescriptor odesc= (ODescriptor) descriptor;
odesc.getDocument().delete();
}
@Override
public boolean update(IDescriptor descriptor ){
ODescriptor odesc= (ODescriptor) descriptor;
odesc.getDocument().save();
return true;
}
@Override
public void deactivate() {
database.close();
}
/**
* Create a descriptor from the given vertex
* @param database
* @param vertex
* @return
*/
protected static ODocument createDocument( IDescriptor describable ){
IDescriptor descriptor = describable.getDescriptor();
ODocument doc = new ODocument( descriptor.getName());
Iterator<String> iterator = descriptor.iterator();
while( iterator.hasNext()) {
String attr = iterator.next();
attr = attr.replace(".", "@8");
String value = descriptor.get( attr );
if( !StringUtils.isEmpty( value ))
doc.field( attr, value);
}
BodyFactory.IDFactory( descriptor );
String date = String.valueOf( Calendar.getInstance().getTimeInMillis());
descriptor.set( IDescriptor.Attributes.CREATE_DATE, date );
return doc;
}
protected class Transaction extends AbstractTransaction<IDescriptor, IModelProvider<D, IDescriptor>>{
protected Transaction( IModelProvider<D,IDescriptor> provider) {
super( provider );
}
public void close() {
super.getProvider().close();
if( !super.getProvider().isOpen())
super.close();
}
@Override
protected boolean onCreate(IModelProvider<D, IDescriptor> provider) {
return super.getProvider().isOpen();
}
}
} | Workspace/org.aieonf.orientdb/src/org/aieonf/orientdb/cache/CacheDatabase.java | package org.aieonf.orientdb.cache;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Iterator;
import org.aieonf.commons.parser.ParseException;
import org.aieonf.commons.strings.StringUtils;
import org.aieonf.commons.transaction.AbstractTransaction;
import org.aieonf.commons.transaction.ITransaction;
import org.aieonf.concept.IConcept;
import org.aieonf.concept.IDescriptor;
import org.aieonf.concept.body.BodyFactory;
import org.aieonf.concept.core.Descriptor;
import org.aieonf.concept.domain.IDomainAieon;
import org.aieonf.concept.file.ProjectFolderUtils;
import org.aieonf.concept.loader.ILoaderAieon;
import org.aieonf.concept.loader.LoaderAieon;
import org.aieonf.concept.security.LoginData;
import org.aieonf.model.builder.IModelBuilderListener;
import org.aieonf.model.builder.ModelBuilderEvent;
import org.aieonf.model.filter.IModelFilter;
import org.aieonf.model.provider.IModelDatabase;
import org.aieonf.model.provider.IModelProvider;
import org.aieonf.orientdb.service.LoginConsumer;
import com.orientechnologies.orient.core.db.OPartitionedDatabasePool;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.*;
/**
* Handles the Orient Databae
* @See :https://orientdb.com/docs/2.2/documenttx-Database-Tinkerpop.html
* @author Kees
*
* @param <D>
* @param <Descriptor>
*/
public class CacheDatabase<D extends IDomainAieon> implements IModelDatabase<D, IDescriptor> {
public static final String S_BUNDLE_ID = "org.aieonf.orientdb";
public static final String S_IDENTIFIER = "documenttxModel";
private static final String S_LOCAL = "plocal:";
private static final String S_FILE = "file:";
protected static final String S_ROOT = "Root";
protected static final String S_CACHE = "Cache";
protected static final String S_DESCRIPTORS = "Descriptors";
private ODatabaseDocumentTx database;
private String source;
private boolean connected;
private Collection<IModelBuilderListener<IDescriptor>> listeners;
public CacheDatabase() {
listeners = new ArrayList<IModelBuilderListener<IDescriptor>>();
this.connected = false;
}
/**
* Connect to the database
*
* @param loader
*/
@SuppressWarnings("resource")
protected void connect( IDomainAieon domain ){
if( connected )
return;
LoginData login = LoginConsumer.getLoginData();
if(( login == null ) || !login.isLoggedIn() )
return;
String user = login.getLoginName();
String pwd = login.getPassword();
ILoaderAieon loader = new LoaderAieon( domain);
loader.set( IConcept.Attributes.SOURCE, S_BUNDLE_ID);
loader.setIdentifier( S_CACHE );
File file = ProjectFolderUtils.getDefaultUserFile( loader, true);
source = file.toURI().toString();
source = source.replace( S_FILE, S_LOCAL);
ODatabaseDocumentTx doc = new ODatabaseDocumentTx (source);
if(!doc.exists() ) {
database = doc.create();
database.addCluster(S_DESCRIPTORS);
OSecurity sm = database.getMetadata().getSecurity();
sm.createUser( user, pwd, new String[]{"admin"});
}
else {
OPartitionedDatabasePool pool = new OPartitionedDatabasePool(source , user, pwd );
database = pool.acquire();
}
this.connected = true;
}
@Override
public String getIdentifier(){
return S_IDENTIFIER;
}
@Override
public void addListener(IModelBuilderListener<IDescriptor> listener) {
this.listeners.add(listener);
}
@Override
public void removeListener(IModelBuilderListener<IDescriptor> listener) {
this.listeners.remove(listener);
}
protected final void notifyListeners( ModelBuilderEvent<IDescriptor> event ){
for( IModelBuilderListener<IDescriptor> listener: this.listeners )
listener.notifyChange(event);
}
@Override
public void open( IDomainAieon domain){
try{
this.connect(domain);
if(!connected )
return;
}
catch( Exception ex ){
ex.printStackTrace();
}
}
@Override
public boolean isOpen(){
return !this.database.isClosed();
}
@Override
public void sync(){
try{
this.database.commit();
}
catch( Exception ex ){
ex.printStackTrace();
}
finally{
if( this.database != null )
this.database.rollback();
}
}
public ITransaction<IDescriptor,IModelProvider<D, IDescriptor>> createTransaction() {
Transaction transaction = new Transaction( this );
transaction.create();
return transaction;
}
@Override
public void close(){
//database.commit();
if( database != null )
database.close();
}
@Override
public boolean contains(IDescriptor descriptor) {
for (ODocument document : database.browseClass( descriptor.getName())) {
String id = document.field( IDescriptor.Attributes.ID.name().toLowerCase());
if( descriptor.getID().equals( id ))
return true;
}
return false;
}
public Collection<IDescriptor> query( String query ){
Collection<IDescriptor> results = this.database.query(new OSQLSynchQuery<ODocument>(query));
return results;
}
@Override
public Collection<IDescriptor> get(IDescriptor descriptor) throws ParseException {
Collection<IDescriptor> results = new ArrayList<IDescriptor>();
for (ODocument document : database.browseClass( descriptor.getName())) {
String id = document.field( IDescriptor.Attributes.ID.name().toLowerCase());
if( descriptor.getID().equals( id ))
results.add( descriptor );
}
return results;
}
@Override
public Collection<IDescriptor> search(IModelFilter<IDescriptor, IDescriptor> filter) throws ParseException {
Collection<IDescriptor> results = new ArrayList<IDescriptor>();
for (ODocument document : database.browseCluster( S_DESCRIPTORS )) {
ODescriptor descriptor = new ODescriptor(document);
if( filter.accept( descriptor ))
results.add( descriptor );
}
return results;
}
@Override
public boolean hasFunction(String function) {
return IModelProvider.DefaultModels.DESCRIPTOR.equals( function );
}
@Override
public boolean add(IDescriptor descriptor) {
ODocument odesc= createDocument( descriptor );
odesc.save( /*S_DESCRIPTORS*/ );//Add to cluster descriptors
return true;
}
@Override
public void remove(IDescriptor descriptor) {
ODescriptor odesc= (ODescriptor) descriptor;
odesc.getDocument().delete();
}
@Override
public boolean update(IDescriptor descriptor ){
ODescriptor odesc= (ODescriptor) descriptor;
odesc.getDocument().save();
return true;
}
@Override
public void deactivate() {
database.close();
}
/**
* Create a descriptor from the given vertex
* @param database
* @param vertex
* @return
*/
protected static ODocument createDocument( IDescriptor describable ){
IDescriptor descriptor = describable.getDescriptor();
ODocument doc = new ODocument( descriptor.getName());
Iterator<String> iterator = descriptor.iterator();
while( iterator.hasNext()) {
String attr = iterator.next();
attr = attr.replace(".", "@8");
String value = descriptor.get( attr );
if( !StringUtils.isEmpty( value ))
doc.field( attr, value);
}
BodyFactory.IDFactory( descriptor );
String date = String.valueOf( Calendar.getInstance().getTimeInMillis());
descriptor.set( IDescriptor.Attributes.CREATE_DATE, date );
return doc;
}
protected class Transaction extends AbstractTransaction<IDescriptor, IModelProvider<D, IDescriptor>>{
protected Transaction( IModelProvider<D,IDescriptor> provider) {
super( provider );
}
public void close() {
super.getProvider().close();
if( !super.getProvider().isOpen())
super.close();
}
@Override
protected boolean onCreate(IModelProvider<D, IDescriptor> provider) {
return super.getProvider().isOpen();
}
}
} | Synchronized with laptop | Workspace/org.aieonf.orientdb/src/org/aieonf/orientdb/cache/CacheDatabase.java | Synchronized with laptop |
|
Java | apache-2.0 | 8df764375de39949271616ae2ecd1d380e11197a | 0 | tokee/lucene,tokee/lucene,tokee/lucene,tokee/lucene | package org.apache.lucene.analysis.shingle;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.Reader;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
/**
* A ShingleAnalyzerWrapper wraps a ShingleFilter around another analyzer. A
* shingle is another namefor a token based n-gram.
*/
public class ShingleAnalyzerWrapper extends Analyzer {
protected Analyzer defaultAnalyzer;
protected int maxShingleSize = 2;
protected boolean outputUnigrams = true;
public ShingleAnalyzerWrapper(Analyzer defaultAnalyzer) {
super();
this.defaultAnalyzer = defaultAnalyzer;
}
public ShingleAnalyzerWrapper(Analyzer defaultAnalyzer, int maxShingleSize) {
this(defaultAnalyzer);
this.maxShingleSize = maxShingleSize;
}
/**
* Wraps {@link StandardAnalyzer}.
*/
public ShingleAnalyzerWrapper() {
super();
this.defaultAnalyzer = new StandardAnalyzer();
}
public ShingleAnalyzerWrapper(int nGramSize) {
this();
this.maxShingleSize = nGramSize;
}
/**
* The max shingle (ngram) size
*
* @return The max shingle (ngram) size
*/
public int getMaxShingleSize() {
return maxShingleSize;
}
/**
* Set the maximum size of output shingles
*
* @param maxShingleSize max shingle size
*/
public void setMaxShingleSize(int maxShingleSize) {
this.maxShingleSize = maxShingleSize;
}
public boolean isOutputUnigrams() {
return outputUnigrams;
}
/**
* Shall the filter pass the original tokens (the "unigrams") to the output
* stream?
*
* @param outputUnigrams Whether or not the filter shall pass the original
* tokens to the output stream
*/
public void setOutputUnigrams(boolean outputUnigrams) {
this.outputUnigrams = outputUnigrams;
}
public TokenStream tokenStream(String fieldName, Reader reader) {
ShingleFilter filter = new ShingleFilter(defaultAnalyzer.tokenStream(
fieldName, reader));
filter.setMaxShingleSize(maxShingleSize);
filter.setOutputUnigrams(outputUnigrams);
return filter;
}
}
| contrib/analyzers/src/java/org/apache/lucene/analysis/shingle/ShingleAnalyzerWrapper.java | package org.apache.lucene.analysis.shingle;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.Reader;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
/**
* A ShingleAnalyzerWrapper wraps a ShingleFilter around another analyzer. A shingle is another term for a token based
* n-gram.
*/
public class ShingleAnalyzerWrapper extends Analyzer {
protected Analyzer defaultAnalyzer;
protected int maxShingleSize = 2;
protected boolean outputUnigrams = true;
public ShingleAnalyzerWrapper(Analyzer defaultAnalyzer) {
super();
this.defaultAnalyzer = defaultAnalyzer;
}
public ShingleAnalyzerWrapper(Analyzer defaultAnalyzer, int maxShingleSize) {
this(defaultAnalyzer);
this.maxShingleSize = maxShingleSize;
}
public ShingleAnalyzerWrapper() {
super();
this.defaultAnalyzer = new StandardAnalyzer();
}
public ShingleAnalyzerWrapper(int nGramSize) {
this();
this.maxShingleSize = nGramSize;
}
/**
* The max shingle (ngram) size
* @return The max shingle (ngram) size
*/
public int getMaxShingleSize() {
return maxShingleSize;
}
/**
* Set the maximum size of output shingles (default: 2)
*
* @param maxShingleSize max shingle size
*/
public void setMaxShingleSize(int maxShingleSize) {
this.maxShingleSize = maxShingleSize;
}
public boolean isOutputUnigrams() {
return outputUnigrams;
}
/**
* Shall the filter pass the original tokens (the "unigrams") to the output
* stream? (default: true)
*
* @param outputUnigrams Whether or not the filter shall pass the original
* tokens to the output stream
*/
public void setOutputUnigrams(boolean outputUnigrams) {
this.outputUnigrams = outputUnigrams;
}
public TokenStream tokenStream(String fieldName, Reader reader) {
ShingleFilter filter
= new ShingleFilter(defaultAnalyzer.tokenStream(fieldName, reader));
filter.setMaxShingleSize(maxShingleSize);
filter.setOutputUnigrams(outputUnigrams);
return filter;
}
}
| - Fixed messed up indentation/tabs
git-svn-id: 4c5078813df38efa56971a28e09a55254294f104@657281 13f79535-47bb-0310-9956-ffa450edef68
| contrib/analyzers/src/java/org/apache/lucene/analysis/shingle/ShingleAnalyzerWrapper.java | - Fixed messed up indentation/tabs |
|
Java | apache-2.0 | 1f250eedfa4d3b2d7d6cdc432f3ce9fe2099893b | 0 | opensingular/singular-core,opensingular/singular-core,opensingular/singular-core,opensingular/singular-core | /*
* Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opensingular.form.wicket.mapper;
import static org.apache.commons.lang3.StringUtils.*;
import static org.opensingular.form.wicket.mapper.components.MetronicPanel.*;
import static org.opensingular.lib.wicket.util.util.Shortcuts.*;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.resource.PackageResourceReference;
import org.opensingular.form.SIList;
import org.opensingular.form.SInstance;
import org.opensingular.form.SType;
import org.opensingular.form.decorator.action.ISInstanceActionCapable;
import org.opensingular.form.decorator.action.ISInstanceActionsProvider;
import org.opensingular.form.view.SViewListByForm;
import org.opensingular.form.wicket.WicketBuildContext;
import org.opensingular.form.wicket.feedback.SValidationFeedbackPanel;
import org.opensingular.form.wicket.mapper.components.MetronicPanel;
import org.opensingular.form.wicket.mapper.decorator.SInstanceActionsPanel;
import org.opensingular.form.wicket.mapper.decorator.SInstanceActionsProviders;
import org.opensingular.form.wicket.model.ReadOnlyCurrentInstanceModel;
import org.opensingular.lib.commons.lambda.IFunction;
import org.opensingular.lib.wicket.util.bootstrap.layout.BSCol;
import org.opensingular.lib.wicket.util.bootstrap.layout.BSContainer;
import org.opensingular.lib.wicket.util.bootstrap.layout.BSGrid;
import org.opensingular.lib.wicket.util.bootstrap.layout.BSRow;
import org.opensingular.lib.wicket.util.bootstrap.layout.TemplatePanel;
import org.opensingular.lib.wicket.util.resource.DefaultIcons;
public class PanelListMapper extends AbstractListMapper implements ISInstanceActionCapable {
private SInstanceActionsProviders instanceActionsProviders = new SInstanceActionsProviders(this);
@Override
public void addSInstanceActionsProvider(int sortPosition, ISInstanceActionsProvider provider) {
this.instanceActionsProviders.addSInstanceActionsProvider(sortPosition, provider);
}
@Override
public void buildView(WicketBuildContext ctx) {
final BSContainer<?> parentCol = ctx.getContainer();
parentCol.appendComponent((id) -> this.newPanel(id, ctx));
}
private MetronicPanel newPanel(String id, WicketBuildContext ctx) {
final IModel<SIList<SInstance>> listaModel = new ReadOnlyCurrentInstanceModel<>(ctx);
final SIList<?> iLista = listaModel.getObject();
final IModel<String> label = $m.ofValue(trimToEmpty(iLista.asAtr().getLabel()));
final SViewListByForm view = (SViewListByForm) ctx.getView();
final SType<?> currentType = ctx.getCurrentInstance().getType();
addMinimumSize(currentType, iLista);
ctx.configureContainer(label);
MetronicPanel panel = MetronicPanel.MetronicPanelBuilder.build(id,
(heading, form) -> {
heading.appendTag("span", new Label("_title", label));
IFunction<AjaxRequestTarget, List<?>> internalContextListProvider = target -> Arrays.asList(
this,
RequestCycle.get().find(AjaxRequestTarget.class),
listaModel,
listaModel.getObject(),
ctx,
ctx.getContainer());
SInstanceActionsPanel.addPrimarySecondaryPanelsTo(
heading,
this.instanceActionsProviders,
listaModel,
true,
internalContextListProvider);
heading.add($b.visibleIf(() -> ctx.getHint(HIDE_LABEL)
|| !this.instanceActionsProviders.actionList(listaModel).isEmpty()));
},
(content, form) -> {
TemplatePanel list = content.newTemplateTag(t -> ""
+ " <ul wicket:id='_u' class='list-group list-by-form'>"
+ " <li wicket:id='_e' class='list-group-item' style='margin-bottom:15px'>"
+ " <div wicket:id='_r'></div>"
+ " </li>"
+ " <div wicket:id='_empty' class='list-by-form-empty-state'>"
+ " <span>Nenhum item foi adicionado</span>"
+ " </div>"
+ " </ul>");
final WebMarkupContainer container = new WebMarkupContainer("_u");
final PanelElementsView elements = new PanelElementsView("_e", listaModel, ctx, view, form, container);
final WebMarkupContainer empty = new WebMarkupContainer("_empty");
list
.add(container
.add(elements
.add($b.onConfigure(c -> c.setVisible(!listaModel.getObject().isEmpty()))))
.add(empty
.add($b.onConfigure(c -> c.setVisible(listaModel.getObject().isEmpty())))));
content.add($b.attrAppender("style", "padding: 15px 15px 10px 15px", ";"));
content.getParent()
.add(dependsOnModifier(listaModel));
},
(f, form) -> {
buildFooter(f, form, ctx);
SValidationFeedbackPanel feedback = ctx.createFeedbackPanel("feedback").setShowBox(true);
AttributeAppender style = $b.attrAppender("style", "margin-top: 15px", ";");
feedback.add(style);
f.appendTag("div", feedback);
});
return panel;
}
private static final class PanelElementsView extends ElementsView {
private final SViewListByForm view;
private final Form<?> form;
private final WicketBuildContext ctx;
private PanelElementsView(String id,
IModel<SIList<SInstance>> model,
WicketBuildContext ctx,
SViewListByForm view,
Form<?> form,
WebMarkupContainer parentContainer) {
super(id, model, parentContainer);
this.ctx = ctx;
this.view = view;
this.form = form;
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
PackageResourceReference cssFile =
new PackageResourceReference(this.getClass(), "PanelElementsView.js");
JavaScriptHeaderItem javascriptItem = JavaScriptHeaderItem.forReference(cssFile);
response.render(javascriptItem);
// response.render(OnDomReadyHeaderItem.forScript("appendListItemEvent();"));
}
@Override
protected void populateItem(Item<SInstance> item) {
BSGrid grid = new BSGrid("_r");
buildHeader(item, grid);
buildBody(item, grid);
item.add(grid);
}
private void buildHeader(Item<SInstance> item, BSGrid grid) {
final BSRow header = grid.newRow();
header.add($b.classAppender("list-item-header"));
final BSCol title = header.newCol(11).newGrid().newColInRow();
Model<Serializable> model = new Model<Serializable>() {
@Override
public Serializable getObject() {
if (view.getHeaderPath() != null) {
return Optional.ofNullable(item.getModelObject().getValue(view.getHeaderPath())).orElse("").toString();
} else {
return item.getModelObject().toStringDisplay();
}
}
};
title.newTemplateTag(tp -> "<span wicket:id='_title' ></span>")
.add(new Label("_title", model));
final BSGrid btnGrid = header.newCol(1).newGrid();
header.add($b.classAppender("list-icons"));
if ((view != null) && (view.isInsertEnabled()) && ctx.getViewMode().isEdition()) {
appendInserirButton(this, form, item, btnGrid.newColInRow()).add($b.classAppender("pull-right"));
}
final BSCol btnCell = btnGrid.newColInRow();
if ((view != null) && view.isDeleteEnabled() && ctx.getViewMode().isEdition()) {
appendRemoverIconButton(this, form, item, btnCell).add($b.classAppender("pull-right"));
}
}
private void buildBody(Item<SInstance> item, BSGrid grid) {
final BSRow body = grid.newRow();
body.add($b.classAppender("list-item-body"));
ctx.createChild(body.newCol(12), item.getModel()).build();
}
}
protected static RemoverButton appendRemoverIconButton(ElementsView elementsView, Form<?> form, Item<SInstance> item, BSContainer<?> cell) {
final RemoverButton btn = new RemoverButton("_remover_", form, elementsView, item);
cell
.newTemplateTag(tp -> "<i wicket:id='_remover_' class='singular-remove-btn " + DefaultIcons.REMOVE + "' />")
.add(btn);
return btn;
}
} | form/wicket/src/main/java/org/opensingular/form/wicket/mapper/PanelListMapper.java | /*
* Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opensingular.form.wicket.mapper;
import static org.apache.commons.lang3.StringUtils.*;
import static org.opensingular.form.wicket.mapper.components.MetronicPanel.*;
import static org.opensingular.lib.wicket.util.util.Shortcuts.*;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.resource.PackageResourceReference;
import org.opensingular.form.SIList;
import org.opensingular.form.SInstance;
import org.opensingular.form.SType;
import org.opensingular.form.decorator.action.ISInstanceActionCapable;
import org.opensingular.form.decorator.action.ISInstanceActionsProvider;
import org.opensingular.form.view.SViewListByForm;
import org.opensingular.form.wicket.WicketBuildContext;
import org.opensingular.form.wicket.mapper.components.MetronicPanel;
import org.opensingular.form.wicket.mapper.decorator.SInstanceActionsPanel;
import org.opensingular.form.wicket.mapper.decorator.SInstanceActionsProviders;
import org.opensingular.form.wicket.model.ReadOnlyCurrentInstanceModel;
import org.opensingular.lib.commons.lambda.IFunction;
import org.opensingular.lib.wicket.util.bootstrap.layout.BSCol;
import org.opensingular.lib.wicket.util.bootstrap.layout.BSContainer;
import org.opensingular.lib.wicket.util.bootstrap.layout.BSGrid;
import org.opensingular.lib.wicket.util.bootstrap.layout.BSRow;
import org.opensingular.lib.wicket.util.bootstrap.layout.TemplatePanel;
import org.opensingular.lib.wicket.util.resource.DefaultIcons;
public class PanelListMapper extends AbstractListMapper implements ISInstanceActionCapable {
private SInstanceActionsProviders instanceActionsProviders = new SInstanceActionsProviders(this);
@Override
public void addSInstanceActionsProvider(int sortPosition, ISInstanceActionsProvider provider) {
this.instanceActionsProviders.addSInstanceActionsProvider(sortPosition, provider);
}
@Override
public void buildView(WicketBuildContext ctx) {
final BSContainer<?> parentCol = ctx.getContainer();
parentCol.appendComponent((id) -> this.newPanel(id, ctx));
}
private MetronicPanel newPanel(String id, WicketBuildContext ctx) {
final IModel<SIList<SInstance>> listaModel = new ReadOnlyCurrentInstanceModel<>(ctx);
final SIList<?> iLista = listaModel.getObject();
final IModel<String> label = $m.ofValue(trimToEmpty(iLista.asAtr().getLabel()));
final SViewListByForm view = (SViewListByForm) ctx.getView();
final SType<?> currentType = ctx.getCurrentInstance().getType();
addMinimumSize(currentType, iLista);
ctx.configureContainer(label);
MetronicPanel panel = MetronicPanel.MetronicPanelBuilder.build(id,
(heading, form) -> {
heading.appendTag("span", new Label("_title", label));
IFunction<AjaxRequestTarget, List<?>> internalContextListProvider = target -> Arrays.asList(
this,
RequestCycle.get().find(AjaxRequestTarget.class),
listaModel,
listaModel.getObject(),
ctx,
ctx.getContainer());
SInstanceActionsPanel.addPrimarySecondaryPanelsTo(
heading,
this.instanceActionsProviders,
listaModel,
true,
internalContextListProvider);
heading.add($b.visibleIf(() -> ctx.getHint(HIDE_LABEL)
|| !this.instanceActionsProviders.actionList(listaModel).isEmpty()));
},
(content, form) -> {
TemplatePanel list = content.newTemplateTag(t -> ""
+ " <ul wicket:id='_u' class='list-group list-by-form'>"
+ " <li wicket:id='_e' class='list-group-item' style='margin-bottom:15px'>"
+ " <div wicket:id='_r'></div>"
+ " </li>"
+ " <div wicket:id='_empty' class='list-by-form-empty-state'>"
+ " <span>Nenhum item foi adicionado</span>"
+ " </div>"
+ " </ul>");
final WebMarkupContainer container = new WebMarkupContainer("_u");
final PanelElementsView elements = new PanelElementsView("_e", listaModel, ctx, view, form, container);
final WebMarkupContainer empty = new WebMarkupContainer("_empty");
list
.add(container
.add(elements
.add($b.onConfigure(c -> c.setVisible(!listaModel.getObject().isEmpty()))))
.add(empty
.add($b.onConfigure(c -> c.setVisible(listaModel.getObject().isEmpty())))));
content.add($b.attrAppender("style", "padding: 15px 15px 10px 15px", ";"));
content.getParent()
.add(dependsOnModifier(listaModel));
},
(f, form) -> buildFooter(f, form, ctx));
return panel;
}
private static final class PanelElementsView extends ElementsView {
private final SViewListByForm view;
private final Form<?> form;
private final WicketBuildContext ctx;
private PanelElementsView(String id,
IModel<SIList<SInstance>> model,
WicketBuildContext ctx,
SViewListByForm view,
Form<?> form,
WebMarkupContainer parentContainer) {
super(id, model, parentContainer);
this.ctx = ctx;
this.view = view;
this.form = form;
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
PackageResourceReference cssFile =
new PackageResourceReference(this.getClass(), "PanelElementsView.js");
JavaScriptHeaderItem javascriptItem = JavaScriptHeaderItem.forReference(cssFile);
response.render(javascriptItem);
// response.render(OnDomReadyHeaderItem.forScript("appendListItemEvent();"));
}
@Override
protected void populateItem(Item<SInstance> item) {
BSGrid grid = new BSGrid("_r");
buildHeader(item, grid);
buildBody(item, grid);
item.add(grid);
}
private void buildHeader(Item<SInstance> item, BSGrid grid) {
final BSRow header = grid.newRow();
header.add($b.classAppender("list-item-header"));
final BSCol title = header.newCol(11).newGrid().newColInRow();
Model<Serializable> model = new Model<Serializable>() {
@Override
public Serializable getObject() {
if (view.getHeaderPath() != null) {
return Optional.ofNullable(item.getModelObject().getValue(view.getHeaderPath())).orElse("").toString();
} else {
return item.getModelObject().toStringDisplay();
}
}
};
title.newTemplateTag(tp -> "<span wicket:id='_title' ></span>")
.add(new Label("_title", model));
final BSGrid btnGrid = header.newCol(1).newGrid();
header.add($b.classAppender("list-icons"));
if ((view != null) && (view.isInsertEnabled()) && ctx.getViewMode().isEdition()) {
appendInserirButton(this, form, item, btnGrid.newColInRow()).add($b.classAppender("pull-right"));
}
final BSCol btnCell = btnGrid.newColInRow();
if ((view != null) && view.isDeleteEnabled() && ctx.getViewMode().isEdition()) {
appendRemoverIconButton(this, form, item, btnCell).add($b.classAppender("pull-right"));
}
}
private void buildBody(Item<SInstance> item, BSGrid grid) {
final BSRow body = grid.newRow();
body.add($b.classAppender("list-item-body"));
ctx.createChild(body.newCol(12), item.getModel()).build();
}
}
protected static RemoverButton appendRemoverIconButton(ElementsView elementsView, Form<?> form, Item<SInstance> item, BSContainer<?> cell) {
final RemoverButton btn = new RemoverButton("_remover_", form, elementsView, item);
cell
.newTemplateTag(tp -> "<i wicket:id='_remover_' class='singular-remove-btn " + DefaultIcons.REMOVE + "' />")
.add(btn);
return btn;
}
} | [FORM-WICKET] - Inclusão de mensagem de validação para Mapper do SViewByForm.
| form/wicket/src/main/java/org/opensingular/form/wicket/mapper/PanelListMapper.java | [FORM-WICKET] - Inclusão de mensagem de validação para Mapper do SViewByForm. |
|
Java | apache-2.0 | 8df6c043ab281010f779f69d8ea413960d0bc077 | 0 | cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x | package org.springframework.jdbc.datasource;
/**
* DataSource transaction object, representing a ConnectionHolder.
* Used as transaction object by DataSourceTransactionManager.
*
* <p>Note: This is an SPI class, not intended to be used by applications.
*
* @author Juergen Hoeller
* @since 02.05.2003
* @see DataSourceTransactionManager
* @see ConnectionHolder
* @version $Id: DataSourceTransactionObject.java,v 1.4 2003-12-30 01:02:44 jhoeller Exp $
*/
public class DataSourceTransactionObject {
private ConnectionHolder connectionHolder;
private Integer previousIsolationLevel;
private boolean mustRestoreAutoCommit;
/**
* Create DataSourceTransactionObject for new ConnectionHolder.
*/
public DataSourceTransactionObject() {
}
/**
* Create DataSourceTransactionObject for existing ConnectionHolder.
*/
protected DataSourceTransactionObject(ConnectionHolder connectionHolder) {
this.connectionHolder = connectionHolder;
}
/**
* Set new ConnectionHolder.
*/
protected void setConnectionHolder(ConnectionHolder connectionHolder) {
this.connectionHolder = connectionHolder;
}
public ConnectionHolder getConnectionHolder() {
return connectionHolder;
}
protected void setPreviousIsolationLevel(Integer previousIsolationLevel) {
this.previousIsolationLevel = previousIsolationLevel;
}
public Integer getPreviousIsolationLevel() {
return previousIsolationLevel;
}
public void setMustRestoreAutoCommit(boolean mustRestoreAutoCommit) {
this.mustRestoreAutoCommit = mustRestoreAutoCommit;
}
public boolean getMustRestoreAutoCommit() {
return mustRestoreAutoCommit;
}
}
| src/org/springframework/jdbc/datasource/DataSourceTransactionObject.java | package org.springframework.jdbc.datasource;
/**
* DataSource transaction object, representing a ConnectionHolder.
* Used as transaction object by DataSourceTransactionManager.
*
* <p>Note: This is an SPI class, not intended to be used by applications.
*
* @author Juergen Hoeller
* @since 02.05.2003
* @see DataSourceTransactionManager
* @see ConnectionHolder
* @version $Id: DataSourceTransactionObject.java,v 1.3 2003-11-27 14:32:42 johnsonr Exp $
*/
public class DataSourceTransactionObject {
private ConnectionHolder connectionHolder;
private Integer previousIsolationLevel;
private boolean mustRestoreAutoCommit;
/**
* Create DataSourceTransactionObject for new ConnectionHolder.
*/
public DataSourceTransactionObject() {
}
/**
* Create DataSourceTransactionObject for existing ConnectionHolder.
*/
protected DataSourceTransactionObject(ConnectionHolder connectionHolder) {
this.connectionHolder = connectionHolder;
}
/**
* Set new ConnectionHolder.
*/
protected void setConnectionHolder(ConnectionHolder connectionHolder) {
this.connectionHolder = connectionHolder;
}
public ConnectionHolder getConnectionHolder() {
return connectionHolder;
}
protected void setPreviousIsolationLevel(Integer previousIsolationLevel) {
this.previousIsolationLevel = previousIsolationLevel;
}
public Integer getPreviousIsolationLevel() {
return previousIsolationLevel;
}
/**
* @return was autocommit previously set?
*/
public boolean getMustRestoreAutoCommit() {
return mustRestoreAutoCommit;
}
/**
* @param whether autocommit was previously set?
*/
public void setMustRestoreAutoCommit(boolean mustRestoreAutoCommit) {
this.mustRestoreAutoCommit = mustRestoreAutoCommit;
}
}
| polishing
git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@1115 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
| src/org/springframework/jdbc/datasource/DataSourceTransactionObject.java | polishing |
|
Java | apache-2.0 | ca794b627cd7ce9634ce215d39bc757d49e5810f | 0 | bpzhang/dubbo,fengyie007/dubbo,bpzhang/dubbo,fengyie007/dubbo,bpzhang/dubbo,lovepoem/dubbo,wuwen5/dubbo,wuwen5/dubbo,fengyie007/dubbo,lovepoem/dubbo,wuwen5/dubbo,lovepoem/dubbo | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.serialize.ObjectInput;
import org.apache.dubbo.common.serialize.ObjectOutput;
import org.apache.dubbo.common.serialize.Serialization;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceRepository;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class CodecSupport {
private static final Logger logger = LoggerFactory.getLogger(CodecSupport.class);
private static Map<Byte, Serialization> ID_SERIALIZATION_MAP = new HashMap<Byte, Serialization>();
private static Map<Byte, String> ID_SERIALIZATIONNAME_MAP = new HashMap<Byte, String>();
private static Map<String, Byte> SERIALIZATIONNAME_ID_MAP = new HashMap<String, Byte>();
// Cache null object serialize results, for heartbeat request/response serialize use.
private static Map<Byte, byte[]> ID_NULLBYTES_MAP = new HashMap<Byte, byte[]>();
private static final ThreadLocal<byte[]> TL_BUFFER = ThreadLocal.withInitial(() -> new byte[1024]);
static {
Set<String> supportedExtensions = ExtensionLoader.getExtensionLoader(Serialization.class).getSupportedExtensions();
for (String name : supportedExtensions) {
Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(name);
byte idByte = serialization.getContentTypeId();
if (ID_SERIALIZATION_MAP.containsKey(idByte)) {
logger.error("Serialization extension " + serialization.getClass().getName()
+ " has duplicate id to Serialization extension "
+ ID_SERIALIZATION_MAP.get(idByte).getClass().getName()
+ ", ignore this Serialization extension");
continue;
}
ID_SERIALIZATION_MAP.put(idByte, serialization);
ID_SERIALIZATIONNAME_MAP.put(idByte, name);
SERIALIZATIONNAME_ID_MAP.put(name, idByte);
}
}
private CodecSupport() {
}
public static Serialization getSerializationById(Byte id) {
return ID_SERIALIZATION_MAP.get(id);
}
public static Byte getIDByName(String name) {
return SERIALIZATIONNAME_ID_MAP.get(name);
}
public static Serialization getSerialization(URL url) {
return ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(
url.getParameter(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION));
}
public static Serialization getSerialization(URL url, Byte id) throws IOException {
Serialization result = getSerializationById(id);
if (result == null) {
throw new IOException("Unrecognized serialize type from consumer: " + id);
}
return result;
}
public static ObjectInput deserialize(URL url, InputStream is, byte proto) throws IOException {
Serialization s = getSerialization(url, proto);
return s.deserialize(url, is);
}
/**
* Get the null object serialize result byte[] of Serialization from the cache,
* if not, generate it first.
*
* @param s Serialization Instances
* @return serialize result of null object
*/
public static byte[] getNullBytesOf(Serialization s) {
return ID_NULLBYTES_MAP.computeIfAbsent(s.getContentTypeId(), k -> {
//Pre-generated Null object bytes
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] nullBytes = new byte[0];
try {
ObjectOutput out = s.serialize(null, baos);
out.writeObject(null);
out.flushBuffer();
nullBytes = baos.toByteArray();
baos.close();
} catch (Exception e) {
logger.warn("Serialization extension " + s.getClass().getName() + " not support serializing null object, return an empty bytes instead.");
}
return nullBytes;
});
}
/**
* Read all payload to byte[]
*
* @param is
* @return
* @throws IOException
*/
public static byte[] getPayload(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = getBuffer(is.available());
int len;
while ((len = is.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
return baos.toByteArray();
}
private static byte[] getBuffer(int size) {
byte[] bytes = TL_BUFFER.get();
if (size <= bytes.length) {
return bytes;
}
return new byte[size];
}
/**
* Check if payload is null object serialize result byte[] of serialization
*
* @param payload
* @param proto
* @return
*/
public static boolean isHeartBeat(byte[] payload, byte proto) {
return Arrays.equals(payload, getNullBytesOf(getSerializationById(proto)));
}
public static void checkSerialization(String path, String version, Byte id) throws IOException {
ServiceRepository repository = ApplicationModel.getServiceRepository();
ProviderModel providerModel = repository.lookupExportedServiceWithoutGroup(path + ":" + version);
if (providerModel == null) {
throw new IOException("Service " + path + " with version " + version + " not found, invocation rejected.");
} else {
List<URL> urls = providerModel.getServiceConfig().getExportedUrls();
if (CollectionUtils.isNotEmpty(urls)) {
URL url = urls.get(0);
String serializationName = url.getParameter(org.apache.dubbo.remoting.Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION);
Byte localId = SERIALIZATIONNAME_ID_MAP.get(serializationName);
if (localId != null && !localId.equals(id)) {
throw new IOException("Unexpected serialization id:" + id + " received from network, please check if the peer send the right id.");
}
}
}
}
}
| dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.remoting.transport;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.serialize.ObjectInput;
import org.apache.dubbo.common.serialize.ObjectOutput;
import org.apache.dubbo.common.serialize.Serialization;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceRepository;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class CodecSupport {
private static final Logger logger = LoggerFactory.getLogger(CodecSupport.class);
private static Map<Byte, Serialization> ID_SERIALIZATION_MAP = new HashMap<Byte, Serialization>();
private static Map<Byte, String> ID_SERIALIZATIONNAME_MAP = new HashMap<Byte, String>();
private static Map<String, Byte> SERIALIZATIONNAME_ID_MAP = new HashMap<String, Byte>();
// Cache null object serialize results, for heartbeat request/response serialize use.
private static Map<Byte, byte[]> ID_NULLBYTES_MAP = new HashMap<Byte, byte[]>();
private static final ThreadLocal<byte[]> TL_BUFFER = ThreadLocal.withInitial(() -> new byte[1024]);
static {
Set<String> supportedExtensions = ExtensionLoader.getExtensionLoader(Serialization.class).getSupportedExtensions();
for (String name : supportedExtensions) {
Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(name);
byte idByte = serialization.getContentTypeId();
if (ID_SERIALIZATION_MAP.containsKey(idByte)) {
logger.error("Serialization extension " + serialization.getClass().getName()
+ " has duplicate id to Serialization extension "
+ ID_SERIALIZATION_MAP.get(idByte).getClass().getName()
+ ", ignore this Serialization extension");
continue;
}
ID_SERIALIZATION_MAP.put(idByte, serialization);
ID_SERIALIZATIONNAME_MAP.put(idByte, name);
SERIALIZATIONNAME_ID_MAP.put(name, idByte);
}
}
private CodecSupport() {
}
public static Serialization getSerializationById(Byte id) {
return ID_SERIALIZATION_MAP.get(id);
}
public static Byte getIDByName(String name) {
return SERIALIZATIONNAME_ID_MAP.get(name);
}
public static Serialization getSerialization(URL url) {
return ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(
url.getParameter(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION));
}
public static Serialization getSerialization(URL url, Byte id) throws IOException {
Serialization result = getSerializationById(id);
if (result == null) {
throw new IOException("Unrecognized serialize type from consumer: " + id);
}
return result;
}
public static ObjectInput deserialize(URL url, InputStream is, byte proto) throws IOException {
Serialization s = getSerialization(url, proto);
return s.deserialize(url, is);
}
/**
* Get the null object serialize result byte[] of Serialization from the cache,
* if not, generate it first.
*
* @param s Serialization Instances
* @return serialize result of null object
*/
public static byte[] getNullBytesOf(Serialization s) {
return ID_NULLBYTES_MAP.computeIfAbsent(s.getContentTypeId(), k -> {
//Pre-generated Null object bytes
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] nullBytes = new byte[0];
try {
ObjectOutput out = s.serialize(null, baos);
out.writeObject(null);
out.flushBuffer();
nullBytes = baos.toByteArray();
baos.close();
} catch (Exception e) {
logger.warn("Serialization extension " + s.getClass().getName() + " not support serializing null object, return an empty bytes instead.");
}
return nullBytes;
});
}
/**
* Read all payload to byte[]
*
* @param is
* @return
* @throws IOException
*/
public static byte[] getPayload(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = getBuffer(is.available());
int len;
while ((len = is.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
return baos.toByteArray();
}
private static byte[] getBuffer(int size) {
byte[] bytes = TL_BUFFER.get();
if (size <= bytes.length) {
return bytes;
}
return new byte[size];
}
/**
* Check if payload is null object serialize result byte[] of serialization
*
* @param payload
* @param proto
* @return
*/
public static boolean isHeartBeat(byte[] payload, byte proto) {
return Arrays.equals(payload, getNullBytesOf(getSerializationById(proto)));
}
public static void checkSerialization(String path, String version, Byte id) throws IOException {
ServiceRepository repository = ApplicationModel.getServiceRepository();
ProviderModel providerModel = repository.lookupExportedServiceWithoutGroup(path + ":" + version);
if (providerModel == null) {
if (logger.isWarnEnabled()) {
logger.warn("Serialization security check is enabled but cannot work as expected because " +
"there's no matched provider model for path " + path + ", version " + version);
}
} else {
List<URL> urls = providerModel.getServiceConfig().getExportedUrls();
if (CollectionUtils.isNotEmpty(urls)) {
URL url = urls.get(0);
String serializationName = url.getParameter(org.apache.dubbo.remoting.Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION);
Byte localId = SERIALIZATIONNAME_ID_MAP.get(serializationName);
if (localId != null && !localId.equals(id)) {
throw new IOException("Unexpected serialization id:" + id + " received from network, please check if the peer send the right id.");
}
}
}
}
}
| throw exception on path+version not found when decoding request (#8357)
| dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/transport/CodecSupport.java | throw exception on path+version not found when decoding request (#8357) |
|
Java | apache-2.0 | ce4d7d7dde5298b3cb716929499cca16cf89657d | 0 | googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020,googleinterns/step240-2020 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.graphgeckos.dashboard.fetchers.github;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.client.util.Preconditions;
import com.google.graphgeckos.dashboard.datatypes.GitHubData;
import com.google.graphgeckos.dashboard.storage.DatastoreRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.lang.NonNull;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;
/** A (external) BuildBot API json data fetcher. */
public class GitHubClient {
/** Provides access to the storage. */
@Autowired
private DatastoreRepository datastoreRepository;
/** Base url of the BuildBot API, LLVM BuildBot API base url is "http://lab.llvm.org:8011/json/builders" */
private String baseUrl;
private static final Logger logger = Logger.getLogger(GitHubClient.class.getName());
private GitHubClient(@NonNull String baseUrl) {
this.baseUrl = Preconditions.checkNotNull(baseUrl);
}
public GitHubClient() {
this("https://api.github.com/repos/llvm/llvm-project/commits/master");
}
/**
* Starts fetching process. Fetches data every {@code delay} seconds from the url:
* {@code baseUrl}/{@code buildBot}/builds/{@code buildId}?as_text=1.
* E.g with buildBot = "clang-x86_64-debian-fast" and buildId = 1000,
* baseUrl = "http://lab.llvm.org:8011/json/builders" the request url will be
* http://lab.llvm.org:8011/json/builders/clang-x86_64-debian-fast/builds/1000?as_text=1 .
* Adds valid fetched data in the form of {@link BuildBotData} to the storage and tries
* to fetch an entry with the next buildId after waiting for {@code delay} seconds.
* If the fetched data is empty (invalid) waits for {@code delay} seconds and tries
* to make the same request.
*
* @param buildBot name of the BuildBot as it is in the API (e.g "clang-x86_64-debian-fast")
* @param initialBuildId the id of the BuildBot's build from where to start fetching data
*/
public void run(@NonNull long delay) {
logger.info(String.format("GitHub: started fetching from the base url: %s",
baseUrl));
WebClient.builder().baseUrl(baseUrl)
.defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.build()
.get()
.uri("/")
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(String.class)
.delaySubscription(Duration.ofSeconds(delay))
.onErrorResume(e -> {
logger.info("Ignoring error: " + e.getMessage());
return Mono.empty();
})
.repeat()
.subscribe(response -> {
if (response.isEmpty()) {
logger.info(
String.format("GitHub: Error occurred, waiting for %d seconds", delay));
return;
}
logger.info(String.format("GitHub: trying to deserialize valid JSON"));
try {
GitHubData gitHubData = new ObjectMapper().readValue(response, GitHubData.class);
datastoreRepository.createRevisionEntry(gitHubData);
} catch (Exception e) {
logger.info(String.format("GitHub: can't deserialize JSON"));
e.printStackTrace();
}
logger.info(
String.format(
"GitHub: Performing re-request in %d seconds", delay));
});
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
}
| src/main/java/com/google/graphgeckos/dashboard/fetchers/github/GitHubClient.java | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.graphgeckos.dashboard.fetchers.buildbot;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.client.util.Preconditions;
import com.google.graphgeckos.dashboard.datatypes.GitHubData;
import com.google.graphgeckos.dashboard.storage.DatastoreRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.lang.NonNull;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;
/** A (external) BuildBot API json data fetcher. */
public class BuildBotClient {
/** Provides access to the storage. */
@Autowired
private DatastoreRepository datastoreRepository;
/** Base url of the BuildBot API, LLVM BuildBot API base url is "http://lab.llvm.org:8011/json/builders" */
private String baseUrl;
private static final Logger logger = Logger.getLogger(BuildBotClient.class.getName());
public BuildBotClient(@NonNull String baseUrl) {
this.baseUrl = Preconditions.checkNotNull(baseUrl);
}
/**
* Starts fetching process. Fetches data every {@code delay} seconds from the url:
* {@code baseUrl}/{@code buildBot}/builds/{@code buildId}?as_text=1.
* E.g with buildBot = "clang-x86_64-debian-fast" and buildId = 1000,
* baseUrl = "http://lab.llvm.org:8011/json/builders" the request url will be
* http://lab.llvm.org:8011/json/builders/clang-x86_64-debian-fast/builds/1000?as_text=1 .
* Adds valid fetched data in the form of {@link BuildBotData} to the storage and tries
* to fetch an entry with the next buildId after waiting for {@code delay} seconds.
* If the fetched data is empty (invalid) waits for {@code delay} seconds and tries
* to make the same request.
*
* @param buildBot name of the BuildBot as it is in the API (e.g "clang-x86_64-debian-fast")
* @param initialBuildId the id of the BuildBot's build from where to start fetching data
*/
public void run(@NonNull String buildBot, long initialBuildId, long delay) {
AtomicLong buildId = new AtomicLong(initialBuildId);
logger.info(String.format("Builder %s: started fetching from the base url: %s",
Preconditions.checkNotNull(initialBuildId), baseUrl));
WebClient.builder().baseUrl(baseUrl)
.defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.build()
.get()
.uri(String.format( "/%s/builds/%d?as_text=1", buildBot, buildId.get()))
.accept(MediaType.TEXT_PLAIN)
.retrieve()
.bodyToMono(String.class)
.delaySubscription(Duration.ofSeconds(delay))
.onErrorResume(e -> {
logger.info("Ignoring error: " + e.getMessage());
return Mono.empty();
})
.repeat()
.subscribe(response -> {
if (response.isEmpty()) {
logger.info(
String.format("Builder %s: Error occurred, waiting for %d seconds", buildBot, delay));
return;
}
logger.info(String.format("Builder %s: trying to deserialize valid JSON", buildBot));
try {
BuildBotData builder = new ObjectMapper().readValue(response, BuildBotData.class);
datastoreRepository.updateRevisionEntry(builder);
} catch (Exception e) {
logger.info(String.format("Builder %s: can't deserialize JSON", buildBot));
e.printStackTrace();
}
long nextBuildId = buildId.incrementAndGet();
logger.info(
String.format(
"Builder %s:Next build id is %d, performing request in %d seconds", buildBot, nextBuildId, delay));
});
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
}
| Move changes to GitHubClient file
| src/main/java/com/google/graphgeckos/dashboard/fetchers/github/GitHubClient.java | Move changes to GitHubClient file |
|
Java | apache-2.0 | cf2a8f521460c9ff15465a579b54d17551b03639 | 0 | selendroid/selendroid,luohaoyu/selendroid,rasata/selendroid,vishals79/appium-uiautomator2-driver,uchida/selendroid,selendroid/selendroid,smiklosovic/selendroid,smiklosovic/selendroid,sri096/selendroid,luohaoyu/selendroid,uchida/selendroid,lukeis/selendroid,ghrud92/selendroid,mach6/selendroid,sri096/selendroid,frolovs/selendroid,mach6/selendroid,PrakashGoulla/selendroid,ghrud92/selendroid,koichirok/selendroid,appium/selendroid,masbog/selendroid,uchida/selendroid,uchida/selendroid,masbog/selendroid,ghrud92/selendroid,mach6/selendroid,SpencerMalone/selendroid,smiklosovic/selendroid,masbog/selendroid,PrakashGoulla/selendroid,vishals79/appium-uiautomator2-driver,selendroid/selendroid,mach6/selendroid,selendroid/selendroid,ghrud92/selendroid,selendroid/selendroid,PrakashGoulla/selendroid,smiklosovic/selendroid,vishals79/appium-uiautomator2-driver,masbog/selendroid,appium/selendroid,vishals79/appium-uiautomator2-driver,sri096/selendroid,luohaoyu/selendroid,appium/selendroid,SpencerMalone/selendroid,smiklosovic/selendroid,anandsadu/selendroid,frolovs/selendroid,uchida/selendroid,PrakashGoulla/selendroid,anandsadu/selendroid,koichirok/selendroid,SpencerMalone/selendroid,lukeis/selendroid,koichirok/selendroid,frolovs/selendroid,appium/selendroid,lukeis/selendroid,rasata/selendroid,luohaoyu/selendroid,rasata/selendroid,sri096/selendroid,SpencerMalone/selendroid,mach6/selendroid,koichirok/selendroid,lukeis/selendroid,luohaoyu/selendroid,sri096/selendroid,lukeis/selendroid,anandsadu/selendroid,masbog/selendroid,frolovs/selendroid,PrakashGoulla/selendroid,anandsadu/selendroid,appium/selendroid,SpencerMalone/selendroid,ghrud92/selendroid,rasata/selendroid,koichirok/selendroid,frolovs/selendroid,rasata/selendroid,vishals79/appium-uiautomator2-driver,anandsadu/selendroid | /*
* Copyright 2012-2014 eBay Software Foundation and selendroid committers.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.selendroid.standalone.android.impl;
import com.android.ddmlib.IDevice;
import com.beust.jcommander.internal.Lists;
import com.google.common.collect.ImmutableMap;
import io.selendroid.common.device.DeviceTargetPlatform;
import io.selendroid.server.common.exceptions.SelendroidException;
import io.selendroid.standalone.android.AndroidEmulator;
import io.selendroid.standalone.android.AndroidSdk;
import io.selendroid.standalone.android.TelnetClient;
import io.selendroid.standalone.exceptions.AndroidDeviceException;
import io.selendroid.standalone.exceptions.ShellCommandException;
import io.selendroid.standalone.io.ShellCommand;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.Dimension;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DefaultAndroidEmulator extends AbstractDevice implements AndroidEmulator {
private static final String EMULATOR_SERIAL_PREFIX = "emulator-";
private static final Logger log = Logger.getLogger(DefaultAndroidEmulator.class.getName());
public static final String ANDROID_EMULATOR_HARDWARE_CONFIG = "hardware-qemu.ini";
public static final String FILE_LOCKING_SUFIX = ".lock";
private static final ImmutableMap<String, Dimension> SKIN_NAME_DIMENSIONS = new
ImmutableMap.Builder<String, Dimension>()
.put("QVGA", new Dimension(240, 320))
.put("WQVGA400", new Dimension(240, 400))
.put("WQVGA432", new Dimension(240, 432))
.put("HVGA", new Dimension(320, 480))
.put("WVGA800", new Dimension(480, 800))
.put("WVGA854", new Dimension(480, 854))
.put("WXGA", new Dimension(1280, 800))
.put("WXGA720", new Dimension(1280, 720))
.put("WXGA800", new Dimension(1280, 800))
.build();
private Dimension screenSize;
private DeviceTargetPlatform targetPlatform;
private String avdName;
private File avdRootFolder;
private Locale locale = null;
private boolean wasStartedBySelendroid;
protected DefaultAndroidEmulator() {
this.wasStartedBySelendroid = Boolean.FALSE;
}
// this contructor is used only for test purposes in setting the capabilities information. Change to public if there
// is ever a desire to construct one of these besides reading the avdOutput
DefaultAndroidEmulator(String avdName, String abi, Dimension screenSize, String target,
String model, File avdFilePath, String apiTargetType) {
this.avdName = avdName;
this.model = model;
this.screenSize = screenSize;
this.avdRootFolder = avdFilePath;
this.targetPlatform = DeviceTargetPlatform.fromInt(target);
this.wasStartedBySelendroid = !isEmulatorStarted();
this.apiTargetType = apiTargetType;
}
// avdOutput is expected to look like the following
/*Name: Android_TV
Device: tv_720p (Google)
Path: /Users/antnguyen/.android/avd/Android_TV.avd
Target: Android 5.0.1 (API level 21)
Tag/ABI: android-tv/armeabi-v7a
Skin: tv_720p
Sdcard: 100M
Snapshot: no*/
public DefaultAndroidEmulator(String avdOutput) {
this.avdName = extractValue("Name: (.*?)$", avdOutput);
this.screenSize = getScreenSizeFromSkin(extractValue("Skin: (.*?)$", avdOutput));
this.targetPlatform = DeviceTargetPlatform.fromInt(extractValue("\\(API level (.*?)\\)", avdOutput));
this.avdRootFolder = new File(extractValue("Path: (.*?)$", avdOutput));
this.model = extractValue("Device: (.*?)$", avdOutput);
extractAPITargetType(avdOutput);
}
private void extractAPITargetType(String avdOutput) {
String target = extractValue("Target: (.*?)$", avdOutput);
// chose to compare against both of these strings because currently some targets say google_api [Google APIs] so
// perhaps the actual name which looks to be google_api will be the only string in the target in the future
if (StringUtils.containsIgnoreCase(target, "Google APIs") || StringUtils.containsIgnoreCase(target, "google_apis")) {
this.apiTargetType = "google";
}
}
public File getAvdRootFolder() {
return avdRootFolder;
}
public Dimension getScreenSize() {
return screenSize;
}
public DeviceTargetPlatform getTargetPlatform() {
return targetPlatform;
}
/*
* (non-Javadoc)
*
* @see io.selendroid.android.impl.AndroidEmulator#isEmulatorAlreadyExistent()
*/
@Override
public boolean isEmulatorAlreadyExistent() {
File emulatorFolder =
new File(FileUtils.getUserDirectory(), File.separator + ".android" + File.separator + "avd"
+ File.separator + getAvdName() + ".avd");
return emulatorFolder.exists();
}
public String getAvdName() {
return avdName;
}
public static List<AndroidEmulator> listAvailableAvds() throws AndroidDeviceException {
List<AndroidEmulator> avds = Lists.newArrayList();
CommandLine cmd = new CommandLine(AndroidSdk.android());
cmd.addArgument("list", false);
cmd.addArgument("avds", false);
String output = null;
try {
output = ShellCommand.exec(cmd, 20000);
} catch (ShellCommandException e) {
throw new AndroidDeviceException(e);
}
Map<String, Integer> startedDevices = mapDeviceNamesToSerial();
String[] avdsOutput = StringUtils.splitByWholeSeparator(output, "---------");
if (avdsOutput != null && avdsOutput.length > 0) {
for (String element : avdsOutput) {
if (!element.contains("Name:")) {
continue;
}
DefaultAndroidEmulator emulator = new DefaultAndroidEmulator(element);
if (startedDevices.containsKey(emulator.getAvdName())) {
emulator.setSerial(startedDevices.get(emulator.getAvdName()));
}
avds.add(emulator);
}
}
return avds;
}
public static Dimension getScreenSizeFromSkin(String skinName) {
final Pattern dimensionSkinPattern = Pattern.compile("([0-9]+)x([0-9]+)");
Matcher matcher = dimensionSkinPattern.matcher(skinName);
if (matcher.matches()) {
int width = Integer.parseInt(matcher.group(1));
int height = Integer.parseInt(matcher.group(2));
return new Dimension(width, height);
} else if (SKIN_NAME_DIMENSIONS.containsKey(skinName.toUpperCase())) {
return SKIN_NAME_DIMENSIONS.get(skinName.toUpperCase());
} else {
log.warning("Failed to get dimensions for skin: " + skinName);
return null;
}
}
private static Map<String, Integer> mapDeviceNamesToSerial() {
Map<String, Integer> mapping = new HashMap<String, Integer>();
CommandLine command = new CommandLine(AndroidSdk.adb());
command.addArgument("devices");
Scanner scanner;
try {
scanner = new Scanner(ShellCommand.exec(command));
} catch (ShellCommandException e) {
return mapping;
}
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Pattern pattern = Pattern.compile("emulator-\\d\\d\\d\\d");
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
String serial = matcher.group(0);
Integer port = Integer.valueOf(serial.replaceAll("emulator-", ""));
TelnetClient client = null;
try {
client = new TelnetClient(port);
String avdName = client.sendCommand("avd name");
mapping.put(avdName, port);
} catch (AndroidDeviceException e) {
// ignore
} finally {
if (client != null) {
client.close();
}
}
}
}
scanner.close();
return mapping;
}
@Override
public boolean isEmulatorStarted() {
File lockedEmulatorHardwareConfig =
new File(avdRootFolder, ANDROID_EMULATOR_HARDWARE_CONFIG + FILE_LOCKING_SUFIX);
return lockedEmulatorHardwareConfig.exists();
}
@Override
public String toString() {
return "AndroidEmulator [screenSize=" + screenSize + ", targetPlatform=" + targetPlatform
+ ", serial=" + serial + ", avdName=" + avdName + ", model=" + model + ", apiTargetType=" + apiTargetType + "]";
}
public void setSerial(int port) {
this.port = port;
serial = EMULATOR_SERIAL_PREFIX + port;
}
public Integer getPort() {
if (isSerialConfigured()) {
return Integer.parseInt(serial.replace(EMULATOR_SERIAL_PREFIX, ""));
}
return null;
}
@Override
public void start(Locale locale, int emulatorPort, Map<String, Object> options)
throws AndroidDeviceException {
if (isEmulatorStarted()) {
throw new SelendroidException("Error - Android emulator is already started " + this);
}
Long timeout = null;
String emulatorOptions = null;
String display = null;
if (options != null) {
if (options.containsKey(TIMEOUT_OPTION)) {
timeout = (Long) options.get(TIMEOUT_OPTION);
}
if (options.containsKey(DISPLAY_OPTION)) {
display = (String) options.get(DISPLAY_OPTION);
}
if (options.containsKey(EMULATOR_OPTIONS)) {
emulatorOptions = (String) options.get(EMULATOR_OPTIONS);
}
}
if (display != null) {
log.info("Using display " + display + " for running the emulator");
}
if (timeout == null) {
timeout = 120000L;
}
log.info("Using timeout of '" + timeout / 1000 + "' seconds to start the emulator.");
this.locale = locale;
CommandLine cmd = new CommandLine(AndroidSdk.emulator());
cmd.addArgument("-no-snapshot-save", false);
cmd.addArgument("-avd", false);
cmd.addArgument(avdName, false);
cmd.addArgument("-port", false);
cmd.addArgument(String.valueOf(emulatorPort), false);
if (locale != null) {
cmd.addArgument("-prop", false);
cmd.addArgument("persist.sys.language=" + locale.getLanguage(), false);
cmd.addArgument("-prop", false);
cmd.addArgument("persist.sys.country=" + locale.getCountry(), false);
}
if (emulatorOptions != null && !emulatorOptions.isEmpty()) {
cmd.addArguments(emulatorOptions.split(" "), false);
}
long start = System.currentTimeMillis();
long timeoutEnd = start + timeout;
try {
ShellCommand.execAsync(display, cmd);
} catch (ShellCommandException e) {
throw new SelendroidException("unable to start the emulator: " + this);
}
setSerial(emulatorPort);
Boolean adbKillServerAttempted = false;
// Without this one seconds, the call to "isDeviceReady" is
// too quickly sent while the emulator is still starting and
// not ready to receive any commands. Because of this the
// while loops failed and sometimes hung in isDeviceReady function.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
while (!isDeviceReady()) {
if (!adbKillServerAttempted && System.currentTimeMillis() - start > 10000) {
CommandLine adbDevicesCmd = new CommandLine(AndroidSdk.adb());
adbDevicesCmd.addArgument("devices", false);
String devices = "";
try {
devices = ShellCommand.exec(adbDevicesCmd, 20000);
} catch (ShellCommandException e) {
// pass
}
if (!devices.contains(String.valueOf(emulatorPort))) {
CommandLine resetAdb = new CommandLine(AndroidSdk.adb());
resetAdb.addArgument("kill-server", false);
try {
ShellCommand.exec(resetAdb, 20000);
} catch (ShellCommandException e) {
throw new SelendroidException("unable to kill the adb server");
}
}
adbKillServerAttempted = true;
}
if (timeoutEnd >= System.currentTimeMillis()) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} else {
throw new AndroidDeviceException("The emulator with avd '" + getAvdName()
+ "' was not started after " + (System.currentTimeMillis() - start) / 1000
+ " seconds.");
}
}
log.info("Emulator start took: " + (System.currentTimeMillis() - start) / 1000 + " seconds");
log.info("Please have in mind, starting an emulator takes usually about 45 seconds.");
unlockScreen();
waitForLauncherToComplete();
// we observed that emulators can sometimes not be 'fully loaded'
// if we click on the All Apps button and wait for it to load it is more likely to be in a
// usable state.
allAppsGridView();
waitForLauncherToComplete();
setWasStartedBySelendroid(true);
}
public void unlockScreen() throws AndroidDeviceException {
// Send menu key event
CommandLine menuKeyCommand = getAdbCommand();
menuKeyCommand.addArgument("shell", false);
menuKeyCommand.addArgument("input", false);
menuKeyCommand.addArgument("keyevent", false);
menuKeyCommand.addArgument("82", false);
try {
ShellCommand.exec(menuKeyCommand, 20000);
} catch (ShellCommandException e) {
throw new AndroidDeviceException(e);
}
// Send back key event
CommandLine backKeyCommand = getAdbCommand();
backKeyCommand.addArgument("shell", false);
backKeyCommand.addArgument("input", false);
backKeyCommand.addArgument("keyevent", false);
backKeyCommand.addArgument("4", false);
try {
ShellCommand.exec(backKeyCommand, 20000);
} catch (ShellCommandException e) {
throw new AndroidDeviceException(e);
}
}
private void waitForLauncherToComplete() throws AndroidDeviceException {
CommandLine processListCommand = getAdbCommand();
processListCommand.addArgument("shell", false);
processListCommand.addArgument("ps", false);
String processList = null;
do {
try {
processList = ShellCommand.exec(processListCommand, 20000);
} catch (ShellCommandException e) {
throw new AndroidDeviceException(e);
}
//Wait a bit
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} while (processList == null || !processList.contains("S com.android.launcher"));
}
private CommandLine getAdbCommand() {
CommandLine processListCommand = new CommandLine(AndroidSdk.adb());
if (isSerialConfigured()) {
processListCommand.addArgument("-s", false);
processListCommand.addArgument(serial, false);
}
return processListCommand;
}
private void allAppsGridView() throws AndroidDeviceException {
int x = screenSize.width;
int y = screenSize.height;
if (x > y) {
y = y / 2;
x = x - 30;
} else {
x = x / 2;
y = y - 30;
}
List<String> coordinates = new ArrayList<String>();
coordinates.add("3 0 " + x);
coordinates.add("3 1 " + y);
coordinates.add("1 330 1");
coordinates.add("0 0 0");
coordinates.add("1 330 0");
coordinates.add("0 0 0");
for (String coordinate : coordinates) {
CommandLine event1 = getAdbCommand();
event1.addArgument("shell", false);
event1.addArgument("sendevent", false);
event1.addArgument("dev/input/event0", false);
event1.addArgument(coordinate, false);
try {
ShellCommand.exec(event1);
} catch (ShellCommandException e) {
throw new AndroidDeviceException(e);
}
}
try {
Thread.sleep(750);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private void stopEmulator() throws AndroidDeviceException {
TelnetClient client = null;
try {
client = new TelnetClient(getPort());
client.sendQuietly("kill");
} catch (AndroidDeviceException e) {
// ignore
} finally {
if (client != null) {
client.close();
}
}
}
@Override
public void stop() throws AndroidDeviceException {
if (wasStartedBySelendroid) {
stopEmulator();
Boolean killed = false;
while (isEmulatorStarted()) {
log.info("emulator still running, sleeping 0.5, waiting for it to release the lock");
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
if (!killed) {
try {
stopEmulator();
} catch (AndroidDeviceException sce) {
killed = true;
}
}
}
}
}
@Override
public Locale getLocale() {
return locale;
}
@Override
public void setIDevice(IDevice iDevice) {
super.device = iDevice;
}
public String getSerial() {
return serial;
}
public void setWasStartedBySelendroid(boolean wasStartedBySelendroid) {
this.wasStartedBySelendroid = wasStartedBySelendroid;
}
}
| selendroid-standalone/src/main/java/io/selendroid/standalone/android/impl/DefaultAndroidEmulator.java | /*
* Copyright 2012-2014 eBay Software Foundation and selendroid committers.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.selendroid.standalone.android.impl;
import com.android.ddmlib.IDevice;
import com.beust.jcommander.internal.Lists;
import com.google.common.collect.ImmutableMap;
import io.selendroid.common.device.DeviceTargetPlatform;
import io.selendroid.server.common.exceptions.SelendroidException;
import io.selendroid.standalone.android.AndroidEmulator;
import io.selendroid.standalone.android.AndroidSdk;
import io.selendroid.standalone.android.TelnetClient;
import io.selendroid.standalone.exceptions.AndroidDeviceException;
import io.selendroid.standalone.exceptions.ShellCommandException;
import io.selendroid.standalone.io.ShellCommand;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.Dimension;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DefaultAndroidEmulator extends AbstractDevice implements AndroidEmulator {
private static final String EMULATOR_SERIAL_PREFIX = "emulator-";
private static final Logger log = Logger.getLogger(DefaultAndroidEmulator.class.getName());
public static final String ANDROID_EMULATOR_HARDWARE_CONFIG = "hardware-qemu.ini";
public static final String FILE_LOCKING_SUFIX = ".lock";
private static final ImmutableMap<String, Dimension> SKIN_NAME_DIMENSIONS = new
ImmutableMap.Builder<String, Dimension>()
.put("QVGA", new Dimension(240, 320))
.put("WQVGA400", new Dimension(240, 400))
.put("WQVGA432", new Dimension(240, 432))
.put("HVGA", new Dimension(320, 480))
.put("WVGA800", new Dimension(480, 800))
.put("WVGA854", new Dimension(480, 854))
.put("WXGA", new Dimension(1280, 800))
.put("WXGA800", new Dimension(1280, 800))
.build();
private Dimension screenSize;
private DeviceTargetPlatform targetPlatform;
private String avdName;
private File avdRootFolder;
private Locale locale = null;
private boolean wasStartedBySelendroid;
protected DefaultAndroidEmulator() {
this.wasStartedBySelendroid = Boolean.FALSE;
}
// this contructor is used only for test purposes in setting the capabilities information. Change to public if there
// is ever a desire to construct one of these besides reading the avdOutput
DefaultAndroidEmulator(String avdName, String abi, Dimension screenSize, String target,
String model, File avdFilePath, String apiTargetType) {
this.avdName = avdName;
this.model = model;
this.screenSize = screenSize;
this.avdRootFolder = avdFilePath;
this.targetPlatform = DeviceTargetPlatform.fromInt(target);
this.wasStartedBySelendroid = !isEmulatorStarted();
this.apiTargetType = apiTargetType;
}
// avdOutput is expected to look like the following
/*Name: Android_TV
Device: tv_720p (Google)
Path: /Users/antnguyen/.android/avd/Android_TV.avd
Target: Android 5.0.1 (API level 21)
Tag/ABI: android-tv/armeabi-v7a
Skin: tv_720p
Sdcard: 100M
Snapshot: no*/
public DefaultAndroidEmulator(String avdOutput) {
this.avdName = extractValue("Name: (.*?)$", avdOutput);
this.screenSize = getScreenSizeFromSkin(extractValue("Skin: (.*?)$", avdOutput));
this.targetPlatform = DeviceTargetPlatform.fromInt(extractValue("\\(API level (.*?)\\)", avdOutput));
this.avdRootFolder = new File(extractValue("Path: (.*?)$", avdOutput));
this.model = extractValue("Device: (.*?)$", avdOutput);
extractAPITargetType(avdOutput);
}
private void extractAPITargetType(String avdOutput) {
String target = extractValue("Target: (.*?)$", avdOutput);
// chose to compare against both of these strings because currently some targets say google_api [Google APIs] so
// perhaps the actual name which looks to be google_api will be the only string in the target in the future
if (StringUtils.containsIgnoreCase(target, "Google APIs") || StringUtils.containsIgnoreCase(target, "google_apis")) {
this.apiTargetType = "google";
}
}
public File getAvdRootFolder() {
return avdRootFolder;
}
public Dimension getScreenSize() {
return screenSize;
}
public DeviceTargetPlatform getTargetPlatform() {
return targetPlatform;
}
/*
* (non-Javadoc)
*
* @see io.selendroid.android.impl.AndroidEmulator#isEmulatorAlreadyExistent()
*/
@Override
public boolean isEmulatorAlreadyExistent() {
File emulatorFolder =
new File(FileUtils.getUserDirectory(), File.separator + ".android" + File.separator + "avd"
+ File.separator + getAvdName() + ".avd");
return emulatorFolder.exists();
}
public String getAvdName() {
return avdName;
}
public static List<AndroidEmulator> listAvailableAvds() throws AndroidDeviceException {
List<AndroidEmulator> avds = Lists.newArrayList();
CommandLine cmd = new CommandLine(AndroidSdk.android());
cmd.addArgument("list", false);
cmd.addArgument("avds", false);
String output = null;
try {
output = ShellCommand.exec(cmd, 20000);
} catch (ShellCommandException e) {
throw new AndroidDeviceException(e);
}
Map<String, Integer> startedDevices = mapDeviceNamesToSerial();
String[] avdsOutput = StringUtils.splitByWholeSeparator(output, "---------");
if (avdsOutput != null && avdsOutput.length > 0) {
for (String element : avdsOutput) {
if (!element.contains("Name:")) {
continue;
}
DefaultAndroidEmulator emulator = new DefaultAndroidEmulator(element);
if (startedDevices.containsKey(emulator.getAvdName())) {
emulator.setSerial(startedDevices.get(emulator.getAvdName()));
}
avds.add(emulator);
}
}
return avds;
}
public static Dimension getScreenSizeFromSkin(String skinName) {
final Pattern dimensionSkinPattern = Pattern.compile("([0-9]+)x([0-9]+)");
Matcher matcher = dimensionSkinPattern.matcher(skinName);
if (matcher.matches()) {
int width = Integer.parseInt(matcher.group(1));
int height = Integer.parseInt(matcher.group(2));
return new Dimension(width, height);
} else if (SKIN_NAME_DIMENSIONS.containsKey(skinName.toUpperCase())) {
return SKIN_NAME_DIMENSIONS.get(skinName.toUpperCase());
} else {
log.warning("Failed to get dimensions for skin: " + skinName);
return null;
}
}
private static Map<String, Integer> mapDeviceNamesToSerial() {
Map<String, Integer> mapping = new HashMap<String, Integer>();
CommandLine command = new CommandLine(AndroidSdk.adb());
command.addArgument("devices");
Scanner scanner;
try {
scanner = new Scanner(ShellCommand.exec(command));
} catch (ShellCommandException e) {
return mapping;
}
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Pattern pattern = Pattern.compile("emulator-\\d\\d\\d\\d");
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
String serial = matcher.group(0);
Integer port = Integer.valueOf(serial.replaceAll("emulator-", ""));
TelnetClient client = null;
try {
client = new TelnetClient(port);
String avdName = client.sendCommand("avd name");
mapping.put(avdName, port);
} catch (AndroidDeviceException e) {
// ignore
} finally {
if (client != null) {
client.close();
}
}
}
}
scanner.close();
return mapping;
}
@Override
public boolean isEmulatorStarted() {
File lockedEmulatorHardwareConfig =
new File(avdRootFolder, ANDROID_EMULATOR_HARDWARE_CONFIG + FILE_LOCKING_SUFIX);
return lockedEmulatorHardwareConfig.exists();
}
@Override
public String toString() {
return "AndroidEmulator [screenSize=" + screenSize + ", targetPlatform=" + targetPlatform
+ ", serial=" + serial + ", avdName=" + avdName + ", model=" + model + ", apiTargetType=" + apiTargetType + "]";
}
public void setSerial(int port) {
this.port = port;
serial = EMULATOR_SERIAL_PREFIX + port;
}
public Integer getPort() {
if (isSerialConfigured()) {
return Integer.parseInt(serial.replace(EMULATOR_SERIAL_PREFIX, ""));
}
return null;
}
@Override
public void start(Locale locale, int emulatorPort, Map<String, Object> options)
throws AndroidDeviceException {
if (isEmulatorStarted()) {
throw new SelendroidException("Error - Android emulator is already started " + this);
}
Long timeout = null;
String emulatorOptions = null;
String display = null;
if (options != null) {
if (options.containsKey(TIMEOUT_OPTION)) {
timeout = (Long) options.get(TIMEOUT_OPTION);
}
if (options.containsKey(DISPLAY_OPTION)) {
display = (String) options.get(DISPLAY_OPTION);
}
if (options.containsKey(EMULATOR_OPTIONS)) {
emulatorOptions = (String) options.get(EMULATOR_OPTIONS);
}
}
if (display != null) {
log.info("Using display " + display + " for running the emulator");
}
if (timeout == null) {
timeout = 120000L;
}
log.info("Using timeout of '" + timeout / 1000 + "' seconds to start the emulator.");
this.locale = locale;
CommandLine cmd = new CommandLine(AndroidSdk.emulator());
cmd.addArgument("-no-snapshot-save", false);
cmd.addArgument("-avd", false);
cmd.addArgument(avdName, false);
cmd.addArgument("-port", false);
cmd.addArgument(String.valueOf(emulatorPort), false);
if (locale != null) {
cmd.addArgument("-prop", false);
cmd.addArgument("persist.sys.language=" + locale.getLanguage(), false);
cmd.addArgument("-prop", false);
cmd.addArgument("persist.sys.country=" + locale.getCountry(), false);
}
if (emulatorOptions != null && !emulatorOptions.isEmpty()) {
cmd.addArguments(emulatorOptions.split(" "), false);
}
long start = System.currentTimeMillis();
long timeoutEnd = start + timeout;
try {
ShellCommand.execAsync(display, cmd);
} catch (ShellCommandException e) {
throw new SelendroidException("unable to start the emulator: " + this);
}
setSerial(emulatorPort);
Boolean adbKillServerAttempted = false;
// Without this one seconds, the call to "isDeviceReady" is
// too quickly sent while the emulator is still starting and
// not ready to receive any commands. Because of this the
// while loops failed and sometimes hung in isDeviceReady function.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
while (!isDeviceReady()) {
if (!adbKillServerAttempted && System.currentTimeMillis() - start > 10000) {
CommandLine adbDevicesCmd = new CommandLine(AndroidSdk.adb());
adbDevicesCmd.addArgument("devices", false);
String devices = "";
try {
devices = ShellCommand.exec(adbDevicesCmd, 20000);
} catch (ShellCommandException e) {
// pass
}
if (!devices.contains(String.valueOf(emulatorPort))) {
CommandLine resetAdb = new CommandLine(AndroidSdk.adb());
resetAdb.addArgument("kill-server", false);
try {
ShellCommand.exec(resetAdb, 20000);
} catch (ShellCommandException e) {
throw new SelendroidException("unable to kill the adb server");
}
}
adbKillServerAttempted = true;
}
if (timeoutEnd >= System.currentTimeMillis()) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} else {
throw new AndroidDeviceException("The emulator with avd '" + getAvdName()
+ "' was not started after " + (System.currentTimeMillis() - start) / 1000
+ " seconds.");
}
}
log.info("Emulator start took: " + (System.currentTimeMillis() - start) / 1000 + " seconds");
log.info("Please have in mind, starting an emulator takes usually about 45 seconds.");
unlockScreen();
waitForLauncherToComplete();
// we observed that emulators can sometimes not be 'fully loaded'
// if we click on the All Apps button and wait for it to load it is more likely to be in a
// usable state.
allAppsGridView();
waitForLauncherToComplete();
setWasStartedBySelendroid(true);
}
public void unlockScreen() throws AndroidDeviceException {
// Send menu key event
CommandLine menuKeyCommand = getAdbCommand();
menuKeyCommand.addArgument("shell", false);
menuKeyCommand.addArgument("input", false);
menuKeyCommand.addArgument("keyevent", false);
menuKeyCommand.addArgument("82", false);
try {
ShellCommand.exec(menuKeyCommand, 20000);
} catch (ShellCommandException e) {
throw new AndroidDeviceException(e);
}
// Send back key event
CommandLine backKeyCommand = getAdbCommand();
backKeyCommand.addArgument("shell", false);
backKeyCommand.addArgument("input", false);
backKeyCommand.addArgument("keyevent", false);
backKeyCommand.addArgument("4", false);
try {
ShellCommand.exec(backKeyCommand, 20000);
} catch (ShellCommandException e) {
throw new AndroidDeviceException(e);
}
}
private void waitForLauncherToComplete() throws AndroidDeviceException {
CommandLine processListCommand = getAdbCommand();
processListCommand.addArgument("shell", false);
processListCommand.addArgument("ps", false);
String processList = null;
do {
try {
processList = ShellCommand.exec(processListCommand, 20000);
} catch (ShellCommandException e) {
throw new AndroidDeviceException(e);
}
//Wait a bit
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} while (processList == null || !processList.contains("S com.android.launcher"));
}
private CommandLine getAdbCommand() {
CommandLine processListCommand = new CommandLine(AndroidSdk.adb());
if (isSerialConfigured()) {
processListCommand.addArgument("-s", false);
processListCommand.addArgument(serial, false);
}
return processListCommand;
}
private void allAppsGridView() throws AndroidDeviceException {
int x = screenSize.width;
int y = screenSize.height;
if (x > y) {
y = y / 2;
x = x - 30;
} else {
x = x / 2;
y = y - 30;
}
List<String> coordinates = new ArrayList<String>();
coordinates.add("3 0 " + x);
coordinates.add("3 1 " + y);
coordinates.add("1 330 1");
coordinates.add("0 0 0");
coordinates.add("1 330 0");
coordinates.add("0 0 0");
for (String coordinate : coordinates) {
CommandLine event1 = getAdbCommand();
event1.addArgument("shell", false);
event1.addArgument("sendevent", false);
event1.addArgument("dev/input/event0", false);
event1.addArgument(coordinate, false);
try {
ShellCommand.exec(event1);
} catch (ShellCommandException e) {
throw new AndroidDeviceException(e);
}
}
try {
Thread.sleep(750);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private void stopEmulator() throws AndroidDeviceException {
TelnetClient client = null;
try {
client = new TelnetClient(getPort());
client.sendQuietly("kill");
} catch (AndroidDeviceException e) {
// ignore
} finally {
if (client != null) {
client.close();
}
}
}
@Override
public void stop() throws AndroidDeviceException {
if (wasStartedBySelendroid) {
stopEmulator();
Boolean killed = false;
while (isEmulatorStarted()) {
log.info("emulator still running, sleeping 0.5, waiting for it to release the lock");
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
if (!killed) {
try {
stopEmulator();
} catch (AndroidDeviceException sce) {
killed = true;
}
}
}
}
}
@Override
public Locale getLocale() {
return locale;
}
@Override
public void setIDevice(IDevice iDevice) {
super.device = iDevice;
}
public String getSerial() {
return serial;
}
public void setWasStartedBySelendroid(boolean wasStartedBySelendroid) {
this.wasStartedBySelendroid = wasStartedBySelendroid;
}
}
| Add WXGA720 skin for detection of screen resolution.
| selendroid-standalone/src/main/java/io/selendroid/standalone/android/impl/DefaultAndroidEmulator.java | Add WXGA720 skin for detection of screen resolution. |
|
Java | apache-2.0 | ad27594fa35e1df532059a2080a997a4ceeeec4d | 0 | JNOSQL/artemis-extension | /*
* Copyright (c) 2017 Otávio Santana and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php.
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
*
* Otavio Santana
*/
package org.jnosql.artemis.graph;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.jnosql.artemis.EntityNotFoundException;
import org.jnosql.artemis.IdNotFoundException;
import java.util.Collection;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Stream;
/**
* This interface that represents the common operation between an entity
* and {@link org.apache.tinkerpop.gremlin.structure.Vertex}
*/
public interface GraphTemplate {
/**
* Inserts entity
*
* @param entity entity to be saved
* @param <T> the instance type
* @return the entity saved
* @throws NullPointerException when document is null
* @throws IdNotFoundException when entity has not {@link org.jnosql.artemis.Id}
*/
<T> T insert(T entity) throws NullPointerException, IdNotFoundException;
/**
* Updates entity
*
* @param entity entity to be updated
* @param <T> the instance type
* @return the entity saved
* @throws NullPointerException when document is null
* @throws IdNotFoundException when an entity is null
*/
<T> T update(T entity) throws NullPointerException, IdNotFoundException;
/**
* Deletes a {@link org.apache.tinkerpop.gremlin.structure.Vertex}
*
* @param id the id to be used in the query {@link org.apache.tinkerpop.gremlin.structure.T#id}
* @param <T> the id type
* @throws NullPointerException when id is null
*/
<T> void delete(T id) throws NullPointerException;
/**
* Deletes a {@link org.apache.tinkerpop.gremlin.structure.Edge}
*
* @param id the id to be used in the query {@link org.apache.tinkerpop.gremlin.structure.T#id}
* @param <T> the id type
* @throws NullPointerException when either label and id are null
*/
<T> void deleteEdge(T id) throws NullPointerException;
/**
* Find an entity given {@link org.apache.tinkerpop.gremlin.structure.T#label} and
* {@link org.apache.tinkerpop.gremlin.structure.T#id}
*
* @param id the id to be used in the query {@link org.apache.tinkerpop.gremlin.structure.T#id}
* @param <T> the entity type
* @param <ID> the id type
* @return the entity found otherwise {@link Optional#empty()}
* @throws NullPointerException when id is null
*/
<T, ID> Optional<T> find(ID id) throws NullPointerException;
/**
* Either find or create an Edge between this two entities.
* {@link org.apache.tinkerpop.gremlin.structure.Edge}
* <pre>entityOUT ---label---> entityIN.</pre>
*
* @param incoming the incoming entity
* @param label the Edge label
* @param outbound the outbound entity
* @param <IN> the incoming type
* @param <OUT> the outgoing type
* @return the {@link EdgeEntity} of these two entities
* @throws NullPointerException Either when any elements are null or the entity is null
* @throws IdNotFoundException when {@link org.jnosql.artemis.Id} annotation is missing in the entities
* @throws EntityNotFoundException when neither outbound or incoming is found
*/
<OUT, IN> EdgeEntity edge(OUT outbound, String label, IN incoming) throws NullPointerException,
IdNotFoundException, EntityNotFoundException;
/**
* returns the edges of from a vertex id
*
* @param id the id
* @param direction the direction
* @param labels the edge labels
* @param <ID> the ID type
* @return the Edges
* @throws NullPointerException where there is any parameter null
*/
<ID> Collection<EdgeEntity> getEdgesById(ID id, Direction direction, String... labels)
throws NullPointerException;
/**
* returns the edges of from a vertex id
*
* @param id the id
* @param direction the direction
* @param labels the edge labels
* @param <ID> the ID type
* @return the Edges
* @throws NullPointerException where there is any parameter null
*/
<ID> Collection<EdgeEntity> getEdgesById(ID id, Direction direction, Supplier<String>... labels)
throws NullPointerException;
/**
* returns the edges of from a vertex id
*
* @param id the id
* @param direction the direction
* @param <ID> the ID type
* @return the Edges
* @throws NullPointerException where there is any parameter null
*/
<ID> Collection<EdgeEntity> getEdgesById(ID id, Direction direction) throws NullPointerException;
/**
* returns the edges of from an entity
*
* @param entity the entity
* @param direction the direction
* @param labels the edge labels
* @param <T> the entity type
* @return the Edges
* @throws NullPointerException where there is any parameter null
*/
<T> Collection<EdgeEntity> getEdges(T entity, Direction direction, String... labels)
throws NullPointerException;
/**
* returns the edges of from an entity
*
* @param entity the entity
* @param direction the direction
* @param labels the edge labels
* @param <T> the entity type
* @return the Edges
* @throws NullPointerException where there is any parameter null
*/
<T> Collection<EdgeEntity> getEdges(T entity, Direction direction, Supplier<String>... labels)
throws NullPointerException;
/**
* returns the edges of from an entity
*
* @param entity the entity
* @param direction the direction
* @param <T> the entity type
* @return the Edges
* @throws NullPointerException where there is any parameter null
*/
<T> Collection<EdgeEntity> getEdges(T entity, Direction direction)
throws NullPointerException;
/**
* Finds an {@link EdgeEntity} from the Edge Id
*
* @param edgeId the edge id
* @param <E> the edge id type
* @return the {@link EdgeEntity} otherwise {@link Optional#empty()}
* @throws NullPointerException when edgeId is null
*/
<E> Optional<EdgeEntity> edge(E edgeId) throws NullPointerException;
/**
* Gets a {@link VertexTraversal} to run a query in the graph
*
* @param vertexIds get ids
* @return a {@link VertexTraversal} instance
* @throws NullPointerException if any id element is null
*/
VertexTraversal getTraversalVertex(Object... vertexIds) throws NullPointerException;
/**
* Gets a {@link EdgeTraversal} to run a query in the graph
*
* @param edgeIds get ids
* @return a {@link VertexTraversal} instance
* @throws NullPointerException if any id element is null
*/
EdgeTraversal getTraversalEdge(Object... edgeIds) throws NullPointerException;
}
| graph-extension/src/main/java/org/jnosql/artemis/graph/GraphTemplate.java | /*
* Copyright (c) 2017 Otávio Santana and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php.
*
* You may elect to redistribute this code under either of these licenses.
*
* Contributors:
*
* Otavio Santana
*/
package org.jnosql.artemis.graph;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.jnosql.artemis.EntityNotFoundException;
import org.jnosql.artemis.IdNotFoundException;
import java.util.Collection;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Stream;
/**
* This interface that represents the common operation between an entity
* and {@link org.apache.tinkerpop.gremlin.structure.Vertex}
*/
public interface GraphTemplate {
/**
* Inserts entity
*
* @param entity entity to be saved
* @param <T> the instance type
* @return the entity saved
* @throws NullPointerException when document is null
* @throws IdNotFoundException when entity has not {@link org.jnosql.artemis.Id}
*/
<T> T insert(T entity) throws NullPointerException, IdNotFoundException;
/**
* Updates entity
*
* @param entity entity to be updated
* @param <T> the instance type
* @return the entity saved
* @throws NullPointerException when document is null
* @throws IdNotFoundException when an entity is null
*/
<T> T update(T entity) throws NullPointerException, IdNotFoundException;
/**
* Deletes a {@link org.apache.tinkerpop.gremlin.structure.Vertex}
*
* @param id the id to be used in the query {@link org.apache.tinkerpop.gremlin.structure.T#id}
* @param <T> the id type
* @throws NullPointerException when id is null
*/
<T> void delete(T id) throws NullPointerException;
/**
* Deletes a {@link org.apache.tinkerpop.gremlin.structure.Edge}
*
* @param id the id to be used in the query {@link org.apache.tinkerpop.gremlin.structure.T#id}
* @param <T> the id type
* @throws NullPointerException when either label and id are null
*/
<T> void deleteEdge(T id) throws NullPointerException;
/**
* Find an entity given {@link org.apache.tinkerpop.gremlin.structure.T#label} and
* {@link org.apache.tinkerpop.gremlin.structure.T#id}
*
* @param id the id to be used in the query {@link org.apache.tinkerpop.gremlin.structure.T#id}
* @param <T> the entity type
* @param <ID> the id type
* @return the entity found otherwise {@link Optional#empty()}
* @throws NullPointerException when id is null
*/
<T, ID> Optional<T> find(ID id) throws NullPointerException;
/**
* Either find or create an Edge between this two entities.
* {@link org.apache.tinkerpop.gremlin.structure.Edge}
* <pre>entityOUT ---label---> entityIN.</pre>
*
* @param incoming the incoming entity
* @param label the Edge label
* @param outbound the outbound entity
* @param <IN> the incoming type
* @param <OUT> the outgoing type
* @return the {@link EdgeEntity} of these two entities
* @throws NullPointerException Either when any elements are null or the entity is null
* @throws IdNotFoundException when {@link org.jnosql.artemis.Id} annotation is missing in the entities
* @throws EntityNotFoundException when neither outbound or incoming is found
*/
<OUT, IN> EdgeEntity edge(OUT outbound, String label, IN incoming) throws NullPointerException,
IdNotFoundException, EntityNotFoundException;
/**
* returns the edges of from a vertex id
*
* @param id the id
* @param direction the direction
* @param labels the edge labels
* @param <ID> the ID type
* @return the Edges
* @throws NullPointerException where there is any parameter null
*/
<ID> Collection<EdgeEntity> getEdgesById(ID id, Direction direction, String... labels)
throws NullPointerException;
/**
* returns the edges of from a vertex id
*
* @param id the id
* @param direction the direction
* @param labels the edge labels
* @param <ID> the ID type
* @return the Edges
* @throws NullPointerException where there is any parameter null
*/
<ID> Collection<EdgeEntity> getEdgesById(ID id, Direction direction, Supplier<String>... labels)
throws NullPointerException;
/**
* returns the edges of from an entity
*
* @param entity the entity
* @param direction the direction
* @param labels the edge labels
* @param <T> the entity type
* @return the Edges
* @throws NullPointerException where there is any parameter null
*/
<T> Collection<EdgeEntity> getEdges(T entity, Direction direction, String... labels)
throws NullPointerException;
/**
* returns the edges of from an entity
*
* @param entity the entity
* @param direction the direction
* @param labels the edge labels
* @param <T> the entity type
* @return the Edges
* @throws NullPointerException where there is any parameter null
*/
<T> Collection<EdgeEntity> getEdges(T entity, Direction direction, Supplier<String>... labels)
throws NullPointerException;
/**
* Finds an {@link EdgeEntity} from the Edge Id
*
* @param edgeId the edge id
* @param <E> the edge id type
* @return the {@link EdgeEntity} otherwise {@link Optional#empty()}
* @throws NullPointerException when edgeId is null
*/
<E> Optional<EdgeEntity> edge(E edgeId) throws NullPointerException;
/**
* Gets a {@link VertexTraversal} to run a query in the graph
*
* @param vertexIds get ids
* @return a {@link VertexTraversal} instance
* @throws NullPointerException if any id element is null
*/
VertexTraversal getTraversalVertex(Object... vertexIds) throws NullPointerException;
/**
* Gets a {@link EdgeTraversal} to run a query in the graph
*
* @param edgeIds get ids
* @return a {@link VertexTraversal} instance
* @throws NullPointerException if any id element is null
*/
EdgeTraversal getTraversalEdge(Object... edgeIds) throws NullPointerException;
}
| adds news template methods
| graph-extension/src/main/java/org/jnosql/artemis/graph/GraphTemplate.java | adds news template methods |
|
Java | apache-2.0 | a8e71e108dfeb7c84ec189add3ba3172e64de0a2 | 0 | trekawek/jackrabbit-oak,anchela/jackrabbit-oak,mreutegg/jackrabbit-oak,apache/jackrabbit-oak,trekawek/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,anchela/jackrabbit-oak,anchela/jackrabbit-oak,amit-jain/jackrabbit-oak,trekawek/jackrabbit-oak,mreutegg/jackrabbit-oak,trekawek/jackrabbit-oak,amit-jain/jackrabbit-oak,amit-jain/jackrabbit-oak,amit-jain/jackrabbit-oak,mreutegg/jackrabbit-oak,amit-jain/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,anchela/jackrabbit-oak,apache/jackrabbit-oak,trekawek/jackrabbit-oak,apache/jackrabbit-oak,anchela/jackrabbit-oak | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.jcr.session;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterators.transform;
import static com.google.common.collect.Sets.newLinkedHashSet;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Collections.singleton;
import static org.apache.jackrabbit.JcrConstants.JCR_MIXINTYPES;
import static org.apache.jackrabbit.JcrConstants.JCR_PRIMARYTYPE;
import static org.apache.jackrabbit.oak.api.Type.NAME;
import static org.apache.jackrabbit.oak.api.Type.NAMES;
import static org.apache.jackrabbit.oak.jcr.session.SessionImpl.checkIndexOnName;
import static org.apache.jackrabbit.oak.util.TreeUtil.getNames;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.jcr.AccessDeniedException;
import javax.jcr.Binary;
import javax.jcr.InvalidItemStateException;
import javax.jcr.Item;
import javax.jcr.ItemExistsException;
import javax.jcr.ItemNotFoundException;
import javax.jcr.ItemVisitor;
import javax.jcr.NoSuchWorkspaceException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.Value;
import javax.jcr.lock.Lock;
import javax.jcr.lock.LockManager;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NodeDefinition;
import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.NodeTypeManager;
import javax.jcr.version.Version;
import javax.jcr.version.VersionException;
import javax.jcr.version.VersionHistory;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.api.JackrabbitNode;
import org.apache.jackrabbit.commons.ItemNameMatcher;
import org.apache.jackrabbit.commons.iterator.NodeIteratorAdapter;
import org.apache.jackrabbit.commons.iterator.PropertyIteratorAdapter;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.api.Tree.Status;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.commons.PathUtils;
import org.apache.jackrabbit.oak.jcr.delegate.NodeDelegate;
import org.apache.jackrabbit.oak.jcr.delegate.PropertyDelegate;
import org.apache.jackrabbit.oak.jcr.delegate.VersionManagerDelegate;
import org.apache.jackrabbit.oak.jcr.session.operation.ItemOperation;
import org.apache.jackrabbit.oak.jcr.session.operation.NodeOperation;
import org.apache.jackrabbit.oak.jcr.version.VersionHistoryImpl;
import org.apache.jackrabbit.oak.jcr.version.VersionImpl;
import org.apache.jackrabbit.oak.plugins.identifier.IdentifierManager;
import org.apache.jackrabbit.oak.plugins.memory.PropertyStates;
import org.apache.jackrabbit.oak.plugins.nodetype.EffectiveNodeType;
import org.apache.jackrabbit.oak.plugins.tree.RootFactory;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.Permissions;
import org.apache.jackrabbit.oak.util.TreeUtil;
import org.apache.jackrabbit.value.ValueHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TODO document
*
* @param <T> the delegate type
*/
public class NodeImpl<T extends NodeDelegate> extends ItemImpl<T> implements Node, JackrabbitNode {
/**
* The maximum returned value for {@link NodeIterator#getSize()}. If there
* are more nodes, the method returns -1.
*/
private static final long NODE_ITERATOR_MAX_SIZE = Long.MAX_VALUE;
/**
* logger instance
*/
private static final Logger LOG = LoggerFactory.getLogger(NodeImpl.class);
@CheckForNull
public static NodeImpl<? extends NodeDelegate> createNodeOrNull(
@CheckForNull NodeDelegate delegate, @Nonnull SessionContext context)
throws RepositoryException {
if (delegate != null) {
return createNode(delegate, context);
} else {
return null;
}
}
@Nonnull
public static NodeImpl<? extends NodeDelegate> createNode(
@Nonnull NodeDelegate delegate, @Nonnull SessionContext context)
throws RepositoryException {
PropertyDelegate pd = delegate.getPropertyOrNull(JCR_PRIMARYTYPE);
String type = pd != null ? pd.getString() : null;
if (JcrConstants.NT_VERSION.equals(type)) {
VersionManagerDelegate vmd =
VersionManagerDelegate.create(context.getSessionDelegate());
return new VersionImpl(vmd.createVersion(delegate), context);
} else if (JcrConstants.NT_VERSIONHISTORY.equals(type)) {
VersionManagerDelegate vmd =
VersionManagerDelegate.create(context.getSessionDelegate());
return new VersionHistoryImpl(vmd.createVersionHistory(delegate), context);
} else {
return new NodeImpl<NodeDelegate>(delegate, context);
}
}
public NodeImpl(T dlg, SessionContext sessionContext) {
super(dlg, sessionContext);
}
//---------------------------------------------------------------< Item >---
/**
* @see javax.jcr.Item#isNode()
*/
@Override
public boolean isNode() {
return true;
}
/**
* @see javax.jcr.Item#getParent()
*/
@Override
@Nonnull
public Node getParent() throws RepositoryException {
return perform(new NodeOperation<Node>(dlg, "getParent") {
@Nonnull
@Override
public Node perform() throws RepositoryException {
if (node.isRoot()) {
throw new ItemNotFoundException("Root has no parent");
} else {
NodeDelegate parent = node.getParent();
if (parent == null) {
throw new AccessDeniedException();
}
return createNode(parent, sessionContext);
}
}
});
}
/**
* @see javax.jcr.Item#isNew()
*/
@Override
public boolean isNew() {
return sessionDelegate.safePerform(new NodeOperation<Boolean>(dlg, "isNew") {
@Nonnull
@Override
public Boolean perform() {
return node.exists() && node.getStatus() == Status.NEW;
}
});
}
/**
* @see javax.jcr.Item#isModified()
*/
@Override
public boolean isModified() {
return sessionDelegate.safePerform(new NodeOperation<Boolean>(dlg, "isModified") {
@Nonnull
@Override
public Boolean perform() {
return node.exists() && node.getStatus() == Status.MODIFIED;
}
});
}
/**
* @see javax.jcr.Item#remove()
*/
@Override
public void remove() throws RepositoryException {
sessionDelegate.performVoid(new ItemWriteOperation<Void>("remove") {
@Override
public void performVoid() throws RepositoryException {
if (dlg.isRoot()) {
throw new RepositoryException("Cannot remove the root node");
}
dlg.remove();
}
@Override
public String toString() {
return format("Removing node [%s]", dlg.getPath());
}
});
}
@Override
public void accept(ItemVisitor visitor) throws RepositoryException {
visitor.visit(this);
}
//---------------------------------------------------------------< Node >---
/**
* @see Node#addNode(String)
*/
@Override
@Nonnull
public Node addNode(String relPath) throws RepositoryException {
return addNode(relPath, null);
}
@Override @Nonnull
public Node addNode(final String relPath, String primaryNodeTypeName)
throws RepositoryException {
final String oakPath = getOakPathOrThrowNotFound(relPath);
final String oakTypeName;
if (primaryNodeTypeName != null) {
oakTypeName = getOakName(primaryNodeTypeName);
} else {
oakTypeName = null;
}
checkIndexOnName(relPath);
return perform(new ItemWriteOperation<Node>("addNode") {
@Nonnull
@Override
public Node perform() throws RepositoryException {
String oakName = PathUtils.getName(oakPath);
String parentPath = PathUtils.getParentPath(oakPath);
NodeDelegate parent = dlg.getChild(parentPath);
if (parent == null) {
// is it a property?
String grandParentPath = PathUtils.getParentPath(parentPath);
NodeDelegate grandParent = dlg.getChild(grandParentPath);
if (grandParent != null) {
String propName = PathUtils.getName(parentPath);
if (grandParent.getPropertyOrNull(propName) != null) {
throw new ConstraintViolationException("Can't add new node to property.");
}
}
throw new PathNotFoundException(relPath);
}
if (parent.getChild(oakName) != null) {
throw new ItemExistsException(relPath);
}
// check for NODE_TYPE_MANAGEMENT permission here as we cannot
// distinguish between user-supplied and system-generated
// modification of that property in the PermissionValidator
if (oakTypeName != null) {
PropertyState prop = PropertyStates.createProperty(JCR_PRIMARYTYPE, oakTypeName, NAME);
sessionContext.getAccessManager().checkPermissions(parent.getTree(), prop, Permissions.NODE_TYPE_MANAGEMENT);
}
NodeDelegate added = parent.addChild(oakName, oakTypeName);
if (added == null) {
throw new ItemExistsException(format("Node [%s/%s] exists", getNodePath(),oakName));
}
return createNode(added, sessionContext);
}
@Override
public String toString() {
return format("Adding node [%s/%s]", dlg.getPath(), relPath);
}
});
}
@Override
public void orderBefore(final String srcChildRelPath, final String destChildRelPath) throws RepositoryException {
sessionDelegate.performVoid(new ItemWriteOperation<Void>("orderBefore") {
@Override
public void performVoid() throws RepositoryException {
getEffectiveNodeType().checkOrderableChildNodes();
String oakSrcChildRelPath = getOakPathOrThrowNotFound(srcChildRelPath);
String oakDestChildRelPath = null;
if (destChildRelPath != null) {
oakDestChildRelPath = getOakPathOrThrowNotFound(destChildRelPath);
}
dlg.orderBefore(oakSrcChildRelPath, oakDestChildRelPath);
}
});
}
//-------------------------------------------------------< setProperty >--
//
// The setProperty() variants below follow the same pattern:
//
// if (value != null) {
// return internalSetProperty(name, ...);
// } else {
// return internalRemoveProperty(name);
// }
//
// In addition the value and value type information is pre-processed
// according to the method signature before being passed to
// internalSetProperty(). The methods that take a non-nullable
// primitive value as an argument can skip the if clause.
//
// Note that due to backwards compatibility reasons (OAK-395) none
// of the methods will ever return null, even if asked to remove
// a non-existing property! See internalRemoveProperty() for details.
@Override @Nonnull
public Property setProperty(String name, Value value)
throws RepositoryException {
if (value != null) {
return internalSetProperty(name, value, false);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, Value value, int type)
throws RepositoryException {
if (value != null) {
boolean exactTypeMatch = true;
if (type == PropertyType.UNDEFINED) {
exactTypeMatch = false;
} else {
value = ValueHelper.convert(value, type, getValueFactory());
}
return internalSetProperty(name, value, exactTypeMatch);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, Value[] values)
throws RepositoryException {
if (values != null) {
// TODO: type
return internalSetProperty(name, values, ValueHelper.getType(values), false);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String jcrName, Value[] values, int type)
throws RepositoryException {
if (values != null) {
boolean exactTypeMatch = true;
if (type == PropertyType.UNDEFINED) {
type = PropertyType.STRING;
exactTypeMatch = false;
}
values = ValueHelper.convert(values, type, getValueFactory());
return internalSetProperty(jcrName, values, type, exactTypeMatch);
} else {
return internalRemoveProperty(jcrName);
}
}
@Override @Nonnull
public Property setProperty(String name, String[] values)
throws RepositoryException {
if (values != null) {
int type = PropertyType.STRING;
Value[] vs = ValueHelper.convert(values, type, getValueFactory());
return internalSetProperty(name, vs, type, false);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, String[] values, int type)
throws RepositoryException {
if (values != null) {
boolean exactTypeMatch = true;
if (type == PropertyType.UNDEFINED) {
type = PropertyType.STRING;
exactTypeMatch = false;
}
Value[] vs = ValueHelper.convert(values, type, getValueFactory());
return internalSetProperty(name, vs, type, exactTypeMatch);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, String value)
throws RepositoryException {
if (value != null) {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, String value, int type)
throws RepositoryException {
if (value != null) {
boolean exactTypeMatch = true;
if (type == PropertyType.UNDEFINED) {
type = PropertyType.STRING;
exactTypeMatch = false;
}
Value v = getValueFactory().createValue(value, type);
return internalSetProperty(name, v, exactTypeMatch);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull @SuppressWarnings("deprecation")
public Property setProperty(String name, InputStream value)
throws RepositoryException {
if (value != null) {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, Binary value)
throws RepositoryException {
if (value != null) {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, boolean value)
throws RepositoryException {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
}
@Override @Nonnull
public Property setProperty(String name, double value)
throws RepositoryException {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
}
@Override @Nonnull
public Property setProperty(String name, BigDecimal value)
throws RepositoryException {
if (value != null) {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, long value)
throws RepositoryException {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
}
@Override @Nonnull
public Property setProperty(String name, Calendar value)
throws RepositoryException {
if (value != null) {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, Node value)
throws RepositoryException {
if (value != null) {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
} else {
return internalRemoveProperty(name);
}
}
@Override
@Nonnull
public Node getNode(String relPath) throws RepositoryException {
final String oakPath = getOakPathOrThrowNotFound(relPath);
return perform(new NodeOperation<Node>(dlg, "getNode") {
@Nonnull
@Override
public Node perform() throws RepositoryException {
NodeDelegate nd = node.getChild(oakPath);
if (nd == null) {
throw new PathNotFoundException(oakPath);
} else {
return createNode(nd, sessionContext);
}
}
});
}
@Override
@Nonnull
public NodeIterator getNodes() throws RepositoryException {
return perform(new NodeOperation<NodeIterator>(dlg, "getNodes") {
@Nonnull
@Override
public NodeIterator perform() throws RepositoryException {
Iterator<NodeDelegate> children = node.getChildren();
return new NodeIteratorAdapter(nodeIterator(children)) {
private long size = -2;
@Override
public long getSize() {
if (size == -2) {
try {
size = node.getChildCount(NODE_ITERATOR_MAX_SIZE); // TODO: perform()
if (size == Long.MAX_VALUE) {
size = -1;
}
} catch (InvalidItemStateException e) {
throw new IllegalStateException(
"This iterator is no longer valid", e);
}
}
return size;
}
};
}
});
}
@Override
@Nonnull
public NodeIterator getNodes(final String namePattern)
throws RepositoryException {
return perform(new NodeOperation<NodeIterator>(dlg, "getNodes") {
@Nonnull
@Override
public NodeIterator perform() throws RepositoryException {
Iterator<NodeDelegate> children = Iterators.filter(
node.getChildren(),
new Predicate<NodeDelegate>() {
@Override
public boolean apply(NodeDelegate state) {
// TODO: use Oak names
return ItemNameMatcher.matches(toJcrPath(state.getName()), namePattern);
}
});
return new NodeIteratorAdapter(nodeIterator(children));
}
});
}
@Override
@Nonnull
public NodeIterator getNodes(final String[] nameGlobs) throws RepositoryException {
return perform(new NodeOperation<NodeIterator>(dlg, "getNodes") {
@Nonnull
@Override
public NodeIterator perform() throws RepositoryException {
Iterator<NodeDelegate> children = Iterators.filter(
node.getChildren(),
new Predicate<NodeDelegate>() {
@Override
public boolean apply(NodeDelegate state) {
// TODO: use Oak names
return ItemNameMatcher.matches(toJcrPath(state.getName()), nameGlobs);
}
});
return new NodeIteratorAdapter(nodeIterator(children));
}
});
}
@Override
@Nonnull
public Property getProperty(String relPath) throws RepositoryException {
final String oakPath = getOakPathOrThrowNotFound(relPath);
return perform(new NodeOperation<PropertyImpl>(dlg, "getProperty") {
@Nonnull
@Override
public PropertyImpl perform() throws RepositoryException {
PropertyDelegate pd = node.getPropertyOrNull(oakPath);
if (pd == null) {
throw new PathNotFoundException(
oakPath + " not found on " + node.getPath());
} else {
return new PropertyImpl(pd, sessionContext);
}
}
});
}
@Override
@Nonnull
public PropertyIterator getProperties() throws RepositoryException {
return perform(new NodeOperation<PropertyIterator>(dlg, "getProperties") {
@Nonnull
@Override
public PropertyIterator perform() throws RepositoryException {
Iterator<PropertyDelegate> properties = node.getProperties();
long size = node.getPropertyCount();
return new PropertyIteratorAdapter(
propertyIterator(properties), size);
}
});
}
@Override
@Nonnull
public PropertyIterator getProperties(final String namePattern) throws RepositoryException {
return perform(new NodeOperation<PropertyIterator>(dlg, "getProperties") {
@Nonnull
@Override
public PropertyIterator perform() throws RepositoryException {
final PropertyIteratorDelegate delegate = new PropertyIteratorDelegate(node, new Predicate<PropertyDelegate>() {
@Override
public boolean apply(PropertyDelegate entry) {
// TODO: use Oak names
return ItemNameMatcher.matches(toJcrPath(entry.getName()), namePattern);
}
});
return new PropertyIteratorAdapter(propertyIterator(delegate.iterator())){
@Override
public long getSize() {
return delegate.getSize();
}
};
}
});
}
@Override
@Nonnull
public PropertyIterator getProperties(final String[] nameGlobs) throws RepositoryException {
return perform(new NodeOperation<PropertyIterator>(dlg, "getProperties") {
@Nonnull
@Override
public PropertyIterator perform() throws RepositoryException {
final PropertyIteratorDelegate delegate = new PropertyIteratorDelegate(node, new Predicate<PropertyDelegate>() {
@Override
public boolean apply(PropertyDelegate entry) {
// TODO: use Oak names
return ItemNameMatcher.matches(toJcrPath(entry.getName()), nameGlobs);
}
});
return new PropertyIteratorAdapter(propertyIterator(delegate.iterator())){
@Override
public long getSize() {
return delegate.getSize();
}
};
}
});
}
/**
* @see javax.jcr.Node#getPrimaryItem()
*/
@Override
@Nonnull
public Item getPrimaryItem() throws RepositoryException {
return perform(new NodeOperation<Item>(dlg, "getPrimaryItem") {
@Nonnull
@Override
public Item perform() throws RepositoryException {
// TODO: avoid nested calls
String name = getPrimaryNodeType().getPrimaryItemName();
if (name == null) {
throw new ItemNotFoundException(
"No primary item present on node " + NodeImpl.this);
}
if (hasProperty(name)) {
return getProperty(name);
} else if (hasNode(name)) {
return getNode(name);
} else {
throw new ItemNotFoundException(
"Primary item " + name +
" does not exist on node " + NodeImpl.this);
}
}
});
}
/**
* @see javax.jcr.Node#getUUID()
*/
@Override
@Nonnull
public String getUUID() throws RepositoryException {
return perform(new NodeOperation<String>(dlg, "getUUID") {
@Nonnull
@Override
public String perform() throws RepositoryException {
// TODO: avoid nested calls
if (isNodeType(NodeType.MIX_REFERENCEABLE)) {
return getIdentifier();
}
throw new UnsupportedRepositoryOperationException(format("Node [%s] is not referenceable.", getNodePath()));
}
});
}
@Override
@Nonnull
public String getIdentifier() throws RepositoryException {
// TODO: name mapping for path identifiers
return perform(new NodeOperation<String>(dlg, "getIdentifier") {
@Nonnull
@Override
public String perform() throws RepositoryException {
return node.getIdentifier();
}
});
}
@Override
public int getIndex() throws RepositoryException {
// as long as we do not support same name siblings, index always is 1
return 1; // TODO
}
private PropertyIterator internalGetReferences(final String name, final boolean weak) throws RepositoryException {
return perform(new NodeOperation<PropertyIterator>(dlg, "internalGetReferences") {
@Nonnull
@Override
public PropertyIterator perform() throws InvalidItemStateException {
IdentifierManager idManager = sessionDelegate.getIdManager();
Iterable<String> propertyOakPaths = idManager.getReferences(weak, node.getTree(), name); // TODO: oak name?
Iterable<Property> properties = Iterables.transform(
propertyOakPaths,
new Function<String, Property>() {
@Override
public Property apply(String oakPath) {
PropertyDelegate pd = sessionDelegate.getProperty(oakPath);
return pd == null ? null : new PropertyImpl(pd, sessionContext);
}
}
);
return new PropertyIteratorAdapter(sessionDelegate.sync(properties.iterator()));
}
});
}
/**
* @see javax.jcr.Node#getReferences()
*/
@Override
@Nonnull
public PropertyIterator getReferences() throws RepositoryException {
return internalGetReferences(null, false);
}
@Override
@Nonnull
public PropertyIterator getReferences(final String name) throws RepositoryException {
return internalGetReferences(name, false);
}
/**
* @see javax.jcr.Node#getWeakReferences()
*/
@Override
@Nonnull
public PropertyIterator getWeakReferences() throws RepositoryException {
return internalGetReferences(null, true);
}
@Override
@Nonnull
public PropertyIterator getWeakReferences(String name) throws RepositoryException {
return internalGetReferences(name, true);
}
@Override
public boolean hasNode(String relPath) throws RepositoryException {
try {
final String oakPath = getOakPathOrThrow(relPath);
return perform(new NodeOperation<Boolean>(dlg, "hasNode") {
@Nonnull
@Override
public Boolean perform() throws RepositoryException {
return node.getChild(oakPath) != null;
}
});
} catch (PathNotFoundException e) {
return false;
}
}
@Override
public boolean hasProperty(String relPath) throws RepositoryException {
try {
final String oakPath = getOakPathOrThrow(relPath);
return perform(new NodeOperation<Boolean>(dlg, "hasProperty") {
@Nonnull
@Override
public Boolean perform() throws RepositoryException {
return node.getPropertyOrNull(oakPath) != null;
}
});
} catch (PathNotFoundException e) {
return false;
}
}
@Override
public boolean hasNodes() throws RepositoryException {
return getNodes().hasNext();
}
@Override
public boolean hasProperties() throws RepositoryException {
return perform(new NodeOperation<Boolean>(dlg, "hasProperties") {
@Nonnull
@Override
public Boolean perform() throws RepositoryException {
return node.getPropertyCount() != 0;
}
});
}
/**
* @see javax.jcr.Node#getPrimaryNodeType()
*/
@Override
@Nonnull
public NodeType getPrimaryNodeType() throws RepositoryException {
return perform(new NodeOperation<NodeType>(dlg, "getPrimaryNodeType") {
@Nonnull
@Override
public NodeType perform() throws RepositoryException {
Tree tree = node.getTree();
String primaryTypeName = getPrimaryTypeName(tree);
if (primaryTypeName != null) {
return getNodeTypeManager().getNodeType(sessionContext.getJcrName(primaryTypeName));
} else {
throw new RepositoryException("Unable to retrieve primary type for Node " + getNodePath());
}
}
});
}
/**
* @see javax.jcr.Node#getMixinNodeTypes()
*/
@Override
@Nonnull
public NodeType[] getMixinNodeTypes() throws RepositoryException {
return perform(new NodeOperation<NodeType[]>(dlg, "getMixinNodeTypes") {
@Nonnull
@Override
public NodeType[] perform() throws RepositoryException {
Tree tree = node.getTree();
Iterator<String> mixinNames = getMixinTypeNames(tree);
if (mixinNames.hasNext()) {
NodeTypeManager ntMgr = getNodeTypeManager();
List<NodeType> mixinTypes = Lists.newArrayList();
while (mixinNames.hasNext()) {
mixinTypes.add(ntMgr.getNodeType(sessionContext.getJcrName(mixinNames.next())));
}
return mixinTypes.toArray(new NodeType[mixinTypes.size()]);
} else {
return new NodeType[0];
}
}
});
}
@Override
public boolean isNodeType(String nodeTypeName) throws RepositoryException {
final String oakName = getOakName(nodeTypeName);
return perform(new NodeOperation<Boolean>(dlg, "isNodeType") {
@Nonnull
@Override
public Boolean perform() throws RepositoryException {
Tree tree = node.getTree();
return getNodeTypeManager().isNodeType(getPrimaryTypeName(tree), getMixinTypeNames(tree), oakName);
}
});
}
@Override
public void setPrimaryType(final String nodeTypeName) throws RepositoryException {
sessionDelegate.performVoid(new ItemWriteOperation<Void>("setPrimaryType") {
@Override
public void checkPreconditions() throws RepositoryException {
super.checkPreconditions();
if (!isCheckedOut()) {
throw new VersionException(format("Cannot set primary type. Node [%s] is checked in.", getNodePath()));
}
}
@Override
public void performVoid() throws RepositoryException {
internalSetPrimaryType(nodeTypeName);
}
});
}
@Override
public void addMixin(String mixinName) throws RepositoryException {
final String oakTypeName = getOakName(checkNotNull(mixinName));
sessionDelegate.performVoid(new ItemWriteOperation<Void>("addMixin") {
@Override
public void checkPreconditions() throws RepositoryException {
super.checkPreconditions();
if (!isCheckedOut()) {
throw new VersionException(format(
"Cannot add mixin type. Node [%s] is checked in.", getNodePath()));
}
}
@Override
public void performVoid() throws RepositoryException {
dlg.addMixin(oakTypeName);
}
});
}
@Override
public void removeMixin(final String mixinName) throws RepositoryException {
final String oakTypeName = getOakName(checkNotNull(mixinName));
sessionDelegate.performVoid(new ItemWriteOperation<Void>("removeMixin") {
@Override
public void checkPreconditions() throws RepositoryException {
super.checkPreconditions();
if (!isCheckedOut()) {
throw new VersionException(format(
"Cannot remove mixin type. Node [%s] is checked in.", getNodePath()));
}
// check for NODE_TYPE_MANAGEMENT permission here as we cannot
// distinguish between a combination of removeMixin and addMixin
// and Node#remove plus subsequent addNode when it comes to
// autocreated properties like jcr:create, jcr:uuid and so forth.
Set<String> mixins = newLinkedHashSet(getNames(dlg.getTree(), JCR_MIXINTYPES));
if (!mixins.isEmpty() && mixins.remove(getOakName(mixinName))) {
PropertyState prop = PropertyStates.createProperty(JCR_MIXINTYPES, mixins, NAMES);
sessionContext.getAccessManager().checkPermissions(dlg.getTree(), prop, Permissions.NODE_TYPE_MANAGEMENT);
}
}
@Override
public void performVoid() throws RepositoryException {
dlg.removeMixin(oakTypeName);
}
});
}
@Override
public boolean canAddMixin(String mixinName) throws RepositoryException {
final String oakTypeName = getOakName(mixinName);
return perform(new NodeOperation<Boolean>(dlg, "canAddMixin") {
@Nonnull
@Override
public Boolean perform() throws RepositoryException {
PropertyState prop = PropertyStates.createProperty(JCR_MIXINTYPES, singleton(oakTypeName), NAMES);
return sessionContext.getAccessManager().hasPermissions(
node.getTree(), prop, Permissions.NODE_TYPE_MANAGEMENT)
&& !node.isProtected()
&& getVersionManager().isCheckedOut(toJcrPath(dlg.getPath())) // TODO: avoid nested calls
&& node.canAddMixin(oakTypeName);
}
});
}
@Override
@Nonnull
public NodeDefinition getDefinition() throws RepositoryException {
return perform(new NodeOperation<NodeDefinition>(dlg, "getDefinition") {
@Nonnull
@Override
public NodeDefinition perform() throws RepositoryException {
NodeDelegate parent = node.getParent();
if (parent == null) {
return getNodeTypeManager().getRootDefinition();
} else {
return getNodeTypeManager().getDefinition(
parent.getTree(), node.getTree());
}
}
});
}
@Override
@Nonnull
public String getCorrespondingNodePath(final String workspaceName) throws RepositoryException {
return toJcrPath(perform(new ItemOperation<String>(dlg, "getCorrespondingNodePath") {
@Nonnull
@Override
public String perform() throws RepositoryException {
checkValidWorkspace(workspaceName);
if (workspaceName.equals(sessionDelegate.getWorkspaceName())) {
return item.getPath();
} else {
throw new UnsupportedRepositoryOperationException("OAK-118: Node.getCorrespondingNodePath at " + getNodePath());
}
}
}));
}
@Override
public void update(final String srcWorkspace) throws RepositoryException {
sessionDelegate.performVoid(new ItemWriteOperation<Void>("update") {
@Override
public void performVoid() throws RepositoryException {
checkValidWorkspace(srcWorkspace);
// check for pending changes
if (sessionDelegate.hasPendingChanges()) {
String msg = format("Unable to perform operation. Session has pending changes. Node [%s]", getNodePath());
LOG.debug(msg);
throw new InvalidItemStateException(msg);
}
if (!srcWorkspace.equals(sessionDelegate.getWorkspaceName())) {
throw new UnsupportedRepositoryOperationException("OAK-118: Node.update at " + getNodePath());
}
}
});
}
/**
* @see javax.jcr.Node#checkin()
*/
@Override
@Nonnull
public Version checkin() throws RepositoryException {
return getVersionManager().checkin(getPath());
}
/**
* @see javax.jcr.Node#checkout()
*/
@Override
public void checkout() throws RepositoryException {
getVersionManager().checkout(getPath());
}
/**
* @see javax.jcr.Node#doneMerge(javax.jcr.version.Version)
*/
@Override
public void doneMerge(Version version) throws RepositoryException {
getVersionManager().doneMerge(getPath(), version);
}
/**
* @see javax.jcr.Node#cancelMerge(javax.jcr.version.Version)
*/
@Override
public void cancelMerge(Version version) throws RepositoryException {
getVersionManager().cancelMerge(getPath(), version);
}
/**
* @see javax.jcr.Node#merge(String, boolean)
*/
@Override
@Nonnull
public NodeIterator merge(String srcWorkspace, boolean bestEffort) throws RepositoryException {
return getVersionManager().merge(getPath(), srcWorkspace, bestEffort);
}
/**
* @see javax.jcr.Node#isCheckedOut()
*/
@Override
public boolean isCheckedOut() throws RepositoryException {
try {
return getVersionManager().isCheckedOut(getPath());
} catch (UnsupportedRepositoryOperationException ex) {
// when versioning is not supported all nodes are considered to be
// checked out
return true;
}
}
/**
* @see javax.jcr.Node#restore(String, boolean)
*/
@Override
public void restore(String versionName, boolean removeExisting) throws RepositoryException {
if (!isNodeType(NodeType.MIX_VERSIONABLE)) {
throw new UnsupportedRepositoryOperationException(format("Node [%s] is not mix:versionable", getNodePath()));
}
getVersionManager().restore(getPath(), versionName, removeExisting);
}
/**
* @see javax.jcr.Node#restore(javax.jcr.version.Version, boolean)
*/
@Override
public void restore(Version version, boolean removeExisting) throws RepositoryException {
if (!isNodeType(NodeType.MIX_VERSIONABLE)) {
throw new UnsupportedRepositoryOperationException(format("Node [%s] is not mix:versionable", getNodePath()));
}
String id = version.getContainingHistory().getVersionableIdentifier();
if (getIdentifier().equals(id)) {
getVersionManager().restore(version, removeExisting);
} else {
throw new VersionException(format("Version does not belong to the " +
"VersionHistory of this node [%s].", getNodePath()));
}
}
/**
* @see javax.jcr.Node#restore(Version, String, boolean)
*/
@Override
public void restore(Version version, String relPath, boolean removeExisting) throws RepositoryException {
// additional checks are performed with subsequent calls.
if (hasNode(relPath)) {
// node at 'relPath' exists -> call restore on the target Node
getNode(relPath).restore(version, removeExisting);
} else {
String absPath = PathUtils.concat(getPath(), relPath);
getVersionManager().restore(absPath, version, removeExisting);
}
}
/**
* @see javax.jcr.Node#restoreByLabel(String, boolean)
*/
@Override
public void restoreByLabel(String versionLabel, boolean removeExisting) throws RepositoryException {
getVersionManager().restoreByLabel(getPath(), versionLabel, removeExisting);
}
/**
* @see javax.jcr.Node#getVersionHistory()
*/
@Override
@Nonnull
public VersionHistory getVersionHistory() throws RepositoryException {
return getVersionManager().getVersionHistory(getPath());
}
/**
* @see javax.jcr.Node#getBaseVersion()
*/
@Override
@Nonnull
public Version getBaseVersion() throws RepositoryException {
return getVersionManager().getBaseVersion(getPath());
}
private LockManager getLockManager() throws RepositoryException {
return getSession().getWorkspace().getLockManager();
}
@Override
public boolean isLocked() throws RepositoryException {
return getLockManager().isLocked(getPath());
}
@Override
public boolean holdsLock() throws RepositoryException {
return getLockManager().holdsLock(getPath());
}
@Override @Nonnull
public Lock getLock() throws RepositoryException {
return getLockManager().getLock(getPath());
}
@Override @Nonnull
public Lock lock(boolean isDeep, boolean isSessionScoped)
throws RepositoryException {
return getLockManager().lock(
getPath(), isDeep, isSessionScoped, Long.MAX_VALUE, null);
}
@Override
public void unlock() throws RepositoryException {
getLockManager().unlock(getPath());
}
@Override @Nonnull
public NodeIterator getSharedSet() {
return new NodeIteratorAdapter(singleton(this));
}
@Override
public void removeSharedSet() throws RepositoryException {
sessionDelegate.performVoid(new ItemWriteOperation<Void>("removeSharedSet") {
@Override
public void performVoid() throws RepositoryException {
// TODO: avoid nested calls
NodeIterator sharedSet = getSharedSet();
while (sharedSet.hasNext()) {
sharedSet.nextNode().removeShare();
}
}
});
}
@Override
public void removeShare() throws RepositoryException {
remove();
}
/**
* @see javax.jcr.Node#followLifecycleTransition(String)
*/
@Override
public void followLifecycleTransition(String transition) throws RepositoryException {
throw new UnsupportedRepositoryOperationException("Lifecycle Management is not supported");
}
/**
* @see javax.jcr.Node#getAllowedLifecycleTransistions()
*/
@Override
@Nonnull
public String[] getAllowedLifecycleTransistions() throws RepositoryException {
throw new UnsupportedRepositoryOperationException("Lifecycle Management is not supported");
}
//------------------------------------------------------------< internal >---
@CheckForNull
private String getPrimaryTypeName(@Nonnull Tree tree) {
String primaryTypeName = null;
if (tree.hasProperty(JcrConstants.JCR_PRIMARYTYPE)) {
primaryTypeName = TreeUtil.getPrimaryTypeName(tree);
} else if (tree.getStatus() != Status.NEW) {
// OAK-2441: for backwards compatibility with Jackrabbit 2.x try to
// read the primary type from the underlying node state.
primaryTypeName = TreeUtil.getPrimaryTypeName(RootFactory.createReadOnlyRoot(sessionDelegate.getRoot()).getTree(tree.getPath()));
}
return primaryTypeName;
}
@Nonnull
private Iterator<String> getMixinTypeNames(@Nonnull Tree tree) throws RepositoryException {
Iterator<String> mixinNames = Iterators.emptyIterator();
if (tree.hasProperty(JcrConstants.JCR_MIXINTYPES) || canReadProperty(tree, JcrConstants.JCR_MIXINTYPES)) {
mixinNames = TreeUtil.getNames(tree, JcrConstants.JCR_MIXINTYPES).iterator();
} else if (tree.getStatus() != Status.NEW) {
// OAK-2441: for backwards compatibility with Jackrabbit 2.x try to
// read the primary type from the underlying node state.
mixinNames = TreeUtil.getNames(
RootFactory.createReadOnlyRoot(sessionDelegate.getRoot()).getTree(tree.getPath()),
JcrConstants.JCR_MIXINTYPES).iterator();
}
return mixinNames;
}
private boolean canReadProperty(@Nonnull Tree tree, @Nonnull String propName) throws RepositoryException {
String propPath = PathUtils.concat(tree.getPath(), propName);
String permName = Permissions.PERMISSION_NAMES.get(Permissions.READ_PROPERTY);
return sessionContext.getAccessManager().hasPermissions(propPath, permName);
}
private EffectiveNodeType getEffectiveNodeType() throws RepositoryException {
return getNodeTypeManager().getEffectiveNodeType(dlg.getTree());
}
private Iterator<Node> nodeIterator(Iterator<NodeDelegate> childNodes) {
return sessionDelegate.sync(transform(
childNodes,
new Function<NodeDelegate, Node>() {
@Override
public Node apply(NodeDelegate nodeDelegate) {
return new NodeImpl<NodeDelegate>(nodeDelegate, sessionContext);
}
}));
}
private Iterator<Property> propertyIterator(Iterator<PropertyDelegate> properties) {
return sessionDelegate.sync(transform(
properties,
new Function<PropertyDelegate, Property>() {
@Override
public Property apply(PropertyDelegate propertyDelegate) {
return new PropertyImpl(propertyDelegate, sessionContext);
}
}));
}
private void checkValidWorkspace(String workspaceName)
throws RepositoryException {
String[] workspaceNames =
getSession().getWorkspace().getAccessibleWorkspaceNames();
if (!asList(workspaceNames).contains(workspaceName)) {
throw new NoSuchWorkspaceException(
"Workspace " + workspaceName + " does not exist");
}
}
private void internalSetPrimaryType(final String nodeTypeName) throws RepositoryException {
// TODO: figure out the right place for this check
NodeType nt = getNodeTypeManager().getNodeType(nodeTypeName); // throws on not found
if (nt.isAbstract() || nt.isMixin()) {
throw new ConstraintViolationException(getNodePath());
}
// TODO: END
PropertyState state = PropertyStates.createProperty(
JCR_PRIMARYTYPE, getOakName(nodeTypeName), NAME);
dlg.setProperty(state, true, true);
dlg.setOrderableChildren(nt.hasOrderableChildNodes());
}
private Property internalSetProperty(
final String jcrName, final Value value, final boolean exactTypeMatch)
throws RepositoryException {
final String oakName = getOakPathOrThrow(checkNotNull(jcrName));
final PropertyState state = createSingleState(
oakName, value, Type.fromTag(value.getType(), false));
return perform(new ItemWriteOperation<Property>("internalSetProperty") {
@Override
public void checkPreconditions() throws RepositoryException {
super.checkPreconditions();
if (!isCheckedOut()) {
throw new VersionException(format(
"Cannot set property. Node [%s] is checked in.", getNodePath()));
}
}
@Nonnull
@Override
public Property perform() throws RepositoryException {
return new PropertyImpl(
dlg.setProperty(state, exactTypeMatch, false),
sessionContext);
}
@Override
public String toString() {
return format("Setting property [%s/%s]", dlg.getPath(), jcrName);
}
});
}
private Property internalSetProperty(
final String jcrName, final Value[] values,
final int type, final boolean exactTypeMatch)
throws RepositoryException {
final String oakName = getOakPathOrThrow(checkNotNull(jcrName));
final PropertyState state = createMultiState(
oakName, compact(values), Type.fromTag(type, true));
if (values.length > MV_PROPERTY_WARN_THRESHOLD) {
LOG.warn("Large multi valued property [{}/{}] detected ({} values).",dlg.getPath(), jcrName, values.length);
}
return perform(new ItemWriteOperation<Property>("internalSetProperty") {
@Override
public void checkPreconditions() throws RepositoryException {
super.checkPreconditions();
if (!isCheckedOut()) {
throw new VersionException(format(
"Cannot set property. Node [%s] is checked in.", getNodePath()));
}
}
@Nonnull
@Override
public Property perform() throws RepositoryException {
return new PropertyImpl(
dlg.setProperty(state, exactTypeMatch, false),
sessionContext);
}
@Override
public String toString() {
return format("Setting property [%s/%s]", dlg.getPath(), jcrName);
}
});
}
/**
* Removes all {@code null} values from the given array.
*
* @param values value array
* @return value list without {@code null} entries
*/
private static List<Value> compact(Value[] values) {
List<Value> list = Lists.newArrayListWithCapacity(values.length);
for (Value value : values) {
if (value != null) {
list.add(value);
}
}
return list;
}
private Property internalRemoveProperty(final String jcrName)
throws RepositoryException {
final String oakName = getOakName(checkNotNull(jcrName));
return perform(new ItemWriteOperation<Property>("internalRemoveProperty") {
@Override
public void checkPreconditions() throws RepositoryException {
super.checkPreconditions();
if (!isCheckedOut()) {
throw new VersionException(format(
"Cannot remove property. Node [%s] is checked in.", getNodePath()));
}
}
@Nonnull
@Override
public Property perform() throws RepositoryException {
PropertyDelegate property = dlg.getPropertyOrNull(oakName);
if (property != null) {
property.remove();
} else {
// Return an instance which throws on access; see OAK-395
property = dlg.getProperty(oakName);
}
return new PropertyImpl(property, sessionContext);
}
@Override
public String toString() {
return format("Removing property [%s]", jcrName);
}
});
}
//-----------------------------------------------------< JackrabbitNode >---
/**
* Simplified implementation of {@link JackrabbitNode#rename(String)}. In
* contrast to the implementation in Jackrabbit 2.x which was operating on
* the NodeState level directly, this implementation does a move plus
* subsequent reorder on the JCR API due to a missing support for renaming
* on the OAK API.
*
* Note, that this also has an impact on how permissions are enforced: In
* Jackrabbit 2.x the rename just required permission to modify the child
* collection on the parent, whereas a move did the full permission check.
* With this simplified implementation that (somewhat inconsistent) difference
* has been removed.
*
* @param newName The new name of this node.
* @throws RepositoryException If an error occurs.
*/
@Override
public void rename(final String newName) throws RepositoryException {
if (dlg.isRoot()) {
throw new RepositoryException("Cannot rename the root node");
}
final String name = getName();
if (newName.equals(name)) {
// nothing to do
return;
}
sessionDelegate.performVoid(new ItemWriteOperation<Void>("rename") {
@Override
public void performVoid() throws RepositoryException {
Node parent = getParent();
String beforeName = null;
if (isOrderable(parent)) {
// remember position amongst siblings
NodeIterator nit = parent.getNodes();
while (nit.hasNext()) {
Node child = nit.nextNode();
if (name.equals(child.getName())) {
if (nit.hasNext()) {
beforeName = nit.nextNode().getName();
}
break;
}
}
}
String srcPath = getPath();
String destPath = '/' + newName;
String parentPath = parent.getPath();
if (!"/".equals(parentPath)) {
destPath = parentPath + destPath;
}
sessionContext.getSession().move(srcPath, destPath);
if (beforeName != null) {
// restore position within siblings
parent.orderBefore(newName, beforeName);
}
}
});
}
private static boolean isOrderable(Node node) throws RepositoryException {
if (node.getPrimaryNodeType().hasOrderableChildNodes()) {
return true;
}
NodeType[] types = node.getMixinNodeTypes();
for (NodeType type : types) {
if (type.hasOrderableChildNodes()) {
return true;
}
}
return false;
}
/**
* Simplified implementation of the {@link org.apache.jackrabbit.api.JackrabbitNode#setMixins(String[])}
* method that adds all mixin types that are not yet present on this node
* and removes all mixins that are no longer contained in the specified
* array. Note, that this implementation will not work exactly like the
* variant in Jackrabbit 2.x which first created the effective node type
* and adjusted the set of child items accordingly.
*
* @param mixinNames
* @throws RepositoryException
*/
@Override
public void setMixins(String[] mixinNames) throws RepositoryException {
final Set<String> oakTypeNames = newLinkedHashSet();
for (String mixinName : mixinNames) {
oakTypeNames.add(getOakName(checkNotNull(mixinName)));
}
sessionDelegate.performVoid(new ItemWriteOperation<Void>("setMixins") {
@Override
public void checkPreconditions() throws RepositoryException {
super.checkPreconditions();
if (!isCheckedOut()) {
throw new VersionException(format("Cannot set mixin types. Node [%s] is checked in.", getNodePath()));
}
// check for NODE_TYPE_MANAGEMENT permission here as we cannot
// distinguish between a combination of removeMixin and addMixin
// and Node#remove plus subsequent addNode when it comes to
// autocreated properties like jcr:create, jcr:uuid and so forth.
PropertyDelegate mixinProp = dlg.getPropertyOrNull(JCR_MIXINTYPES);
if (mixinProp != null) {
sessionContext.getAccessManager().checkPermissions(dlg.getTree(), mixinProp.getPropertyState(), Permissions.NODE_TYPE_MANAGEMENT);
}
}
@Override
public void performVoid() throws RepositoryException {
dlg.setMixins(oakTypeNames);
}
});
}
/**
* Provide current node path. Should be invoked from within
* the SessionDelegate#perform and preferred instead of getPath
* as it provides direct access to path
*/
private String getNodePath(){
return dlg.getPath();
}
private static class PropertyIteratorDelegate {
private final NodeDelegate node;
private final Predicate<PropertyDelegate> predicate;
PropertyIteratorDelegate(NodeDelegate node, Predicate<PropertyDelegate> predicate) {
this.node = node;
this.predicate = predicate;
}
public Iterator<PropertyDelegate> iterator() throws InvalidItemStateException {
return Iterators.filter(node.getProperties(), predicate);
}
public long getSize() {
try {
return Iterators.size(iterator());
} catch (InvalidItemStateException e) {
throw new IllegalStateException(
"This iterator is no longer valid", e);
}
}
}
}
| oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/session/NodeImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.jcr.session;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterators.transform;
import static com.google.common.collect.Sets.newLinkedHashSet;
import static java.util.Arrays.asList;
import static java.util.Collections.singleton;
import static org.apache.jackrabbit.JcrConstants.JCR_MIXINTYPES;
import static org.apache.jackrabbit.JcrConstants.JCR_PRIMARYTYPE;
import static org.apache.jackrabbit.oak.api.Type.NAME;
import static org.apache.jackrabbit.oak.api.Type.NAMES;
import static org.apache.jackrabbit.oak.jcr.session.SessionImpl.checkIndexOnName;
import static org.apache.jackrabbit.oak.util.TreeUtil.getNames;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.jcr.AccessDeniedException;
import javax.jcr.Binary;
import javax.jcr.InvalidItemStateException;
import javax.jcr.Item;
import javax.jcr.ItemExistsException;
import javax.jcr.ItemNotFoundException;
import javax.jcr.ItemVisitor;
import javax.jcr.NoSuchWorkspaceException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.Value;
import javax.jcr.lock.Lock;
import javax.jcr.lock.LockManager;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NodeDefinition;
import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.NodeTypeManager;
import javax.jcr.version.Version;
import javax.jcr.version.VersionException;
import javax.jcr.version.VersionHistory;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.api.JackrabbitNode;
import org.apache.jackrabbit.commons.ItemNameMatcher;
import org.apache.jackrabbit.commons.iterator.NodeIteratorAdapter;
import org.apache.jackrabbit.commons.iterator.PropertyIteratorAdapter;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.api.Tree.Status;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.commons.PathUtils;
import org.apache.jackrabbit.oak.jcr.delegate.NodeDelegate;
import org.apache.jackrabbit.oak.jcr.delegate.PropertyDelegate;
import org.apache.jackrabbit.oak.jcr.delegate.VersionManagerDelegate;
import org.apache.jackrabbit.oak.jcr.session.operation.ItemOperation;
import org.apache.jackrabbit.oak.jcr.session.operation.NodeOperation;
import org.apache.jackrabbit.oak.jcr.version.VersionHistoryImpl;
import org.apache.jackrabbit.oak.jcr.version.VersionImpl;
import org.apache.jackrabbit.oak.plugins.identifier.IdentifierManager;
import org.apache.jackrabbit.oak.plugins.memory.PropertyStates;
import org.apache.jackrabbit.oak.plugins.nodetype.EffectiveNodeType;
import org.apache.jackrabbit.oak.plugins.tree.RootFactory;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.Permissions;
import org.apache.jackrabbit.oak.util.TreeUtil;
import org.apache.jackrabbit.value.ValueHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TODO document
*
* @param <T> the delegate type
*/
public class NodeImpl<T extends NodeDelegate> extends ItemImpl<T> implements Node, JackrabbitNode {
/**
* The maximum returned value for {@link NodeIterator#getSize()}. If there
* are more nodes, the method returns -1.
*/
private static final long NODE_ITERATOR_MAX_SIZE = Long.MAX_VALUE;
/**
* logger instance
*/
private static final Logger LOG = LoggerFactory.getLogger(NodeImpl.class);
@CheckForNull
public static NodeImpl<? extends NodeDelegate> createNodeOrNull(
@CheckForNull NodeDelegate delegate, @Nonnull SessionContext context)
throws RepositoryException {
if (delegate != null) {
return createNode(delegate, context);
} else {
return null;
}
}
@Nonnull
public static NodeImpl<? extends NodeDelegate> createNode(
@Nonnull NodeDelegate delegate, @Nonnull SessionContext context)
throws RepositoryException {
PropertyDelegate pd = delegate.getPropertyOrNull(JCR_PRIMARYTYPE);
String type = pd != null ? pd.getString() : null;
if (JcrConstants.NT_VERSION.equals(type)) {
VersionManagerDelegate vmd =
VersionManagerDelegate.create(context.getSessionDelegate());
return new VersionImpl(vmd.createVersion(delegate), context);
} else if (JcrConstants.NT_VERSIONHISTORY.equals(type)) {
VersionManagerDelegate vmd =
VersionManagerDelegate.create(context.getSessionDelegate());
return new VersionHistoryImpl(vmd.createVersionHistory(delegate), context);
} else {
return new NodeImpl<NodeDelegate>(delegate, context);
}
}
public NodeImpl(T dlg, SessionContext sessionContext) {
super(dlg, sessionContext);
}
//---------------------------------------------------------------< Item >---
/**
* @see javax.jcr.Item#isNode()
*/
@Override
public boolean isNode() {
return true;
}
/**
* @see javax.jcr.Item#getParent()
*/
@Override
@Nonnull
public Node getParent() throws RepositoryException {
return perform(new NodeOperation<Node>(dlg, "getParent") {
@Nonnull
@Override
public Node perform() throws RepositoryException {
if (node.isRoot()) {
throw new ItemNotFoundException("Root has no parent");
} else {
NodeDelegate parent = node.getParent();
if (parent == null) {
throw new AccessDeniedException();
}
return createNode(parent, sessionContext);
}
}
});
}
/**
* @see javax.jcr.Item#isNew()
*/
@Override
public boolean isNew() {
return sessionDelegate.safePerform(new NodeOperation<Boolean>(dlg, "isNew") {
@Nonnull
@Override
public Boolean perform() {
return node.exists() && node.getStatus() == Status.NEW;
}
});
}
/**
* @see javax.jcr.Item#isModified()
*/
@Override
public boolean isModified() {
return sessionDelegate.safePerform(new NodeOperation<Boolean>(dlg, "isModified") {
@Nonnull
@Override
public Boolean perform() {
return node.exists() && node.getStatus() == Status.MODIFIED;
}
});
}
/**
* @see javax.jcr.Item#remove()
*/
@Override
public void remove() throws RepositoryException {
sessionDelegate.performVoid(new ItemWriteOperation<Void>("remove") {
@Override
public void performVoid() throws RepositoryException {
if (dlg.isRoot()) {
throw new RepositoryException("Cannot remove the root node");
}
dlg.remove();
}
@Override
public String toString() {
return String.format("Removing node [%s]", dlg.getPath());
}
});
}
@Override
public void accept(ItemVisitor visitor) throws RepositoryException {
visitor.visit(this);
}
//---------------------------------------------------------------< Node >---
/**
* @see Node#addNode(String)
*/
@Override
@Nonnull
public Node addNode(String relPath) throws RepositoryException {
return addNode(relPath, null);
}
@Override @Nonnull
public Node addNode(final String relPath, String primaryNodeTypeName)
throws RepositoryException {
final String oakPath = getOakPathOrThrowNotFound(relPath);
final String oakTypeName;
if (primaryNodeTypeName != null) {
oakTypeName = getOakName(primaryNodeTypeName);
} else {
oakTypeName = null;
}
checkIndexOnName(relPath);
return perform(new ItemWriteOperation<Node>("addNode") {
@Nonnull
@Override
public Node perform() throws RepositoryException {
String oakName = PathUtils.getName(oakPath);
String parentPath = PathUtils.getParentPath(oakPath);
NodeDelegate parent = dlg.getChild(parentPath);
if (parent == null) {
// is it a property?
String grandParentPath = PathUtils.getParentPath(parentPath);
NodeDelegate grandParent = dlg.getChild(grandParentPath);
if (grandParent != null) {
String propName = PathUtils.getName(parentPath);
if (grandParent.getPropertyOrNull(propName) != null) {
throw new ConstraintViolationException("Can't add new node to property.");
}
}
throw new PathNotFoundException(relPath);
}
if (parent.getChild(oakName) != null) {
throw new ItemExistsException(relPath);
}
// check for NODE_TYPE_MANAGEMENT permission here as we cannot
// distinguish between user-supplied and system-generated
// modification of that property in the PermissionValidator
if (oakTypeName != null) {
PropertyState prop = PropertyStates.createProperty(JCR_PRIMARYTYPE, oakTypeName, NAME);
sessionContext.getAccessManager().checkPermissions(parent.getTree(), prop, Permissions.NODE_TYPE_MANAGEMENT);
}
NodeDelegate added = parent.addChild(oakName, oakTypeName);
if (added == null) {
throw new ItemExistsException();
}
return createNode(added, sessionContext);
}
@Override
public String toString() {
return String.format("Adding node [%s/%s]", dlg.getPath(), relPath);
}
});
}
@Override
public void orderBefore(final String srcChildRelPath, final String destChildRelPath) throws RepositoryException {
sessionDelegate.performVoid(new ItemWriteOperation<Void>("orderBefore") {
@Override
public void performVoid() throws RepositoryException {
getEffectiveNodeType().checkOrderableChildNodes();
String oakSrcChildRelPath = getOakPathOrThrowNotFound(srcChildRelPath);
String oakDestChildRelPath = null;
if (destChildRelPath != null) {
oakDestChildRelPath = getOakPathOrThrowNotFound(destChildRelPath);
}
dlg.orderBefore(oakSrcChildRelPath, oakDestChildRelPath);
}
});
}
//-------------------------------------------------------< setProperty >--
//
// The setProperty() variants below follow the same pattern:
//
// if (value != null) {
// return internalSetProperty(name, ...);
// } else {
// return internalRemoveProperty(name);
// }
//
// In addition the value and value type information is pre-processed
// according to the method signature before being passed to
// internalSetProperty(). The methods that take a non-nullable
// primitive value as an argument can skip the if clause.
//
// Note that due to backwards compatibility reasons (OAK-395) none
// of the methods will ever return null, even if asked to remove
// a non-existing property! See internalRemoveProperty() for details.
@Override @Nonnull
public Property setProperty(String name, Value value)
throws RepositoryException {
if (value != null) {
return internalSetProperty(name, value, false);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, Value value, int type)
throws RepositoryException {
if (value != null) {
boolean exactTypeMatch = true;
if (type == PropertyType.UNDEFINED) {
exactTypeMatch = false;
} else {
value = ValueHelper.convert(value, type, getValueFactory());
}
return internalSetProperty(name, value, exactTypeMatch);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, Value[] values)
throws RepositoryException {
if (values != null) {
// TODO: type
return internalSetProperty(name, values, ValueHelper.getType(values), false);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String jcrName, Value[] values, int type)
throws RepositoryException {
if (values != null) {
boolean exactTypeMatch = true;
if (type == PropertyType.UNDEFINED) {
type = PropertyType.STRING;
exactTypeMatch = false;
}
values = ValueHelper.convert(values, type, getValueFactory());
return internalSetProperty(jcrName, values, type, exactTypeMatch);
} else {
return internalRemoveProperty(jcrName);
}
}
@Override @Nonnull
public Property setProperty(String name, String[] values)
throws RepositoryException {
if (values != null) {
int type = PropertyType.STRING;
Value[] vs = ValueHelper.convert(values, type, getValueFactory());
return internalSetProperty(name, vs, type, false);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, String[] values, int type)
throws RepositoryException {
if (values != null) {
boolean exactTypeMatch = true;
if (type == PropertyType.UNDEFINED) {
type = PropertyType.STRING;
exactTypeMatch = false;
}
Value[] vs = ValueHelper.convert(values, type, getValueFactory());
return internalSetProperty(name, vs, type, exactTypeMatch);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, String value)
throws RepositoryException {
if (value != null) {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, String value, int type)
throws RepositoryException {
if (value != null) {
boolean exactTypeMatch = true;
if (type == PropertyType.UNDEFINED) {
type = PropertyType.STRING;
exactTypeMatch = false;
}
Value v = getValueFactory().createValue(value, type);
return internalSetProperty(name, v, exactTypeMatch);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull @SuppressWarnings("deprecation")
public Property setProperty(String name, InputStream value)
throws RepositoryException {
if (value != null) {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, Binary value)
throws RepositoryException {
if (value != null) {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, boolean value)
throws RepositoryException {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
}
@Override @Nonnull
public Property setProperty(String name, double value)
throws RepositoryException {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
}
@Override @Nonnull
public Property setProperty(String name, BigDecimal value)
throws RepositoryException {
if (value != null) {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, long value)
throws RepositoryException {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
}
@Override @Nonnull
public Property setProperty(String name, Calendar value)
throws RepositoryException {
if (value != null) {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
} else {
return internalRemoveProperty(name);
}
}
@Override @Nonnull
public Property setProperty(String name, Node value)
throws RepositoryException {
if (value != null) {
Value v = getValueFactory().createValue(value);
return internalSetProperty(name, v, false);
} else {
return internalRemoveProperty(name);
}
}
@Override
@Nonnull
public Node getNode(String relPath) throws RepositoryException {
final String oakPath = getOakPathOrThrowNotFound(relPath);
return perform(new NodeOperation<Node>(dlg, "getNode") {
@Nonnull
@Override
public Node perform() throws RepositoryException {
NodeDelegate nd = node.getChild(oakPath);
if (nd == null) {
throw new PathNotFoundException(oakPath);
} else {
return createNode(nd, sessionContext);
}
}
});
}
@Override
@Nonnull
public NodeIterator getNodes() throws RepositoryException {
return perform(new NodeOperation<NodeIterator>(dlg, "getNodes") {
@Nonnull
@Override
public NodeIterator perform() throws RepositoryException {
Iterator<NodeDelegate> children = node.getChildren();
return new NodeIteratorAdapter(nodeIterator(children)) {
private long size = -2;
@Override
public long getSize() {
if (size == -2) {
try {
size = node.getChildCount(NODE_ITERATOR_MAX_SIZE); // TODO: perform()
if (size == Long.MAX_VALUE) {
size = -1;
}
} catch (InvalidItemStateException e) {
throw new IllegalStateException(
"This iterator is no longer valid", e);
}
}
return size;
}
};
}
});
}
@Override
@Nonnull
public NodeIterator getNodes(final String namePattern)
throws RepositoryException {
return perform(new NodeOperation<NodeIterator>(dlg, "getNodes") {
@Nonnull
@Override
public NodeIterator perform() throws RepositoryException {
Iterator<NodeDelegate> children = Iterators.filter(
node.getChildren(),
new Predicate<NodeDelegate>() {
@Override
public boolean apply(NodeDelegate state) {
// TODO: use Oak names
return ItemNameMatcher.matches(toJcrPath(state.getName()), namePattern);
}
});
return new NodeIteratorAdapter(nodeIterator(children));
}
});
}
@Override
@Nonnull
public NodeIterator getNodes(final String[] nameGlobs) throws RepositoryException {
return perform(new NodeOperation<NodeIterator>(dlg, "getNodes") {
@Nonnull
@Override
public NodeIterator perform() throws RepositoryException {
Iterator<NodeDelegate> children = Iterators.filter(
node.getChildren(),
new Predicate<NodeDelegate>() {
@Override
public boolean apply(NodeDelegate state) {
// TODO: use Oak names
return ItemNameMatcher.matches(toJcrPath(state.getName()), nameGlobs);
}
});
return new NodeIteratorAdapter(nodeIterator(children));
}
});
}
@Override
@Nonnull
public Property getProperty(String relPath) throws RepositoryException {
final String oakPath = getOakPathOrThrowNotFound(relPath);
return perform(new NodeOperation<PropertyImpl>(dlg, "getProperty") {
@Nonnull
@Override
public PropertyImpl perform() throws RepositoryException {
PropertyDelegate pd = node.getPropertyOrNull(oakPath);
if (pd == null) {
throw new PathNotFoundException(
oakPath + " not found on " + node.getPath());
} else {
return new PropertyImpl(pd, sessionContext);
}
}
});
}
@Override
@Nonnull
public PropertyIterator getProperties() throws RepositoryException {
return perform(new NodeOperation<PropertyIterator>(dlg, "getProperties") {
@Nonnull
@Override
public PropertyIterator perform() throws RepositoryException {
Iterator<PropertyDelegate> properties = node.getProperties();
long size = node.getPropertyCount();
return new PropertyIteratorAdapter(
propertyIterator(properties), size);
}
});
}
@Override
@Nonnull
public PropertyIterator getProperties(final String namePattern) throws RepositoryException {
return perform(new NodeOperation<PropertyIterator>(dlg, "getProperties") {
@Nonnull
@Override
public PropertyIterator perform() throws RepositoryException {
final PropertyIteratorDelegate delegate = new PropertyIteratorDelegate(node, new Predicate<PropertyDelegate>() {
@Override
public boolean apply(PropertyDelegate entry) {
// TODO: use Oak names
return ItemNameMatcher.matches(toJcrPath(entry.getName()), namePattern);
}
});
return new PropertyIteratorAdapter(propertyIterator(delegate.iterator())){
@Override
public long getSize() {
return delegate.getSize();
}
};
}
});
}
@Override
@Nonnull
public PropertyIterator getProperties(final String[] nameGlobs) throws RepositoryException {
return perform(new NodeOperation<PropertyIterator>(dlg, "getProperties") {
@Nonnull
@Override
public PropertyIterator perform() throws RepositoryException {
final PropertyIteratorDelegate delegate = new PropertyIteratorDelegate(node, new Predicate<PropertyDelegate>() {
@Override
public boolean apply(PropertyDelegate entry) {
// TODO: use Oak names
return ItemNameMatcher.matches(toJcrPath(entry.getName()), nameGlobs);
}
});
return new PropertyIteratorAdapter(propertyIterator(delegate.iterator())){
@Override
public long getSize() {
return delegate.getSize();
}
};
}
});
}
/**
* @see javax.jcr.Node#getPrimaryItem()
*/
@Override
@Nonnull
public Item getPrimaryItem() throws RepositoryException {
return perform(new NodeOperation<Item>(dlg, "getPrimaryItem") {
@Nonnull
@Override
public Item perform() throws RepositoryException {
// TODO: avoid nested calls
String name = getPrimaryNodeType().getPrimaryItemName();
if (name == null) {
throw new ItemNotFoundException(
"No primary item present on node " + NodeImpl.this);
}
if (hasProperty(name)) {
return getProperty(name);
} else if (hasNode(name)) {
return getNode(name);
} else {
throw new ItemNotFoundException(
"Primary item " + name +
" does not exist on node " + NodeImpl.this);
}
}
});
}
/**
* @see javax.jcr.Node#getUUID()
*/
@Override
@Nonnull
public String getUUID() throws RepositoryException {
return perform(new NodeOperation<String>(dlg, "getUUID") {
@Nonnull
@Override
public String perform() throws RepositoryException {
// TODO: avoid nested calls
if (isNodeType(NodeType.MIX_REFERENCEABLE)) {
return getIdentifier();
}
throw new UnsupportedRepositoryOperationException("Node is not referenceable.");
}
});
}
@Override
@Nonnull
public String getIdentifier() throws RepositoryException {
// TODO: name mapping for path identifiers
return perform(new NodeOperation<String>(dlg, "getIdentifier") {
@Nonnull
@Override
public String perform() throws RepositoryException {
return node.getIdentifier();
}
});
}
@Override
public int getIndex() throws RepositoryException {
// as long as we do not support same name siblings, index always is 1
return 1; // TODO
}
private PropertyIterator internalGetReferences(final String name, final boolean weak) throws RepositoryException {
return perform(new NodeOperation<PropertyIterator>(dlg, "internalGetReferences") {
@Nonnull
@Override
public PropertyIterator perform() throws InvalidItemStateException {
IdentifierManager idManager = sessionDelegate.getIdManager();
Iterable<String> propertyOakPaths = idManager.getReferences(weak, node.getTree(), name); // TODO: oak name?
Iterable<Property> properties = Iterables.transform(
propertyOakPaths,
new Function<String, Property>() {
@Override
public Property apply(String oakPath) {
PropertyDelegate pd = sessionDelegate.getProperty(oakPath);
return pd == null ? null : new PropertyImpl(pd, sessionContext);
}
}
);
return new PropertyIteratorAdapter(sessionDelegate.sync(properties.iterator()));
}
});
}
/**
* @see javax.jcr.Node#getReferences()
*/
@Override
@Nonnull
public PropertyIterator getReferences() throws RepositoryException {
return internalGetReferences(null, false);
}
@Override
@Nonnull
public PropertyIterator getReferences(final String name) throws RepositoryException {
return internalGetReferences(name, false);
}
/**
* @see javax.jcr.Node#getWeakReferences()
*/
@Override
@Nonnull
public PropertyIterator getWeakReferences() throws RepositoryException {
return internalGetReferences(null, true);
}
@Override
@Nonnull
public PropertyIterator getWeakReferences(String name) throws RepositoryException {
return internalGetReferences(name, true);
}
@Override
public boolean hasNode(String relPath) throws RepositoryException {
try {
final String oakPath = getOakPathOrThrow(relPath);
return perform(new NodeOperation<Boolean>(dlg, "hasNode") {
@Nonnull
@Override
public Boolean perform() throws RepositoryException {
return node.getChild(oakPath) != null;
}
});
} catch (PathNotFoundException e) {
return false;
}
}
@Override
public boolean hasProperty(String relPath) throws RepositoryException {
try {
final String oakPath = getOakPathOrThrow(relPath);
return perform(new NodeOperation<Boolean>(dlg, "hasProperty") {
@Nonnull
@Override
public Boolean perform() throws RepositoryException {
return node.getPropertyOrNull(oakPath) != null;
}
});
} catch (PathNotFoundException e) {
return false;
}
}
@Override
public boolean hasNodes() throws RepositoryException {
return getNodes().hasNext();
}
@Override
public boolean hasProperties() throws RepositoryException {
return perform(new NodeOperation<Boolean>(dlg, "hasProperties") {
@Nonnull
@Override
public Boolean perform() throws RepositoryException {
return node.getPropertyCount() != 0;
}
});
}
/**
* @see javax.jcr.Node#getPrimaryNodeType()
*/
@Override
@Nonnull
public NodeType getPrimaryNodeType() throws RepositoryException {
return perform(new NodeOperation<NodeType>(dlg, "getPrimaryNodeType") {
@Nonnull
@Override
public NodeType perform() throws RepositoryException {
Tree tree = node.getTree();
String primaryTypeName = getPrimaryTypeName(tree);
if (primaryTypeName != null) {
return getNodeTypeManager().getNodeType(sessionContext.getJcrName(primaryTypeName));
} else {
throw new RepositoryException("Unable to retrieve primary type for Node " + getPath());
}
}
});
}
/**
* @see javax.jcr.Node#getMixinNodeTypes()
*/
@Override
@Nonnull
public NodeType[] getMixinNodeTypes() throws RepositoryException {
return perform(new NodeOperation<NodeType[]>(dlg, "getMixinNodeTypes") {
@Nonnull
@Override
public NodeType[] perform() throws RepositoryException {
Tree tree = node.getTree();
Iterator<String> mixinNames = getMixinTypeNames(tree);
if (mixinNames.hasNext()) {
NodeTypeManager ntMgr = getNodeTypeManager();
List<NodeType> mixinTypes = Lists.newArrayList();
while (mixinNames.hasNext()) {
mixinTypes.add(ntMgr.getNodeType(sessionContext.getJcrName(mixinNames.next())));
}
return mixinTypes.toArray(new NodeType[mixinTypes.size()]);
} else {
return new NodeType[0];
}
}
});
}
@Override
public boolean isNodeType(String nodeTypeName) throws RepositoryException {
final String oakName = getOakName(nodeTypeName);
return perform(new NodeOperation<Boolean>(dlg, "isNodeType") {
@Nonnull
@Override
public Boolean perform() throws RepositoryException {
Tree tree = node.getTree();
return getNodeTypeManager().isNodeType(getPrimaryTypeName(tree), getMixinTypeNames(tree), oakName);
}
});
}
@Override
public void setPrimaryType(final String nodeTypeName) throws RepositoryException {
sessionDelegate.performVoid(new ItemWriteOperation<Void>("setPrimaryType") {
@Override
public void checkPreconditions() throws RepositoryException {
super.checkPreconditions();
if (!isCheckedOut()) {
throw new VersionException("Cannot set primary type. Node is checked in.");
}
}
@Override
public void performVoid() throws RepositoryException {
internalSetPrimaryType(nodeTypeName);
}
});
}
@Override
public void addMixin(String mixinName) throws RepositoryException {
final String oakTypeName = getOakName(checkNotNull(mixinName));
sessionDelegate.performVoid(new ItemWriteOperation<Void>("addMixin") {
@Override
public void checkPreconditions() throws RepositoryException {
super.checkPreconditions();
if (!isCheckedOut()) {
throw new VersionException(
"Cannot add mixin type. Node is checked in.");
}
}
@Override
public void performVoid() throws RepositoryException {
dlg.addMixin(oakTypeName);
}
});
}
@Override
public void removeMixin(final String mixinName) throws RepositoryException {
final String oakTypeName = getOakName(checkNotNull(mixinName));
sessionDelegate.performVoid(new ItemWriteOperation<Void>("removeMixin") {
@Override
public void checkPreconditions() throws RepositoryException {
super.checkPreconditions();
if (!isCheckedOut()) {
throw new VersionException(
"Cannot remove mixin type. Node is checked in.");
}
// check for NODE_TYPE_MANAGEMENT permission here as we cannot
// distinguish between a combination of removeMixin and addMixin
// and Node#remove plus subsequent addNode when it comes to
// autocreated properties like jcr:create, jcr:uuid and so forth.
Set<String> mixins = newLinkedHashSet(getNames(dlg.getTree(), JCR_MIXINTYPES));
if (!mixins.isEmpty() && mixins.remove(getOakName(mixinName))) {
PropertyState prop = PropertyStates.createProperty(JCR_MIXINTYPES, mixins, NAMES);
sessionContext.getAccessManager().checkPermissions(dlg.getTree(), prop, Permissions.NODE_TYPE_MANAGEMENT);
}
}
@Override
public void performVoid() throws RepositoryException {
dlg.removeMixin(oakTypeName);
}
});
}
@Override
public boolean canAddMixin(String mixinName) throws RepositoryException {
final String oakTypeName = getOakName(mixinName);
return perform(new NodeOperation<Boolean>(dlg, "canAddMixin") {
@Nonnull
@Override
public Boolean perform() throws RepositoryException {
PropertyState prop = PropertyStates.createProperty(JCR_MIXINTYPES, singleton(oakTypeName), NAMES);
return sessionContext.getAccessManager().hasPermissions(
node.getTree(), prop, Permissions.NODE_TYPE_MANAGEMENT)
&& !node.isProtected()
&& getVersionManager().isCheckedOut(toJcrPath(dlg.getPath())) // TODO: avoid nested calls
&& node.canAddMixin(oakTypeName);
}
});
}
@Override
@Nonnull
public NodeDefinition getDefinition() throws RepositoryException {
return perform(new NodeOperation<NodeDefinition>(dlg, "getDefinition") {
@Nonnull
@Override
public NodeDefinition perform() throws RepositoryException {
NodeDelegate parent = node.getParent();
if (parent == null) {
return getNodeTypeManager().getRootDefinition();
} else {
return getNodeTypeManager().getDefinition(
parent.getTree(), node.getTree());
}
}
});
}
@Override
@Nonnull
public String getCorrespondingNodePath(final String workspaceName) throws RepositoryException {
return toJcrPath(perform(new ItemOperation<String>(dlg, "getCorrespondingNodePath") {
@Nonnull
@Override
public String perform() throws RepositoryException {
checkValidWorkspace(workspaceName);
if (workspaceName.equals(sessionDelegate.getWorkspaceName())) {
return item.getPath();
} else {
throw new UnsupportedRepositoryOperationException("OAK-118: Node.getCorrespondingNodePath");
}
}
}));
}
@Override
public void update(final String srcWorkspace) throws RepositoryException {
sessionDelegate.performVoid(new ItemWriteOperation<Void>("update") {
@Override
public void performVoid() throws RepositoryException {
checkValidWorkspace(srcWorkspace);
// check for pending changes
if (sessionDelegate.hasPendingChanges()) {
String msg = "Unable to perform operation. Session has pending changes.";
LOG.debug(msg);
throw new InvalidItemStateException(msg);
}
if (!srcWorkspace.equals(sessionDelegate.getWorkspaceName())) {
throw new UnsupportedRepositoryOperationException("OAK-118: Node.update");
}
}
});
}
/**
* @see javax.jcr.Node#checkin()
*/
@Override
@Nonnull
public Version checkin() throws RepositoryException {
return getVersionManager().checkin(getPath());
}
/**
* @see javax.jcr.Node#checkout()
*/
@Override
public void checkout() throws RepositoryException {
getVersionManager().checkout(getPath());
}
/**
* @see javax.jcr.Node#doneMerge(javax.jcr.version.Version)
*/
@Override
public void doneMerge(Version version) throws RepositoryException {
getVersionManager().doneMerge(getPath(), version);
}
/**
* @see javax.jcr.Node#cancelMerge(javax.jcr.version.Version)
*/
@Override
public void cancelMerge(Version version) throws RepositoryException {
getVersionManager().cancelMerge(getPath(), version);
}
/**
* @see javax.jcr.Node#merge(String, boolean)
*/
@Override
@Nonnull
public NodeIterator merge(String srcWorkspace, boolean bestEffort) throws RepositoryException {
return getVersionManager().merge(getPath(), srcWorkspace, bestEffort);
}
/**
* @see javax.jcr.Node#isCheckedOut()
*/
@Override
public boolean isCheckedOut() throws RepositoryException {
try {
return getVersionManager().isCheckedOut(getPath());
} catch (UnsupportedRepositoryOperationException ex) {
// when versioning is not supported all nodes are considered to be
// checked out
return true;
}
}
/**
* @see javax.jcr.Node#restore(String, boolean)
*/
@Override
public void restore(String versionName, boolean removeExisting) throws RepositoryException {
if (!isNodeType(NodeType.MIX_VERSIONABLE)) {
throw new UnsupportedRepositoryOperationException("Node is not mix:versionable");
}
getVersionManager().restore(getPath(), versionName, removeExisting);
}
/**
* @see javax.jcr.Node#restore(javax.jcr.version.Version, boolean)
*/
@Override
public void restore(Version version, boolean removeExisting) throws RepositoryException {
if (!isNodeType(NodeType.MIX_VERSIONABLE)) {
throw new UnsupportedRepositoryOperationException("Node is not mix:versionable");
}
String id = version.getContainingHistory().getVersionableIdentifier();
if (getIdentifier().equals(id)) {
getVersionManager().restore(version, removeExisting);
} else {
throw new VersionException("Version does not belong to the " +
"VersionHistory of this node.");
}
}
/**
* @see javax.jcr.Node#restore(Version, String, boolean)
*/
@Override
public void restore(Version version, String relPath, boolean removeExisting) throws RepositoryException {
// additional checks are performed with subsequent calls.
if (hasNode(relPath)) {
// node at 'relPath' exists -> call restore on the target Node
getNode(relPath).restore(version, removeExisting);
} else {
String absPath = PathUtils.concat(getPath(), relPath);
getVersionManager().restore(absPath, version, removeExisting);
}
}
/**
* @see javax.jcr.Node#restoreByLabel(String, boolean)
*/
@Override
public void restoreByLabel(String versionLabel, boolean removeExisting) throws RepositoryException {
getVersionManager().restoreByLabel(getPath(), versionLabel, removeExisting);
}
/**
* @see javax.jcr.Node#getVersionHistory()
*/
@Override
@Nonnull
public VersionHistory getVersionHistory() throws RepositoryException {
return getVersionManager().getVersionHistory(getPath());
}
/**
* @see javax.jcr.Node#getBaseVersion()
*/
@Override
@Nonnull
public Version getBaseVersion() throws RepositoryException {
return getVersionManager().getBaseVersion(getPath());
}
private LockManager getLockManager() throws RepositoryException {
return getSession().getWorkspace().getLockManager();
}
@Override
public boolean isLocked() throws RepositoryException {
return getLockManager().isLocked(getPath());
}
@Override
public boolean holdsLock() throws RepositoryException {
return getLockManager().holdsLock(getPath());
}
@Override @Nonnull
public Lock getLock() throws RepositoryException {
return getLockManager().getLock(getPath());
}
@Override @Nonnull
public Lock lock(boolean isDeep, boolean isSessionScoped)
throws RepositoryException {
return getLockManager().lock(
getPath(), isDeep, isSessionScoped, Long.MAX_VALUE, null);
}
@Override
public void unlock() throws RepositoryException {
getLockManager().unlock(getPath());
}
@Override @Nonnull
public NodeIterator getSharedSet() {
return new NodeIteratorAdapter(singleton(this));
}
@Override
public void removeSharedSet() throws RepositoryException {
sessionDelegate.performVoid(new ItemWriteOperation<Void>("removeSharedSet") {
@Override
public void performVoid() throws RepositoryException {
// TODO: avoid nested calls
NodeIterator sharedSet = getSharedSet();
while (sharedSet.hasNext()) {
sharedSet.nextNode().removeShare();
}
}
});
}
@Override
public void removeShare() throws RepositoryException {
remove();
}
/**
* @see javax.jcr.Node#followLifecycleTransition(String)
*/
@Override
public void followLifecycleTransition(String transition) throws RepositoryException {
throw new UnsupportedRepositoryOperationException("Lifecycle Management is not supported");
}
/**
* @see javax.jcr.Node#getAllowedLifecycleTransistions()
*/
@Override
@Nonnull
public String[] getAllowedLifecycleTransistions() throws RepositoryException {
throw new UnsupportedRepositoryOperationException("Lifecycle Management is not supported");
}
//------------------------------------------------------------< internal >---
@CheckForNull
private String getPrimaryTypeName(@Nonnull Tree tree) {
String primaryTypeName = null;
if (tree.hasProperty(JcrConstants.JCR_PRIMARYTYPE)) {
primaryTypeName = TreeUtil.getPrimaryTypeName(tree);
} else if (tree.getStatus() != Status.NEW) {
// OAK-2441: for backwards compatibility with Jackrabbit 2.x try to
// read the primary type from the underlying node state.
primaryTypeName = TreeUtil.getPrimaryTypeName(RootFactory.createReadOnlyRoot(sessionDelegate.getRoot()).getTree(tree.getPath()));
}
return primaryTypeName;
}
@Nonnull
private Iterator<String> getMixinTypeNames(@Nonnull Tree tree) throws RepositoryException {
Iterator<String> mixinNames = Iterators.emptyIterator();
if (tree.hasProperty(JcrConstants.JCR_MIXINTYPES) || canReadProperty(tree, JcrConstants.JCR_MIXINTYPES)) {
mixinNames = TreeUtil.getNames(tree, JcrConstants.JCR_MIXINTYPES).iterator();
} else if (tree.getStatus() != Status.NEW) {
// OAK-2441: for backwards compatibility with Jackrabbit 2.x try to
// read the primary type from the underlying node state.
mixinNames = TreeUtil.getNames(
RootFactory.createReadOnlyRoot(sessionDelegate.getRoot()).getTree(tree.getPath()),
JcrConstants.JCR_MIXINTYPES).iterator();
}
return mixinNames;
}
private boolean canReadProperty(@Nonnull Tree tree, @Nonnull String propName) throws RepositoryException {
String propPath = PathUtils.concat(tree.getPath(), propName);
String permName = Permissions.PERMISSION_NAMES.get(Permissions.READ_PROPERTY);
return sessionContext.getAccessManager().hasPermissions(propPath, permName);
}
private EffectiveNodeType getEffectiveNodeType() throws RepositoryException {
return getNodeTypeManager().getEffectiveNodeType(dlg.getTree());
}
private Iterator<Node> nodeIterator(Iterator<NodeDelegate> childNodes) {
return sessionDelegate.sync(transform(
childNodes,
new Function<NodeDelegate, Node>() {
@Override
public Node apply(NodeDelegate nodeDelegate) {
return new NodeImpl<NodeDelegate>(nodeDelegate, sessionContext);
}
}));
}
private Iterator<Property> propertyIterator(Iterator<PropertyDelegate> properties) {
return sessionDelegate.sync(transform(
properties,
new Function<PropertyDelegate, Property>() {
@Override
public Property apply(PropertyDelegate propertyDelegate) {
return new PropertyImpl(propertyDelegate, sessionContext);
}
}));
}
private void checkValidWorkspace(String workspaceName)
throws RepositoryException {
String[] workspaceNames =
getSession().getWorkspace().getAccessibleWorkspaceNames();
if (!asList(workspaceNames).contains(workspaceName)) {
throw new NoSuchWorkspaceException(
"Workspace " + workspaceName + " does not exist");
}
}
private void internalSetPrimaryType(final String nodeTypeName) throws RepositoryException {
// TODO: figure out the right place for this check
NodeType nt = getNodeTypeManager().getNodeType(nodeTypeName); // throws on not found
if (nt.isAbstract() || nt.isMixin()) {
throw new ConstraintViolationException();
}
// TODO: END
PropertyState state = PropertyStates.createProperty(
JCR_PRIMARYTYPE, getOakName(nodeTypeName), NAME);
dlg.setProperty(state, true, true);
dlg.setOrderableChildren(nt.hasOrderableChildNodes());
}
private Property internalSetProperty(
final String jcrName, final Value value, final boolean exactTypeMatch)
throws RepositoryException {
final String oakName = getOakPathOrThrow(checkNotNull(jcrName));
final PropertyState state = createSingleState(
oakName, value, Type.fromTag(value.getType(), false));
return perform(new ItemWriteOperation<Property>("internalSetProperty") {
@Override
public void checkPreconditions() throws RepositoryException {
super.checkPreconditions();
if (!isCheckedOut()) {
throw new VersionException(
"Cannot set property. Node is checked in.");
}
}
@Nonnull
@Override
public Property perform() throws RepositoryException {
return new PropertyImpl(
dlg.setProperty(state, exactTypeMatch, false),
sessionContext);
}
@Override
public String toString() {
return String.format("Setting property [%s/%s]", dlg.getPath(), jcrName);
}
});
}
private Property internalSetProperty(
final String jcrName, final Value[] values,
final int type, final boolean exactTypeMatch)
throws RepositoryException {
final String oakName = getOakPathOrThrow(checkNotNull(jcrName));
final PropertyState state = createMultiState(
oakName, compact(values), Type.fromTag(type, true));
if (values.length > MV_PROPERTY_WARN_THRESHOLD) {
LOG.warn("Large multi valued property [{}/{}] detected ({} values).",dlg.getPath(), jcrName, values.length);
}
return perform(new ItemWriteOperation<Property>("internalSetProperty") {
@Override
public void checkPreconditions() throws RepositoryException {
super.checkPreconditions();
if (!isCheckedOut()) {
throw new VersionException(
"Cannot set property. Node is checked in.");
}
}
@Nonnull
@Override
public Property perform() throws RepositoryException {
return new PropertyImpl(
dlg.setProperty(state, exactTypeMatch, false),
sessionContext);
}
@Override
public String toString() {
return String.format("Setting property [%s/%s]", dlg.getPath(), jcrName);
}
});
}
/**
* Removes all {@code null} values from the given array.
*
* @param values value array
* @return value list without {@code null} entries
*/
private static List<Value> compact(Value[] values) {
List<Value> list = Lists.newArrayListWithCapacity(values.length);
for (Value value : values) {
if (value != null) {
list.add(value);
}
}
return list;
}
private Property internalRemoveProperty(final String jcrName)
throws RepositoryException {
final String oakName = getOakName(checkNotNull(jcrName));
return perform(new ItemWriteOperation<Property>("internalRemoveProperty") {
@Override
public void checkPreconditions() throws RepositoryException {
super.checkPreconditions();
if (!isCheckedOut()) {
throw new VersionException(
"Cannot remove property. Node is checked in.");
}
}
@Nonnull
@Override
public Property perform() throws RepositoryException {
PropertyDelegate property = dlg.getPropertyOrNull(oakName);
if (property != null) {
property.remove();
} else {
// Return an instance which throws on access; see OAK-395
property = dlg.getProperty(oakName);
}
return new PropertyImpl(property, sessionContext);
}
@Override
public String toString() {
return String.format("Removing property [%s]", jcrName);
}
});
}
//-----------------------------------------------------< JackrabbitNode >---
/**
* Simplified implementation of {@link JackrabbitNode#rename(String)}. In
* contrast to the implementation in Jackrabbit 2.x which was operating on
* the NodeState level directly, this implementation does a move plus
* subsequent reorder on the JCR API due to a missing support for renaming
* on the OAK API.
*
* Note, that this also has an impact on how permissions are enforced: In
* Jackrabbit 2.x the rename just required permission to modify the child
* collection on the parent, whereas a move did the full permission check.
* With this simplified implementation that (somewhat inconsistent) difference
* has been removed.
*
* @param newName The new name of this node.
* @throws RepositoryException If an error occurs.
*/
@Override
public void rename(final String newName) throws RepositoryException {
if (dlg.isRoot()) {
throw new RepositoryException("Cannot rename the root node");
}
final String name = getName();
if (newName.equals(name)) {
// nothing to do
return;
}
sessionDelegate.performVoid(new ItemWriteOperation<Void>("rename") {
@Override
public void performVoid() throws RepositoryException {
Node parent = getParent();
String beforeName = null;
if (isOrderable(parent)) {
// remember position amongst siblings
NodeIterator nit = parent.getNodes();
while (nit.hasNext()) {
Node child = nit.nextNode();
if (name.equals(child.getName())) {
if (nit.hasNext()) {
beforeName = nit.nextNode().getName();
}
break;
}
}
}
String srcPath = getPath();
String destPath = '/' + newName;
String parentPath = parent.getPath();
if (!"/".equals(parentPath)) {
destPath = parentPath + destPath;
}
sessionContext.getSession().move(srcPath, destPath);
if (beforeName != null) {
// restore position within siblings
parent.orderBefore(newName, beforeName);
}
}
});
}
private static boolean isOrderable(Node node) throws RepositoryException {
if (node.getPrimaryNodeType().hasOrderableChildNodes()) {
return true;
}
NodeType[] types = node.getMixinNodeTypes();
for (NodeType type : types) {
if (type.hasOrderableChildNodes()) {
return true;
}
}
return false;
}
/**
* Simplified implementation of the {@link org.apache.jackrabbit.api.JackrabbitNode#setMixins(String[])}
* method that adds all mixin types that are not yet present on this node
* and removes all mixins that are no longer contained in the specified
* array. Note, that this implementation will not work exactly like the
* variant in Jackrabbit 2.x which first created the effective node type
* and adjusted the set of child items accordingly.
*
* @param mixinNames
* @throws RepositoryException
*/
@Override
public void setMixins(String[] mixinNames) throws RepositoryException {
final Set<String> oakTypeNames = newLinkedHashSet();
for (String mixinName : mixinNames) {
oakTypeNames.add(getOakName(checkNotNull(mixinName)));
}
sessionDelegate.performVoid(new ItemWriteOperation<Void>("setMixins") {
@Override
public void checkPreconditions() throws RepositoryException {
super.checkPreconditions();
if (!isCheckedOut()) {
throw new VersionException("Cannot set mixin types. Node is checked in.");
}
// check for NODE_TYPE_MANAGEMENT permission here as we cannot
// distinguish between a combination of removeMixin and addMixin
// and Node#remove plus subsequent addNode when it comes to
// autocreated properties like jcr:create, jcr:uuid and so forth.
PropertyDelegate mixinProp = dlg.getPropertyOrNull(JCR_MIXINTYPES);
if (mixinProp != null) {
sessionContext.getAccessManager().checkPermissions(dlg.getTree(), mixinProp.getPropertyState(), Permissions.NODE_TYPE_MANAGEMENT);
}
}
@Override
public void performVoid() throws RepositoryException {
dlg.setMixins(oakTypeNames);
}
});
}
private static class PropertyIteratorDelegate {
private final NodeDelegate node;
private final Predicate<PropertyDelegate> predicate;
PropertyIteratorDelegate(NodeDelegate node, Predicate<PropertyDelegate> predicate) {
this.node = node;
this.predicate = predicate;
}
public Iterator<PropertyDelegate> iterator() throws InvalidItemStateException {
return Iterators.filter(node.getProperties(), predicate);
}
public long getSize() {
try {
return Iterators.size(iterator());
} catch (InvalidItemStateException e) {
throw new IllegalStateException(
"This iterator is no longer valid", e);
}
}
}
}
| OAK-4071 - Include node path in VersionException
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1732898 13f79535-47bb-0310-9956-ffa450edef68
| oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/session/NodeImpl.java | OAK-4071 - Include node path in VersionException |
|
Java | apache-2.0 | e0fe31e4baf5766a1ce4e0f6810edb7631cba063 | 0 | aarpon/obit_annotation_tool | package ch.ethz.scu.obit.bdfacsdivafcs.readers;
import java.io.*;
import java.nio.*;
import java.util.*;
import ch.ethz.scu.obit.readers.AbstractReader;
/**
* FCSReader parses "Data File Standard for Flow Cytometry, Version FCS3.0 or
* FCS3.1" files.
*
* Parsing is currently not complete: - additional byte buffer manipulation
* needed for datatype "A" (ASCII) - only one DATA segment per file is processed
* (since apparently no vendor makes use of the possibility to store more than
* experiment per file) - ANALYSIS segment is not parsed - OTHER text segment is
* not parsed
*
* @author Aaron Ponti
*/
public final class FCSReader extends AbstractReader {
/* Private instance variables */
private File filename;
private boolean enableDataParsing;
private RandomAccessFile in = null;
private String fcsVersion = "";
private int TEXTbegin = 0;
private int TEXTend = 0;
private int DATAbegin = 0;
private int DATAend = 0;
private int ANALYSISbegin = 0;
private int ANALYSISend = 0;
private int OTHERbegin = 0;
private char DELIMITER;
private boolean isFileParsed = false;
private boolean isDataLoaded = false;
private int[] bytesPerParameter;
private float[] parameterDecades;
private float[] parameterLogs;
private float[] parameterLogZeros;
private float[] parameterRanges;
private float[] parameterGains;
/* Public instance variables */
/**
* String-string map of parametersAttr attributes
*/
public Map<String, String> parametersAttr = new HashMap<String, String>();
/**
* String-to-string map of key-value pairs for the standard FCS 3.0/3.1
* keywords
*/
public Map<String, String> TEXTMapStandard = new LinkedHashMap<String, String>();
/**
* String-to-string map of key-value pairs for custom FCS 3.0/3.1 keywords
*/
public Map<String, String> TEXTMapCustom = new LinkedHashMap<String, String>();
/**
* DATA segment (linear array of bytes)
*/
public ByteBuffer DATA = null;
/**
* Constructor
*
* @param filename Name with full path of the file to be opened.
* @param parseData True if the data should be read, false if only metadata
* should be parsed.
*/
public FCSReader(File filename, boolean parseData) {
this.filename = filename;
this.enableDataParsing = parseData;
}
/**
* Destructor.
*/
public void finalize() throws Throwable {
// Make sure the file is closed
if (in != null) {
try {
in.close();
} catch (IOException e) {
System.err.println("Could not close FCS file on garbage collection!");
}
}
// Call the parent finalize()
super.finalize();
}
/**
* Return information regarding the file format.
*
* @return descriptive String for the Processor.
*/
public String info() {
return "Data File Standard for Flow Cytometry, Version FCS3.0 and FCS3.1.";
}
/**
* Return the FCS file version
*
* @return a String containing the file version (FCS3.0 or FCS3.1).
*/
public String getFCSVersion() {
return fcsVersion;
}
/**
* Parses the file to extract data and metadata.
*
* @return true if parsing was successful, false otherwise.
* @throws IOException if parsing the FCS file failed.
*/
@Override
public boolean parse() throws IOException {
try {
// We use a RandomAccessFile to be able to seek around freely
in = new RandomAccessFile(filename, "r");
// Read the HEADER
parseHeader();
// Read the main TEXT
parseText();
// Process the parameters
processParameters();
if (enableDataParsing) {
// Read the DATA (events)
parseData();
// Read the ANALYSIS (if present)
parseAnalysis();
}
// Read the OTHER text segment (if present)
parseOther();
} catch (IOException e) {
errorMessage = "Could not open file.";
System.err.println(errorMessage);
} finally {
// Always close the stream
if (in != null) {
try {
in.close();
} catch (Exception e) {
// Silent
}
}
}
// Reset the error message
errorMessage = "";
// Store and return state
isFileParsed = (in != null);
return isFileParsed;
}
/**
* Return the file name of associated to the FCSReader.
*
* @return String containing the file name associated to the FCSReader.
*/
public String toString() {
return filename.getName();
}
/**
* Return a simplified class name to use in XML.
*
* @return simplified class name.
*/
@Override
public String getType() {
return "fcs";
}
/**
* Returns the stored File object (pointing to the FCS file being processed)
*
* @return File object pointing to the FCS file
*/
public File getFile() {
return filename;
}
/**
* Return the parsed FCSReader metadata information.
*
* @return String containing the metadata of the FCSReader.
*/
public String metadataDump() {
if (!isFileParsed) {
return "File could not be parsed.";
}
String str = "Valid " + fcsVersion + " file with TEXT: " + TEXTbegin + " - " + TEXTend + ", DATA: " + DATAbegin
+ " - " + DATAend + ", ANALYSIS: " + ANALYSISbegin + " - " + ANALYSISend + ", OTHER: " + OTHERbegin
+ ".\n" + "DELIMITER: (char) " + (int) DELIMITER + "\n\n";
// Output the list of standard key-value pairs
Set<String> keySet = TEXTMapStandard.keySet();
str += "Standard TEXT keyword-value pairs (" + keySet.size() + "):\n\n";
for (String key : keySet) {
str += (key + ": " + TEXTMapStandard.get(key) + "\n");
}
// Output the list of custom key-value pairs
keySet = TEXTMapCustom.keySet();
str += "\n\n";
str += "Custom TEXT keyword-value pairs (" + keySet.size() + "):\n\n";
for (String key : keySet) {
str += (key + ": " + TEXTMapCustom.get(key) + "\n");
}
// Output the list of parameters (and their attributes)
str += "\n\n";
str += "Parameters and their attributes:\n\n";
for (String key : parametersAttr.keySet()) {
str += (key + ": " + parametersAttr.get(key) + "\n");
}
return str;
}
/**
* Returns all parameter names.
*
* @return The String array of parameter names.
*/
public ArrayList<String> getParameterNames() {
ArrayList<String> paramNames = new ArrayList<String>(numParameters());
for (int i = 1; i <= numParameters(); i++) {
paramNames.add(parametersAttr.get("P" + i + "N"));
}
return paramNames;
}
/**
* Returns all standard FCS 3.0/3.1 keywords as a String - String map
*
* @return The String - String Map of all standard FCS 3.0/3.1 keywords
*/
public Map<String, String> getStandardKeywords() {
return TEXTMapStandard;
}
/**
* Return the value associated to a standard FCS 3.0/3.1 keyword or empty
*
* @param key
* One of the standard keywords (staring with "$")
* @return The value associated with the passed keyword or empty String if
* not found
*/
public String getStandardKeyword(String key) {
if (TEXTMapStandard.containsKey(key)) {
return TEXTMapStandard.get(key);
} else {
return "";
}
}
/**
* Returns all custom, non FCS 3.0/3.1-compliant keywords as a String -
* String map
*
* @return The String - String Map of all custom, non FCS 3.0/3.1-compliant
* keywords
*/
public Map<String, String> getCustomKeywords() {
return TEXTMapStandard;
}
/**
* Return the value associated with a custom, non FCS 3.0/3.1-compliant
* keyword or empty
*
* @param key
* A custom keywords (without $ at the beginning)
* @return The value associated with the passed keyword or empty String if
* not found
*/
public String getCustomKeyword(String key) {
if (TEXTMapCustom.containsKey(key)) {
return TEXTMapCustom.get(key);
} else {
return "";
}
}
/**
* Returns all keywords as a String - String map (FCS 3.0/3.1-compliant and
* custom)
*
* @return The String - String Map of all keywords
*/
public Map<String, String> getAllKeywords() {
Map<String, String> allMap = new HashMap<String, String>();
allMap.putAll(TEXTMapStandard);
allMap.putAll(TEXTMapCustom);
return allMap;
}
/**
* Return the number of events in the dataset.
*
* @return number of events.
*/
public int numEvents() {
int numEvents = 0;
if (TEXTMapStandard.containsKey("$TOT")) {
numEvents = Integer.parseInt(TEXTMapStandard.get("$TOT"));
}
return numEvents;
}
/**
* Return the number of parameters in the dataset.
*
* @return number of parameters.
*/
public int numParameters() {
int numParameters = 0;
if (TEXTMapStandard.containsKey("$PAR")) {
numParameters = Integer.parseInt(TEXTMapStandard.get("$PAR"));
}
return numParameters;
}
/**
* Return subset of measurements with optional stride for parameter with
* given column index in double precision. The measurements are returned
* as is without any scaling.
* @param columnIndex Index of the measurement column.
* @param nValues number of values to be read. Set to 0 to read them all.
* @param sampled True if the nValues must be sampled with constant stride
* throughout the total number of rows, false if the first
* nValues rows must simply be returned.
* @return array of measurements.
* @throws IOException If something unexpected with the datatype is found.
*/
public double[] getRawDataPerColumnIndex(int columnIndex, int nValues,
boolean sampled) throws IOException {
// Make sure that he data was loaded
if (!isDataLoaded) {
return new double[0];
}
// Datatype
String datatype = datatype();
// If the datatype is INTEGER, we currently only support 16 bit
if (datatype == "I" && bytesPerParameter[columnIndex] != 2) {
throw new IOException("Integer data type is expected to be"
+ "unsigned 16 bit!");
}
// Some constants
int nParams = numParameters();
int nEvents = numEvents();
int step;
// If all values must be read, the step is 1.
if (nValues == 0 || nValues > nEvents) {
nValues = nEvents;
step = 1;
} else {
if (sampled) {
step = (int) (((float) nEvents) / nValues);
if (step == 0) {
step = 1;
}
} else {
step = 1;
}
}
// Pre-calculate the positions to extract
int[] positions = new int[nValues];
int c = 0; // Global measurement counter
int cBytes = 0; // Global measurement counter in bytes
int n = 0; // Row counter
int t = 0; // Accepted value counter
while (t < nValues) {
// If we are at the right column, we store it
if (c % nParams == columnIndex) {
if (n % step == 0) {
// We use the correct data width per column
positions[t] = cBytes;
t++;
}
n++;
}
cBytes += bytesPerParameter[c % nParams];
c++;
}
// Allocate space for the events
double[] m = new double[nValues];
// Go through the buffer and return the values at the pre-calculate
// positions (i.e. for the requested column with given stride and
// requested total number)
DATA.rewind();
for (int i = 0; i < positions.length; i++) {
// Jump to position
DATA.position(positions[i]);
// Get the value, convert it to double
double tmp;
if (datatype.equals("F")) {
tmp = (double) DATA.getFloat();
} else if (datatype.equals("I")) {
// The integer format is 2 bytes only and unsigned!
tmp = (double) ((short) (DATA.getShort()) & 0xffff);
} else if (datatype.equals("D")) {
tmp = (double) DATA.getDouble();
} else if (datatype.equals("A")) {
tmp = (double) DATA.get();
} else {
throw new IOException("Unknown data type!");
}
// Store the value
m[i] = tmp;
}
// Return the array
return m;
}
/**
* Return subset of measurements with optional stride for parameter with
* given column index in double precision. The measurements are scaled as
* instructed in the FCS file (parameters 'PnR', 'PnE', 'PnG').
* @param columnIndex Index of the measurement column.
* @param nValues number of values to be read. Set to 0 to read them all.
* @param sampled True if the nValues must be sampled with constant stride
* throughout the total number of rows, false if the first
* nValues rows must simply be returned.
* @return array of measurements.
* @throws IOException If something unexpected with the datatype is found.
*/
public double[] getDataPerColumnIndex(int columnIndex, int nValues,
boolean sampled) throws IOException {
// Make sure that he data was loaded
if (!isDataLoaded) {
return new double[0];
}
// Get the unscaled parameters
double[] m = getRawDataPerColumnIndex(columnIndex, nValues, sampled);
// Allocate space for the scaled parameters
double[] n = new double[m.length];
// Apply transformations
double decade = (double) parameterDecades[columnIndex];
double range = (double) parameterRanges[columnIndex];
double log = (double) parameterLogs[columnIndex] ;
double logz = (double) parameterLogZeros[columnIndex];
double gain = (double) parameterGains[columnIndex];
for (int i = 0; i < m.length; i++) {
if (gain != 1.0) {
n[i] = m[i] / gain;
} else if (log != 0.0) {
n[i] = logz * Math.pow(10, m[i] / range * decade);
} else {
// No transformation
n[i] = m[i];
}
}
// Return the transformed data
return n;
}
/**
* Export the full data (not scaled!) to a CSV file.
*
* @param csvFile Full path of the CSV file
* @return true if the CSV file could be saved, false otherwise.
* @throws IOException If something unexpected with the datatype is found.
*/
public boolean exportDataToCSV(File csvFile) throws IOException {
// Make sure that he data was loaded
if (!isDataLoaded) {
return false;
}
// Datatype
String datatype = datatype();
// If the datatype is INTEGER, we currently only support 16 bit
for (int i = 0; i < bytesPerParameter.hashCode(); i++) {
if (datatype == "I" && bytesPerParameter[i] != 2) {
throw new IOException("Integer data type is expected to be"
+ "unsigned 16 bit!");
}
}
FileWriter fw;
try {
fw = new FileWriter(csvFile);
} catch (IOException e) {
return false;
}
BufferedWriter writer = new BufferedWriter(fw);
// Write the parameters names as header line
for (int i = 1; i <= numParameters(); i++) {
try {
writer.write(parametersAttr.get("P" + i + "N") + ",");
} catch (IOException e) {
// Close writer
try {
writer.close();
} catch (IOException e1) {
return false;
}
return false;
}
}
// Next line
try {
writer.write("\n");
} catch (IOException e) {
// Close writer
try {
writer.close();
} catch (IOException e1) {
return false;
}
return false;
}
// Store some constants
int numParameters = numParameters();
// Make sure to rewind the buffer
DATA.rewind();
// Write the values
int nParameter = 0;
while (DATA.hasRemaining()) {
try {
if (datatype.equals("F")) {
writer.write((float) DATA.getFloat() + ",");
} else if (datatype.equals("I")) {
// The integer format is 2 bytes only and unsigned!
writer.write(((short) (DATA.getShort()) & 0xffff) + ",");
} else if (datatype.equals("D")) {
writer.write((double) DATA.getDouble() + ",");
} else if (datatype.equals("A")) {
// Get a single byte
writer.write((char) DATA.get() + ",");
} else {
throw new IOException("Unknown data type!");
}
// New line
nParameter++;
if (nParameter == numParameters) {
writer.write("\n");
nParameter = 0;
}
} catch (IOException e) {
// Close writer
try {
writer.close();
} catch (IOException e1) {
return false;
}
return false;
}
}
// Close writer
try {
writer.close();
} catch (IOException e) {
return false;
}
return true;
}
/**
* Parse the header.
*
* @return true if the file header could be parsed successfully, false
* otherwise.
* @throws IOException
*/
private boolean parseHeader() throws IOException {
// Read and check the version
in.seek(0);
byte[] VERSION = new byte[6];
in.read(VERSION);
fcsVersion = new String(VERSION);
if (!(fcsVersion.equals("FCS3.0") || fcsVersion.equals("FCS3.1"))) {
errorMessage = filename + " is not a valid FCS version 3.0 or 3.1 file!";
System.out.println(errorMessage);
return false;
}
// We will use an 8-byte array several times in the following
byte[] eightByteArray = new byte[8];
// ASCII-encoded offset to first byte of TEXT segment (bytes 10 - 17)
in.seek(10);
in.read(eightByteArray);
TEXTbegin = Integer.parseInt((new String(eightByteArray)).trim());
// ASCII-encoded offset to last byte of TEXT segment (bytes 18 - 25)
in.seek(18);
in.read(eightByteArray);
TEXTend = Integer.parseInt((new String(eightByteArray)).trim());
// ASCII-encoded offset to first byte of DATA segment (bytes 26 - 33)
// This can be a valid offset, or 0: if it is 0, it means that the
// segment
// is larger than 99,999,999 bytes
in.seek(26);
in.read(eightByteArray);
DATAbegin = Integer.parseInt((new String(eightByteArray)).trim());
// ASCII-encoded offset to last byte of DATA segment (bytes 34 - 41)
// This can be a valid offset, or 0: if it is 0, it means that the
// segment
// is larger than 99,999,999 bytes
in.seek(34);
in.read(eightByteArray);
DATAend = Integer.parseInt((new String(eightByteArray)).trim());
// ASCII-encoded offset to first byte of ANALYSIS segment (bytes 42 -
// 49)
// This can be a valid offset, 0, or even blank. If 0, $BEGINANALYSIS
// must
// be checked
in.seek(42);
in.read(eightByteArray);
String tmp = (new String(eightByteArray)).trim();
if (tmp.length() == 0) {
ANALYSISbegin = 0;
} else {
ANALYSISbegin = Integer.parseInt(tmp);
}
// ASCII-encoded offset to last byte of ANALYSIS segment (bytes 50 - 57)
// This can be a valid offset, 0, or even blank. If 0, $ENDANALYSIS must
// be checked
in.seek(50);
tmp = (new String(eightByteArray)).trim();
if (tmp.length() == 0) {
ANALYSISend = 0;
} else {
ANALYSISend = Integer.parseInt(tmp);
}
// ASCII-encoded offset to user defined OTHER segments (bytes 58 -
// beginning of next segment)
in.seek(58);
tmp = (new String(eightByteArray)).trim();
if (tmp.length() == 0) {
OTHERbegin = 0;
} else {
OTHERbegin = Integer.parseInt(tmp);
}
// The TEXT and DATA offsets can theoretically be swapped in the header
// segment
swapOffsetsIfNeeded();
return true;
}
/**
* Parse the TEXT segment.
*
* @return true if parsing was successful, false otherwise.
* @throws IOException
*/
private boolean parseText() throws IOException {
// Read the TEXT segment
in.seek(TEXTbegin);
int LEN = (TEXTend - TEXTbegin + 1); // TEXT cannot be longer than
// 99,999,999 bytes
byte[] bText = new byte[LEN];
in.read(bText);
// Get the delimiter character
DELIMITER = (char) bText[0];
// Get the keyword-value pairs and store them in the hash map.
// All values are UTF-8-encoded, the keywords are strictly ASCII
// (but can be parsed as UTF-8).
storeKeyValuePairs(new String(bText, "UTF-8"));
return true;
}
/**
* Parse the DATA (events) segment.
*
* @return true if the parsing was successful (or no data was present),
* false otherwise.
* @throws IOException
* TODO Add support for multiple DATA segments.
*/
private boolean parseData() throws IOException {
// Seek to the DATA segment
long dataOffset;
try {
dataOffset = Long.parseLong(TEXTMapStandard.get("$BEGINDATA").trim());
} catch (NumberFormatException e) {
errorMessage = "Invalid offset for the DATA segment! " + "This is a bug! Please report it.";
System.out.println(errorMessage);
return false;
}
if (dataOffset == 0) {
System.out.println("No DATA present.");
return true;
}
// Seek to the beginning of the data offset
in.seek(dataOffset);
// Read and store the data
return readDataBlock();
}
/**
* Parse the ANALYSIS segment.
*
* @return true if parsing was successful, false otherwise.
* @throws IOException
* TODO Implement
*/
private boolean parseAnalysis() throws IOException {
return true;
}
/**
* Parse the OTHER segment.
*
* @return true if parsing was successful, false otherwise.
* @throws IOException
* TODO Implement
*/
private boolean parseOther() throws IOException {
return true;
}
/**
* The TEXT and DATA offsets can theoretically be swapped in the header
* segment. We make sure that TEXT is assigned the lower and DATA the higher
* offset.
*/
private void swapOffsetsIfNeeded() {
// If the data block is larger than 99,999,999 bytes,
// DATAbegin will be 0.
// In this case we do NOT want to swap!
if (DATAbegin == 0) {
return;
}
if (TEXTbegin > DATAbegin) {
int tmp;
tmp = TEXTbegin;
TEXTbegin = DATAbegin;
DATAbegin = tmp;
tmp = TEXTend;
TEXTend = DATAend;
DATAend = tmp;
}
}
/**
* Extracts and returns the value in a segment for a given key.
*
* @param segment
* String containing the full segment (e.g. TEXT).
*/
private void storeKeyValuePairs(String segment) {
assert(segment.charAt(0) == DELIMITER);
assert(segment.charAt(segment.length() - 1) == DELIMITER);
// Process all
int beginIndex = 0;
int interIndex = 0;
int endIndex = 0;
// Parse the full segment
while (true) {
interIndex = segment.indexOf(DELIMITER, beginIndex + 1);
if (interIndex == -1) {
break;
}
endIndex = segment.indexOf(DELIMITER, interIndex + 1);
String key = segment.substring(beginIndex + 1, interIndex).trim();
String value = segment.substring(interIndex + 1, endIndex).trim();
// If the key starts with a $ sign, we found a standard FCS keyword
// and we store it in the TEXTMapStandard map; otherwise, we have a
// custom keyword we store it in the TEXTMapCustom map
if (key.charAt(0) == '$') {
TEXTMapStandard.put(key, value);
} else {
TEXTMapCustom.put(key, value);
}
beginIndex = endIndex;
}
}
/**
* Process the extracted parameters from the standard TEXT map.
*
* @return true if there were parameters and they could be processed
* successfully, false otherwise.
*/
private boolean processParameters() {
// Number of events
int numEvents = numEvents();
// Number of parameters
int numParameters = numParameters();
// Store the number of events
parametersAttr.put("numEvents", Integer.toString(numEvents));
// Store the number of parameters
parametersAttr.put("numParameters", Integer.toString(numParameters));
// If there are no parameters, we leave.
if (numParameters == 0) {
return false;
}
// We store the number of bytes that are used to store each of the
// parameter values
bytesPerParameter = new int[numParameters];
// We also store gain and transformation details
parameterDecades = new float[numParameters];
parameterLogs = new float[numParameters];
parameterLogZeros = new float[numParameters];
parameterRanges = new float[numParameters];
parameterGains = new float[numParameters];
// Keep track of the datatype
String datatype = datatype();
// Now go over the parameters and extract all info.
// Mind that parameter count starts at 1.
String key = "";
for (int i = 1; i <= numParameters; i++) {
// Name
key = "P" + i + "N";
String name = TEXTMapStandard.get("$" + key);
if (name == null) {
name = "<not set>";
}
parametersAttr.put(key, name);
// Label
key = "P" + i + "S";
String label = TEXTMapStandard.get("$" + key);
if (label == null) {
label = "";
}
parametersAttr.put(key, label);
// Range
key = "P" + i + "R";
String range = TEXTMapStandard.get("$" + key);
if (range == null) {
range = "262144";
}
parametersAttr.put(key, range);
parameterRanges[i - 1] = Integer.parseInt(range);
// Bits
key = "P" + i + "B";
String bits = TEXTMapStandard.get("$" + key);
if (bits == null) {
if (datatype == "D") {
bits = "64";
} else if (datatype == "F") {
bits = "32";
} else if (datatype == "I") {
bits = "16";
} else if (datatype == "A") {
bits = "8";
} else {
bits = "32";
}
}
parametersAttr.put(key, bits);
// Store the value for later use
bytesPerParameter[i - 1] = Integer.parseInt(bits) / 8;
// Linear or logarithmic amplifiers?
float log = 0.0f;
float log_zero = 0.0f;
key = "P" + i + "E";
String decade = TEXTMapStandard.get("$" + key);
float f_decade = 0.0f;
if (decade != null) {
String decadeParts[] = decade.split(",");
f_decade = Float.parseFloat(decadeParts[0]);
float f_value = Float.parseFloat(decadeParts[1]);
if (f_decade == 0.0) {
// Amplification is linear or undefined
log = 0.0f;
log_zero = 0.0f;
} else {
log = 1.0f;
if (f_value == 0.0) {
log_zero = 1.0f;
} else {
log_zero = f_value;
}
}
}
parametersAttr.put(key + "_LOG", Float.toString(log));
parametersAttr.put(key + "_LOGZERO", Float.toString(log_zero));
parameterDecades[i - 1] = f_decade;
parameterLogs[i - 1] = log;
parameterLogZeros[i - 1] = log_zero;
// Gain
key = "P" + i + "G";
String gain = TEXTMapStandard.get("$" + key);
if (gain == null) {
gain = "1.0";
}
parametersAttr.put(key, gain);
parameterGains[i - 1] = Float.parseFloat(gain);
// Voltage
key = "P" + i + "V";
String voltage = TEXTMapStandard.get("$" + key);
if (voltage == null) {
voltage = "NaN";
}
parametersAttr.put(key, voltage);
// Log or linear
key = "P" + i + "DISPLAY";
String display = TEXTMapCustom.get(key);
if (display == null) {
display = "LIN";
}
parametersAttr.put(key, display);
// If present (for instance in files from the BD Influx
// Cell Sorter), we also store the CHANNELTYPE
key = "P" + i + "CHANNELTYPE";
String channelType = TEXTMapCustom.get(key);
if (channelType != null) {
parametersAttr.put(key, channelType);
}
}
return true;
}
/**
* Return the datatype of the data bytes, one of "I", "F", "D", or "A". I:
* unsigned integer; F: single-precision IEEE floating point; D:
* double-precision IEEE floating point; A: ASCII.
*
* @return datatype of the measurements ("I", "F", "D", "A"), or "N" if not
* defined.
*/
private String datatype() {
String datatype = "N";
if (TEXTMapStandard.containsKey("$DATATYPE")) {
datatype = TEXTMapStandard.get("$DATATYPE");
}
return datatype;
}
/**
* Return the endianity of the data bytes, one of "L", "B", "U". L: little
* endian (1,2,3,4); B: big endian (4,3,2,1); U: unsupported (3,4,1,2); N:
* not defined.
*
* @return endianity of the data bytes ("L", "B", "U"), or "N" if not
* defined.
*/
private String endianity() {
String datatype = "N";
if (TEXTMapStandard.containsKey("$BYTEORD")) {
String byteOrd = TEXTMapStandard.get("$BYTEORD");
if (byteOrd.equals("1,2,3,4")) {
datatype = "L";
} else if (byteOrd.equals("4,3,2,1")) {
datatype = "B";
} else {
datatype = "U";
}
}
return datatype;
}
/**
* Return the data acquisition mode, one of "C", "L", "U". C: One correlated
* multivariate histogram stored as a multidimensional array; L: list mode:
* for each event, the value of each parameter is stored in the order in
* which the parameters are described. U: Uncorrelated univariate
* histograms: there can be more than one univariate histogram per data set.
* N: not defined.
*
* @return acquisition mode of the data ("C", "L", "U"), or "N" if not
* defined.
*/
private String mode() {
if (TEXTMapStandard.containsKey("$MODE")) {
String mode = TEXTMapStandard.get("$MODE");
if (mode.equals("C") || mode.equals("L") || mode.equals("U")) {
return mode;
} else {
return "N";
}
}
return "N";
}
/**
* Reads and stores the data segment
*
* @return true if reading the data segment was successful, false otherwise
* TODO Use the information about the type of data
*/
private boolean readDataBlock() {
// Reset the isDataLoaded flag
isDataLoaded = false;
// To read the data in the correct format we need to know the endianity.
String endianity = endianity();
// Endianity
ByteOrder endian;
if (endianity.equals("L")) {
endian = ByteOrder.LITTLE_ENDIAN;
} else if (endianity.equals("B")) {
endian = ByteOrder.BIG_ENDIAN;
} else {
errorMessage = "Unknown endianity!";
System.err.println(errorMessage);
return false;
}
// Allocate a (byte) buffer to hold the data segment
int size = (DATAend - DATAbegin + 1);
byte[] recordBuffer = new byte[size];
// Create a ByteBuffer wrapped around the byte array that
// reads with the desired endianity
DATA = ByteBuffer.wrap(recordBuffer);
DATA.order(endian);
// Read
try {
in.read(recordBuffer);
} catch (IOException e) {
errorMessage = "Could not read the data segment from file!";
System.out.println(errorMessage);
return false;
}
// Make sure to be at the beginning of the buffer
DATA.rewind();
// Reset error message
errorMessage = "";
// Set the isDataLoaded flag
isDataLoaded = true;
// Return success
return true;
}
}
| AnnotationToolBDFACSDIVAFCS/ch/ethz/scu/obit/bdfacsdivafcs/readers/FCSReader.java | package ch.ethz.scu.obit.bdfacsdivafcs.readers;
import java.io.*;
import java.nio.*;
import java.util.*;
import ch.ethz.scu.obit.readers.AbstractReader;
/**
* FCSReader parses "Data File Standard for Flow Cytometry, Version FCS3.0 or
* FCS3.1" files.
*
* Parsing is currently not complete: - additional byte buffer manipulation
* needed for datatype "A" (ASCII) - only one DATA segment per file is processed
* (since apparently no vendor makes use of the possibility to store more than
* experiment per file) - ANALYSIS segment is not parsed - OTHER text segment is
* not parsed
*
* @author Aaron Ponti
*/
public final class FCSReader extends AbstractReader {
/* Private instance variables */
private File filename;
private boolean enableDataParsing;
private RandomAccessFile in = null;
private String fcsVersion = "";
private int TEXTbegin = 0;
private int TEXTend = 0;
private int DATAbegin = 0;
private int DATAend = 0;
private int ANALYSISbegin = 0;
private int ANALYSISend = 0;
private int OTHERbegin = 0;
private char DELIMITER;
private boolean isFileParsed = false;
private boolean isDataLoaded = false;
private int[] bytesPerParameter;
private float[] parameterDecades;
private float[] parameterLogs;
private float[] parameterLogZeros;
private float[] parameterRanges;
private float[] parameterGains;
/* Public instance variables */
/**
* String-string map of parametersAttr attributes
*/
public Map<String, String> parametersAttr = new HashMap<String, String>();
/**
* String-to-string map of key-value pairs for the standard FCS 3.0/3.1
* keywords
*/
public Map<String, String> TEXTMapStandard = new LinkedHashMap<String, String>();
/**
* String-to-string map of key-value pairs for custom FCS 3.0/3.1 keywords
*/
public Map<String, String> TEXTMapCustom = new LinkedHashMap<String, String>();
/**
* DATA segment (linear array of bytes)
*/
public ByteBuffer DATA = null;
/**
* Constructor
*
* @param filename Name with full path of the file to be opened.
* @param parseData True if the data should be read, false if only metadata
* should be parsed.
*/
public FCSReader(File filename, boolean parseData) {
this.filename = filename;
this.enableDataParsing = parseData;
}
/**
* Destructor.
*/
public void finalize() throws Throwable {
// Make sure the file is closed
if (in != null) {
try {
in.close();
} catch (IOException e) {
System.err.println("Could not close FCS file on garbage collection!");
}
}
// Call the parent finalize()
super.finalize();
}
/**
* Return information regarding the file format.
*
* @return descriptive String for the Processor.
*/
public String info() {
return "Data File Standard for Flow Cytometry, Version FCS3.0 and FCS3.1.";
}
/**
* Return the FCS file version
*
* @return a String containing the file version (FCS3.0 or FCS3.1).
*/
public String getFCSVersion() {
return fcsVersion;
}
/**
* Parses the file to extract data and metadata.
*
* @return true if parsing was successful, false otherwise.
* @throws IOException if parsing the FCS file failed.
*/
@Override
public boolean parse() throws IOException {
try {
// We use a RandomAccessFile to be able to seek around freely
in = new RandomAccessFile(filename, "r");
// Read the HEADER
parseHeader();
// Read the main TEXT
parseText();
// Process the parameters
processParameters();
if (enableDataParsing) {
// Read the DATA (events)
parseData();
// Read the ANALYSIS (if present)
parseAnalysis();
}
// Read the OTHER text segment (if present)
parseOther();
} catch (IOException e) {
errorMessage = "Could not open file.";
System.err.println(errorMessage);
} finally {
// Always close the stream
if (in != null) {
try {
in.close();
} catch (Exception e) {
// Silent
}
}
}
// Reset the error message
errorMessage = "";
// Store and return state
isFileParsed = (in != null);
return isFileParsed;
}
/**
* Return the file name of associated to the FCSReader.
*
* @return String containing the file name associated to the FCSReader.
*/
public String toString() {
return filename.getName();
}
/**
* Return a simplified class name to use in XML.
*
* @return simplified class name.
*/
@Override
public String getType() {
return "fcs";
}
/**
* Returns the stored File object (pointing to the FCS file being processed)
*
* @return File object pointing to the FCS file
*/
public File getFile() {
return filename;
}
/**
* Return the parsed FCSReader metadata information.
*
* @return String containing the metadata of the FCSReader.
*/
public String metadataDump() {
if (!isFileParsed) {
return "File could not be parsed.";
}
String str = "Valid " + fcsVersion + " file with TEXT: " + TEXTbegin + " - " + TEXTend + ", DATA: " + DATAbegin
+ " - " + DATAend + ", ANALYSIS: " + ANALYSISbegin + " - " + ANALYSISend + ", OTHER: " + OTHERbegin
+ ".\n" + "DELIMITER: (char) " + (int) DELIMITER + "\n\n";
// Output the list of standard key-value pairs
Set<String> keySet = TEXTMapStandard.keySet();
str += "Standard TEXT keyword-value pairs (" + keySet.size() + "):\n\n";
for (String key : keySet) {
str += (key + ": " + TEXTMapStandard.get(key) + "\n");
}
// Output the list of custom key-value pairs
keySet = TEXTMapCustom.keySet();
str += "\n\n";
str += "Custom TEXT keyword-value pairs (" + keySet.size() + "):\n\n";
for (String key : keySet) {
str += (key + ": " + TEXTMapCustom.get(key) + "\n");
}
// Output the list of parameters (and their attributes)
str += "\n\n";
str += "Parameters and their attributes:\n\n";
for (String key : parametersAttr.keySet()) {
str += (key + ": " + parametersAttr.get(key) + "\n");
}
return str;
}
/**
* Returns all parameter names.
*
* @return The String array of parameter names.
*/
public ArrayList<String> getParameterNames() {
ArrayList<String> paramNames = new ArrayList<String>(numParameters());
for (int i = 1; i <= numParameters(); i++) {
paramNames.add(parametersAttr.get("P" + i + "N"));
}
return paramNames;
}
/**
* Returns all standard FCS 3.0/3.1 keywords as a String - String map
*
* @return The String - String Map of all standard FCS 3.0/3.1 keywords
*/
public Map<String, String> getStandardKeywords() {
return TEXTMapStandard;
}
/**
* Return the value associated to a standard FCS 3.0/3.1 keyword or empty
*
* @param key
* One of the standard keywords (staring with "$")
* @return The value associated with the passed keyword or empty String if
* not found
*/
public String getStandardKeyword(String key) {
if (TEXTMapStandard.containsKey(key)) {
return TEXTMapStandard.get(key);
} else {
return "";
}
}
/**
* Returns all custom, non FCS 3.0/3.1-compliant keywords as a String -
* String map
*
* @return The String - String Map of all custom, non FCS 3.0/3.1-compliant
* keywords
*/
public Map<String, String> getCustomKeywords() {
return TEXTMapStandard;
}
/**
* Return the value associated with a custom, non FCS 3.0/3.1-compliant
* keyword or empty
*
* @param key
* A custom keywords (without $ at the beginning)
* @return The value associated with the passed keyword or empty String if
* not found
*/
public String getCustomKeyword(String key) {
if (TEXTMapCustom.containsKey(key)) {
return TEXTMapCustom.get(key);
} else {
return "";
}
}
/**
* Returns all keywords as a String - String map (FCS 3.0/3.1-compliant and
* custom)
*
* @return The String - String Map of all keywords
*/
public Map<String, String> getAllKeywords() {
Map<String, String> allMap = new HashMap<String, String>();
allMap.putAll(TEXTMapStandard);
allMap.putAll(TEXTMapCustom);
return allMap;
}
/**
* Return the number of events in the dataset.
*
* @return number of events.
*/
public int numEvents() {
int numEvents = 0;
if (TEXTMapStandard.containsKey("$TOT")) {
numEvents = Integer.parseInt(TEXTMapStandard.get("$TOT"));
}
return numEvents;
}
/**
* Return the number of parameters in the dataset.
*
* @return number of parameters.
*/
public int numParameters() {
int numParameters = 0;
if (TEXTMapStandard.containsKey("$PAR")) {
numParameters = Integer.parseInt(TEXTMapStandard.get("$PAR"));
}
return numParameters;
}
/**
* Return subset of measurements with optional stride for parameter with
* given column index in double precision. The measurements are returned
* as is without any scaling.
* @param columnIndex Index of the measurement column.
* @param nValues number of values to be read. Set to 0 to read them all.
* @param sampled True if the nValues must be sampled with constant stride
* throughout the total number of rows, false if the first
* nValues rows must simply be returned.
* @return array of measurements.
* @throws IOException If something unexpected with the datatype is found.
*/
public double[] getRawDataPerColumnIndex(int columnIndex, int nValues,
boolean sampled) throws IOException {
// Make sure that he data was loaded
if (!isDataLoaded) {
return new double[0];
}
// Datatype
String datatype = datatype();
// If the datatype is INTEGER, we currently only support 16 bit
if (datatype == "I" && bytesPerParameter[columnIndex] != 2) {
throw new IOException("Integer data type is expected to be"
+ "unsigned 16 bit!");
}
// Some constants
int nParams = numParameters();
int nEvents = numEvents();
int step;
// If all values must be read, the step is 1.
if (nValues == 0 || nValues > nEvents) {
nValues = nEvents;
step = 1;
} else {
if (sampled) {
step = (int) (((float) nEvents) / nValues);
if (step == 0) {
step = 1;
}
} else {
step = 1;
}
}
// Pre-calculate the positions to extract
int[] positions = new int[nValues];
int c = 0; // Global measurement counter
int cBytes = 0; // Global measurement counter in bytes
int n = 0; // Row counter
int t = 0; // Accepted value counter
while (t < nValues) {
// If we are at the right column, we store it
if (c % nParams == columnIndex) {
if (n % step == 0) {
// We use the correct data width per column
positions[t] = cBytes;
t++;
}
n++;
}
cBytes += bytesPerParameter[c % nParams];
c++;
}
// Allocate space for the events
double[] m = new double[nValues];
// Go through the buffer and return the values at the pre-calculate
// positions (i.e. for the requested column with given stride and
// requested total number)
DATA.rewind();
for (int i = 0; i < positions.length; i++) {
// Jump to position
DATA.position(positions[i]);
// Get the value, convert it to double
double tmp;
if (datatype.equals("F")) {
tmp = (double) DATA.getFloat();
} else if (datatype.equals("I")) {
// The integer format is 2 bytes only and unsigned!
tmp = (double) ((short) (DATA.getShort()) & 0xffff);
} else if (datatype.equals("D")) {
tmp = (double) DATA.getDouble();
} else if (datatype.equals("A")) {
tmp = (double) DATA.get();
} else {
throw new IOException("Unknown data type!");
}
// Store the value
m[i] = tmp;
}
// Return the array
return m;
}
/**
* Return subset of measurements with optional stride for parameter with
* given column index in double precision. The measurements are scaled as
* instructed in the FCS file (parameters 'PnR', 'PnE', 'PnG').
* @param columnIndex Index of the measurement column.
* @param nValues number of values to be read. Set to 0 to read them all.
* @param sampled True if the nValues must be sampled with constant stride
* throughout the total number of rows, false if the first
* nValues rows must simply be returned.
* @return array of measurements.
* @throws IOException If something unexpected with the datatype is found.
*/
public double[] getDataPerColumnIndex(int columnIndex, int nValues,
boolean sampled) throws IOException {
// Make sure that he data was loaded
if (!isDataLoaded) {
return new double[0];
}
// Get the unscaled parameters
double[] m = getRawDataPerColumnIndex(columnIndex, nValues, sampled);
// Allocate space for the scaled parameters
double[] n = new double[m.length];
// Apply transformations
double decade = (double) parameterDecades[columnIndex];
double range = (double) parameterRanges[columnIndex];
double log = (double) parameterLogs[columnIndex] ;
double logz = (double) parameterLogZeros[columnIndex];
double gain = (double) parameterGains[columnIndex];
for (int i = 0; i < m.length; i++) {
if (gain != 1.0) {
n[i] = m[i] / gain;
} else if (log != 0.0) {
n[i] = logz * Math.pow(10, m[i] / range * decade);
} else {
// No transformation
n[i] = m[i];
}
}
// Return the transformed data
return n;
}
/**
* Export the full data (not scaled!) to a CSV file.
*
* @param csvFile Full path of the CSV file
* @return true if the CSV file could be saved, false otherwise.
* @throws IOException If something unexpected with the datatype is found.
*/
public boolean exportDataToCSV(File csvFile) throws IOException {
// Make sure that he data was loaded
if (!isDataLoaded) {
return false;
}
// Datatype
String datatype = datatype();
// If the datatype is INTEGER, we currently only support 16 bit
for (int i = 0; i < bytesPerParameter.hashCode(); i++) {
if (datatype == "I" && bytesPerParameter[i] != 2) {
throw new IOException("Integer data type is expected to be"
+ "unsigned 16 bit!");
}
}
FileWriter fw;
try {
fw = new FileWriter(csvFile);
} catch (IOException e) {
return false;
}
BufferedWriter writer = new BufferedWriter(fw);
// Write the parameters names as header line
for (int i = 1; i <= numParameters(); i++) {
try {
writer.write(parametersAttr.get("P" + i + "N") + ",");
} catch (IOException e) {
// Close writer
try {
writer.close();
} catch (IOException e1) {
return false;
}
return false;
}
}
// Next line
try {
writer.write("\n");
} catch (IOException e) {
// Close writer
try {
writer.close();
} catch (IOException e1) {
return false;
}
return false;
}
// Store some constants
int numParameters = numParameters();
// Make sure to rewind the buffer
DATA.rewind();
// Write the values
int nParameter = 0;
while (DATA.hasRemaining()) {
try {
if (datatype.equals("F")) {
writer.write((float) DATA.getFloat() + ",");
} else if (datatype.equals("I")) {
// The integer format is 2 bytes only and unsigned!
writer.write(((short) (DATA.getShort()) & 0xffff) + ",");
} else if (datatype.equals("D")) {
writer.write((double) DATA.getDouble() + ",");
} else if (datatype.equals("A")) {
// Get a single byte
writer.write((char) DATA.get() + ",");
} else {
throw new IOException("Unknown data type!");
}
// New line
nParameter++;
if (nParameter == numParameters) {
writer.write("\n");
nParameter = 0;
}
} catch (IOException e) {
// Close writer
try {
writer.close();
} catch (IOException e1) {
return false;
}
return false;
}
}
// Close writer
try {
writer.close();
} catch (IOException e) {
return false;
}
return true;
}
/**
* Parse the header.
*
* @return true if the file header could be parsed successfully, false
* otherwise.
* @throws IOException
*/
private boolean parseHeader() throws IOException {
// Read and check the version
in.seek(0);
byte[] VERSION = new byte[6];
in.read(VERSION);
fcsVersion = new String(VERSION);
if (!(fcsVersion.equals("FCS3.0") || fcsVersion.equals("FCS3.1"))) {
errorMessage = filename + " is not a valid FCS version 3.0 or 3.1 file!";
System.out.println(errorMessage);
return false;
}
// We will use an 8-byte array several times in the following
byte[] eightByteArray = new byte[8];
// ASCII-encoded offset to first byte of TEXT segment (bytes 10 - 17)
in.seek(10);
in.read(eightByteArray);
TEXTbegin = Integer.parseInt((new String(eightByteArray)).trim());
// ASCII-encoded offset to last byte of TEXT segment (bytes 18 - 25)
in.seek(18);
in.read(eightByteArray);
TEXTend = Integer.parseInt((new String(eightByteArray)).trim());
// ASCII-encoded offset to first byte of DATA segment (bytes 26 - 33)
// This can be a valid offset, or 0: if it is 0, it means that the
// segment
// is larger than 99,999,999 bytes
in.seek(26);
in.read(eightByteArray);
DATAbegin = Integer.parseInt((new String(eightByteArray)).trim());
// ASCII-encoded offset to last byte of DATA segment (bytes 34 - 41)
// This can be a valid offset, or 0: if it is 0, it means that the
// segment
// is larger than 99,999,999 bytes
in.seek(34);
in.read(eightByteArray);
DATAend = Integer.parseInt((new String(eightByteArray)).trim());
// ASCII-encoded offset to first byte of ANALYSIS segment (bytes 42 -
// 49)
// This can be a valid offset, 0, or even blank. If 0, $BEGINANALYSIS
// must
// be checked
in.seek(42);
in.read(eightByteArray);
String tmp = (new String(eightByteArray)).trim();
if (tmp.length() == 0) {
ANALYSISbegin = 0;
} else {
ANALYSISbegin = Integer.parseInt(tmp);
}
// ASCII-encoded offset to last byte of ANALYSIS segment (bytes 50 - 57)
// This can be a valid offset, 0, or even blank. If 0, $ENDANALYSIS must
// be checked
in.seek(50);
tmp = (new String(eightByteArray)).trim();
if (tmp.length() == 0) {
ANALYSISend = 0;
} else {
ANALYSISend = Integer.parseInt(tmp);
}
// ASCII-encoded offset to user defined OTHER segments (bytes 58 -
// beginning of next segment)
in.seek(58);
tmp = (new String(eightByteArray)).trim();
if (tmp.length() == 0) {
OTHERbegin = 0;
} else {
OTHERbegin = Integer.parseInt(tmp);
}
// The TEXT and DATA offsets can theoretically be swapped in the header
// segment
swapOffsetsIfNeeded();
return true;
}
/**
* Parse the TEXT segment.
*
* @return true if parsing was successful, false otherwise.
* @throws IOException
*/
private boolean parseText() throws IOException {
// Read the TEXT segment
in.seek(TEXTbegin);
int LEN = (TEXTend - TEXTbegin + 1); // TEXT cannot be longer than
// 99,999,999 bytes
byte[] bText = new byte[LEN];
in.read(bText);
// Get the delimiter character
DELIMITER = (char) bText[0];
// Get the keyword-value pairs and store them in the hash map.
// All values are UTF-8-encoded, the keywords are strictly ASCII
// (but can be parsed as UTF-8).
storeKeyValuePairs(new String(bText, "UTF-8"));
return true;
}
/**
* Parse the DATA (events) segment.
*
* @return true if the parsing was successful (or no data was present),
* false otherwise.
* @throws IOException
* TODO Add support for multiple DATA segments.
*/
private boolean parseData() throws IOException {
// Seek to the DATA segment
long dataOffset;
try {
dataOffset = Long.parseLong(TEXTMapStandard.get("$BEGINDATA").trim());
} catch (NumberFormatException e) {
errorMessage = "Invalid offset for the DATA segment! " + "This is a bug! Please report it.";
System.out.println(errorMessage);
return false;
}
if (dataOffset == 0) {
System.out.println("No DATA present.");
return true;
}
// Seek to the beginning of the data offset
in.seek(dataOffset);
// Read and store the data
return readDataBlock();
}
/**
* Parse the ANALYSIS segment.
*
* @return true if parsing was successful, false otherwise.
* @throws IOException
* TODO Implement
*/
private boolean parseAnalysis() throws IOException {
return true;
}
/**
* Parse the OTHER segment.
*
* @return true if parsing was successful, false otherwise.
* @throws IOException
* TODO Implement
*/
private boolean parseOther() throws IOException {
return true;
}
/**
* The TEXT and DATA offsets can theoretically be swapped in the header
* segment. We make sure that TEXT is assigned the lower and DATA the higher
* offset.
*/
private void swapOffsetsIfNeeded() {
// If the data block is larger than 99,999,999 bytes,
// DATAbegin will be 0.
// In this case we do NOT want to swap!
if (DATAbegin == 0) {
return;
}
if (TEXTbegin > DATAbegin) {
int tmp;
tmp = TEXTbegin;
TEXTbegin = DATAbegin;
DATAbegin = tmp;
tmp = TEXTend;
TEXTend = DATAend;
DATAend = tmp;
}
}
/**
* Extracts and returns the value in a segment for a given key.
*
* @param segment
* String containing the full segment (e.g. TEXT).
*/
private void storeKeyValuePairs(String segment) {
assert(segment.charAt(0) == DELIMITER);
assert(segment.charAt(segment.length() - 1) == DELIMITER);
// Process all
int beginIndex = 0;
int interIndex = 0;
int endIndex = 0;
// Parse the full segment
while (true) {
interIndex = segment.indexOf(DELIMITER, beginIndex + 1);
if (interIndex == -1) {
break;
}
endIndex = segment.indexOf(DELIMITER, interIndex + 1);
String key = segment.substring(beginIndex + 1, interIndex).trim();
String value = segment.substring(interIndex + 1, endIndex).trim();
// If the key starts with a $ sign, we found a standard FCS keyword
// and we store it in the TEXTMapStandard map; otherwise, we have a
// custom keyword we store it in the TEXTMapCustom map
if (key.charAt(0) == '$') {
TEXTMapStandard.put(key, value);
} else {
TEXTMapCustom.put(key, value);
}
beginIndex = endIndex;
}
}
/**
* Process the extracted parameters from the standard TEXT map.
*
* @return true if there were parameters and they could be processed
* successfully, false otherwise.
*/
private boolean processParameters() {
// Number of events
int numEvents = numEvents();
// Number of parameters
int numParameters = numParameters();
// Store the number of events
parametersAttr.put("numEvents", Integer.toString(numEvents));
// Store the number of parameters
parametersAttr.put("numParameters", Integer.toString(numParameters));
// If there are no parameters, we leave.
if (numParameters == 0) {
return false;
}
// We store the number of bytes that are used to store each of the
// parameter values
bytesPerParameter = new int[numParameters];
// We also store gain and transformation details
parameterDecades = new float[numParameters];
parameterLogs = new float[numParameters];
parameterLogZeros = new float[numParameters];
parameterRanges = new float[numParameters];
parameterGains = new float[numParameters];
// Keep track of the datatype
String datatype = datatype();
// Now go over the parameters and extract all info.
// Mind that parameter count starts at 1.
String key = "";
for (int i = 1; i <= numParameters; i++) {
// Name
key = "P" + i + "N";
String name = TEXTMapStandard.get("$" + key);
if (name == null) {
name = "<not set>";
}
parametersAttr.put(key, name);
// Label
key = "P" + i + "S";
String label = TEXTMapStandard.get("$" + key);
if (label == null) {
label = "";
}
parametersAttr.put(key, label);
// Range
key = "P" + i + "R";
String range = TEXTMapStandard.get("$" + key);
if (range == null) {
range = "262144";
}
parametersAttr.put(key, range);
parameterRanges[i - 1] = Integer.parseInt(range);
// Bits
key = "P" + i + "B";
String bits = TEXTMapStandard.get("$" + key);
if (bits == null) {
if (datatype == "D") {
bits = "64";
} else if (datatype == "F") {
bits = "32";
} else if (datatype == "I") {
bits = "16";
} else if (datatype == "A") {
bits = "8";
} else {
bits = "32";
}
}
parametersAttr.put(key, bits);
// Store the value for later use
bytesPerParameter[i - 1] = Integer.parseInt(bits) / 8;
// Linear or logarithmic amplifiers?
float log = 0.0f;
float log_zero = 0.0f;
key = "P" + i + "E";
String decade = TEXTMapStandard.get("$" + key);
float f_decade = 0.0f;
if (decade != null) {
String decadeParts[] = decade.split(",");
f_decade = Float.parseFloat(decadeParts[0]);
float f_value = Float.parseFloat(decadeParts[1]);
if (f_decade == 0.0) {
// Amplification is linear or undefined
log = 0.0f;
log_zero = 0.0f;
} else {
log = 1.0f;
if (f_value == 0.0) {
log_zero = 1.0f;
} else {
log_zero = f_value;
}
}
}
parametersAttr.put(key + "_LOG", Float.toString(log));
parametersAttr.put(key + "_LOGZERO", Float.toString(log_zero));
parameterDecades[i - 1] = f_decade;
parameterLogs[i - 1] = log;
parameterLogZeros[i - 1] = log_zero;
// Gain
key = "P" + i + "G";
String gain = TEXTMapStandard.get("$" + key);
if (gain == null) {
gain = "1.0";
}
parametersAttr.put(key, gain);
parameterGains[i - 1] = Float.parseFloat(gain);
// Voltage
key = "P" + i + "V";
String voltage = TEXTMapStandard.get("$" + key);
if (voltage == null) {
voltage = "NaN";
}
parametersAttr.put(key, voltage);
// Log or linear
key = "P" + i + "DISPLAY";
String display = TEXTMapCustom.get(key);
if (display == null) {
display = "LIN";
}
parametersAttr.put(key, display);
}
return true;
}
/**
* Return the datatype of the data bytes, one of "I", "F", "D", or "A". I:
* unsigned integer; F: single-precision IEEE floating point; D:
* double-precision IEEE floating point; A: ASCII.
*
* @return datatype of the measurements ("I", "F", "D", "A"), or "N" if not
* defined.
*/
private String datatype() {
String datatype = "N";
if (TEXTMapStandard.containsKey("$DATATYPE")) {
datatype = TEXTMapStandard.get("$DATATYPE");
}
return datatype;
}
/**
* Return the endianity of the data bytes, one of "L", "B", "U". L: little
* endian (1,2,3,4); B: big endian (4,3,2,1); U: unsupported (3,4,1,2); N:
* not defined.
*
* @return endianity of the data bytes ("L", "B", "U"), or "N" if not
* defined.
*/
private String endianity() {
String datatype = "N";
if (TEXTMapStandard.containsKey("$BYTEORD")) {
String byteOrd = TEXTMapStandard.get("$BYTEORD");
if (byteOrd.equals("1,2,3,4")) {
datatype = "L";
} else if (byteOrd.equals("4,3,2,1")) {
datatype = "B";
} else {
datatype = "U";
}
}
return datatype;
}
/**
* Return the data acquisition mode, one of "C", "L", "U". C: One correlated
* multivariate histogram stored as a multidimensional array; L: list mode:
* for each event, the value of each parameter is stored in the order in
* which the parameters are described. U: Uncorrelated univariate
* histograms: there can be more than one univariate histogram per data set.
* N: not defined.
*
* @return acquisition mode of the data ("C", "L", "U"), or "N" if not
* defined.
*/
private String mode() {
if (TEXTMapStandard.containsKey("$MODE")) {
String mode = TEXTMapStandard.get("$MODE");
if (mode.equals("C") || mode.equals("L") || mode.equals("U")) {
return mode;
} else {
return "N";
}
}
return "N";
}
/**
* Reads and stores the data segment
*
* @return true if reading the data segment was successful, false otherwise
* TODO Use the information about the type of data
*/
private boolean readDataBlock() {
// Reset the isDataLoaded flag
isDataLoaded = false;
// To read the data in the correct format we need to know the endianity.
String endianity = endianity();
// Endianity
ByteOrder endian;
if (endianity.equals("L")) {
endian = ByteOrder.LITTLE_ENDIAN;
} else if (endianity.equals("B")) {
endian = ByteOrder.BIG_ENDIAN;
} else {
errorMessage = "Unknown endianity!";
System.err.println(errorMessage);
return false;
}
// Allocate a (byte) buffer to hold the data segment
int size = (DATAend - DATAbegin + 1);
byte[] recordBuffer = new byte[size];
// Create a ByteBuffer wrapped around the byte array that
// reads with the desired endianity
DATA = ByteBuffer.wrap(recordBuffer);
DATA.order(endian);
// Read
try {
in.read(recordBuffer);
} catch (IOException e) {
errorMessage = "Could not read the data segment from file!";
System.out.println(errorMessage);
return false;
}
// Make sure to be at the beginning of the buffer
DATA.rewind();
// Reset error message
errorMessage = "";
// Set the isDataLoaded flag
isDataLoaded = true;
// Return success
return true;
}
}
| Register the PnCHANNELTYPE parameter if it exists in the FCS file (BD Influx).
| AnnotationToolBDFACSDIVAFCS/ch/ethz/scu/obit/bdfacsdivafcs/readers/FCSReader.java | Register the PnCHANNELTYPE parameter if it exists in the FCS file (BD Influx). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.